From: Tony Tkacik Date: Mon, 27 Apr 2015 08:24:21 +0000 (+0000) Subject: Bug 868: Remove AD-SAL components which were deprecated in Lithium X-Git-Tag: release/beryllium~568 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=commitdiff_plain;h=50f88249a65c52ba56a48852b71ce432fed2bbeb Bug 868: Remove AD-SAL components which were deprecated in Lithium Removes legacy components,which were deprecated in Lithium and scheduled to be removed Berrylium. Code is still preserved on stable/lithium branch. Change-Id: Icef5e39cc59324db203ccb2cb5f9a3aea0e57b21 Signed-off-by: Tony Tkacik --- diff --git a/karaf/opendaylight-karaf/pom.xml b/karaf/opendaylight-karaf/pom.xml index 57d4657271..8365369d5b 100644 --- a/karaf/opendaylight-karaf/pom.xml +++ b/karaf/opendaylight-karaf/pom.xml @@ -57,20 +57,6 @@ xml runtime - - org.opendaylight.controller - features-adsal - features - xml - runtime - - - org.opendaylight.controller - features-nsf - features - xml - runtime - org.opendaylight.controller diff --git a/opendaylight/adsal/adsal-enunciate-parent/enunciate.xml b/opendaylight/adsal/adsal-enunciate-parent/enunciate.xml deleted file mode 100644 index 431ea7b316..0000000000 --- a/opendaylight/adsal/adsal-enunciate-parent/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - diff --git a/opendaylight/adsal/adsal-enunciate-parent/pom.xml b/opendaylight/adsal/adsal-enunciate-parent/pom.xml deleted file mode 100644 index 1c6f99f8c1..0000000000 --- a/opendaylight/adsal/adsal-enunciate-parent/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - org.opendaylight.controller - enunciate-parent - 1.6.0-SNAPSHOT - ../../commons/enunciate-parent - - - 4.0.0 - adsal-enunciate-parent - pom - - - - - - org.codehaus.enunciate - maven-enunciate-plugin - - - org.opendaylight.controller - sal - ${sal.version} - - - - - - - - diff --git a/opendaylight/adsal/appauth/pom.xml b/opendaylight/adsal/appauth/pom.xml deleted file mode 100644 index 00de90bb08..0000000000 --- a/opendaylight/adsal/appauth/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../commons/opendaylight - - appauth - 0.6.0-SNAPSHOT - bundle - - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - usermanager - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.configuration, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.usermanager, - org.slf4j, - org.apache.felix.dm, - org.opendaylight.controller.appauth, - org.opendaylight.controller.appauth.authorization - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/appauth/src/main/java/org/opendaylight/controller/appauth/Application.java b/opendaylight/adsal/appauth/src/main/java/org/opendaylight/controller/appauth/Application.java deleted file mode 100644 index 84a2e919f7..0000000000 --- a/opendaylight/adsal/appauth/src/main/java/org/opendaylight/controller/appauth/Application.java +++ /dev/null @@ -1,20 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.appauth; - -import org.opendaylight.controller.appauth.authorization.Authorization; - -public abstract class Application extends Authorization { - - public Application() { - super(); - } - -} diff --git a/opendaylight/adsal/appauth/src/main/java/org/opendaylight/controller/appauth/authorization/Authorization.java b/opendaylight/adsal/appauth/src/main/java/org/opendaylight/controller/appauth/authorization/Authorization.java deleted file mode 100644 index b70a79b4ae..0000000000 --- a/opendaylight/adsal/appauth/src/main/java/org/opendaylight/controller/appauth/authorization/Authorization.java +++ /dev/null @@ -1,675 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.appauth.authorization; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.containermanager.IContainerAuthorization; -import org.opendaylight.controller.sal.authorization.AppRoleLevel; -import org.opendaylight.controller.sal.authorization.IResourceAuthorization; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.authorization.Resource; -import org.opendaylight.controller.sal.authorization.ResourceGroup; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.usermanager.IUserManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This abstract class implements the methods defined by IResourceAuthorization - * interface for each application class. - */ -public abstract class Authorization implements IResourceAuthorization { -private static final Logger logger = LoggerFactory.getLogger(Authorization.class); - private static final String namesRegex = ConfigurationObject.getRegularExpression(); - /* - * The configured resource groups - */ - protected ConcurrentMap> resourceGroups; - /* - * The configured roles along with their level - */ - protected ConcurrentMap roles; - /* - * The association of groups to roles - */ - protected ConcurrentMap> groupsAuthorizations; - /* - * The name of the default group. It is the group which contains all the - * resources - */ - protected String allResourcesGroupName; - - @Override - public Status createRole(String role, AppRoleLevel level) { - if (role == null || role.trim().isEmpty() - || !role.matches(Authorization.namesRegex)) { - return new Status(StatusCode.BADREQUEST, - "Role name must start with alphanumeric, no special characters."); - } - if (isControllerRole(role)) { - return new Status(StatusCode.NOTALLOWED, - "Controller roles cannot be explicitely " - + "created in App context"); - } - if (isContainerRole(role)) { - return new Status(StatusCode.NOTALLOWED, - "Container roles cannot be explicitely " - + "created in App context"); - } - if (isRoleInUse(role)) { - return new Status(StatusCode.CONFLICT, "Role already in use"); - } - if (roles.containsKey(role)) { - if (roles.get(role).equals(level)) { - return new Status(StatusCode.SUCCESS, "Role is already present"); - } else { - return new Status(StatusCode.BADREQUEST, - "Role exists and has different level"); - } - } - - return createRoleInternal(role, level); - } - - protected Status createRoleInternal(String role, AppRoleLevel level) { - roles.put(role, level); - groupsAuthorizations.put(role, new HashSet()); - return new Status(StatusCode.SUCCESS); - } - - @Override - public Status removeRole(String role) { - if (role == null || role.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Role name can't be empty"); - } - if (isControllerRole(role)) { - return new Status(StatusCode.NOTALLOWED, - "Controller roles cannot be removed"); - } - if (isContainerRole(role)) { - return new Status(StatusCode.NOTALLOWED, - "Container roles cannot be removed"); - } - return removeRoleInternal(role); - } - - protected Status removeRoleInternal(String role) { - groupsAuthorizations.remove(role); - roles.remove(role); - return new Status(StatusCode.SUCCESS); - } - - @Override - public List getRoles() { - return new ArrayList(groupsAuthorizations.keySet()); - } - - @SuppressWarnings("unchecked") - @Override - public Status createResourceGroup(String groupName, List resources) { - //verify group name not null/empty - if (groupName == null || groupName.trim().isEmpty() - || !groupName.matches(Authorization.namesRegex)) { - return new Status(StatusCode.BADREQUEST, "Group name must start with alphanumeric, no special characters"); - } - //verify group name is not same as all-resources - if (groupName.equals(this.allResourcesGroupName)) { - return new Status(StatusCode.NOTALLOWED, "All resource group cannot be created"); - } - //verify group name is unique - if (resourceGroups.containsKey(groupName)) { - return new Status(StatusCode.CONFLICT, "Group name already exists"); - } - - //try adding resources, discard if not of type T - Set toBeAdded = new HashSet(); - boolean allAdded = true; - for (Object obj : resources) { - try { - toBeAdded.add((T) obj); - } catch (ClassCastException e) { - logger.debug("Attempt to add a resource with invalid type"); - allAdded = false; - } - } - resourceGroups.put(groupName, toBeAdded); - return (allAdded ? new Status(StatusCode.SUCCESS, "All resources added succesfully") : - new Status(StatusCode.SUCCESS, "One or more resources couldn't be added")); - } - - @SuppressWarnings("unchecked") - @Override - public Status addResourceToGroup(String groupName, Object resource) { - if (groupName == null || groupName.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid group name"); - } - - if (resource == null) { - return new Status(StatusCode.BADREQUEST, "Null resource"); - } - - T castedResource = null; - try { - castedResource = (T) resource; - } catch (ClassCastException e) { - logger.debug("Attempt to add a resource with invalid type"); - return new Status(StatusCode.BADREQUEST, "Incompatible resource"); - } - - Set group = resourceGroups.get(groupName); - if (group == null) { - return new Status(StatusCode.NOTFOUND, "Group not found"); - } - - return addResourceToGroupInternal(groupName, castedResource); - } - - /* - * Method child classes can overload if they need application specific - * checks on the resource - */ - protected Status addResourceToGroupInternal(String groupName, T resource) { - Set group = resourceGroups.get(groupName); - // Update group and cluster - group.add(resource); - resourceGroups.put(groupName, group); - - return new Status(StatusCode.SUCCESS, "Resource added successfully"); - - } - - private Status removeRoleResourceGroupMapping(String groupName) { - List affectedRoles = new ArrayList(); - Status result; - for (Entry> pairs : groupsAuthorizations.entrySet()) { - String role = pairs.getKey(); - Set groups = pairs.getValue(); - for (ResourceGroup group : groups) { - if (group.getGroupName().equals(groupName)) { - affectedRoles.add(role); - break; - } - } - } - StringBuffer msg = new StringBuffer(); - for (String role : affectedRoles) { - result = unassignResourceGroupFromRole(groupName, role); - if (!result.isSuccess()) { - msg.append(result.getDescription()); - msg.append(' '); - } - } - - if (msg.length() != 0) { - return new Status(StatusCode.BADREQUEST, msg.toString()); - } else { - return new Status(StatusCode.SUCCESS); - } - } - - @Override - public Status removeResourceGroup(String groupName) { - // Default resource group cannot be deleted - if (groupName == null || groupName.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid group name"); - } - if (groupName.equals(this.allResourcesGroupName)) { - return new Status(StatusCode.NOTALLOWED, - "All resource group cannot be removed"); - } - resourceGroups.remove(groupName); - Status result = removeRoleResourceGroupMapping(groupName); - - return result.isSuccess() ? result : - new Status(StatusCode.SUCCESS, "Failed removing group from: " + result.getDescription()); - } - - - @Override - public Status removeResourceFromGroup(String groupName, Object resource) { - if (groupName == null || groupName.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid group name"); - } - - Set group = resourceGroups.get(groupName); - if (group != null && group.remove(resource)) { - // Update cluster - resourceGroups.put(groupName, group); - return new Status(StatusCode.SUCCESS, "Resource removed successfully"); - } - - return new Status(StatusCode.NOTFOUND, "Group/Resource not found"); - } - - - /** - * Relay the call to user manager - */ - @Override - public UserLevel getUserLevel(String userName) { - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - - if (logger.isDebugEnabled()) { - logger.debug("User {} has UserLevel {}", userName, userManager.getUserLevel(userName)); - } - - return (userManager == null) ? UserLevel.NOUSER : userManager - .getUserLevel(userName); - } - - @Override - public Set getAllResourcesforUser(String userName) { - Set resources = new HashSet(); - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return new HashSet(0); - } - - // Get the roles associated with this user - List roles = userManager.getUserRoles(userName); - if (roles == null) { - return resources; - } - - for (String role : roles) { - // Get our resource groups associated with this role - List groups = this.getAuthorizedGroups(role); - if (groups.isEmpty()) { - continue; - } - for (ResourceGroup group : groups) { - // Get the list of resources in this group - List list = this.getResources(group.getGroupName()); - if (list.isEmpty()) { - continue; - } - for (Object resource : list) { - Resource toBeAdded = new Resource(resource, - group.getPrivilege()); - /* - * Add the resource to the set if the same resource with - * higher privilege is not present. If the same resource - * with lower privilege is present, remove it. No check on - * same privilege resource as set guarantees no duplicates. - */ - Resource existing = higherPrivilegeResourcePresent( - resources, toBeAdded); - if (existing == null) { - resources.add(toBeAdded); - } - existing = lowerPrivilegeResourcePresent(resources, - toBeAdded); - if (existing != null) { - resources.remove(existing); - } - } - } - } - - if (logger.isDebugEnabled()) { - logger.debug("User {} has resources {}", userName, resources); - } - - return resources; - } - - @Override - public List getAuthorizedResources(String role) { - Set resources = new HashSet(); - - // Get our resource groups associated with this role - List groups = this.getAuthorizedGroups(role); - if (groups.isEmpty()) { - return new ArrayList(0); - } - for (ResourceGroup group : groups) { - // Get the list of resources in this group - List list = this.getResources(group.getGroupName()); - if (list.isEmpty()) { - continue; - } - for (Object resource : list) { - Resource toBeAdded = new Resource(resource, - group.getPrivilege()); - /* - * Add the resource to the set if the same resource with higher - * privilege is not present. If the same resource with lower - * privilege is present, remove it. No check on same privilege - * resource as set guarantees no duplicates. - */ - Resource existing = higherPrivilegeResourcePresent(resources, - toBeAdded); - if (existing == null) { - resources.add(toBeAdded); - } - existing = lowerPrivilegeResourcePresent(resources, toBeAdded); - if (existing != null) { - resources.remove(existing); - } - } - } - - if (logger.isDebugEnabled()) { - logger.debug("For the Role {}, Authorized Resources are {}", role, resources); - } - - return new ArrayList(resources); - } - - /** - * Given a set of resources and a resource to test, it returns the element - * in the set which represent the same resource with a lower privilege - * associated to it, if present. - * - * @param resources - * @param resource - * @return - */ - private Resource lowerPrivilegeResourcePresent(Set resources, - Resource resource) { - - if (resource == null || resources == null) { - return null; - } - - Object resourceElement = resource.getResource(); - Privilege resourcePrivilege = resource.getPrivilege(); - for (Resource element : resources) { - if (element.getResource().equals(resourceElement) - && element.getPrivilege().ordinal() < resourcePrivilege - .ordinal()) { - return element; - } - } - return null; - } - - /** - * Given a set of resources and a resource to test, it returns the element - * in the set which represents the same resource with an higher privilege, - * if present. - * - * @param resources - * @param resource - * @return - */ - private Resource higherPrivilegeResourcePresent(Set resources, - Resource resource) { - - if (resource == null || resources == null) { - return null; - } - - Object resourceElement = resource.getResource(); - Privilege resourcePrivilege = resource.getPrivilege(); - for (Resource element : resources) { - if (element.getResource().equals(resourceElement) - && element.getPrivilege().ordinal() > resourcePrivilege - .ordinal()) { - return element; - } - } - - return null; - } - - @Override - public Privilege getResourcePrivilege(String userName, Object resource) { - - if (userName == null || userName.trim().isEmpty() || resource == null) { - return Privilege.NONE; - } - - Set hisResources = getAllResourcesforUser(userName); - for (Resource element : hisResources) { - if (element.getResource().equals(resource)) { - return element.getPrivilege(); - } - } - - return Privilege.NONE; - } - - @Override - public List getResourceGroups() { - return new ArrayList(resourceGroups.keySet()); - } - - @Override - public Status assignResourceGroupToRole(String group, Privilege privilege, - String role) { - if (group == null || group.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid group name"); - } - if (role == null || role.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Role name can't be empty"); - } - if (isControllerRole(role)) { - return new Status(StatusCode.NOTALLOWED, - "No group assignment is accepted for Controller roles"); - } - - return assignResourceGroupToRoleInternal(group, privilege, role); - } - - protected Status assignResourceGroupToRoleInternal(String group, Privilege privilege, String role) { - Set roleGroups = groupsAuthorizations.get(role); - roleGroups.add(new ResourceGroup(group, privilege)); - // Update cluster - groupsAuthorizations.put(role, roleGroups); - return new Status(StatusCode.SUCCESS); - } - - @Override - public Status assignResourceGroupToRole(String groupName, String roleName) { - if (groupName == null || groupName.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Group name can't be empty"); - } - if (roleName == null || roleName.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Role name can't be empty"); - } - // Infer group privilege from role's level - Privilege privilege = Privilege.NONE; - switch (this.getApplicationRoleLevel(roleName)) { - case APPADMIN: - privilege = Privilege.WRITE; - break; - case APPUSER: - privilege = Privilege.USE; - break; - case APPOPERATOR: - privilege = Privilege.READ; - break; - default: - break; - } - return this.assignResourceGroupToRole(groupName, privilege, roleName); - } - - @Override - public Status unassignResourceGroupFromRole(String group, String role) { - if (group == null || group.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Group name can't be empty"); - } - if (role == null || role.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Role name can't be empty"); - } - if (isControllerRole(role)) { - return new Status(StatusCode.NOTALLOWED, - "No group assignment change is allowed for " - + "Controller roles"); - } - - return unassignResourceGroupFromRoleInternal(group, role); - } - - protected Status unassignResourceGroupFromRoleInternal(String group, String role) { - ResourceGroup target = null; - for (ResourceGroup rGroup : groupsAuthorizations.get(role)) { - if (rGroup.getGroupName().equals(group)) { - target = rGroup; - break; - } - } - if (target == null) { - return new Status(StatusCode.SUCCESS, "Group " + group + " was not assigned to " + role); - } else { - Set groups = groupsAuthorizations.get(role); - groups.remove(target); - // Update cluster - groupsAuthorizations.put(role, groups); - return new Status(StatusCode.SUCCESS); - - } - } - - @Override - public List getAuthorizedGroups(String role) { - return (groupsAuthorizations.containsKey(role)) ? new ArrayList( - groupsAuthorizations.get(role)) - : new ArrayList(); - } - - @Override - public List getResources(String groupName) { - return (resourceGroups.containsKey(groupName)) ? new ArrayList( - resourceGroups.get(groupName)) : new ArrayList(0); - } - - @Override - public boolean isApplicationRole(String roleName) { - if (roleName == null) { - return false; - } - return roles.containsKey(roleName); - } - - @Override - public boolean isApplicationUser(String userName) { - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return false; - } - List roles = userManager.getUserRoles(userName); - if (roles != null && !roles.isEmpty()) { - for (String role : roles) { - if (isApplicationRole(role)) { - return true; - } - } - } - return false; - } - - @Override - public AppRoleLevel getApplicationRoleLevel(String roleName) { - if (roleName == null || roleName.trim().isEmpty()) { - return AppRoleLevel.NOUSER; - } - - if (isControllerRole(roleName)) { - if (roleName.equals(UserLevel.NETWORKADMIN.toString()) || - roleName.equals(UserLevel.SYSTEMADMIN.toString())) { - return AppRoleLevel.APPADMIN; - } else { - return AppRoleLevel.APPOPERATOR; - } - } - - return (roles.containsKey(roleName)) ? roles.get(roleName) - : AppRoleLevel.NOUSER; - } - - @Override - public AppRoleLevel getUserApplicationLevel(String userName) { - List roles = null; - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - - if (userName == null || userName.trim().isEmpty() - || (userManager == null) - || (roles = userManager.getUserRoles(userName)).isEmpty()) { - return AppRoleLevel.NOUSER; - } - AppRoleLevel highestLevel = AppRoleLevel.NOUSER; - for (String role : roles) { - AppRoleLevel level = getApplicationRoleLevel(role); - if (level.ordinal() < highestLevel.ordinal()) { - highestLevel = level; - } - } - return highestLevel; - } - - /** - * Returns the highest role the specified user has in this application - * context - * - * @param user - * The user name - * @return The highest role associated to the user in this application - * context - */ - public String getHighestUserRole(String user) { - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - String highestRole = ""; - if (userManager != null && !userManager.getUserRoles(user).isEmpty()) { - List roles = userManager.getUserRoles(user); - AppRoleLevel highestLevel = AppRoleLevel.NOUSER; - for (String role : roles) { - AppRoleLevel current; - if (isApplicationRole(role) - && (current = getApplicationRoleLevel(role)).ordinal() < highestLevel.ordinal()) { - highestRole = role; - highestLevel = current; - } - } - } - return highestRole; - } - - private boolean isControllerRole(String role) { - return (role.equals(UserLevel.NETWORKADMIN.toString()) - || role.equals(UserLevel.SYSTEMADMIN.toString()) || role - .equals(UserLevel.NETWORKOPERATOR.toString())); - } - - private boolean isContainerRole(String role) { - IContainerAuthorization containerAuth = (IContainerAuthorization) ServiceHelper.getGlobalInstance( - IContainerAuthorization.class, this); - if (containerAuth == null) { - return false; - } - return containerAuth.isApplicationRole(role); - } - - private boolean isRoleInUse(String role) { - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - - if (userManager == null) { - return true; - } - return userManager.isRoleInUse(role); - } -} diff --git a/opendaylight/adsal/arphandler/pom.xml b/opendaylight/adsal/arphandler/pom.xml deleted file mode 100644 index 34cecaf783..0000000000 --- a/opendaylight/adsal/arphandler/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../commons/opendaylight - - arphandler - 0.7.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - topologymanager - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.sal.packet.address, - org.opendaylight.controller.connectionmanager, - org.opendaylight.controller.sal.connection, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.routing, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.topologymanager, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.hosttracker, - org.opendaylight.controller.hosttracker.hostAware, - org.apache.felix.dm, - org.osgi.service.component, - org.slf4j - org.opendaylight.controller.arphandler - org.opendaylight.controller.arphandler.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPCacheEvent.java b/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPCacheEvent.java deleted file mode 100644 index e7b342fb7f..0000000000 --- a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPCacheEvent.java +++ /dev/null @@ -1,62 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.arphandler; - -public class ARPCacheEvent { - private ARPEvent event; - private boolean newReply; - - public ARPCacheEvent(ARPEvent event, boolean newReply) { - super(); - this.event = event; - this.newReply = newReply; - } - - public ARPEvent getEvent() { - return event; - } - - public boolean isNewReply() { - return newReply; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((event == null) ? 0 : event.hashCode()); - result = prime * result + (newReply ? 1231 : 1237); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ARPCacheEvent other = (ARPCacheEvent) obj; - if (event == null) { - if (other.event != null) - return false; - } else if (!event.equals(other.event)) - return false; - if (newReply != other.newReply) - return false; - return true; - } - - @Override - public String toString() { - return "ARPCacheEvent [event=" + event + ", newReply=" + newReply + "]"; - } -} diff --git a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPEvent.java b/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPEvent.java deleted file mode 100644 index f676a79d49..0000000000 --- a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPEvent.java +++ /dev/null @@ -1,76 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.arphandler; - -import java.io.Serializable; -import java.net.InetAddress; -/* - * ARP Event base class - */ -public abstract class ARPEvent implements Serializable{ - - private static final long serialVersionUID = 1L; - private final InetAddress tIP; - - - @Override - public int hashCode() { - final int prime = 31; - int result = prime + ((tIP == null) ? 0 : tIP.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof ARPEvent)) { - return false; - } - ARPEvent other = (ARPEvent) obj; - if (tIP == null) { - if (other.tIP != null) { - return false; - } - } else if (!tIP.equals(other.tIP)) { - return false; - } - return true; - } - - public ARPEvent(InetAddress ip) { - this.tIP = ip; - } - - public InetAddress getTargetIP() { - return tIP; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("ARPEvent ["); - if (tIP != null) { - builder.append("tIP=") - .append(tIP); - } - builder.append("]"); - return builder.toString(); - } -} diff --git a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPReply.java b/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPReply.java deleted file mode 100644 index 1a446b83db..0000000000 --- a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPReply.java +++ /dev/null @@ -1,151 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.arphandler; - -import java.net.InetAddress; -import java.util.Arrays; - -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.HexEncode; -/* - * ARP Reply event wrapper - */ -public class ARPReply extends ARPEvent { - private static final long serialVersionUID = 1L; - private final NodeConnector port; - private final byte[] tMac; - private final byte[] sMac; - private final InetAddress sIP; - private final short vlan; - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((port == null) ? 0 : port.hashCode()); - result = prime * result + ((sIP == null) ? 0 : sIP.hashCode()); - result = prime * result + Arrays.hashCode(sMac); - result = prime * result + Arrays.hashCode(tMac); - result = prime * result + vlan; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof ARPReply)) { - return false; - } - ARPReply other = (ARPReply) obj; - if (port == null) { - if (other.port != null) { - return false; - } - } else if (!port.equals(other.port)) { - return false; - } - if (sIP == null) { - if (other.sIP != null) { - return false; - } - } else if (!sIP.equals(other.sIP)) { - return false; - } - if (!Arrays.equals(sMac, other.sMac)) { - return false; - } - if (!Arrays.equals(tMac, other.tMac)) { - return false; - } - if (vlan != other.vlan) { - return false; - } - return true; - } - - public ARPReply(NodeConnector port, InetAddress sIP, byte[] sMAC, InetAddress tIP, byte[] tMAC, short vlan) { - super(tIP); - this.tMac = tMAC; - this.sIP = sIP; - this.sMac = sMAC; - this.port = port; - this.vlan = vlan; - } - - public ARPReply(InetAddress tIP, byte[] tMAC, short vlan) { - super(tIP); - this.tMac = tMAC; - this.sIP = null; - this.sMac = null; - this.port = null; - this.vlan = vlan; - } - - public byte[] getTargetMac() { - return tMac; - } - - public byte[] getSourceMac() { - return sMac; - } - - public InetAddress getSourceIP() { - return sIP; - } - - public NodeConnector getPort() { - return port; - } - - public short getVlan() { - return vlan; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("ARPReply ["); - if (port != null) { - builder.append("port=") - .append(port) - .append(", "); - } - if (tMac != null) { - builder.append("tMac=") - .append(HexEncode.bytesToHexString(tMac)) - .append(", "); - } - if (sMac != null) { - builder.append("sMac=") - .append(HexEncode.bytesToHexString(sMac)) - .append(", "); - } - if (sIP != null) { - builder.append("sIP=") - .append(sIP); - } - if (vlan != 0) { - builder.append(", vlan=") - .append(vlan); - } - builder.append("]"); - return builder.toString(); - } -} diff --git a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPRequest.java b/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPRequest.java deleted file mode 100644 index 051635ad53..0000000000 --- a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPRequest.java +++ /dev/null @@ -1,107 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.arphandler; - -import java.net.InetAddress; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.switchmanager.Subnet; -/* - * ARP Request event wrapper Consists of IP and Subnet (and a - * HostNodeConnector if is unicast) For unicast request, construct with a - * specified host - */ -public class ARPRequest extends ARPEvent { - private static final long serialVersionUID = 1L; - private final Subnet subnet; - private final HostNodeConnector host; - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((subnet == null) ? 0 : subnet.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof ARPRequest)) { - return false; - } - ARPRequest other = (ARPRequest) obj; - if (host == null) { - if (other.host != null) { - return false; - } - } else if (!host.equals(other.host)) { - return false; - } - if (subnet == null) { - if (other.subnet != null) { - return false; - } - } else if (!subnet.equals(other.subnet)) { - return false; - } - return true; - } - - // broadcast - public ARPRequest(InetAddress ip, Subnet subnet) { - super(ip); - this.subnet = subnet; - this.host = null; - } - - // unicast - public ARPRequest(HostNodeConnector host, Subnet subnet) { - super(host.getNetworkAddress()); - this.host = host; - this.subnet = subnet; - } - - public Subnet getSubnet() { - return subnet; - } - - public HostNodeConnector getHost() { - return host; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("ARPRequest ["); - if (subnet != null) { - builder.append("subnet=") - .append(subnet) - .append(", "); - } - if (host != null) { - builder.append("host=") - .append(host); - } - builder.append("]"); - return builder.toString(); - } -} diff --git a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/Activator.java b/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/Activator.java deleted file mode 100644 index b7639bed2b..0000000000 --- a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/Activator.java +++ /dev/null @@ -1,115 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.arphandler.internal; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.hosttracker.IfHostListener; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.hostAware.IHostFinder; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { ArpHandler.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(ArpHandler.class)) { - // export the service - Dictionary props = new Hashtable(); - props.put("salListenerName", "arphandler"); - Set propSet = new HashSet(); - propSet.add(ArpHandler.ARP_EVENT_CACHE_NAME); - props.put("cachenames", propSet); - - c.setInterface(new String[] { - IHostFinder.class.getName(), - IListenDataPacket.class.getName(), - ICacheUpdateAware.class.getName()}, props); - - // We need connection mgr to distribute packet out across the cluster - c.add(createServiceDependency().setService( - IConnectionManager.class).setCallbacks("setConnectionManager", - "unsetConnectionManager").setRequired(true)); - - - c.add(createContainerServiceDependency(containerName).setService( - ISwitchManager.class).setCallbacks("setSwitchManager", - "unsetSwitchManager").setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - ITopologyManager.class).setCallbacks("setTopologyManager", - "unsetTopologyMananger").setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - IDataPacketService.class).setCallbacks( - "setDataPacketService", "unsetDataPacketService") - .setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - IClusterContainerServices.class).setCallbacks( - "setClusterContainerService", "unsetClusterContainerService") - .setRequired(true)); - - // the Host Listener is optional - c.add(createContainerServiceDependency(containerName).setService( - IfHostListener.class).setCallbacks("setHostListener", - "unsetHostListener").setRequired(false)); - - // the IfIptoHost is a required dependency - c.add(createContainerServiceDependency(containerName).setService( - IfIptoHost.class).setCallbacks("setHostTracker", - "unsetHostTracker").setRequired(true)); - } - } -} diff --git a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/ArpHandler.java b/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/ArpHandler.java deleted file mode 100644 index 4efcada2f8..0000000000 --- a/opendaylight/adsal/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/ArpHandler.java +++ /dev/null @@ -1,855 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/* - * - */ -package org.opendaylight.controller.arphandler.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.LinkedBlockingQueue; - -import org.opendaylight.controller.arphandler.ARPCacheEvent; -import org.opendaylight.controller.arphandler.ARPEvent; -import org.opendaylight.controller.arphandler.ARPReply; -import org.opendaylight.controller.arphandler.ARPRequest; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.hosttracker.HostIdFactory; -import org.opendaylight.controller.hosttracker.IHostId; -import org.opendaylight.controller.hosttracker.IfHostListener; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.hosttracker.hostAware.IHostFinder; -import org.opendaylight.controller.sal.connection.ConnectionLocality; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.packet.ARP; -import org.opendaylight.controller.sal.packet.Ethernet; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IEEE8021Q; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.sal.packet.IPv4; -import org.opendaylight.controller.sal.packet.Packet; -import org.opendaylight.controller.sal.packet.PacketResult; -import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.Subnet; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The ArpHandler offers services to react on ARP requests and replies - * sent by network hosts. Moreover it allows for creating ARP messages - * by the controller itself. - * - * The ARP Handler on ODL doesn't use the requester MAC address in - * order to avoid to have to build a spanning tree where to forward - * ARP Requests. The ARP requests are broadcast packets so in order to - * reach everywhere need to be flooded, when you flood in a network - * that is not a tree (all the networks has some level of redundancy) - * that would create forwarding loops without a spanning tree. Given - * the need is only to send out the ARP requests toward all the hosts - * we actually don't need to implement a flooding mechanism in software - * (which would be expensive) we just send out the ARP request toward - * all the ports that are suspected to be host ports on all the - * switches (from the controller). Now the condition for which a port - * is marked as host port could potentially be incorrect so when the - * controller sends out the ARP Request that could come back to the - * controller and could cause another request not needed. So changing - * the source MAC address of the request to be the one of the controller, - * controller can protect itself from honoring twice the same request. - * This enables an ARP handler resolution, without the need of spanning - * tree and limiting software flooding to the minimum required. - */ - -public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateAware { - private static final Logger log = LoggerFactory.getLogger(ArpHandler.class); - static final String ARP_EVENT_CACHE_NAME = "arphandler.arpRequestReplyEvent"; - private IfIptoHost hostTracker; - private ISwitchManager switchManager; - private ITopologyManager topologyManager; - private IDataPacketService dataPacketService; - private IClusterContainerServices clusterContainerService; - private IConnectionManager connectionManager; - private Set hostListeners = new CopyOnWriteArraySet(); - private ConcurrentMap> arpRequestors; - private ConcurrentMap countDownTimers; - private Timer periodicTimer; - private BlockingQueue ARPCacheEvents = new LinkedBlockingQueue(); - private Thread cacheEventHandler; - private boolean stopping = false; - - /* - * A cluster allocated cache. Used for synchronizing ARP request/reply - * events across all cluster controllers. To raise an event, we put() a - * specific event object (as key) and all nodes handle it in the - * entryUpdated callback. - * - * In case of ARPReply, we put true value to send replies to any requestors - * by calling generateAndSendReply - */ - private ConcurrentMap arpRequestReplyEvent; - - void setConnectionManager(IConnectionManager cm) { - this.connectionManager = cm; - } - - void unsetConnectionManager(IConnectionManager cm) { - if (this.connectionManager == cm) { - connectionManager = null; - } - } - - void setClusterContainerService(IClusterContainerServices s) { - this.clusterContainerService = s; - } - - void unsetClusterContainerService(IClusterContainerServices s) { - if (this.clusterContainerService == s) { - this.clusterContainerService = null; - } - } - - void setHostListener(IfHostListener s) { - if (this.hostListeners != null) { - this.hostListeners.add(s); - } - } - - void unsetHostListener(IfHostListener s) { - if (this.hostListeners != null) { - this.hostListeners.remove(s); - } - } - - void setDataPacketService(IDataPacketService s) { - this.dataPacketService = s; - } - - void unsetDataPacketService(IDataPacketService s) { - if (this.dataPacketService == s) { - this.dataPacketService = null; - } - } - - public void setHostTracker(IfIptoHost hostTracker) { - log.debug("Setting HostTracker"); - this.hostTracker = hostTracker; - } - - public void unsetHostTracker(IfIptoHost s) { - log.debug("UNSetting HostTracker"); - if (this.hostTracker == s) { - this.hostTracker = null; - } - } - - public void setTopologyManager(ITopologyManager tm) { - this.topologyManager = tm; - } - - public void unsetTopologyManager(ITopologyManager tm) { - if (this.topologyManager == tm) { - this.topologyManager = null; - } - } - - protected void sendARPReply(NodeConnector p, byte[] sMAC, InetAddress sIP, byte[] tMAC, InetAddress tIP, short vlan) { - byte[] senderIP = sIP.getAddress(); - byte[] targetIP = tIP.getAddress(); - ARP arp = createARP(ARP.REPLY, sMAC, senderIP, tMAC, targetIP); - - if(log.isTraceEnabled()) { - log.trace("Sending Arp Reply with srcMac {} - srcIp {} - dstMac {} - dstIp {} - outport {}", - HexEncode.bytesToHexString(sMAC), - sIP, HexEncode.bytesToHexString(tMAC), tIP, p); - } - - Ethernet ethernet = createEthernet(sMAC, tMAC, arp, vlan); - - RawPacket destPkt = this.dataPacketService.encodeDataPacket(ethernet); - destPkt.setOutgoingNodeConnector(p); - - this.dataPacketService.transmitDataPacket(destPkt); - } - - private void logArpPacket(ARP pkt, NodeConnector p, short vlan) { - try { - log.trace("Received Arp {} with srcMac {} - srcIp {} - dstMac {} - dstIp {} - inport {} {}", - ((pkt.getOpCode() == ARP.REQUEST) ? "Request" : "Reply"), - HexEncode.bytesToHexString(pkt.getSenderHardwareAddress()), - InetAddress.getByAddress(pkt.getSenderProtocolAddress()), - HexEncode.bytesToHexString(pkt.getTargetHardwareAddress()), - InetAddress.getByAddress(pkt.getTargetProtocolAddress()), p, (vlan != 0 ? "on vlan " + vlan : "")); - - } catch (UnknownHostException e) { - log.warn("Illegal Ip Address in the ARP packet", e); - } - } - - protected void handleARPPacket(Ethernet eHeader, ARP pkt, NodeConnector p, short vlan) { - - if(log.isTraceEnabled()) { - logArpPacket(pkt, p, vlan); - } - - byte[] sourceMAC = eHeader.getSourceMACAddress(); - byte[] targetMAC = eHeader.getDestinationMACAddress(); - /* - * Sanity Check; drop ARP packets originated by the controller itself. - * This is to avoid continuous flooding - */ - if (Arrays.equals(sourceMAC, getControllerMAC())) { - if (log.isDebugEnabled()) { - log.debug("Receive a self originated ARP pkt (srcMAC {}) --> DROP", - HexEncode.bytesToHexString(sourceMAC)); - } - return; - } - - InetAddress targetIP, sourceIP; - try { - targetIP = InetAddress.getByAddress(pkt.getTargetProtocolAddress()); - sourceIP = InetAddress.getByAddress(pkt.getSenderProtocolAddress()); - } catch (UnknownHostException e1) { - log.debug("Invalid host in ARP packet: {}", e1.getMessage()); - return; - } - - Subnet subnet = null; - if (switchManager != null) { - subnet = switchManager.getSubnetByNetworkAddress(sourceIP); - } - if (subnet == null) { - log.debug("ARPHandler: can't find subnet matching {}, drop packet", sourceIP); - return; - } - - // Make sure that the host is a legitimate member of this subnet - if (!subnet.hasNodeConnector(p)) { - log.debug("{} showing up on {} does not belong to {}", new Object[] { sourceIP, p, subnet }); - return; - } - - HostNodeConnector requestor = null; - if (NetUtils.isUnicastMACAddr(sourceMAC) && p.getNode() != null) { - try { - requestor = new HostNodeConnector(sourceMAC, sourceIP, p, vlan); - } catch (ConstructionException e) { - log.debug("Received ARP packet with invalid MAC: {}", HexEncode.bytesToHexString(sourceMAC)); - return; - } - /* - * Learn host from the received ARP REQ/REPLY, inform Host Tracker - */ - log.trace("Inform Host tracker of new host {}", requestor.getNetworkAddress()); - for (IfHostListener listener : this.hostListeners) { - listener.hostListener(requestor); - } - } - - /* - * OpCode != request -> ARP Reply. If there are hosts (in arpRequestors) - * waiting for the ARP reply for this sourceIP, it's time to generate - * the reply and send it to these hosts. - * - * If sourceIP==targetIP, it is a Gratuitous ARP. If there are hosts (in - * arpRequestors) waiting for the ARP reply for this sourceIP, it's time - * to generate the reply and send it to these hosts - */ - - if (pkt.getOpCode() != ARP.REQUEST || sourceIP.equals(targetIP)) { - // Raise a reply event so that any waiting requestors will be sent a - // reply - // the true value indicates we should generate replies to requestors - // across the cluster - log.trace("Received ARP reply packet from {}, reply to all requestors.", sourceIP); - arpRequestReplyEvent.put(new ARPReply(sourceIP, sourceMAC, vlan), true); - return; - } - - /* - * ARP Request Handling: If targetIP is the IP of the subnet, reply with - * ARP REPLY If targetIP is a known host, PROXY ARP (by sending ARP - * REPLY) on behalf of known target hosts. For unknown target hosts, - * generate and send an ARP request to ALL switches/ports using the IP - * address defined in the subnet as source address - */ - /* - * If target IP is gateway IP, Send ARP reply - */ - if ((targetIP.equals(subnet.getNetworkAddress())) - && (NetUtils.isBroadcastMACAddr(targetMAC) || Arrays.equals(targetMAC, getControllerMAC()))) { - if (connectionManager.getLocalityStatus(p.getNode()) == ConnectionLocality.LOCAL) { - if (log.isTraceEnabled()) { - log.trace("Received local ARP req. for default gateway. Replying with controller MAC: {}", - HexEncode.bytesToHexString(getControllerMAC())); - } - sendARPReply(p, getControllerMAC(), targetIP, pkt.getSenderHardwareAddress(), sourceIP, vlan); - } else { - log.trace("Received non-local ARP req. for default gateway. Raising reply event"); - arpRequestReplyEvent.put( - new ARPReply(p, targetIP, getControllerMAC(), sourceIP, pkt.getSenderHardwareAddress(), vlan), false); - } - return; - } - - // Hosttracker hosts db key implementation - IHostId id = HostIdFactory.create(targetIP, null); - HostNodeConnector host = hostTracker.hostQuery(id); - // unknown host, initiate ARP request - if (host == null) { - // add the requestor to the list so that we can replay the reply - // when the host responds - if (requestor != null) { - Set requestorSet = arpRequestors.get(targetIP); - if (requestorSet == null) { - requestorSet = Collections.newSetFromMap(new ConcurrentHashMap()); - arpRequestors.put(targetIP, requestorSet); - } - requestorSet.add(requestor); - countDownTimers.put(targetIP, (short) 2); // reset timeout to - // 2sec - } - // Raise a bcast request event, all controllers need to send one - log.trace("Sending a bcast ARP request for {}", targetIP); - arpRequestReplyEvent.put(new ARPRequest(targetIP, subnet), false); - } else { - /* - * Target host known (across the cluster), send ARP REPLY make sure - * that targetMAC matches the host's MAC if it is not broadcastMAC - */ - if (NetUtils.isBroadcastMACAddr(targetMAC) || Arrays.equals(host.getDataLayerAddressBytes(), targetMAC)) { - log.trace("Received ARP req. for known host {}, sending reply...", targetIP); - if (connectionManager.getLocalityStatus(p.getNode()) == ConnectionLocality.LOCAL) { - sendARPReply(p, host.getDataLayerAddressBytes(), host.getNetworkAddress(), - pkt.getSenderHardwareAddress(), sourceIP, vlan); - } else { - arpRequestReplyEvent.put(new ARPReply(p, host.getNetworkAddress(), host.getDataLayerAddressBytes(), - sourceIP, pkt.getSenderHardwareAddress(), vlan), false); - } - } else { - /* - * Target MAC has been changed. For now, discard it. TODO: We - * may need to send unicast ARP REQUEST on behalf of the target - * back to the sender to trigger the sender to update its table - */ - } - } - } - - /** - * Send a broadcast ARP Request to the switch/ ports using the - * networkAddress of the subnet as sender IP the controller's MAC as sender - * MAC the targetIP as the target Network Address - */ - protected void sendBcastARPRequest(InetAddress targetIP, Subnet subnet) { - log.trace("sendBcatARPRequest targetIP:{} subnet:{}", targetIP, subnet); - Set nodeConnectors; - if (subnet.isFlatLayer2()) { - nodeConnectors = new HashSet(); - for (Node n : this.switchManager.getNodes()) { - nodeConnectors.addAll(this.switchManager.getUpNodeConnectors(n)); - } - } else { - nodeConnectors = subnet.getNodeConnectors(); - } - byte[] targetHardwareAddress = new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 }; - - // TODO: should use IBroadcastHandler instead - for (NodeConnector p : nodeConnectors) { - // filter out any non-local or internal ports - if (!(connectionManager.getLocalityStatus(p.getNode()) == ConnectionLocality.LOCAL) - || topologyManager.isInternal(p)) { - continue; - } - log.trace("Sending toward nodeConnector:{}", p); - byte[] senderIP = subnet.getNetworkAddress().getAddress(); - byte[] targetIPByte = targetIP.getAddress(); - ARP arp = createARP(ARP.REQUEST, getControllerMAC(), senderIP, targetHardwareAddress, targetIPByte); - - if(log.isTraceEnabled()) { - log.trace("Sending Broadcast Arp Request with srcMac {} - srcIp {} - dstMac {} - dstIp {} - outport {}", HexEncode.bytesToHexString(getControllerMAC()), - subnet.getNetworkAddress(), HexEncode.bytesToHexString(targetHardwareAddress), targetIP, p); - } - - byte[] destMACAddress = NetUtils.getBroadcastMACAddr(); - Ethernet ethernet = createEthernet(getControllerMAC(), destMACAddress, arp, (short)0); - - // TODO For now send port-by-port, see how to optimize to - // send to multiple ports at once - RawPacket destPkt = this.dataPacketService.encodeDataPacket(ethernet); - destPkt.setOutgoingNodeConnector(p); - - this.dataPacketService.transmitDataPacket(destPkt); - } - } - - /** - * Send a unicast ARP Request to the known host on specific (switch/port, - * vlan) as defined in the host. The sender IP is the networkAddress of the - * subnet The sender MAC is the controller's MAC - */ - protected void sendUcastARPRequest(HostNodeConnector host, Subnet subnet) { - log.trace("sendUcastARPRequest host:{} subnet:{}", host, subnet); - NodeConnector outPort = host.getnodeConnector(); - if (outPort == null) { - log.error("Failed sending UcastARP because cannot extract output port from Host: {}", host); - return; - } - - byte[] senderIP = subnet.getNetworkAddress().getAddress(); - byte[] targetIP = host.getNetworkAddress().getAddress(); - byte[] targetMAC = host.getDataLayerAddressBytes(); - ARP arp = createARP(ARP.REQUEST, getControllerMAC(), senderIP, targetMAC, targetIP); - - if(log.isTraceEnabled()) { - log.trace("Sending Unicast Arp Request with srcMac {} - srcIp {} - dstMac {} - dstIp {} - outport {}", - HexEncode.bytesToHexString(getControllerMAC()), - subnet.getNetworkAddress(), HexEncode.bytesToHexString(targetMAC), host.getNetworkAddress(), - outPort); - } - - Ethernet ethernet = createEthernet(getControllerMAC(), targetMAC, arp, host.getVlan()); - - RawPacket destPkt = this.dataPacketService.encodeDataPacket(ethernet); - destPkt.setOutgoingNodeConnector(outPort); - - this.dataPacketService.transmitDataPacket(destPkt); - } - - @Override - public void find(InetAddress networkAddress) { - log.trace("Received find IP {}", networkAddress); - - Subnet subnet = null; - if (switchManager != null) { - subnet = switchManager.getSubnetByNetworkAddress(networkAddress); - } - if (subnet == null) { - log.debug("Can't find subnet matching IP {}", networkAddress); - return; - } - - // send a broadcast ARP Request to this IP - arpRequestReplyEvent.put(new ARPRequest(networkAddress, subnet), false); - } - - /* - * Probe the host by sending a unicast ARP Request to the host - */ - @Override - public void probe(HostNodeConnector host) { - log.trace("Received probe host {}", host); - - Subnet subnet = null; - if (switchManager != null) { - subnet = switchManager.getSubnetByNetworkAddress(host.getNetworkAddress()); - } - if (subnet == null) { - log.debug("can't find subnet matching {}", host.getNetworkAddress()); - return; - } - - if (connectionManager.getLocalityStatus(host.getnodeconnectorNode()) == ConnectionLocality.LOCAL) { - log.trace("Send a ucast ARP req. to: {}", host); - sendUcastARPRequest(host, subnet); - } else { - log.trace("Raise a ucast ARP req. event to: {}", host); - arpRequestReplyEvent.put(new ARPRequest(host, subnet), false); - } - } - - /** - * An IP packet is punted to the controller, this means that the destination - * host is not known to the controller. Need to discover it by sending a - * Broadcast ARP Request - * - * @param pkt - * @param p - */ - protected void handlePuntedIPPacket(IPv4 pkt, NodeConnector p, short vlan) { - - InetAddress dIP = NetUtils.getInetAddress(pkt.getDestinationAddress()); - if (dIP == null) { - return; - } - - // try to find a matching subnet - Subnet subnet = null; - if (switchManager != null) { - subnet = switchManager.getSubnetByNetworkAddress(dIP); - } - if (subnet == null) { - log.debug("Can't find subnet matching {}, drop packet", dIP); - return; - } - // If packet is sent to the default gw (us), ignore it for now - if (subnet.getNetworkAddress().equals(dIP)) { - log.trace("Ignore IP packet destined to default gw"); - return; - } - - // see if we know about the host - // Hosttracker hosts db key implementation - HostNodeConnector host = hostTracker.hostFind(dIP); - - if (host == null) { - // if we don't know about the host, try to find it - log.trace("Punted IP pkt to {}, sending bcast ARP event...", dIP); - /* - * unknown destination host, initiate bcast ARP request - */ - arpRequestReplyEvent.put(new ARPRequest(dIP, subnet), false); - - } else { - log.trace("Ignoring punted IP pkt to known host: {} (received on: {})", dIP, p); - } - } - - public byte[] getControllerMAC() { - if (switchManager == null) { - return null; - } - return switchManager.getControllerMAC(); - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - arpRequestors = new ConcurrentHashMap>(); - countDownTimers = new ConcurrentHashMap(); - cacheEventHandler = new Thread(new ARPCacheEventHandler(), "ARPCacheEventHandler Thread"); - - allocateCaches(); - retrieveCaches(); - - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - ConcurrentMap map; - - if (this.clusterContainerService == null) { - log.error("Cluster service unavailable, can't retieve ARPHandler caches!"); - return; - } - - map = clusterContainerService.getCache(ARP_EVENT_CACHE_NAME); - if (map != null) { - this.arpRequestReplyEvent = (ConcurrentMap) map; - } else { - log.error("Cache allocation failed for {}", ARP_EVENT_CACHE_NAME); - } - } - - private void allocateCaches() { - if (clusterContainerService == null) { - nonClusterObjectCreate(); - log.error("Clustering service unavailable. Allocated non-cluster caches for ARPHandler."); - return; - } - - try { - clusterContainerService.createCache(ARP_EVENT_CACHE_NAME, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheConfigException e) { - log.error("ARPHandler cache configuration invalid!"); - } catch (CacheExistException e) { - log.debug("ARPHandler cache exists, skipped allocation."); - } - - } - - private void nonClusterObjectCreate() { - arpRequestReplyEvent = new ConcurrentHashMap(); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - cacheEventHandler.interrupt(); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - stopping = false; - startPeriodicTimer(); - cacheEventHandler.start(); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - } - - void stopping() { - stopping = true; - cancelPeriodicTimer(); - } - - void setSwitchManager(ISwitchManager s) { - log.debug("SwitchManager service set."); - this.switchManager = s; - } - - void unsetSwitchManager(ISwitchManager s) { - if (this.switchManager == s) { - log.debug("SwitchManager service UNset."); - this.switchManager = null; - } - } - - @Override - public PacketResult receiveDataPacket(RawPacket inPkt) { - if (inPkt == null) { - return PacketResult.IGNORED; - } - log.trace("Received a frame of size: {}", inPkt.getPacketData().length); - Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt); - if (formattedPak instanceof Ethernet) { - Packet nextPak = formattedPak.getPayload(); - short vlan = 0; - if (nextPak instanceof IEEE8021Q) { - vlan = ((IEEE8021Q) nextPak).getVid(); - log.trace("Moved after the dot1Q header"); - nextPak = ((IEEE8021Q) nextPak).getPayload(); - } - if (nextPak instanceof IPv4) { - log.trace("Handle IP packet: {}", formattedPak); - handlePuntedIPPacket((IPv4) nextPak, inPkt.getIncomingNodeConnector(), vlan); - } else if (nextPak instanceof ARP) { - log.trace("Handle ARP packet: {}", formattedPak); - handleARPPacket((Ethernet) formattedPak, (ARP) nextPak, inPkt.getIncomingNodeConnector(), vlan); - } - } - return PacketResult.IGNORED; - } - - private ARP createARP(short opCode, byte[] senderMacAddress, byte[] senderIP, byte[] targetMacAddress, - byte[] targetIP) { - ARP arp = new ARP(); - arp.setHardwareType(ARP.HW_TYPE_ETHERNET); - arp.setProtocolType(EtherTypes.IPv4.shortValue()); - arp.setHardwareAddressLength((byte) 6); - arp.setProtocolAddressLength((byte) 4); - arp.setOpCode(opCode); - arp.setSenderHardwareAddress(senderMacAddress); - arp.setSenderProtocolAddress(senderIP); - arp.setTargetHardwareAddress(targetMacAddress); - arp.setTargetProtocolAddress(targetIP); - return arp; - } - - private Ethernet createEthernet(byte[] sourceMAC, byte[] targetMAC, ARP arp, short vlan) { - Ethernet ethernet = new Ethernet(); - ethernet.setSourceMACAddress(sourceMAC); - ethernet.setDestinationMACAddress(targetMAC); - if (vlan == 0) { - ethernet.setEtherType(EtherTypes.ARP.shortValue()); - ethernet.setPayload(arp); - } else { - IEEE8021Q dot1q = new IEEE8021Q(); - dot1q.setVid(vlan); - dot1q.setEtherType(EtherTypes.ARP.shortValue()); - dot1q.setPayload(arp); - dot1q.setCfi((byte)0); - dot1q.setPcp((byte)0); - ethernet.setEtherType(EtherTypes.VLANTAGGED.shortValue()); - ethernet.setPayload(dot1q); - } - return ethernet; - } - - private void startPeriodicTimer() { - this.periodicTimer = new Timer("ArpHandler Periodic Timer"); - this.periodicTimer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - Set targetIPs = countDownTimers.keySet(); - Set expiredTargets = new HashSet(); - for (InetAddress t : targetIPs) { - short tick = countDownTimers.get(t); - tick--; - if (tick <= 0) { - expiredTargets.add(t); - } else { - countDownTimers.replace(t, tick); - } - } - for (InetAddress tIP : expiredTargets) { - countDownTimers.remove(tIP); - // Remove the requestor(s) who have been waiting for the ARP - // reply from this target for more than 1sec - arpRequestors.remove(tIP); - log.debug("ARP reply was not received from {}", tIP); - } - - // Clean up ARP event cache - try { - if (clusterContainerService.amICoordinator() && !arpRequestReplyEvent.isEmpty()) { - arpRequestReplyEvent.clear(); - } - } catch (Exception e) { - log.warn("ARPHandler: A cluster member failed to clear event cache."); - } - } - }, 0, 1000); - } - - private void cancelPeriodicTimer() { - if (this.periodicTimer != null) { - this.periodicTimer.cancel(); - } - } - - private void generateAndSendReply(InetAddress sourceIP, byte[] sourceMAC, short vlan) { - if (log.isTraceEnabled()) { - log.trace("generateAndSendReply called with params sourceIP:{} sourceMAC:{}", sourceIP, - HexEncode.bytesToHexString(sourceMAC)); - } - Set hosts = arpRequestors.remove(sourceIP); - if ((hosts == null) || hosts.isEmpty()) { - log.trace("Bailing out no requestors Hosts"); - return; - } - countDownTimers.remove(sourceIP); - for (HostNodeConnector host : hosts) { - if (log.isTraceEnabled()) { - log.trace( - "Sending ARP Reply with src {}/{}, target {}/{} {}", - new Object[] { HexEncode.bytesToHexString(sourceMAC), sourceIP, - HexEncode.bytesToHexString(host.getDataLayerAddressBytes()), host.getNetworkAddress(), - (vlan != 0 ? "on vlan " + vlan : "") }); - } - if (connectionManager.getLocalityStatus(host.getnodeconnectorNode()) == ConnectionLocality.LOCAL) { - sendARPReply(host.getnodeConnector(), sourceMAC, sourceIP, host.getDataLayerAddressBytes(), - host.getNetworkAddress(), vlan); - } else { - /* - * In the remote event a requestor moved to another controller - * it may turn out it now we need to send the ARP reply from a - * different controller, this cover the case - */ - arpRequestReplyEvent.put( - new ARPReply(host.getnodeConnector(), sourceIP, sourceMAC, host.getNetworkAddress(), host - .getDataLayerAddressBytes(), vlan), false); - } - } - } - - @Override - public void entryUpdated(ARPEvent key, Boolean new_value, String cacheName, boolean originLocal) { - log.trace("Got and entryUpdated for cacheName {} key {} isNew {}", cacheName, key, new_value); - enqueueARPCacheEvent(key, new_value); - } - - @Override - public void entryCreated(ARPEvent key, String cacheName, boolean originLocal) { - // nothing to do - } - - @Override - public void entryDeleted(ARPEvent key, String cacheName, boolean originLocal) { - // nothing to do - } - - private void enqueueARPCacheEvent(ARPEvent event, boolean new_value) { - try { - ARPCacheEvent cacheEvent = new ARPCacheEvent(event, new_value); - if (!ARPCacheEvents.contains(cacheEvent)) { - this.ARPCacheEvents.add(cacheEvent); - log.trace("Enqueued {}", event); - } - } catch (Exception e) { - log.debug("enqueueARPCacheEvent caught Interrupt Exception for event {}", event); - } - } - - /* - * this thread monitors the connectionEvent queue for new incoming events - * from - */ - private class ARPCacheEventHandler implements Runnable { - @Override - public void run() { - while (!stopping) { - try { - ARPCacheEvent ev = ARPCacheEvents.take(); - ARPEvent event = ev.getEvent(); - if (event instanceof ARPRequest) { - ARPRequest req = (ARPRequest) event; - // If broadcast request - if (req.getHost() == null) { - log.trace("Trigger and ARP Broadcast Request upon receipt of {}", req); - sendBcastARPRequest(req.getTargetIP(), req.getSubnet()); - - // If unicast and local, send reply - } else if (connectionManager.getLocalityStatus(req.getHost().getnodeconnectorNode()) == ConnectionLocality.LOCAL) { - log.trace("ARPCacheEventHandler - sendUcatARPRequest upon receipt of {}", req); - sendUcastARPRequest(req.getHost(), req.getSubnet()); - } - } else if (event instanceof ARPReply) { - ARPReply rep = (ARPReply) event; - // New reply received by controller, notify all awaiting - // requestors across the cluster - if (ev.isNewReply()) { - log.trace("Trigger a generateAndSendReply in response to {}", rep); - generateAndSendReply(rep.getTargetIP(), rep.getTargetMac(), rep.getVlan()); - // Otherwise, a specific reply. If local, send out. - } else if (connectionManager.getLocalityStatus(rep.getPort().getNode()) == ConnectionLocality.LOCAL) { - log.trace("ARPCacheEventHandler - sendUcatARPReply locally in response to {}", rep); - sendARPReply(rep.getPort(), rep.getSourceMac(), rep.getSourceIP(), rep.getTargetMac(), - rep.getTargetIP(), rep.getVlan()); - } - } - } catch (InterruptedException e) { - ARPCacheEvents.clear(); - return; - } - } - } - } -} diff --git a/opendaylight/adsal/arphandler/src/test/java/org/opendaylight/controller/arphandler/internal/ArphandlerTest.java b/opendaylight/adsal/arphandler/src/test/java/org/opendaylight/controller/arphandler/internal/ArphandlerTest.java deleted file mode 100644 index 892a0bc370..0000000000 --- a/opendaylight/adsal/arphandler/src/test/java/org/opendaylight/controller/arphandler/internal/ArphandlerTest.java +++ /dev/null @@ -1,27 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.arphandler.internal; - - -import org.junit.Assert; -import org.junit.Test; - -public class ArphandlerTest { - - @Test - public void testArphandlerCreation() { - - ArpHandler ah = null; - ah = new ArpHandler(); - Assert.assertTrue(ah != null); - - } - -} diff --git a/opendaylight/adsal/clustering/integrationtest/pom.xml b/opendaylight/adsal/clustering/integrationtest/pom.xml deleted file mode 100644 index e30eb67551..0000000000 --- a/opendaylight/adsal/clustering/integrationtest/pom.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.integrationtest - 0.7.0-SNAPSHOT - ../../commons/integrationtest - - - clustering.services.integrationtest - 0.6.0-SNAPSHOT - - ../../implementation/target/jacoco-it.exec - - ../../implementation/target/jacoco.exec - - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - eclipselink - javax.resource - - - junit - junit - - - org.apache.felix - org.apache.felix.dependencymanager.shell - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - clustering.services-implementation - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.it.implementation - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.implementation - - - org.slf4j - log4j-over-slf4j - - - org.ops4j.pax.exam - pax-exam-container-native - test - - - org.ops4j.pax.exam - pax-exam-junit4 - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - test - - - org.ops4j.pax.url - pax-url-aether - test - - - - - - org.jacoco - jacoco-maven-plugin - - ../../implementation/target/jacoco-it.exec - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - true - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/clustering/integrationtest/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusteringServicesIT.java b/opendaylight/adsal/clustering/integrationtest/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusteringServicesIT.java deleted file mode 100644 index 166dec4b48..0000000000 --- a/opendaylight/adsal/clustering/integrationtest/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusteringServicesIT.java +++ /dev/null @@ -1,717 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.clustering.services_implementation.internal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; -import static org.ops4j.pax.exam.CoreOptions.options; -import static org.ops4j.pax.exam.CoreOptions.systemPackages; -import static org.ops4j.pax.exam.CoreOptions.systemProperty; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.TimeUnit; -import java.net.InetAddress; -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import javax.inject.Inject; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.CacheListenerAddException; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterServices.cacheMode; -import org.opendaylight.controller.clustering.services.IGetUpdates; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.core.UpdateType; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.util.PathUtils; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.util.concurrent.CountDownLatch; - -@RunWith(PaxExam.class) -public class ClusteringServicesIT { - private Logger log = LoggerFactory - .getLogger(ClusteringServicesIT.class); - // get the OSGI bundle context - @Inject - private BundleContext bc; - private IClusterServices clusterServices = null; - private IClusterContainerServices clusterDefaultServices = null; - private IClusterGlobalServices clusterGlobalServices = null; - - // Configure the OSGi container - @Configuration - public Option[] config() { - return options( - // - systemProperty("logback.configurationFile").value( - "file:" + PathUtils.getBaseDir() - + "/src/test/resources/logback.xml"), - // To start OSGi console for inspection remotely - systemProperty("osgi.console").value("2401"), - // Set the systemPackages (used by clustering) - systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"), - // List framework bundles - mavenBundle("equinoxSDK381", - "org.eclipse.equinox.console").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.eclipse.equinox.util").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.eclipse.osgi.services").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.eclipse.equinox.ds").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.apache.felix.gogo.command").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.apache.felix.gogo.runtime").versionAsInProject(), - mavenBundle("equinoxSDK381", - "org.apache.felix.gogo.shell").versionAsInProject(), - // List logger bundles - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), - mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(), - // List all the bundles on which the test case depends - mavenBundle("org.opendaylight.controller", - "clustering.services").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "clustering.services-implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "sal.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "configuration").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "containermanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "containermanager.it.implementation").versionAsInProject(), - mavenBundle("org.jboss.spec.javax.transaction", - "jboss-transaction-api_1.1_spec").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(), - mavenBundle("org.apache.felix", - "org.apache.felix.dependencymanager").versionAsInProject(), - mavenBundle("org.apache.felix", - "org.apache.felix.dependencymanager.shell").versionAsInProject(), - mavenBundle("eclipselink", "javax.resource").versionAsInProject(), - junitBundles()); - } - - private String stateToString(int state) { - switch (state) { - case Bundle.ACTIVE: - return "ACTIVE"; - case Bundle.INSTALLED: - return "INSTALLED"; - case Bundle.RESOLVED: - return "RESOLVED"; - case Bundle.UNINSTALLED: - return "UNINSTALLED"; - default: - return "Not CONVERTED"; - } - } - - @Before - public void areWeReady() { - assertNotNull(bc); - boolean debugit = false; - Bundle b[] = bc.getBundles(); - for (Bundle element : b) { - int state = element.getState(); - if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) { - log.debug("Bundle:" + element.getSymbolicName() + " state:" - + stateToString(state)); - debugit = true; - } - } - if (debugit) { - log.debug("Do some debugging because some bundle is " - + "unresolved"); - } - - // Assert if true, if false we are good to go! - assertFalse(debugit); - - this.clusterServices = (IClusterServices)ServiceHelper - .getGlobalInstance(IClusterServices.class, this); - assertNotNull(this.clusterServices); - - this.clusterDefaultServices = (IClusterContainerServices)ServiceHelper - .getInstance(IClusterContainerServices.class, "default", this); - assertNotNull(this.clusterDefaultServices); - - this.clusterGlobalServices = (IClusterGlobalServices)ServiceHelper - .getGlobalInstance(IClusterGlobalServices.class, this); - assertNotNull(this.clusterGlobalServices); - } - - @Test - public void clusterTest() throws CacheExistException, CacheConfigException, - CacheListenerAddException { - - String container1 = "Container1"; - String container2 = "Container2"; - String cache1 = "Cache1"; - String cache2 = "Cache2"; - String cache3 = "Cache3"; - - HashSet cacheModeSet = new HashSet(); - cacheModeSet.add(cacheMode.NON_TRANSACTIONAL); - ConcurrentMap cm11 = this.clusterServices.createCache(container1, - cache1, cacheModeSet); - assertNotNull(cm11); - - assertNull(this.clusterServices.getCache(container2, cache2)); - assertEquals(cm11, this.clusterServices.getCache(container1, cache1)); - - assertFalse(this.clusterServices.existCache(container2, cache2)); - assertTrue(this.clusterServices.existCache(container1, cache1)); - - ConcurrentMap cm12 = this.clusterServices.createCache(container1, - cache2, cacheModeSet); - ConcurrentMap cm23 = this.clusterServices.createCache(container2, - cache3, cacheModeSet); - - HashSet cacheList = (HashSet) this.clusterServices - .getCacheList(container1); - assertEquals(2, cacheList.size()); - assertTrue(cacheList.contains(cache1)); - assertTrue(cacheList.contains(cache2)); - assertFalse(cacheList.contains(cache3)); - - assertNotNull(this.clusterServices.getCacheProperties(container1, - cache1)); - - HashSet> listeners = (HashSet>) this.clusterServices - .getListeners(container1, cache1); - assertEquals(0, listeners.size()); - - IGetUpdates getUpdate1 = new GetUpdates(); - this.clusterServices.addListener(container1, cache1, getUpdate1); - listeners = (HashSet>) this.clusterServices - .getListeners(container1, cache1); - assertEquals(1, listeners.size()); - this.clusterServices.addListener(container1, cache1, new GetUpdates()); - listeners = (HashSet>) this.clusterServices - .getListeners(container1, cache1); - assertEquals(2, listeners.size()); - - listeners = (HashSet>) this.clusterServices - .getListeners(container2, cache3); - assertEquals(0, listeners.size()); - - this.clusterServices.removeListener(container1, cache1, getUpdate1); - listeners = (HashSet>) this.clusterServices - .getListeners(container1, cache1); - assertEquals(1, listeners.size()); - - InetAddress addr = this.clusterServices.getMyAddress(); - assertNotNull(addr); - - List addrList = this.clusterServices - .getClusteredControllers(); - - this.clusterServices.destroyCache(container1, cache1); - assertFalse(this.clusterServices.existCache(container1, cache1)); - - } - - private class GetUpdates implements IGetUpdates { - - @Override - public void entryCreated(Integer key, String containerName, - String cacheName, boolean originLocal) { - return; - } - - @Override - public void entryUpdated(Integer key, String newValue, - String containerName, String cacheName, boolean originLocal) { - return; - } - - @Override - public void entryDeleted(Integer key, String containerName, - String cacheName, boolean originLocal) { - return; - } - } - - @Test - public void clusterContainerAndGlobalTest() throws CacheExistException, CacheConfigException, - CacheListenerAddException, InterruptedException { - String cache1 = "Cache1"; - String cache2 = "Cache2"; - // Lets test the case of caches with same name in different - // containers (actually global an container case) - String cache3 = "Cache2"; - - HashSet cacheModeSet = new HashSet(); - cacheModeSet.add(cacheMode.NON_TRANSACTIONAL); - ConcurrentMap cm11 = this.clusterDefaultServices.createCache(cache1, cacheModeSet); - assertNotNull(cm11); - - assertTrue(this.clusterDefaultServices.existCache(cache1)); - assertEquals(cm11, this.clusterDefaultServices.getCache(cache1)); - - ConcurrentMap cm12 = this.clusterDefaultServices.createCache(cache2, cacheModeSet); - ConcurrentMap cm23 = this.clusterGlobalServices.createCache(cache3, cacheModeSet); - - // Now given cahe2 and cache3 have same name lets make sure - // they don't return the same reference - assertNotNull(this.clusterGlobalServices.getCache(cache2)); - // cm12 reference must be different than cm23 - assertTrue(cm12 != cm23); - - HashSet cacheList = (HashSet) this.clusterDefaultServices - .getCacheList(); - assertEquals(2, cacheList.size()); - assertTrue(cacheList.contains(cache1)); - assertTrue(cacheList.contains(cache2)); - - assertNotNull(this.clusterDefaultServices.getCacheProperties(cache1)); - - { - /***********************************/ - /* Testing cacheAware in Container */ - /***********************************/ - Dictionary props = new Hashtable(); - Set propSet = new HashSet(); - propSet.add(cache1); - propSet.add(cache2); - props.put("cachenames", propSet); - CacheAware listener = new CacheAware(); - CacheAware listenerRepeated = new CacheAware(); - ServiceRegistration updateServiceReg = ServiceHelper.registerServiceWReg(ICacheUpdateAware.class, "default", - listener, props); - assertNotNull(updateServiceReg); - - // Register another service for the same caches, this - // should not get any update because we don't allow to - // override the existing unless before unregistered - ServiceRegistration updateServiceRegRepeated = ServiceHelper.registerServiceWReg(ICacheUpdateAware.class, - "default", - listenerRepeated, props); - assertNotNull(updateServiceRegRepeated); - CountDownLatch res = null; - List ups = null; - Update up = null; - Integer k1 = new Integer(10); - Long k2 = new Long(100L); - - /***********************/ - /* CREATE NEW KEY CASE */ - /***********************/ - // Start monitoring the updates - res = listener.restart(2); - // modify the cache - cm11.put(k1, "foo"); - // Wait - res.await(100L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 2); - // Validate that first we get an update (yes even in case of a - // new value added) - up = ups.get(0); - assertTrue(up.t.equals(UpdateType.CHANGED)); - assertTrue(up.key.equals(k1)); - assertTrue(up.value.equals("foo")); - assertTrue(up.cacheName.equals(cache1)); - // Validate that we then get a create - up = ups.get(1); - assertTrue(up.t.equals(UpdateType.ADDED)); - assertTrue(up.key.equals(k1)); - assertNull(up.value); - assertTrue(up.cacheName.equals(cache1)); - - /*******************************/ - /* UPDATE AN EXISTING KEY CASE */ - /*******************************/ - // Start monitoring the updates - res = listener.restart(1); - // modify the cache - cm11.put(k1, "baz"); - // Wait - res.await(100L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 1); - // Validate we get an update with expect fields - up = ups.get(0); - assertTrue(up.t.equals(UpdateType.CHANGED)); - assertTrue(up.key.equals(k1)); - assertTrue(up.value.equals("baz")); - assertTrue(up.cacheName.equals(cache1)); - - /**********************************/ - /* RE-UPDATE AN EXISTING KEY CASE */ - /**********************************/ - // Start monitoring the updates - res = listener.restart(1); - // modify the cache - cm11.put(k1, "baz"); - // Wait - res.await(100L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 1); - // Validate we get an update with expect fields - up = ups.get(0); - assertTrue(up.t.equals(UpdateType.CHANGED)); - assertTrue(up.key.equals(k1)); - assertTrue(up.value.equals("baz")); - assertTrue(up.cacheName.equals(cache1)); - - /********************************/ - /* REMOVAL OF EXISTING KEY CASE */ - /********************************/ - // Start monitoring the updates - res = listener.restart(1); - // modify the cache - cm11.remove(k1); - // Wait - res.await(100L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 1); - // Validate we get a delete with expected fields - up = ups.get(0); - assertTrue(up.t.equals(UpdateType.REMOVED)); - assertTrue(up.key.equals(k1)); - assertNull(up.value); - assertTrue(up.cacheName.equals(cache1)); - - /***********************/ - /* CREATE NEW KEY CASE */ - /***********************/ - // Start monitoring the updates - res = listener.restart(2); - // modify the cache - cm12.put(k2, new Short((short)15)); - // Wait - res.await(100L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 2); - // Validate that first we get an update (yes even in case of a - // new value added) - up = ups.get(0); - assertTrue(up.t.equals(UpdateType.CHANGED)); - assertTrue(up.key.equals(k2)); - assertTrue(up.value.equals(new Short((short)15))); - assertTrue(up.cacheName.equals(cache2)); - // Validate that we then get a create - up = ups.get(1); - assertTrue(up.t.equals(UpdateType.ADDED)); - assertTrue(up.key.equals(k2)); - assertNull(up.value); - assertTrue(up.cacheName.equals(cache2)); - - /*******************************/ - /* UPDATE AN EXISTING KEY CASE */ - /*******************************/ - // Start monitoring the updates - res = listener.restart(1); - // modify the cache - cm12.put(k2, "BAZ"); - // Wait - res.await(100L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 1); - // Validate we get an update with expect fields - up = ups.get(0); - assertTrue(up.t.equals(UpdateType.CHANGED)); - assertTrue(up.key.equals(k2)); - assertTrue(up.value.equals("BAZ")); - assertTrue(up.cacheName.equals(cache2)); - - /********************************/ - /* REMOVAL OF EXISTING KEY CASE */ - /********************************/ - // Start monitoring the updates - res = listener.restart(1); - // modify the cache - cm12.remove(k2); - // Wait - res.await(100L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 1); - // Validate we get a delete with expected fields - up = ups.get(0); - assertTrue(up.t.equals(UpdateType.REMOVED)); - assertTrue(up.key.equals(k2)); - assertNull(up.value); - assertTrue(up.cacheName.equals(cache2)); - - /******************************************************************/ - /* NOW LETS REMOVE THE REGISTRATION AND MAKE SURE NO UPDATS COMES */ - /******************************************************************/ - updateServiceReg.unregister(); - // Start monitoring the updates, noone should come in - res = listener.restart(1); - - /***********************/ - /* CREATE NEW KEY CASE */ - /***********************/ - // modify the cache - cm11.put(k1, "foo"); - - /*******************************/ - /* UPDATE AN EXISTING KEY CASE */ - /*******************************/ - // modify the cache - cm11.put(k1, "baz"); - - /********************************/ - /* REMOVAL OF EXISTING KEY CASE */ - /********************************/ - // modify the cache - cm11.remove(k1); - - /***********************/ - /* CREATE NEW KEY CASE */ - /***********************/ - // modify the cache - cm12.put(k2, new Short((short)15)); - - /*******************************/ - /* UPDATE AN EXISTING KEY CASE */ - /*******************************/ - // modify the cache - cm12.put(k2, "BAZ"); - - /********************************/ - /* REMOVAL OF EXISTING KEY CASE */ - /********************************/ - // modify the cache - cm12.remove(k2); - - - // Wait to make sure no updates came in, clearly this is - // error prone as logic, but cannot find a better way than - // this to make sure updates didn't get in - res.await(1L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 0); - } - - { - /***********************************/ - /* Testing cacheAware in Global */ - /***********************************/ - Dictionary props = new Hashtable(); - Set propSet = new HashSet(); - propSet.add(cache3); - props.put("cachenames", propSet); - CacheAware listener = new CacheAware(); - ServiceRegistration updateServiceReg = ServiceHelper.registerGlobalServiceWReg(ICacheUpdateAware.class, - listener, props); - assertNotNull(updateServiceReg); - - CountDownLatch res = null; - List ups = null; - Update up = null; - Integer k1 = new Integer(10); - - /***********************/ - /* CREATE NEW KEY CASE */ - /***********************/ - // Start monitoring the updates - res = listener.restart(2); - // modify the cache - cm23.put(k1, "foo"); - // Wait - res.await(100L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 2); - // Validate that first we get an update (yes even in case of a - // new value added) - up = ups.get(0); - assertTrue(up.t.equals(UpdateType.CHANGED)); - assertTrue(up.key.equals(k1)); - assertTrue(up.value.equals("foo")); - assertTrue(up.cacheName.equals(cache3)); - // Validate that we then get a create - up = ups.get(1); - assertTrue(up.t.equals(UpdateType.ADDED)); - assertTrue(up.key.equals(k1)); - assertNull(up.value); - assertTrue(up.cacheName.equals(cache3)); - - /*******************************/ - /* UPDATE AN EXISTING KEY CASE */ - /*******************************/ - // Start monitoring the updates - res = listener.restart(1); - // modify the cache - cm23.put(k1, "baz"); - // Wait - res.await(100L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 1); - // Validate we get an update with expect fields - up = ups.get(0); - assertTrue(up.t.equals(UpdateType.CHANGED)); - assertTrue(up.key.equals(k1)); - assertTrue(up.value.equals("baz")); - assertTrue(up.cacheName.equals(cache3)); - - /********************************/ - /* REMOVAL OF EXISTING KEY CASE */ - /********************************/ - // Start monitoring the updates - res = listener.restart(1); - // modify the cache - cm23.remove(k1); - // Wait - res.await(100L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 1); - // Validate we get a delete with expected fields - up = ups.get(0); - assertTrue(up.t.equals(UpdateType.REMOVED)); - assertTrue(up.key.equals(k1)); - assertNull(up.value); - assertTrue(up.cacheName.equals(cache3)); - - /******************************************************************/ - /* NOW LETS REMOVE THE REGISTRATION AND MAKE SURE NO UPDATS COMES */ - /******************************************************************/ - updateServiceReg.unregister(); - // Start monitoring the updates, noone should come in - res = listener.restart(1); - - /***********************/ - /* CREATE NEW KEY CASE */ - /***********************/ - // modify the cache - cm23.put(k1, "foo"); - - /*******************************/ - /* UPDATE AN EXISTING KEY CASE */ - /*******************************/ - // modify the cache - cm23.put(k1, "baz"); - - /********************************/ - /* REMOVAL OF EXISTING KEY CASE */ - /********************************/ - // modify the cache - cm23.remove(k1); - - // Wait to make sure no updates came in, clearly this is - // error prone as logic, but cannot find a better way than - // this to make sure updates didn't get in - res.await(1L, TimeUnit.SECONDS); - // Analyze the updates - ups = listener.getUpdates(); - assertTrue(ups.size() == 0); - } - - InetAddress addr = this.clusterDefaultServices.getMyAddress(); - assertNotNull(addr); - - List addrList = this.clusterDefaultServices - .getClusteredControllers(); - - this.clusterDefaultServices.destroyCache(cache1); - assertFalse(this.clusterDefaultServices.existCache(cache1)); - } - - private class Update { - Object key; - Object value; - String cacheName; - UpdateType t; - - Update (UpdateType t, Object key, Object value, String cacheName) { - this.t = t; - this.key = key; - this.value = value; - this.cacheName = cacheName; - } - } - - private class CacheAware implements ICacheUpdateAware { - private CopyOnWriteArrayList gotUpdates; - private CountDownLatch latch = null; - - CacheAware() { - this.gotUpdates = new CopyOnWriteArrayList(); - } - - - /** - * Restart the monitor of the updates on the CacheAware object - * - * @param expectedOperations Number of expected updates - * - * @return a countdown latch which will be used to wait till the updates are done - */ - CountDownLatch restart(int expectedOperations) { - this.gotUpdates.clear(); - this.latch = new CountDownLatch(expectedOperations); - return this.latch; - } - - List getUpdates() { - return this.gotUpdates; - } - - @Override - public void entryCreated(Object key, String cacheName, boolean originLocal) { - log.debug("CACHE[{}] Got an entry created for key:{}", cacheName, key); - Update u = new Update(UpdateType.ADDED, key, null, cacheName); - this.gotUpdates.add(u); - this.latch.countDown(); - } - - @Override - public void entryUpdated(Object key, Object newValue, String cacheName, boolean originLocal) { - log.debug("CACHE[{}] Got an entry updated for key:{} newValue:{}", cacheName, key, newValue); - Update u = new Update(UpdateType.CHANGED, key, newValue, cacheName); - this.gotUpdates.add(u); - this.latch.countDown(); - } - - @Override - public void entryDeleted(Object key, String cacheName, boolean originLocal) { - log.debug("CACHE[{}] Got an entry delete for key:{}", cacheName, key); - Update u = new Update(UpdateType.REMOVED, key, null, cacheName); - this.gotUpdates.add(u); - this.latch.countDown(); - } - } -} diff --git a/opendaylight/adsal/clustering/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/clustering/integrationtest/src/test/resources/logback.xml deleted file mode 100644 index 6d9dfda9a3..0000000000 --- a/opendaylight/adsal/clustering/integrationtest/src/test/resources/logback.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/opendaylight/adsal/clustering/services/pom.xml b/opendaylight/adsal/clustering/services/pom.xml deleted file mode 100644 index ebe8436da8..0000000000 --- a/opendaylight/adsal/clustering/services/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - clustering.services - 0.7.0-SNAPSHOT - bundle - - - - org.jboss.spec.javax.transaction - jboss-transaction-api_1.1_spec - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.clustering.services - javax.transaction - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheConfigException.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheConfigException.java deleted file mode 100644 index e030142016..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheConfigException.java +++ /dev/null @@ -1,35 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file CacheConfigException.java - * - * @brief Describe an exception that is raised when the cache being - * allocated has configuration errors, like mismatch parameters are - * passed and so on. - * - * - */ -package org.opendaylight.controller.clustering.services; - -/** - * Describe an exception that is raised when the cache being - * allocated has configuration errors, like mismatch parameters are - * passed and so on. - */ -public class CacheConfigException extends Exception { - private static final long serialVersionUID = 1L; - - /** - * Instantiates a new cache config exception. - */ - public CacheConfigException() { - super(); - } -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheExistException.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheExistException.java deleted file mode 100644 index 70165cce1f..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheExistException.java +++ /dev/null @@ -1,34 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file CacheExistException.java - * - * @brief Describe an exception that is raised when the cache being - * allocated already exists - * - * - */ -package org.opendaylight.controller.clustering.services; - - -/** - * Describe an exception that is raised when the cache being - * allocated already exists - */ -public class CacheExistException extends Exception { - private static final long serialVersionUID = 1L; - - /** - * Instantiates a new cache exist exception. - */ - public CacheExistException() { - super(); - } -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheListenerAddException.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheListenerAddException.java deleted file mode 100644 index 996e0a0767..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/CacheListenerAddException.java +++ /dev/null @@ -1,32 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file CacheListenerAddException.java - * - * @brief Describe an exception that is raised when the cache - * Listener being added fails for any reason - * - */ -package org.opendaylight.controller.clustering.services; - -/** - * Describe an exception that is raised when the cache - * Listener being added fails for any reason - */ -public class CacheListenerAddException extends Exception { - private static final long serialVersionUID = 1L; - - /** - * Instantiates a new cache listener add exception. - */ - public CacheListenerAddException() { - super(); - } -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICacheUpdateAware.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICacheUpdateAware.java deleted file mode 100644 index 187309ba82..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICacheUpdateAware.java +++ /dev/null @@ -1,67 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file ICacheUpdateAware.java - * - * @brief Interface for getting clustered cache updates - * - * Interface that needs to be implemented by the components - * that want to be informed of an update in a Clustered Cache. The - * interface need to be registerd in the OSGi service registry with a - * property "cachenames" which will contains a PropertySet object - * listing all the caches for which their is interes. - */ -package org.opendaylight.controller.clustering.services; - -/** - * Interface that needs to be implemented by the components - * that want to be informed of an update in a Clustered Cache. The - * interface need to be registerd in the OSGi service registry with a - * property "cachenames" which will contains a PropertySet object - * listing all the caches for which their is interes. - * - */ -public interface ICacheUpdateAware { - /** - * Invoked when a new entry is available in the cache, the key is - * only provided, the value will come as an entryUpdate invocation - * - * @param key Key for the entry just created - * @param cacheName name of the cache for which update has been - * received - * @param originLocal true if the event is generated from this - * node - */ - void entryCreated(K key, String cacheName, boolean originLocal); - - /** - * Called anytime a given entry is updated - * - * @param key Key for the entry modified - * @param new_value the new value the key will have - * @param cacheName name of the cache for which update has been - * received - * @param originLocal true if the event is generated from this - * node - */ - void entryUpdated(K key, V new_value, String cacheName, boolean originLocal); - - /** - * Called anytime a given key is removed from the - * ConcurrentHashMap we are listening to. - * - * @param key Key of the entry removed - * @param cacheName name of the cache for which update has been - * received - * @param originLocal true if the event is generated from this - * node - */ - void entryDeleted(K key, String cacheName, boolean originLocal); -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterContainerServices.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterContainerServices.java deleted file mode 100644 index fdf08bcbac..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterContainerServices.java +++ /dev/null @@ -1,30 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IClusterContainerServices.java - * - * @brief : Set of services an application will expect from the - * clustering services provider. This interface is per-container and so - * the container parameter is implicitely known - * - * Contract between the applications and the clustering service - * providers. Container version - */ - -package org.opendaylight.controller.clustering.services; - -/** - * Set of services an application will expect from the clustering services - * provider. This interface is per-container and so the container parameter is - * implicitly known - * - */ -public interface IClusterContainerServices extends IClusterServicesCommon { -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterGlobalServices.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterGlobalServices.java deleted file mode 100644 index e25a9537c0..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterGlobalServices.java +++ /dev/null @@ -1,30 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IClusterGlobalServices.java - * - * @brief : Set of services an application will expect from the - * clustering services provider. This interface is supposed to have - * Global scope - * - * Contract between the applications and the clustering service - * providers. Global version - */ - -package org.opendaylight.controller.clustering.services; - -/** - * Set of services an application will expect from the clustering services - * provider. This interface is supposed to have Global scope - * - */ -public interface IClusterGlobalServices extends IClusterServicesCommon { - public void removeContainerCaches(String containerName); -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServices.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServices.java deleted file mode 100644 index b3427c7fcc..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServices.java +++ /dev/null @@ -1,312 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IClusterServices.java - * - * @brief : Set of services an application will expect from the - * clustering services provider - * - * Contract between the applications and the clustering service - * providers. - */ - -package org.opendaylight.controller.clustering.services; - -import java.net.InetAddress; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.TimeUnit; - -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.NotSupportedException; -import javax.transaction.RollbackException; -import javax.transaction.SystemException; -import javax.transaction.Transaction; - -/** - * Set of services an application will expect from the - * clustering services provider - * - */ -public interface IClusterServices { - - /** - * Enumeration of the several modality with which a - * ConcurrentHashMap cache can be requested to the clustering - * services. The property that can be requested can be multiple. - * - */ - public enum cacheMode { - /** - * Set for a cache that supports transaction that implies that - * is a transaction is open on the current thread the data - * will not immediately be reflected in the cache but will be - * staged till commit or rollback. If the transaction if NOT - * open the data will immediately go in the cache without - * staging. - */ - TRANSACTIONAL, - /** - * Set on a cache that doesn't want to support - * transaction, so irrespective of the fact that we are in - * the middle of a transaction or no data will be - * immediately committed in the cache. - * - */ - NON_TRANSACTIONAL, - /** - * Set on a cache that can transfer the updates asynchronously from the - * calling thread. The caller when doing put/clear/remove cannot expect - * that the operation has happened clusterwide - */ - ASYNC, - /** - * Set on a cache that transfer the updates synchronously to the calling - * thread so when getting back the operation is supposed to have - * completed on all the cluster nodes. Slow but safe. - */ - SYNC; - } - - /** - * Enumeration of the several properties that a cache can carry - * - */ - public enum cacheProps { - /** - * The property returned describe the characteristics of the - * transaction setup for the cache it was retrieved. - */ - TRANSACTION_PROP, - /** - * The property returned report the clustering - * characteristics of the cache for which property was - * queried. - */ - CLUSTERING_PROP, - /** - * The property returned reports the locking - * characteristics of the cache for which the property was - * queried - */ - LOCKING_PROP; - } - - /** - * Method that will create a new named cache per-container. The data - * structure if already present will cause an exception to be - * thrown to the caller. - * - * @param containerName Container to which the datastructure is associated - * @param cacheName Name of the ConcurrentHashMap to create - * @param cMode Mode of the cache that need to be retrieved. This - * is a set such that more than one property can be provided, of - * course contrasting requirements will not be accepted and in - * that case an exception is thrown - * - * @return ConcurrentHashMap to be used to modify the data structure - */ - ConcurrentMap createCache(String containerName, String cacheName, - Set cMode) throws CacheExistException, - CacheConfigException; - - /** - * Method that will retrieve and return the handle to modify a - * data structire distributed via clustering services. The - * datastructure shall already have been created else a null - * reference will be returned. - * - * @param containerName Container to which the datastructure is associated - * @param cacheName Name of the ConcurrentHashMap to retrieve - * - * @return ConcurrentHashMap to be used to modify the data structure - */ - ConcurrentMap getCache(String containerName, String cacheName); - - /** - * Destroy a cachename given containerName/cachename, if doesn't exist - * the function does nothing. If the datastructure exists, the - * whole cluster will destroy the instance - * - * @param containerName Container to which the datastructure is associated - * @param cacheName Name of the ConcurrentHashMap to destroy - */ - void destroyCache(String containerName, String cacheName); - - /** - * Function to test the existance of a cache with a given name already - * - * @param containerName Container to which the datastructure is associated - * @param cacheName Name of the ConcurrentHashMap to destroy - * - * @return true if exists already, false otherwise - */ - boolean existCache(String containerName, String cacheName); - - /** - * Return the list of all teh caches registered with a container - * - * @param containerName Container for which we want to list all the caches registered - * - * @return The set of names, expressed as strings - */ - Set getCacheList(String containerName); - - /** - * Return a list of properties that caracterize the cache - * - * @param containerName Name of the container where data structure resides - * @param cacheName Name of the cache - * - * @return The list of properties related to the cache - */ - Properties getCacheProperties(String containerName, String cacheName); - - /** - * Register an update handler for a given containerName/cacheName - * shared data structure. Multiple listeners are possible. - * - * @param containerName Container to which the datastructure is associated - * @param cacheName Name of the ConcurrentHashMap for which we - * want to register the listener - * @param u Interface to invoke when the updates are received - */ - void addListener(String containerName, String cacheName, IGetUpdates u) - throws CacheListenerAddException; - - /** - * Return a set of interfaces that are interesteed to listen to - * updates coming for a given datastructure shared via clustering - * services. - * - * @param containerName Container to which the datastructure is associated - * @param cacheName Name of the ConcurrentHashMap for which we - * want to retrieve the listener - */ - Set> getListeners(String containerName, String cacheName); - - /** - * UN-Register an update handler for a given containerName/cacheName - * shared data structure. Multiple listeners are possible. - * - * @param containerName Container to which the datastructure is associated - * @param cacheName Name of the ConcurrentHashMap for which we - * want to un-register the listener - * @param u Interface to un-register - */ - void removeListener(String containerName, String cacheName, - IGetUpdates u); - - /** - * Begin a transaction covering with all the data structures/HW - * updates. One transaction per-thread can be opened at the - * most, that means if multiple thread are available, multiple - * transactions can be outstanding. - * - */ - void tbegin() throws NotSupportedException, SystemException; - - /** - * tbegin with a timeout - * @see IClusterServices#tbegin - * @param timeout the transaction timeout - * @param unit TimeUnit for the timeout - * @throws NotSupportedException - * @throws SystemException - */ - void tbegin(long timeout, TimeUnit unit) throws NotSupportedException, SystemException; - - /** - * Commit a transaction covering all the data structures/HW updates. - */ - void tcommit() throws RollbackException, HeuristicMixedException, - HeuristicRollbackException, java.lang.SecurityException, - java.lang.IllegalStateException, SystemException; - - /** - * Rollback a transaction covering all the data structures/HW updates - */ - void trollback() throws java.lang.IllegalStateException, - java.lang.SecurityException, SystemException; - - /** - * Return the javax.transaction.Transaction associated with this thread - * - * - * @return Return the current transaction associated with this thread - */ - Transaction tgetTransaction() throws SystemException; - - /** - * @deprecated - * Function that says if we are standby in the 1-1 redundancy with - * active/standby model. The API is not encouraged hence is - * deprecated. It is supposed to be used as a stop-gap till the - * active-standby goal is achieved. The only guys that are - * supposed to use are: - * - southbound layer, should not listen on the OF port if standby - * - jetty configuration, on standby jetty should redirect calls - * to the active. - * - * @return true if the role is the one of standby, else false - */ - @Deprecated - boolean amIStandby(); - - /** - * @deprecated - * Get the InetAddress of the active controller for the - * active-standby case, where the standby controller has to - * redirect the HTTP requests received from applications layer - * - * @return Address of the active controller - */ - @Deprecated - InetAddress getActiveAddress(); - - /** - * Get the InetAddress of the all the controllers that make up this - * Cluster - * - * @return List of InetAddress'es of all the controllers - */ - List getClusteredControllers(); - - /** - * Get the InetAddress of this Controller as seen by the Cluster Manager - * - * @return InetAddress of this Controller as seen by the Cluster Manager. - */ - InetAddress getMyAddress(); - - /** - * @deprecated - * Register a listener to the event of ChangeRole, raised every - * time there is a change in the role of active or standby. - * - * @param i Interface that will be called when the Role Change happens - */ - @Deprecated - void listenRoleChange(IListenRoleChange i) - throws ListenRoleChangeAddException; - - /** - * @deprecated - * UN-Register a listener to the event of ChangeRole, raised every - * time there is a change in the role of active or standby. - * - * @param i Interface that will be called when the Role Change happens - */ - @Deprecated - void unlistenRoleChange(IListenRoleChange i); -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServicesCommon.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServicesCommon.java deleted file mode 100644 index 7ea86c6db7..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IClusterServicesCommon.java +++ /dev/null @@ -1,190 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IClusterServicesCommon.java - * - * @brief : Set of services an application will expect from the - * clustering services provider. This interface is going to be the - * base for per-container and Global services and so the container - * parameter is omitted but who uses knows about it - * - * Contract between the applications and the clustering service - * providers. Common version - */ - -package org.opendaylight.controller.clustering.services; - -import java.net.InetAddress; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.TimeUnit; - -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.NotSupportedException; -import javax.transaction.RollbackException; -import javax.transaction.SystemException; -import javax.transaction.Transaction; - -/** - * This WILL NOT BE USED DIRECTLY, but VIA SUBCLASS - * - * Set of services and application will expect from the clustering services - * provider. This interface is going to be the base for per-container and Global - * services and so the container parameter is omitted but who uses knows about - * it - * - */ -public interface IClusterServicesCommon { - /** - * Method that will create a new named cache. The data - * structure if already present will cause an exception to be - * thrown to the caller. - * - * @param cacheName Name of the ConcurrentHashMap to create - * @param cMode Mode of the cache that need to be retrieved. This - * is a set such that more than one property can be provided, of - * course contrasting requirements will not be accepted and in - * that case an exception is thrown - * - * @return ConcurrentHashMap to be used to modify the data structure - */ - ConcurrentMap createCache(String cacheName, - Set cMode) throws CacheExistException, - CacheConfigException; - - /** - * Method that will retrieve and return the handle to modify a - * data structire distributed via clustering services. The - * datastructure shall already have been created else a null - * reference will be returned. - * - * @param cacheName Name of the ConcurrentHashMap to retrieve - * - * @return ConcurrentHashMap to be used to modify the data structure - */ - ConcurrentMap getCache(String cacheName); - - /** - * Destroy a cachename given cachename, if doesn't exist - * the function does nothing. If the datastructure exists, the - * whole cluster will destroy the instance - * - * @param cacheName Name of the ConcurrentHashMap to destroy - */ - void destroyCache(String cacheName); - - /** - * Function to test the existance of a cache with a given name already - * - * @param cacheName Name of the ConcurrentHashMap to destroy - * - * @return true if exists already, false otherwise - */ - boolean existCache(String cacheName); - - /** - * Return the list of all teh caches registered in the context of - * the called - * - * - * @return The set of names, expressed as strings - */ - Set getCacheList(); - - /** - * Return a list of properties that caracterize the cache - * - * @param cacheName Name of the cache - * - * @return The list of properties related to the cache - */ - Properties getCacheProperties(String cacheName); - - /** - * Begin a transaction covering with all the data structures/HW - * updates. One transaction per-thread can be opened at the - * most, that means if multiple thread are available, multiple - * transactions can be outstanding. - * - */ - void tbegin() throws NotSupportedException, SystemException; - - /** - * tbegin with a timeout - * @see IClusterServicesCommon#tbegin - * @param timeout the transaction timeout - * @param unit TimeUnit for the timeout - * @throws NotSupportedException - * @throws SystemException - */ - void tbegin(long timeout, TimeUnit unit) throws NotSupportedException, SystemException; - - /** - * Commit a transaction covering all the data structures/HW updates. - */ - void tcommit() throws RollbackException, HeuristicMixedException, - HeuristicRollbackException, java.lang.SecurityException, - java.lang.IllegalStateException, SystemException; - - /** - * Rollback a transaction covering all the data structures/HW updates - */ - void trollback() throws java.lang.IllegalStateException, - java.lang.SecurityException, SystemException; - - /** - * Return the javax.transaction.Transaction associated with this thread - * - * - * @return Return the current transaction associated with this thread - */ - Transaction tgetTransaction() throws SystemException; - - /** - * - * Get the InetAddress of the coordinator controller in the cluster - * - * @return Address of the coordinator controller - */ - InetAddress getCoordinatorAddress(); - - /** - * Get the InetAddress of the all the controllers that make up this - * Cluster - * - * @return List of InetAddress'es of all the controllers - */ - List getClusteredControllers(); - - /** - * Get the InetAddress of this Controller as seen by the Cluster Manager - * - * @return InetAddress of this Controller as seen by the Cluster Manager. - */ - InetAddress getMyAddress(); - - /** - * Function that is used to know if the node on which is called is - * the cluster coordinator. The API is useful in scenario where - * the same logic is not worthed to be replicated on multiple - * nodes in the cluster and one can cook it up for all the - * others. In this scenario running the logic on the coordinator - * make sense, this of course implies logics that are not heavy - * and don't need to be scaled out linearly with the size of the - * cluster. - * - * @return true if the node on which the API is called is the - * coordinator for the cluster - */ - boolean amICoordinator(); -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICoordinatorChangeAware.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICoordinatorChangeAware.java deleted file mode 100644 index 5d0edd8d00..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ICoordinatorChangeAware.java +++ /dev/null @@ -1,32 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file ICoordinatorChangeAware.java - * - * - * @brief Interface that needs to be implemented by who wants to be - * notified of coordinator role change - * - */ -package org.opendaylight.controller.clustering.services; - -/** - * Interface that needs to be implemented by who wants to be - * notified of coordinator role change - * - */ -public interface ICoordinatorChangeAware { - - /** - * Function that will be called when there is the event of - * coordinator change in the cluster. - */ - void coordinatorChanged(); -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IGetUpdates.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IGetUpdates.java deleted file mode 100644 index 1f9a45a249..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IGetUpdates.java +++ /dev/null @@ -1,59 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IGetUpdates.java - * - * @brief Interface that needs to be implemented by the listeners of - * updates received on data structure shared in the cluster - * - * Interface that needs to be implemented by the listeners of updates - * received on data structure shared in the cluster - */ -package org.opendaylight.controller.clustering.services; - -/** - * @deprecated for internal use - * Interface that needs to be implemented by the listeners of - * updates received on data structure shared in the cluster - */ -public interface IGetUpdates { - /** - * Invoked when a new entry is available in the cache, the key is - * only provided, the value will come as an entryUpdate invocation - * - * @param key Key for the entry just created - * @param containerName container for which the update has been received - * @param cacheName name of the cache for which update has been received - */ - void entryCreated(K key, String containerName, String cacheName, - boolean local); - - /** - * Called anytime a given entry is updated - * - * @param key Key for the entry modified - * @param new_value the new value the key will have - * @param containerName container for which the update has been received - * @param cacheName name of the cache for which update has been received - */ - void entryUpdated(K key, V new_value, String containerName, - String cacheName, boolean local); - - /** - * Called anytime a given key is removed from the - * ConcurrentHashMap we are listening to. - * - * @param key Key of the entry removed - * @param containerName container for which the update has been received - * @param cacheName name of the cache for which update has been received - */ - void entryDeleted(K key, String containerName, String cacheName, - boolean originLocal); -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IListenRoleChange.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IListenRoleChange.java deleted file mode 100644 index b8798e6705..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/IListenRoleChange.java +++ /dev/null @@ -1,41 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IListenRoleChange.java - * - * - * @brief Interface that needs to be implemented by who wants to be - * notified of new active change - * - * @deprecated - * - * Interface that needs to be implemented by who wants to be notified - * of newly active taking over. Interface that is supposed to be - * short-lived and will be removed as soon as active-standby goal is reached. - */ -package org.opendaylight.controller.clustering.services; - -/** - * Interface that needs to be implemented by who wants to be notified - * of newly active taking over. Interface that is supposed to be - * short-lived and will be removed as soon as active-standby goal is reached. - * - */ -public interface IListenRoleChange { - - /** - * @deprecated - * Function that will be called when a new active is - * available. This function is supposed only to be of use till - * active-standby milestone is reached, after will be removed. - * - */ - void newActiveAvailable(); -} diff --git a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ListenRoleChangeAddException.java b/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ListenRoleChangeAddException.java deleted file mode 100644 index dd2585b17e..0000000000 --- a/opendaylight/adsal/clustering/services/src/main/java/org/opendaylight/controller/clustering/services/ListenRoleChangeAddException.java +++ /dev/null @@ -1,33 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file ListenRoleChangeAddException.java - * - * @brief Describe an exception that is raised when the cache - * Listener being added fails for any reason - * - */ -package org.opendaylight.controller.clustering.services; - -/** - * @deprecated for internal use - * The Class ListenRoleChangeAddException. - */ -@Deprecated -public class ListenRoleChangeAddException extends Exception { - private static final long serialVersionUID = 1L; - - /** - * Instantiates a new listen role change add exception. - */ - public ListenRoleChangeAddException() { - super(); - } -} diff --git a/opendaylight/adsal/clustering/services_implementation/pom.xml b/opendaylight/adsal/clustering/services_implementation/pom.xml deleted file mode 100644 index d3b0578084..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/pom.xml +++ /dev/null @@ -1,152 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - clustering.services-implementation - 0.6.0-SNAPSHOT - bundle - - - reuseReports - target/jacoco.exec - target/jacoco-it.exec - - - - equinoxSDK381 - org.apache.felix.gogo.runtime - - - junit - junit - - - org.infinispan - infinispan-core - 6.0.2.Final - - - org.jboss.jbossts.jta - narayana-jta - 4.17.7.Final - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - commons.logback_settings - - - org.opendaylight.controller - sal - - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.slf4j, - !org.apache.logging.log4j.*, - !bsh*, - !net.jcip.*, - !javax.swing, - !org.hornetq.*, - !org.jboss.*, - javax.transaction, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.core,* - org.opendaylight.controller.clustering.services_implementation.internal.Activator - - - - - - - - * - infinispan-core,infinispan-commons,jgroups,jboss-marshalling-river,jboss-marshalling,jboss-logging,staxmapper,narayana-jta;type=!pom;inline=false - true - - ${project.basedir}/META-INF - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${enforcer.version} - - - enforce-banned-dependencies - - enforce - - - - - - org.infinispan:infinispan-core:* - - - org.infinispan:infinispan-core:[6.0.2.Final] - - - - true - - - - - - org.jacoco - jacoco-maven-plugin - - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - report - - test - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/Activator.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/Activator.java deleted file mode 100644 index 1c6a5db6d5..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/Activator.java +++ /dev/null @@ -1,139 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.services_implementation.internal; - -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; - -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.clustering.services.ICoordinatorChangeAware; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.apache.felix.dm.Component; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getGlobalImplementations() { - Object[] res = { ClusterManager.class, ClusterGlobalManager.class, ClusterManagerCLI.class }; - return res; - } - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { ClusterContainerManager.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(ClusterContainerManager.class)) { - c.setInterface(new String[] { IClusterContainerServices.class.getName() }, - null); - - c.add(createServiceDependency() - .setService(IClusterServices.class) - .setCallbacks("setClusterService", "unsetClusterService") - .setRequired(true)); - - // CacheUpdate services will be none or many so the - // dependency is optional - c.add(createContainerServiceDependency(containerName) - .setService(ICacheUpdateAware.class) - .setCallbacks("setCacheUpdateAware", "unsetCacheUpdateAware") - .setRequired(false)); - - // Coordinator change event can be one or many so - // dependency is optional - c.add(createContainerServiceDependency(containerName) - .setService(ICoordinatorChangeAware.class) - .setCallbacks("setCoordinatorChangeAware", "unsetCoordinatorChangeAware") - .setRequired(false)); - } - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - */ - @Override - public void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(ClusterManager.class)) { - // export the service for Apps and Plugins - c.setInterface(new String[] { IClusterServices.class.getName() }, null); - } - - if (imp.equals(ClusterGlobalManager.class)) { - c.setInterface(new String[] { IClusterGlobalServices.class.getName() }, null); - - c.add(createServiceDependency() - .setService(IClusterServices.class) - .setCallbacks("setClusterService", "unsetClusterService") - .setRequired(true)); - - // CacheUpdate services will be none or many so the - // dependency is optional - c.add(createServiceDependency() - .setService(ICacheUpdateAware.class) - .setCallbacks("setCacheUpdateAware", "unsetCacheUpdateAware") - .setRequired(false)); - - // Coordinator change event can be one or many so - // dependency is optional - c.add(createServiceDependency() - .setService(ICoordinatorChangeAware.class) - .setCallbacks("setCoordinatorChangeAware", "unsetCoordinatorChangeAware") - .setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/CacheListenerContainer.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/CacheListenerContainer.java deleted file mode 100644 index c3c0621e8c..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/CacheListenerContainer.java +++ /dev/null @@ -1,73 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.services_implementation.internal; - -import org.infinispan.notifications.Listener; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; -import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; -import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; -import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; -import org.opendaylight.controller.clustering.services.IGetUpdates; - -@Listener -public class CacheListenerContainer { - private IGetUpdates toBeUpdated; - private String containerName; - private String cacheName; - - public CacheListenerContainer(IGetUpdates i, String containerName, - String cacheName) { - this.toBeUpdated = i; - this.containerName = containerName; - this.cacheName = cacheName; - } - - public IGetUpdates whichListener() { - return this.toBeUpdated; - } - - @CacheEntryCreated - public void observeCreate(CacheEntryCreatedEvent event) { - if (event.isPre()) { - return; - } - - if (this.toBeUpdated != null) { - this.toBeUpdated.entryCreated(event.getKey(), this.containerName, - this.cacheName, event.isOriginLocal()); - } - } - - @CacheEntryModified - public void observeModify(CacheEntryModifiedEvent event) { - if (event.isPre()) { - return; - } - - if (this.toBeUpdated != null) { - this.toBeUpdated.entryUpdated(event.getKey(), event.getValue(), - this.containerName, this.cacheName, event.isOriginLocal()); - } - } - - @CacheEntryRemoved - public void observeRemove(CacheEntryRemovedEvent event) { - if (event.isPre()) { - return; - } - - if (this.toBeUpdated != null) { - this.toBeUpdated.entryDeleted(event.getKey(), this.containerName, - this.cacheName, event.isOriginLocal()); - } - } -} diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClassResolver.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClassResolver.java deleted file mode 100644 index 521a773966..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClassResolver.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.services_implementation.internal; - -import java.lang.ref.WeakReference; - -import org.jboss.marshalling.ContextClassResolver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public final class ClassResolver extends ContextClassResolver { - private WeakReference osgiClassLoader = null; - private static final Logger logger = LoggerFactory.getLogger(ClassResolver.class); - - public ClassResolver() { - ClassLoader cl = this.getClass() - .getClassLoader(); - if (cl != null) { - this.osgiClassLoader = new WeakReference(cl); - logger.trace("Acquired weak reference to OSGi classLoader {}", cl); - } - } - - @Override - protected ClassLoader getClassLoader() { - ClassLoader ret = null; - if (this.osgiClassLoader != null) { - ret = this.osgiClassLoader.get(); - if (ret != null) { - if (logger.isTraceEnabled()) { - logger.trace("Returning OSGi class loader {}", ret); - } - return ret; - } - } - - logger.warn("Could not resolve classloader!"); - return ret; - } -} diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterContainerManager.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterContainerManager.java deleted file mode 100644 index 9496c33191..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterContainerManager.java +++ /dev/null @@ -1,16 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.services_implementation.internal; - -import org.opendaylight.controller.clustering.services.IClusterContainerServices; - -public class ClusterContainerManager extends ClusterManagerCommon implements - IClusterContainerServices { -} diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterGlobalManager.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterGlobalManager.java deleted file mode 100644 index e05f9dfe16..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterGlobalManager.java +++ /dev/null @@ -1,54 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.services_implementation.internal; - -import java.util.Map; - -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ClusterGlobalManager - extends ClusterManagerCommon - implements IClusterGlobalServices { - protected static final Logger logger = LoggerFactory.getLogger(ClusterGlobalManager.class); - - @Override - void setCacheUpdateAware(Map props, ICacheUpdateAware s) { - logger.trace("setCacheUpdateAware: {}",s); - if (props.get("containerName") != null) { - // If we got a reference with the containerName property - // that is not what we are looking for, so filter it out. - return; - } - super.setCacheUpdateAware(props, s); - } - - @Override - void unsetCacheUpdateAware(Map props, ICacheUpdateAware s) { - logger.trace("unsetCacheUpdateAware: {}",s); - if (props.get("containerName") != null) { - // If we got a reference with the containerName property - // that is not what we are looking for, so filter it out. - return; - } - super.unsetCacheUpdateAware(props, s); - } - - @Override - public void removeContainerCaches(String containerName) { - logger.debug("Removing caches for container {}", containerName); - for (String cacheName : clusterService.getCacheList(containerName)) { - clusterService.destroyCache(containerName, cacheName); - } - } - -} diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManager.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManager.java deleted file mode 100644 index 4febcd07c1..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManager.java +++ /dev/null @@ -1,783 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.services_implementation.internal; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.TimeUnit; - -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.NotSupportedException; -import javax.transaction.RollbackException; -import javax.transaction.SystemException; -import javax.transaction.Transaction; -import javax.transaction.TransactionManager; - -import org.infinispan.Cache; -import org.infinispan.configuration.cache.Configuration; -import org.infinispan.configuration.cache.ConfigurationBuilder; -import org.infinispan.configuration.global.GlobalConfigurationBuilder; -import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; -import org.infinispan.configuration.parsing.ParserRegistry; -import org.infinispan.manager.DefaultCacheManager; -import org.infinispan.manager.EmbeddedCacheManager; -import org.infinispan.notifications.Listener; -import org.infinispan.notifications.cachemanagerlistener.annotation.ViewChanged; -import org.infinispan.notifications.cachemanagerlistener.event.ViewChangedEvent; -import org.infinispan.remoting.transport.Address; -import org.infinispan.remoting.transport.Transport; -import org.infinispan.remoting.transport.jgroups.JGroupsAddress; -import org.infinispan.remoting.transport.jgroups.JGroupsTransport; -import org.jgroups.Channel; -import org.jgroups.Event; -import org.jgroups.stack.GossipRouter; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.CacheListenerAddException; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.clustering.services.IGetUpdates; -import org.opendaylight.controller.clustering.services.IListenRoleChange; -import org.opendaylight.controller.clustering.services.ListenRoleChangeAddException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ClusterManager implements IClusterServices { - protected static final Logger logger = LoggerFactory - .getLogger(ClusterManager.class); - private DefaultCacheManager cm; - GossipRouter gossiper; - private HashSet roleChangeListeners; - private ViewChangedListener cacheManagerListener; - - private static String loopbackAddress = InetAddress.getLoopbackAddress().getHostAddress(); - private static final int gossipRouterPortDefault = 12001; - // defaultTransactionTimeout is 60 seconds - private static int DEFAULT_TRANSACTION_TIMEOUT = 60; - - /** - * Start a JGroups GossipRouter if we are a supernode. The - * GosispRouter is nothing more than a simple - * rendevouz-pointer. All the nodes that wants to join the cluster - * will come to any of the rendevouz point and they introduce the - * nodes to all the others. Once the meet and greet phase if over, - * the nodes will open a full-mesh with the remaining n-1 nodes, - * so even if the GossipRouter goes down nothing is lost. - * NOTE: This function has the side effect to set some of the - * JGROUPS configurations, this because in this function already - * we try to retrieve some of the network capabilities of the - * device and so it's better not to do that again - * - * - * @return GossipRouter - */ - private GossipRouter startGossiper() { - boolean amIGossipRouter = false; - Integer gossipRouterPort = gossipRouterPortDefault; - InetAddress gossipRouterAddress = null; - String supernodes_list = System.getProperty("supernodes", - loopbackAddress); - /* - * Check the environment for the "container" variable, if this is set - * and is equal to "lxc", then ODL is running inside an lxc - * container, and address resolution of supernodes will be modified - * accordingly. - */ - boolean inContainer = "lxc".equals(System.getenv("container")); - StringBuffer sanitized_supernodes_list = new StringBuffer(); - List myAddresses = new ArrayList(); - - if (inContainer) { - logger.trace("DOCKER: Resolving supernode host names using docker container semantics"); - } - - StringTokenizer supernodes = new StringTokenizer(supernodes_list, ":"); - if (supernodes.hasMoreTokens()) { - // Populate the list of my addresses - try { - Enumeration e = NetworkInterface.getNetworkInterfaces(); - while (e.hasMoreElements()) { - NetworkInterface n = e.nextElement(); - Enumeration ee = n.getInetAddresses(); - while (ee.hasMoreElements()) { - InetAddress i = ee.nextElement(); - myAddresses.add(i); - } - } - } catch (SocketException se) { - logger.error("Cannot get the list of network interfaces"); - return null; - } - } - while (supernodes.hasMoreTokens()) { - String curr_supernode = supernodes.nextToken(); - logger.debug("Examining supernode {}", curr_supernode); - StringTokenizer host_port = new StringTokenizer(curr_supernode, - "[]"); - String host; - String port; - Integer port_num = gossipRouterPortDefault; - if (host_port.countTokens() > 2) { - logger.error("Error parsing supernode {} proceed to the next one", - curr_supernode); - continue; - } - host = host_port.nextToken(); - InetAddress hostAddr; - /* - * If we are in a container and the hostname begins with a '+', this is - * an indication that we should resolve this host name in the context - * of a docker container. - * - * Specifically this means: - * '+self' : self reference and the host will be mapped to the value of - * HOSTNAME in the environment - * '+' : references another container by its name. The docker established - * environment variables will be used to resolve the host to an - * IP address. - */ - if (inContainer && host != null && host.charAt(0) == '+') { - if ("+self".equals(host)) { - host = System.getenv("HOSTNAME"); - } else { - String link = System.getenv(host.substring(1).toUpperCase() + "_PORT"); - if (link != null) { - try { - host = new URI(link).getHost(); - } catch (URISyntaxException e) { - logger.error("DOCKER: Unable to translate container reference ({}) to host IP Address, will attempt using normal host name", - host.substring(1)); - } - } - } - } - - try { - hostAddr = InetAddress.getByName(host); - } catch (UnknownHostException ue) { - logger.error("Host {} is not known", host); - continue; - } - if (host_port.hasMoreTokens()) { - port = host_port.nextToken(); - try { - port_num = Integer.valueOf(port); - } catch (NumberFormatException ne) { - logger.error("Supplied supernode gossip port is not recognized, using default gossip port {}", - gossipRouterPortDefault); - port_num = gossipRouterPortDefault; - } - if ((port_num > 65535) || (port_num < 0)) { - logger.error("Supplied supernode gossip port is outside a valid TCP port range"); - port_num = gossipRouterPortDefault; - } - } - if (!amIGossipRouter) { - if (host != null) { - for (InetAddress myAddr : myAddresses) { - if (myAddr.equals(hostAddr)) { - amIGossipRouter = true; - gossipRouterAddress = hostAddr; - gossipRouterPort = port_num; - break; - } - } - } - } - if (!sanitized_supernodes_list.toString().equals("")) { - sanitized_supernodes_list.append(","); - } - sanitized_supernodes_list.append(hostAddr.getHostAddress()).append("[").append(port_num).append("]"); - } - - if (amIGossipRouter) { - // Set the Jgroups binding interface to the one we got - // from the supernodes attribute - if (gossipRouterAddress != null) { - System.setProperty("jgroups.tcp.address", gossipRouterAddress - .getHostAddress()); - } - } else { - // Set the Jgroup binding interface to the one we are well - // known outside or else to the first with non-local - // scope. - try { - String myBind = InetAddress.getLocalHost().getHostAddress(); - if (myBind == null - || InetAddress.getLocalHost().isLoopbackAddress()) { - for (InetAddress myAddr : myAddresses) { - if (myAddr.isLoopbackAddress() - || myAddr.isLinkLocalAddress()) { - logger.debug("Skipping local address {}", - myAddr.getHostAddress()); - continue; - } else { - // First non-local address - myBind = myAddr.getHostAddress(); - logger.debug("First non-local address {}", myBind); - break; - } - } - } - String jgroupAddress = System - .getProperty("jgroups.tcp.address"); - if (jgroupAddress == null) { - if (myBind != null) { - logger.debug("Set bind address to be {}", myBind); - System.setProperty("jgroups.tcp.address", myBind); - } else { - logger - .debug("Set bind address to be LOCALHOST=127.0.0.1"); - System.setProperty("jgroups.tcp.address", "127.0.0.1"); - } - } else { - logger.debug("jgroup.tcp.address already set to be {}", - jgroupAddress); - } - } catch (UnknownHostException uhe) { - logger - .error("Met UnknownHostException while trying to get binding address for jgroups"); - } - } - - // The supernodes list constitute also the tcpgossip initial - // host list - System.setProperty("jgroups.tcpgossip.initial_hosts", - sanitized_supernodes_list.toString()); - logger.debug("jgroups.tcp.address set to {}", - System.getProperty("jgroups.tcp.address")); - logger.debug("jgroups.tcpgossip.initial_hosts set to {}", - System.getProperty("jgroups.tcpgossip.initial_hosts")); - GossipRouter res = null; - if (amIGossipRouter) { - logger.info("I'm a GossipRouter will listen on port {}", - gossipRouterPort); - // Start a GossipRouter with JMX support - res = new GossipRouter(gossipRouterPort, null, true); - } - return res; - } - - private void exitOnSecurityException(Exception ioe) { - Throwable cause = ioe.getCause(); - while (cause != null) { - if (cause instanceof java.lang.SecurityException) { - logger.error("Failed Cluster authentication. Stopping Controller..."); - System.exit(0); - } - cause = cause.getCause(); - } - } - - public void start() { - this.gossiper = startGossiper(); - if (this.gossiper != null) { - logger.debug("Trying to start Gossiper"); - try { - this.gossiper.start(); - logger.info("Started GossipRouter"); - } catch (Exception e) { - logger.error("GossipRouter didn't start. Exception Stack Trace", - e); - } - } - logger.info("Starting the ClusterManager"); - try { - ParserRegistry parser = new ParserRegistry(this.getClass() - .getClassLoader()); - String infinispanConfigFile = - System.getProperty("org.infinispan.config.file", "config/infinispan-config.xml"); - logger.debug("Using configuration file:{}", infinispanConfigFile); - ConfigurationBuilderHolder holder = parser.parseFile(infinispanConfigFile); - GlobalConfigurationBuilder globalBuilder = holder.getGlobalConfigurationBuilder(); - globalBuilder.serialization() - .classResolver(new ClassResolver()) - .build(); - this.cm = new DefaultCacheManager(holder, false); - logger.debug("Allocated ClusterManager"); - if (this.cm != null) { - this.cm.start(); - this.cm.startCache(); - logger.debug("Started the ClusterManager"); - } - } catch (Exception ioe) { - logger.error("Cannot configure infinispan .. bailing out "); - logger.error("Stack Trace that raised th exception"); - logger.error("",ioe); - this.cm = null; - exitOnSecurityException(ioe); - this.stop(); - } - logger.debug("Cache Manager has value {}", this.cm); - } - - public void stop() { - logger.info("Stopping the ClusterManager"); - if (this.cm != null) { - logger.info("Found a valid ClusterManager, now let it be stopped"); - this.cm.stop(); - this.cm = null; - } - if (this.gossiper != null) { - this.gossiper.stop(); - this.gossiper = null; - } - } - - @Override - public ConcurrentMap createCache(String containerName, - String cacheName, Set cMode) throws CacheExistException, - CacheConfigException { - EmbeddedCacheManager manager = this.cm; - Cache c; - String realCacheName = "{" + containerName + "}_{" + cacheName + "}"; - if (manager == null) { - return null; - } - - if (manager.cacheExists(realCacheName)) { - throw new CacheExistException(); - } - - // Sanity check to avoid contrasting parameters between transactional - // and not - if (cMode.containsAll(EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, - IClusterServices.cacheMode.TRANSACTIONAL))) { - throw new CacheConfigException(); - } - - // Sanity check to avoid contrasting parameters between sync and async - if (cMode.containsAll(EnumSet.of(IClusterServices.cacheMode.SYNC, IClusterServices.cacheMode.ASYNC))) { - throw new CacheConfigException(); - } - - Configuration fromTemplateConfig = null; - /* - * Fetch transactional/non-transactional templates - */ - // Check if transactional - if (cMode.contains(IClusterServices.cacheMode.TRANSACTIONAL)) { - fromTemplateConfig = manager.getCacheConfiguration("transactional-type"); - } else if (cMode.contains(IClusterServices.cacheMode.NON_TRANSACTIONAL)) { - fromTemplateConfig = manager.getDefaultCacheConfiguration(); - } - - // If none set the transactional property then just return null - if (fromTemplateConfig == null) { - return null; - } - - ConfigurationBuilder builder = new ConfigurationBuilder(); - builder.read(fromTemplateConfig); - /* - * Now evaluate async/sync - */ - if (cMode.contains(IClusterServices.cacheMode.ASYNC)) { - builder.clustering() - .cacheMode(fromTemplateConfig.clustering() - .cacheMode() - .toAsync()); - } else if (cMode.contains(IClusterServices.cacheMode.SYNC)) { - builder.clustering() - .cacheMode(fromTemplateConfig.clustering() - .cacheMode() - .toSync()); - } - - manager.defineConfiguration(realCacheName, builder.build()); - c = manager.getCache(realCacheName); - return c; - } - - @Override - public ConcurrentMap getCache(String containerName, String cacheName) { - EmbeddedCacheManager manager = this.cm; - Cache c; - String realCacheName = "{" + containerName + "}_{" + cacheName + "}"; - if (manager == null) { - return null; - } - - if (manager.cacheExists(realCacheName)) { - c = manager.getCache(realCacheName); - return c; - } - return null; - } - - @Override - public void destroyCache(String containerName, String cacheName) { - EmbeddedCacheManager manager = this.cm; - String realCacheName = "{" + containerName + "}_{" + cacheName + "}"; - if (manager == null) { - return; - } - if (manager.cacheExists(realCacheName)) { - manager.removeCache(realCacheName); - } - } - - @Override - public boolean existCache(String containerName, String cacheName) { - EmbeddedCacheManager manager = this.cm; - - if (manager == null) { - return false; - } - - String realCacheName = "{" + containerName + "}_{" + cacheName + "}"; - return manager.cacheExists(realCacheName); - } - - @Override - public Set getCacheList(String containerName) { - Set perContainerCaches = new HashSet(); - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - return null; - } - for (String cacheName : manager.getCacheNames()) { - if (!manager.isRunning(cacheName)) { - continue; - } - if (cacheName.startsWith("{" + containerName + "}_")) { - String[] res = cacheName.split("[{}]"); - if (res.length >= 4 && res[1].equals(containerName) - && res[2].equals("_")) { - perContainerCaches.add(res[3]); - } - } - } - - return (perContainerCaches); - } - - @Override - public Properties getCacheProperties(String containerName, String cacheName) { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - return null; - } - String realCacheName = "{" + containerName + "}_{" + cacheName + "}"; - if (!manager.cacheExists(realCacheName)) { - return null; - } - Configuration conf = manager.getCache(realCacheName).getAdvancedCache() - .getCacheConfiguration(); - Properties p = new Properties(); - p.setProperty(IClusterServices.cacheProps.TRANSACTION_PROP.toString(), - conf.transaction().toString()); - p.setProperty(IClusterServices.cacheProps.CLUSTERING_PROP.toString(), - conf.clustering().toString()); - p.setProperty(IClusterServices.cacheProps.LOCKING_PROP.toString(), conf - .locking().toString()); - return p; - } - - @Override - public void addListener(String containerName, String cacheName, - IGetUpdates u) throws CacheListenerAddException { - EmbeddedCacheManager manager = this.cm; - Cache c; - String realCacheName = "{" + containerName + "}_{" + cacheName + "}"; - if (manager == null) { - return; - } - - if (!manager.cacheExists(realCacheName)) { - throw new CacheListenerAddException(); - } - c = manager.getCache(realCacheName); - CacheListenerContainer cl = new CacheListenerContainer(u, - containerName, cacheName); - c.addListener(cl); - } - - @Override - public Set> getListeners(String containerName, - String cacheName) { - EmbeddedCacheManager manager = this.cm; - Cache c; - String realCacheName = "{" + containerName + "}_{" + cacheName + "}"; - if (manager == null) { - return null; - } - - if (!manager.cacheExists(realCacheName)) { - return null; - } - c = manager.getCache(realCacheName); - - Set> res = new HashSet>(); - Set listeners = c.getListeners(); - for (Object listener : listeners) { - if (listener instanceof CacheListenerContainer) { - CacheListenerContainer cl = (CacheListenerContainer) listener; - res.add(cl.whichListener()); - } - } - - return res; - } - - @Override - public void removeListener(String containerName, String cacheName, - IGetUpdates u) { - EmbeddedCacheManager manager = this.cm; - Cache c; - String realCacheName = "{" + containerName + "}_{" + cacheName + "}"; - if (manager == null) { - return; - } - - if (!manager.cacheExists(realCacheName)) { - return; - } - c = manager.getCache(realCacheName); - - Set listeners = c.getListeners(); - for (Object listener : listeners) { - if (listener instanceof CacheListenerContainer) { - CacheListenerContainer cl = (CacheListenerContainer) listener; - if (cl.whichListener() == u) { - c.removeListener(listener); - return; - } - } - } - } - - @Override - public void tbegin() throws NotSupportedException, SystemException { - // call tbegin with the default timeout - tbegin(DEFAULT_TRANSACTION_TIMEOUT, TimeUnit.SECONDS); - } - - @Override - public void tbegin(long timeout, TimeUnit unit) throws NotSupportedException, SystemException { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - throw new IllegalStateException(); - } - TransactionManager tm = manager.getCache("transactional-type") - .getAdvancedCache().getTransactionManager(); - if (tm == null) { - throw new IllegalStateException(); - } - long timeoutSec = unit.toSeconds(timeout); - if((timeoutSec > Integer.MAX_VALUE) || (timeoutSec <= 0)) { - // fall back to the default timeout - tm.setTransactionTimeout(DEFAULT_TRANSACTION_TIMEOUT); - } else { - // cast is ok here - // as here we are sure that timeoutSec < = Integer.MAX_VALUE. - tm.setTransactionTimeout((int) timeoutSec); - } - tm.begin(); - } - - @Override - public void tcommit() throws RollbackException, HeuristicMixedException, - HeuristicRollbackException, java.lang.SecurityException, - java.lang.IllegalStateException, SystemException { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - throw new IllegalStateException(); - } - TransactionManager tm = manager.getCache("transactional-type") - .getAdvancedCache().getTransactionManager(); - if (tm == null) { - throw new IllegalStateException(); - } - tm.commit(); - } - - @Override - public void trollback() throws java.lang.IllegalStateException, - java.lang.SecurityException, SystemException { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - throw new IllegalStateException(); - } - TransactionManager tm = manager.getCache("transactional-type") - .getAdvancedCache().getTransactionManager(); - if (tm == null) { - throw new IllegalStateException(); - } - tm.rollback(); - } - - @Override - public Transaction tgetTransaction() throws SystemException { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - throw new IllegalStateException(); - } - TransactionManager tm = manager.getCache("transactional-type") - .getAdvancedCache().getTransactionManager(); - if (tm == null) { - return null; - } - return tm.getTransaction(); - } - - @Override - public boolean amIStandby() { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - // In case we cannot fetch the information, lets assume we - // are standby, so to have less responsibility. - return true; - } - return (!manager.isCoordinator()); - } - - private InetAddress addressToInetAddress(Address a) { - EmbeddedCacheManager manager = this.cm; - if ((manager == null) || (a == null)) { - // In case we cannot fetch the information, lets assume we - // are standby, so to have less responsibility. - return null; - } - Transport t = manager.getTransport(); - if (t instanceof JGroupsTransport) { - JGroupsTransport jt = (JGroupsTransport) t; - Channel c = jt.getChannel(); - if (a instanceof JGroupsAddress) { - JGroupsAddress ja = (JGroupsAddress) a; - org.jgroups.Address phys = (org.jgroups.Address) c - .down(new Event(Event.GET_PHYSICAL_ADDRESS, ja - .getJGroupsAddress())); - if (phys instanceof org.jgroups.stack.IpAddress) { - InetAddress bindAddress = ((org.jgroups.stack.IpAddress) phys) - .getIpAddress(); - return bindAddress; - } - } - } - return null; - } - - @Override - public List getClusteredControllers() { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - return null; - } - List
controllers = manager.getMembers(); - if ((controllers == null) || controllers.size() == 0) { - return null; - } - - List clusteredControllers = new ArrayList(); - for (Address a : controllers) { - InetAddress inetAddress = addressToInetAddress(a); - if (inetAddress != null - && !inetAddress.getHostAddress().equals(loopbackAddress)) { - clusteredControllers.add(inetAddress); - } - } - return clusteredControllers; - } - - @Override - public InetAddress getMyAddress() { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - return null; - } - return addressToInetAddress(manager.getAddress()); - } - - @Override - public InetAddress getActiveAddress() { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - // In case we cannot fetch the information, lets assume we - // are standby, so to have less responsibility. - return null; - } - - return addressToInetAddress(manager.getCoordinator()); - } - - @Override - public void listenRoleChange(IListenRoleChange i) - throws ListenRoleChangeAddException { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - // In case we cannot fetch the information, lets assume we - // are standby, so to have less responsibility. - throw new ListenRoleChangeAddException(); - } - - if (this.roleChangeListeners == null) { - this.roleChangeListeners = new HashSet(); - this.cacheManagerListener = new ViewChangedListener( - this.roleChangeListeners); - manager.addListener(this.cacheManagerListener); - } - - if (this.roleChangeListeners != null) { - this.roleChangeListeners.add(i); - } - } - - @Override - public void unlistenRoleChange(IListenRoleChange i) { - EmbeddedCacheManager manager = this.cm; - if (manager == null) { - // In case we cannot fetch the information, lets assume we - // are standby, so to have less responsibility. - return; - } - - if (this.roleChangeListeners != null) { - this.roleChangeListeners.remove(i); - } - - if ((this.roleChangeListeners != null && this.roleChangeListeners - .isEmpty()) - && (this.cacheManagerListener != null)) { - manager.removeListener(this.cacheManagerListener); - this.cacheManagerListener = null; - this.roleChangeListeners = null; - } - } - - @Listener - public class ViewChangedListener { - Set roleListeners; - - public ViewChangedListener(Set s) { - this.roleListeners = s; - } - - @ViewChanged - public void viewChanged(ViewChangedEvent e) { - for (IListenRoleChange i : this.roleListeners) { - i.newActiveAvailable(); - } - } - } -} diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCLI.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCLI.java deleted file mode 100644 index 402b853088..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCLI.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.clustering.services_implementation.internal; - -import java.util.Dictionary; -import java.util.Hashtable; -import java.util.concurrent.ConcurrentMap; - -import org.apache.felix.service.command.Descriptor; -import org.infinispan.AdvancedCache; -import org.infinispan.distribution.DistributionManager; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.osgi.framework.ServiceRegistration; - -public class ClusterManagerCLI { - @SuppressWarnings("rawtypes") - private ServiceRegistration sr = null; - - public void init() { - } - - public void destroy() { - } - - public void start() { - final Dictionary props = new Hashtable(); - props.put("osgi.command.scope", "odpcontroller"); - props.put("osgi.command.function", new String[] { "getContainerAdvancedCacheInfo" }); - this.sr = ServiceHelper.registerGlobalServiceWReg(ClusterManagerCLI.class, this, props); - } - - public void stop() { - if (this.sr != null) { - this.sr.unregister(); - this.sr = null; - } - } - - @Descriptor("Get advanced cache infos") - public void getContainerAdvancedCacheInfo(@Descriptor("Container for the cache to be fetched") String container, - @Descriptor("cache to get information about") String cacheName) { - IClusterContainerServices s = - (IClusterContainerServices) ServiceHelper.getInstance(IClusterContainerServices.class, container, this); - if (s == null) { - System.out.println("Could not get an handle to the container cluster service:" + container); - return; - } - if (!s.existCache(cacheName)) { - System.out.println("Could not get cache named:" + cacheName); - } - ConcurrentMap aC = s.getCache(cacheName); - if (aC == null) { - System.out.println("Could not get cache named:" + cacheName); - return; - } - if (aC instanceof AdvancedCache) { - @SuppressWarnings("rawtypes") - AdvancedCache advCache = (AdvancedCache) aC; - System.out.println("AdvancedCache retrieved!"); - DistributionManager dMgr = advCache.getDistributionManager(); - if (dMgr == null) { - return; - } - System.out.println("Routing Table for the Hash:" + dMgr.getConsistentHash() - .getRoutingTableAsString()); - System.out.println("Get Members:" + dMgr.getConsistentHash() - .getMembers()); - } - } -} diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCommon.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCommon.java deleted file mode 100644 index 06e5bc5b61..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerCommon.java +++ /dev/null @@ -1,333 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.services_implementation.internal; - -import java.net.InetAddress; -import java.util.Collections; -import java.util.Dictionary; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.TimeUnit; - -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.NotSupportedException; -import javax.transaction.RollbackException; -import javax.transaction.SystemException; -import javax.transaction.Transaction; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.CacheListenerAddException; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.clustering.services.IClusterServicesCommon; -import org.opendaylight.controller.clustering.services.ICoordinatorChangeAware; -import org.opendaylight.controller.clustering.services.IListenRoleChange; -import org.opendaylight.controller.clustering.services.ListenRoleChangeAddException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class ClusterManagerCommon implements IClusterServicesCommon { - protected String containerName = null; - protected IClusterServices clusterService = null; - protected static final Logger logger = LoggerFactory - .getLogger(ClusterManagerCommon.class); - private ConcurrentMap cacheUpdateAware = - new ConcurrentHashMap(); - private Set coordinatorChangeAware = Collections - .synchronizedSet(new HashSet()); - private ListenCoordinatorChange coordinatorChangeListener = null; - - /** - * Class needed to listen to the role changes from the cluster - * manager and to pass it along to the other components that - * export the interface ICoordinatorChangeAware - */ - class ListenCoordinatorChange implements IListenRoleChange { - @Override - public void newActiveAvailable() { - if (coordinatorChangeAware != null) { - // Make sure to look the set while walking it - synchronized (coordinatorChangeAware) { - for (ICoordinatorChangeAware s : coordinatorChangeAware) { - // Now walk every instance and signal that the - // coordinator has changed - s.coordinatorChanged(); - } - } - } - } - } - - void setCoordinatorChangeAware(ICoordinatorChangeAware s) { - if (this.coordinatorChangeAware != null) { - this.coordinatorChangeAware.add(s); - } - } - - void unsetCoordinatorChangeAware(ICoordinatorChangeAware s) { - if (this.coordinatorChangeAware != null) { - this.coordinatorChangeAware.remove(s); - } - } - - void setCacheUpdateAware(Map props, ICacheUpdateAware s) { - logger.trace("CacheUpdateAware being set on container:{}", - this.containerName); - if (this.cacheUpdateAware != null) { - Set caches = (Set)props.get("cachenames"); - if (caches != null) { - logger.trace("cachenames provided below:"); - for (String cache : caches) { - if (this.cacheUpdateAware.get(cache) != null) { - logger.error("cachename:{} on container:{} has already a listener", cache, this.containerName); - } else { - GetUpdatesContainer up = new GetUpdatesContainer(s, this.containerName, cache); - if (up != null) { - try { - this.clusterService.addListener(this.containerName, - cache, up); - this.cacheUpdateAware.put(cache, up); - logger.trace("cachename:{} on container:{} has " + - "been registered", cache, - this.containerName); - } catch (CacheListenerAddException exc) { - logger.debug("Cache {} didn't exist when {} tried to register to its updates", cache, s); - // Do nothing, the important is that - // we don't register the listener in - // the shadow, and we are not doing - // that. - } - } - } - } - } - } - } - - void unsetCacheUpdateAware(Map props, ICacheUpdateAware s) { - logger.trace("CacheUpdateAware being unset on container:{}", - this.containerName); - if (this.cacheUpdateAware != null) { - Set caches = (Set)props.get("cachenames"); - if (caches != null) { - logger.trace("cachenames provided below:"); - GetUpdatesContainer up = null; - for (String cache : caches) { - up = this.cacheUpdateAware.get(cache); - if (up != null) { - this.cacheUpdateAware.remove(cache); - this.clusterService.removeListener(this.containerName, - cache, up); - } - } - } - } - } - - public void setClusterService(IClusterServices s) { - this.clusterService = s; - } - - public void unsetClusterServices(IClusterServices s) { - if (this.clusterService == s) { - this.clusterService = null; - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init(Component c) { - Dictionary props = c.getServiceProperties(); - if (props != null) { - this.containerName = (String) props.get("containerName"); - logger.debug("Running containerName: {}", this.containerName); - } else { - // In the Global instance case the containerName is empty - this.containerName = ""; - } - if (this.clusterService != null) { - this.coordinatorChangeListener = new ListenCoordinatorChange(); - try { - this.clusterService - .listenRoleChange(this.coordinatorChangeListener); - logger.debug("Coordinator change handler registered"); - } catch (ListenRoleChangeAddException ex) { - logger.error("Could not register coordinator change"); - } - } - } - - /** - * Function called by the dependency manager when any of the required - * dependencies are going away - * - */ - void destroy() { - if (this.clusterService != null - && this.coordinatorChangeListener != null) { - this.clusterService - .unlistenRoleChange(this.coordinatorChangeListener); - this.coordinatorChangeListener = null; - logger.debug("Coordinator change handler UNregistered"); - } - } - - @Override - public ConcurrentMap createCache(String cacheName, - Set cMode) throws CacheExistException, - CacheConfigException { - if (this.clusterService != null) { - return this.clusterService.createCache(this.containerName, - cacheName, cMode); - } else { - return null; - } - } - - @Override - public ConcurrentMap getCache(String cacheName) { - if (this.clusterService != null) { - return this.clusterService.getCache(this.containerName, cacheName); - } else { - return null; - } - } - - @Override - public void destroyCache(String cacheName) { - if (this.clusterService != null) { - this.clusterService.destroyCache(this.containerName, cacheName); - } - } - - @Override - public boolean existCache(String cacheName) { - if (this.clusterService != null) { - return this.clusterService - .existCache(this.containerName, cacheName); - } else { - return false; - } - } - - @Override - public Set getCacheList() { - if (this.clusterService != null) { - return this.clusterService.getCacheList(this.containerName); - } else { - return null; - } - } - - @Override - public Properties getCacheProperties(String cacheName) { - if (this.clusterService != null) { - return this.clusterService.getCacheProperties(this.containerName, - cacheName); - } else { - return null; - } - } - - @Override - public void tbegin() throws NotSupportedException, SystemException { - if (this.clusterService != null) { - this.clusterService.tbegin(); - } else { - throw new IllegalStateException(); - } - } - - @Override - public void tbegin(long timeout, TimeUnit unit) throws NotSupportedException, SystemException { - if (this.clusterService != null) { - this.clusterService.tbegin(timeout, unit); - } else { - throw new IllegalStateException(); - } - } - - @Override - public void tcommit() throws RollbackException, HeuristicMixedException, - HeuristicRollbackException, java.lang.SecurityException, - java.lang.IllegalStateException, SystemException { - if (this.clusterService != null) { - this.clusterService.tcommit(); - } else { - throw new IllegalStateException(); - } - } - - @Override - public void trollback() throws java.lang.IllegalStateException, - java.lang.SecurityException, SystemException { - if (this.clusterService != null) { - this.clusterService.trollback(); - } else { - throw new IllegalStateException(); - } - } - - @Override - public Transaction tgetTransaction() throws SystemException { - if (this.clusterService != null) { - return this.clusterService.tgetTransaction(); - } else { - return null; - } - } - - @Override - public List getClusteredControllers() { - if (this.clusterService != null) { - return this.clusterService.getClusteredControllers(); - } else { - return null; - } - } - - @Override - public InetAddress getMyAddress() { - if (this.clusterService != null) { - return this.clusterService.getMyAddress(); - } else { - return null; - } - } - - @Override - public InetAddress getCoordinatorAddress() { - if (this.clusterService != null) { - return this.clusterService.getActiveAddress(); - } else { - return null; - } - } - - @Override - public boolean amICoordinator() { - if (this.clusterService != null) { - return (!this.clusterService.amIStandby()); - } else { - return false; - } - } -} diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/GetUpdatesContainer.java b/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/GetUpdatesContainer.java deleted file mode 100644 index 3444a171ea..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/java/org/opendaylight/controller/clustering/services_implementation/internal/GetUpdatesContainer.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.services_implementation.internal; - -import org.opendaylight.controller.clustering.services.IGetUpdates; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; - -public class GetUpdatesContainer implements IGetUpdates { - private ICacheUpdateAware toBeUpdated; - private String containerName; - private String cacheName; - - public GetUpdatesContainer(ICacheUpdateAware i, String containerName, - String cacheName) { - this.toBeUpdated = i; - this.containerName = containerName; - this.cacheName = cacheName; - } - - public ICacheUpdateAware whichListener() { - return this.toBeUpdated; - } - - @Override - public void entryCreated(K key, String containerName, String cacheName, - boolean local) { - if (this.toBeUpdated != null) { - this.toBeUpdated.entryCreated(key, cacheName, local); - } - } - - @Override - public void entryUpdated(K key, V new_value, String containerName, - String cacheName, - boolean local) { - if (this.toBeUpdated != null) { - this.toBeUpdated.entryUpdated(key, new_value, cacheName, local); - } - } - - @Override - public void entryDeleted(K key, String containerName, String cacheName, - boolean local) { - if (this.toBeUpdated != null) { - this.toBeUpdated.entryDeleted(key, cacheName, local); - } - } -} diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/resources/config/infinispan-config.xml b/opendaylight/adsal/clustering/services_implementation/src/main/resources/config/infinispan-config.xml deleted file mode 100644 index 5fb0ddff60..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/resources/config/infinispan-config.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/clustering/services_implementation/src/main/resources/config/jgroups.xml b/opendaylight/adsal/clustering/services_implementation/src/main/resources/config/jgroups.xml deleted file mode 100644 index b1dc0334e5..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/main/resources/config/jgroups.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/clustering/services_implementation/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerTest.java b/opendaylight/adsal/clustering/services_implementation/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerTest.java deleted file mode 100644 index 3d234d32c5..0000000000 --- a/opendaylight/adsal/clustering/services_implementation/src/test/java/org/opendaylight/controller/clustering/services_implementation/internal/ClusterManagerTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.clustering.services_implementation.internal; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; - -import java.net.InetAddress; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; - -import org.infinispan.CacheImpl; -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.clustering.services.IClusterServices.cacheMode; - -public class ClusterManagerTest { - - @Test - public void noManagerSetTest() throws CacheExistException, - CacheConfigException { - ClusterManager cm = new ClusterManager(); - CacheImpl c1 = null; - CacheImpl c2 = null; - Assert.assertNull(cm.createCache("Container", "Cache", null)); - Assert.assertNull(cm.getCacheProperties("Container", "Cache")); - Assert.assertNull(cm.getCache("Container", "Cache")); - Assert.assertFalse(cm.existCache("Container", "Cache")); - Assert.assertNull(cm.getCacheList("Container")); - Assert.assertTrue(cm.amIStandby()); - Assert.assertNull(cm.getActiveAddress()); - Assert.assertNull(cm.getMyAddress()); - Assert.assertNull(cm.getClusteredControllers()); - } - - @Test - public void withManagerTest() throws CacheExistException, - CacheConfigException { - - ClusterManager cm = new ClusterManager(); - CacheImpl c1 = null; - CacheImpl c2 = null; - - cm.start(); - - // Check no cache created yet - assertFalse(cm.existCache("NonExistantContainerName", - "NonExistantCacheName")); - - String cacheName = "Cache1"; - String containerName = "Container1"; - // Create cache with no cacheMode set, expecting it to fail - HashSet cacheModeSet = new HashSet(); - Assert.assertNull(cm.createCache(containerName,cacheName, cacheModeSet)); - - // Create first cache as transactional - cacheModeSet.add(cacheMode.TRANSACTIONAL); - try { - c1 = (CacheImpl) cm.createCache(containerName, - cacheName, cacheModeSet); - } catch (CacheExistException | CacheConfigException cce) { - fail("Failed to create cache " + cacheName); - } - - // Try creating exact same cache again - try { - c1 = (CacheImpl) cm.createCache(containerName, - cacheName, cacheModeSet); - } catch (CacheExistException cee) { - - } catch (CacheConfigException cce) { - fail("Creating cache failed with " + cce); - } - - // Create second cache with both types of cacheMode, expecting it to - // complain - String cacheName2 = "Cache2"; - cacheModeSet.add(cacheMode.NON_TRANSACTIONAL); - try { - c2 = (CacheImpl) cm.createCache(containerName, - cacheName2, cacheModeSet); - } catch (CacheExistException cee) { - fail("Failed to create cache " + cacheName2 + cee); - } catch (CacheConfigException cce) { - - } - - // Create second cache NON_TRANSACTIONAL but with both ASYNC and SYNC, - // expect to complain - cacheModeSet.remove(cacheMode.TRANSACTIONAL); - cacheModeSet.add(cacheMode.SYNC); - cacheModeSet.add(cacheMode.ASYNC); - try { - c2 = (CacheImpl) cm.createCache(containerName, cacheName2, cacheModeSet); - } catch (CacheExistException cee) { - fail("Attempted to create cache " + cacheName2 + " with illegal cache modes set " + cacheModeSet); - } catch (CacheConfigException cce) { - - } - - // Create second cache properly this time, as non_transactional and - // ASYNC - cacheModeSet.remove(cacheMode.SYNC); - try { - c2 = (CacheImpl) cm.createCache(containerName, - cacheName2, cacheModeSet); - } catch (CacheExistException | CacheConfigException e) { - fail("Failed to create cache " + cacheName + " though it was supposed to succeed." + e); - } - - // Make sure correct caches exists - Assert.assertTrue(cm.existCache(containerName, cacheName)); - c1 = (CacheImpl) cm.getCache(containerName, cacheName); - Assert.assertNotNull(c1); - - Assert.assertTrue(cm.existCache(containerName, cacheName2)); - c2 = (CacheImpl) cm.getCache(containerName, cacheName2); - Assert.assertNotNull(c2); - - Assert.assertNull(cm.getCache(containerName, "Cache3")); - - // Get CacheList - HashSet cacheList = (HashSet) cm - .getCacheList("Container2"); - Assert.assertEquals(0, cacheList.size()); - - cacheList = (HashSet) cm.getCacheList(containerName); - Assert.assertEquals(2, cacheList.size()); - Assert.assertTrue(cacheList.contains(cacheName)); - Assert.assertTrue(cacheList.contains(cacheName2)); - - // Get CacheProperties - Assert.assertNull(cm.getCacheProperties(containerName, "")); - Properties p = cm.getCacheProperties(containerName, cacheName); - Assert.assertEquals(3, p.size()); - Assert.assertNotNull(p - .getProperty(IClusterServices.cacheProps.TRANSACTION_PROP - .toString())); - Assert.assertNotNull(p - .getProperty(IClusterServices.cacheProps.CLUSTERING_PROP - .toString())); - Assert.assertNotNull(p - .getProperty(IClusterServices.cacheProps.LOCKING_PROP - .toString())); - - // Destroy cache1 and make sure it's gone - cm.destroyCache(containerName, cacheName); - cm.destroyCache(containerName, "Cache3"); - Assert.assertFalse(cm.existCache(containerName, cacheName)); - Assert.assertTrue(cm.existCache(containerName, cacheName2)); - - // Check amIStandBy() - boolean standby = cm.amIStandby(); - Assert.assertFalse(standby); - - // Check addresses, which are all loopback - InetAddress activeAddress = cm.getActiveAddress(); - Assert.assertEquals("/127.0.0.1", activeAddress.toString()); - InetAddress myAddress = cm.getMyAddress(); - Assert.assertEquals("/127.0.0.1", myAddress.toString()); - - List cc = cm.getClusteredControllers(); - Assert.assertEquals(0, cc.size()); - - cm.stop(); - } - -} diff --git a/opendaylight/adsal/clustering/stub/pom.xml b/opendaylight/adsal/clustering/stub/pom.xml deleted file mode 100644 index b2e845f418..0000000000 --- a/opendaylight/adsal/clustering/stub/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - clustering.stub - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - sal - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - javax.transaction, - org.apache.felix.dm, - org.slf4j, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.core - org.opendaylight.controller.clustering.stub.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/Activator.java b/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/Activator.java deleted file mode 100644 index 437d7368da..0000000000 --- a/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/Activator.java +++ /dev/null @@ -1,89 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.stub.internal; - -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; - -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.apache.felix.dm.Component; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - public Object[] getGlobalImplementations() { - Object[] res = { ClusterGlobalManager.class }; - return res; - } - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - public Object[] getImplementations() { - Object[] res = { ClusterContainerManager.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(ClusterContainerManager.class)) { - c.setInterface(new String[] { IClusterContainerServices.class - .getName() }, null); - } - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - */ - public void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(ClusterGlobalManager.class)) { - c.setInterface(new String[] { IClusterGlobalServices.class - .getName() }, null); - } - } -} diff --git a/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterContainerManager.java b/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterContainerManager.java deleted file mode 100644 index 627db22a0a..0000000000 --- a/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterContainerManager.java +++ /dev/null @@ -1,21 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.stub.internal; - -import java.net.UnknownHostException; - -import org.opendaylight.controller.clustering.services.IClusterContainerServices; - -public class ClusterContainerManager extends ClusterManagerCommon implements - IClusterContainerServices { - public ClusterContainerManager() throws UnknownHostException { - super(); - } -} diff --git a/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterGlobalManager.java b/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterGlobalManager.java deleted file mode 100644 index 6dcc0a10a3..0000000000 --- a/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterGlobalManager.java +++ /dev/null @@ -1,23 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.stub.internal; - -import java.net.UnknownHostException; - -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; - -public class ClusterGlobalManager extends ClusterManagerCommon implements - IClusterGlobalServices { - public ClusterGlobalManager() throws UnknownHostException { - super(); - } - public void removeContainerCaches(String containerName) { - } -} diff --git a/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterManagerCommon.java b/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterManagerCommon.java deleted file mode 100644 index f27e6f069f..0000000000 --- a/opendaylight/adsal/clustering/stub/src/main/java/org/opendaylight/controller/clustering/stub/internal/ClusterManagerCommon.java +++ /dev/null @@ -1,159 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.stub.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Dictionary; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.TimeUnit; - -import javax.transaction.HeuristicMixedException; -import javax.transaction.HeuristicRollbackException; -import javax.transaction.NotSupportedException; -import javax.transaction.RollbackException; -import javax.transaction.SystemException; -import javax.transaction.Transaction; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.clustering.services.IClusterServicesCommon; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class ClusterManagerCommon implements IClusterServicesCommon { - protected String containerName = ""; - protected static final Logger logger = LoggerFactory - .getLogger(ClusterManagerCommon.class); - private InetAddress loopbackAddress; - private ConcurrentMap> caches = new ConcurrentHashMap>(); - - protected ClusterManagerCommon() throws UnknownHostException { - loopbackAddress = InetAddress.getLoopbackAddress(); - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init(Component c) { - Dictionary props = c.getServiceProperties(); - if (props != null) { - this.containerName = (String) props.get("containerName"); - logger.debug("Running containerName: {}", this.containerName); - } else { - // In the Global instance case the containerName is empty - this.containerName = ""; - } - } - - /** - * Function called by the dependency manager when any of the required - * dependencies are going away - * - */ - void destroy() { - // Clear the caches, will restart on the new life - this.caches.clear(); - } - - @Override - public ConcurrentMap createCache(String cacheName, - Set cMode) throws CacheExistException, - CacheConfigException { - ConcurrentMap res = this.caches.get(cacheName); - if (res == null) { - res = new ConcurrentHashMap(); - this.caches.put(cacheName, res); - return res; - } - throw new CacheExistException(); - } - - @Override - public ConcurrentMap getCache(String cacheName) { - return this.caches.get(cacheName); - } - - @Override - public void destroyCache(String cacheName) { - this.caches.remove(cacheName); - } - - @Override - public boolean existCache(String cacheName) { - return (this.caches.get(cacheName) != null); - } - - @Override - public Set getCacheList() { - return this.caches.keySet(); - } - - @Override - public Properties getCacheProperties(String cacheName) { - return null; - } - - @Override - public void tbegin() throws NotSupportedException, SystemException { - } - - @Override - public void tcommit() throws RollbackException, HeuristicMixedException, - HeuristicRollbackException, java.lang.SecurityException, - java.lang.IllegalStateException, SystemException { - } - - @Override - public void tbegin(long timeout, TimeUnit unit) throws NotSupportedException, SystemException { - - } - - @Override - public void trollback() throws java.lang.IllegalStateException, - java.lang.SecurityException, SystemException { - } - - @Override - public Transaction tgetTransaction() throws SystemException { - return null; - } - - @Override - public List getClusteredControllers() { - List res = new ArrayList(); - res.add(loopbackAddress); - return res; - } - - @Override - public InetAddress getMyAddress() { - return loopbackAddress; - } - - @Override - public InetAddress getCoordinatorAddress() { - return loopbackAddress; - } - - @Override - public boolean amICoordinator() { - return true; - } -} diff --git a/opendaylight/adsal/clustering/stub/src/test/java/org/opendaylight/controller/clustering/stub/internal/TestClusteringStub.java b/opendaylight/adsal/clustering/stub/src/test/java/org/opendaylight/controller/clustering/stub/internal/TestClusteringStub.java deleted file mode 100644 index 93f35ac03d..0000000000 --- a/opendaylight/adsal/clustering/stub/src/test/java/org/opendaylight/controller/clustering/stub/internal/TestClusteringStub.java +++ /dev/null @@ -1,201 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file TestClusteringStub.java - * - * @brief Unit tests for the stub implementation of clustering, - * needed only to run the integration tests - * - * Unit tests for the stub implementation of clustering, - * needed only to run the integration tests - */ -package org.opendaylight.controller.clustering.stub.internal; - -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import java.net.UnknownHostException; -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; - -public class TestClusteringStub { - @Test - public void testStub1() { - IClusterGlobalServices c = null; - ClusterGlobalManager cm = null; - try { - cm = new ClusterGlobalManager(); - c = (IClusterGlobalServices) cm; - } catch (UnknownHostException un) { - // Don't expect this assertion, so if happens signal a - // failure in the testcase - Assert.assertTrue(false); - } - - // Make sure the stub cluster manager is allocated - Assert.assertTrue(cm != null); - Assert.assertTrue(c != null); - - // ======================================== - // Now start testing the several aspects of it. - // ======================================== - - // Allocate few caches - ConcurrentMap c1 = null; - ConcurrentMap c2 = null; - ConcurrentMap c3 = null; - try { - c1 = (ConcurrentMap) c.createCache("c1", null); - } catch (CacheExistException cee) { - // Don't expect this assertion, so if happens signal a - // failure in the testcase - Assert.assertTrue(false); - } catch (CacheConfigException cce) { - // Don't expect this assertion, so if happens signal a - // failure in the testcase - Assert.assertTrue(false); - } - - // Put some data to it - c1.put("FOO", 1); - c1.put("BAZ", 2); - c1.put("BAR", 3); - - try { - c1 = (ConcurrentMap) c.createCache("c1", null); - } catch (CacheExistException cee) { - // This exception should be raised because the cache - // already exists - Assert.assertTrue(true); - } catch (CacheConfigException cce) { - // Don't expect this assertion, so if happens signal a - // failure in the testcase - Assert.assertTrue(false); - } - - // Make sure this cache is retrieved - c1 = (ConcurrentMap) c.getCache("c1"); - Assert.assertTrue(c1 != null); - - // Now make sure the data exists - Integer res = null; - res = c1.get("FOO"); - Assert.assertTrue(res != null); - res = c1.get("BAR"); - Assert.assertTrue(res != null); - res = c1.get("BAZ"); - Assert.assertTrue(res != null); - - // Now create yet another two caches - try { - c2 = (ConcurrentMap) c.createCache("c2", null); - c3 = (ConcurrentMap) c.createCache("c3", null); - } catch (CacheExistException cee) { - // Don't expect this assertion, so if happens signal a - // failure in the testcase - Assert.assertTrue(false); - } catch (CacheConfigException cce) { - // Don't expect this assertion, so if happens signal a - // failure in the testcase - Assert.assertTrue(false); - } - - // Make sure the caches exist - Assert.assertTrue(c2 != null); - Assert.assertTrue(c3 != null); - - // Put some fake data - c2.put("FOO", 11); - c2.put("BAZ", 22); - c2.put("BAR", 33); - - c3.put("FOOBAR", 110); - - // Test for cache existance - Assert.assertTrue(c.existCache("c1")); - Assert.assertTrue(c.existCache("c2")); - Assert.assertTrue(c.existCache("c3")); - - // Get the Cache List - Set caches = c.getCacheList(); - Assert.assertTrue(caches != null); - - // Check if the cachelist is correct - System.out.println("cache size:" + caches.size()); - Assert.assertTrue(caches.size() == 3); - Assert.assertTrue(caches.contains("c1")); - Assert.assertTrue(caches.contains("c2")); - Assert.assertTrue(caches.contains("c3")); - - // Check that the utility API for the cluster are working too - Assert.assertTrue(c.getCoordinatorAddress() != null); - Assert.assertTrue(c.getClusteredControllers() != null); - // This a one man-show - Assert.assertTrue(c.getClusteredControllers().size() == 1); - Assert.assertTrue(c.getMyAddress() != null); - // Make sure i'm the coordinator - Assert.assertTrue(c.amICoordinator()); - - // Now destroy some caches make sure they are gone - c.destroyCache("c1"); - Assert.assertTrue(!c.existCache("c1")); - caches = c.getCacheList(); - Assert.assertTrue(caches.size() == 2); - - // Now recreate the cache, make sure a different one is - // retrieved, which should be empty - try { - c1 = (ConcurrentMap) c.createCache("c1", null); - } catch (CacheExistException cee) { - // This exception should be raised because the cache - // already exists - Assert.assertTrue(true); - } catch (CacheConfigException cce) { - // Don't expect this assertion, so if happens signal a - // failure in the testcase - Assert.assertTrue(false); - } - c1 = (ConcurrentMap) c.getCache("c1"); - Assert.assertTrue(c1 != null); - Assert.assertTrue(c1.keySet().size() == 0); - caches = c.getCacheList(); - Assert.assertTrue(caches.size() == 3); - - // Now destroy the cache manager and make sure things are - // clean - cm.destroy(); - caches = c.getCacheList(); - Assert.assertTrue(caches.size() == 0); - - // Now to re-create two caches and make sure they exists, but - // are different than in previous life - try { - c2 = (ConcurrentMap) c.createCache("c2", null); - c3 = (ConcurrentMap) c.createCache("c3", null); - } catch (CacheExistException cee) { - // Don't expect this assertion, so if happens signal a - // failure in the testcase - Assert.assertTrue(false); - } catch (CacheConfigException cce) { - // Don't expect this assertion, so if happens signal a - // failure in the testcase - Assert.assertTrue(false); - } - Assert.assertTrue(c2 != null); - Assert.assertTrue(c3 != null); - caches = c.getCacheList(); - Assert.assertTrue(caches.size() == 2); - Assert.assertTrue(c2.keySet().size() == 0); - Assert.assertTrue(c3.keySet().size() == 0); - } -} diff --git a/opendaylight/adsal/clustering/test/pom.xml b/opendaylight/adsal/clustering/test/pom.xml deleted file mode 100644 index 6e2c6dc0f9..0000000000 --- a/opendaylight/adsal/clustering/test/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - clustering.test - 0.6.0-SNAPSHOT - bundle - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - equinoxSDK381 - org.apache.felix.gogo.command - - - equinoxSDK381 - org.apache.felix.gogo.runtime - - - equinoxSDK381 - org.apache.felix.gogo.shell - - - equinoxSDK381 - org.eclipse.osgi - - - equinoxSDK381 - org.eclipse.osgi.services - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - sal - - - junit - junit - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.slf4j, - javax.transaction, - org.eclipse.osgi.framework.console, - ch.qos.logback.classic, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.core, - org.apache.felix.dm - org.opendaylight.controller.clustering.test.internal - org.opendaylight.controller.clustering.test.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/Activator.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/Activator.java deleted file mode 100644 index 1c02a1495c..0000000000 --- a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/Activator.java +++ /dev/null @@ -1,57 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.test.internal; - -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.apache.felix.dm.Component; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - public Object[] getGlobalImplementations() { - Object[] res = { SimpleClient.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - */ - public void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(SimpleClient.class)) { - // export the service for Apps and Plugins - c.setInterface(new String[] { org.eclipse.osgi.framework.console.CommandProvider.class.getName() }, - null); - c.add(createServiceDependency().setService(IClusterServices.class) - .setCallbacks("setIClusterServices", "unsetIClusterServices") - .setRequired(true)); - } - } -} diff --git a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass.java deleted file mode 100644 index 51f8128382..0000000000 --- a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass.java +++ /dev/null @@ -1,31 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.test.internal; - -import java.io.Serializable; - -public class ComplexClass implements IComplex, Serializable { - private static final long serialVersionUID = 1L; - private String identity; - - public ComplexClass(String i) { - this.identity = i; - } - - @Override - public String whoAmI() { - return ("ComplexClass_" + this.identity); - } - - @Override - public void IAm(String s) { - this.identity = s; - } -} diff --git a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass1.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass1.java deleted file mode 100644 index 876fb656ac..0000000000 --- a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexClass1.java +++ /dev/null @@ -1,31 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.test.internal; - -import java.io.Serializable; - -public class ComplexClass1 implements IComplex, Serializable { - private static final long serialVersionUID = 1L; - private String identity; - - public ComplexClass1(String i) { - this.identity = i; - } - - @Override - public String whoAmI() { - return ("ComplexClass1_" + this.identity); - } - - @Override - public void IAm(String s) { - this.identity = s; - } -} diff --git a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexContainer.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexContainer.java deleted file mode 100644 index d07c192241..0000000000 --- a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/ComplexContainer.java +++ /dev/null @@ -1,50 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.test.internal; - -import java.io.Serializable; - -public class ComplexContainer implements Serializable { - private static final long serialVersionUID = 1L; - private final IComplex f; - private final IComplex f1; - private final Integer state; - - public ComplexContainer(String i, Integer s) { - this.state = s; - this.f = new ComplexClass(i); - this.f1 = new ComplexClass1(i); - } - - public String getIdentity() { - if (this.f != null && this.f1 != null) { - return ("[" + f.whoAmI() + "]-[" + f1.whoAmI() + "]"); - } - return ""; - } - - public void setIdentity(String i) { - if (this.f != null) { - this.f.IAm(i); - } - if (this.f1 != null) { - this.f1.IAm(i); - } - } - - public Integer getState() { - return this.state; - } - - @Override - public String toString() { - return ("{ID:" + this.getIdentity() + ",STATE:" + this.state + "}"); - } -} diff --git a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/IComplex.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/IComplex.java deleted file mode 100644 index c1d5c31726..0000000000 --- a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/IComplex.java +++ /dev/null @@ -1,16 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.test.internal; - -public interface IComplex { - String whoAmI(); - - void IAm(String s); -} diff --git a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/LoggingListener.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/LoggingListener.java deleted file mode 100644 index 1aef9ce276..0000000000 --- a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/LoggingListener.java +++ /dev/null @@ -1,40 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.test.internal; - -import org.opendaylight.controller.clustering.services.IGetUpdates; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LoggingListener implements IGetUpdates { - protected static Logger logger = LoggerFactory - .getLogger(LoggingListener.class); - - @Override - public void entryCreated(Integer key, String containerName, - String cacheName, boolean originLocal) { - logger.debug(" Cache entry with key " + key + " created in cache " - + cacheName); - } - - @Override - public void entryUpdated(Integer key, StringContainer newValue, - String containerName, String cacheName, boolean originLocal) { - logger.debug(" Cache entry with key " + key + " modified to value " - + newValue + " in cache " + cacheName); - } - - @Override - public void entryDeleted(Integer key, String containerName, - String cacheName, boolean originLocal) { - logger.debug(" Cache entry with key " + key + " removed in cache " - + cacheName); - } -} diff --git a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/SimpleClient.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/SimpleClient.java deleted file mode 100644 index 52cc56e377..0000000000 --- a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/SimpleClient.java +++ /dev/null @@ -1,653 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.test.internal; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.CacheListenerAddException; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.clustering.services.IGetUpdates; -import org.opendaylight.controller.clustering.services.IListenRoleChange; -import org.opendaylight.controller.clustering.services.ListenRoleChangeAddException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SimpleClient implements CommandProvider { - protected static Logger logger = LoggerFactory - .getLogger(SimpleClient.class); - IClusterServices icluster; - DoListenRoleChanged doListen; - - public void _tbegin(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - try { - this.icluster.tbegin(); - ci.println("Transaction Open " - + this.icluster.tgetTransaction().toString()); - } catch (Exception e) { - ci.println("Caught exception during transaction begin: " + e); - } - } - - public void _tcommit(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - try { - ci.println("Committing transaction ....." - + this.icluster.tgetTransaction().toString()); - this.icluster.tcommit(); - ci.println("Transaction Committed"); - } catch (Exception e) { - ci.println("Caught exception during transaction commit: " + e); - } - } - - public void _trollback(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - try { - ci.println("Rolling back transaction ....." - + this.icluster.tgetTransaction().toString()); - this.icluster.trollback(); - ci.println("Transaction Rolled Back"); - } catch (Exception e) { - ci.println("Caught exception during transaction rollback: " + e); - } - } - - public void _cacheinfo(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - if (!this.icluster.existCache(containerName, cacheName)) { - ci.println("\tCache " + cacheName + " doesn't exists"); - return; - } - ci.println("\tInfo for cache " + cacheName + " on container " - + containerName); - Properties p = this.icluster.getCacheProperties(containerName, - cacheName); - if (p != null) { - for (String key : p.stringPropertyNames()) { - ci.println("\t\t" + key + " = " + p.getProperty(key)); - } - } - } - - public void _setLogLevel(CommandInterpreter ci) { - String loggerName = ci.nextArgument(); - if (loggerName == null) { - ci.println("Logger Name not supplied"); - return; - } - String loggerLevel = ci.nextArgument(); - if (loggerLevel == null) { - ci.println("Logger Level not supplied"); - return; - } - - ch.qos.logback.classic.Logger l = (ch.qos.logback.classic.Logger) LoggerFactory - .getLogger(loggerName); - ch.qos.logback.classic.Level level = ch.qos.logback.classic.Level - .toLevel(loggerLevel); - if (level == null) { - ci.println("Level not understood"); - return; - } - l.setLevel(level); - } - - private String retrieveLogLevel(ch.qos.logback.classic.Logger l) { - if (l == null) { - return ("Logger not supplied"); - } - ch.qos.logback.classic.Level level = l.getLevel(); - if (level == null) { - return ("Logger " + l.getName() + " at unknown level"); - } else { - return ("Logger " + l.getName() + " at level " + l.getLevel() - .toString()); - } - } - - public void _getLogLevel(CommandInterpreter ci) { - String loggerName = ci.nextArgument(); - ch.qos.logback.classic.LoggerContext lc = (ch.qos.logback.classic.LoggerContext) LoggerFactory - .getILoggerFactory(); - if (lc != null) { - for (ch.qos.logback.classic.Logger l : lc.getLoggerList()) { - if ((loggerName == null) || l.getName().startsWith(loggerName)) { - ci.println(retrieveLogLevel(l)); - } - } - } - } - - public void _create(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - try { - if (cacheName.startsWith("T-")) { - this.icluster.createCache(containerName, cacheName, EnumSet - .of(IClusterServices.cacheMode.TRANSACTIONAL)); - } else { - this.icluster.createCache(containerName, cacheName, EnumSet - .of(IClusterServices.cacheMode.NON_TRANSACTIONAL)); - } - } catch (CacheExistException ce) { - ci - .println("\nCache already exits - destroy and recreate if needed"); - return; - } catch (CacheConfigException cfe) { - ci.println("\nCache configured with contrasting parameters"); - return; - } - - if (this.icluster.existCache(containerName, cacheName)) { - ci.println(cacheName + " has been created on container " - + containerName); - } - } - - public void _destroy(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - if (this.icluster.existCache(containerName, cacheName)) { - this.icluster.destroyCache(containerName, cacheName); - ci.println(cacheName + " has been destroyed"); - } - } - - public void _listen(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - try { - this.icluster.addListener(containerName, cacheName, - new LoggingListener()); - ci.println("cache " + cacheName + " on container " + containerName - + " is begin monitored for updates"); - } catch (CacheListenerAddException clae) { - ci.println("Couldn't attach the listener to cache " + cacheName - + " on container " + containerName); - } - } - - @SuppressWarnings("deprecation") //IGetUpdates intentionally deprecated - public void _unlisten(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - - Set> listeners = this.icluster.getListeners( - containerName, cacheName); - for (IGetUpdates l : listeners) { - this.icluster.removeListener(containerName, cacheName, l); - } - ci.println(cacheName + " is no longer being monitored for updates"); - } - - public void _myController(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - ci.println("This Controller : " +icluster.getMyAddress().getHostAddress()); - } - - public void _getClusterNodes(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - for (InetAddress address : icluster.getClusteredControllers()) { - ci.println("\t"+address.getHostAddress()); - } - } - - public void _listcaches(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument().toLowerCase(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - - // For user's convenience, let's return the sorted cache list - List sortedCacheList = new ArrayList(this.icluster - .getCacheList(containerName)); - java.util.Collections.sort(sortedCacheList); - for (String cacheName : sortedCacheList) { - ci.println("\t" + cacheName); - } - } - - public void _put(CommandInterpreter ci) { - ConcurrentMap c; - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - String sKey = ci.nextArgument(); - String sValue = ci.nextArgument(); - if (sKey == null) { - ci.println("Key not supplied"); - return; - } - if (sValue == null) { - ci.println("Value not supplied"); - return; - } - Integer key = null; - try { - key = Integer.valueOf(sKey); - } catch (NumberFormatException nfe) { - ci.println("Key is not a valid integer: " + sKey); - } - - c = (ConcurrentMap) this.icluster.getCache( - containerName, cacheName); - if (c != null) { - ci.println("\nAdd mapping " + key + " = " + sValue); - try { - c.put(key, new StringContainer(sValue)); - } catch (Exception e) { - ci.println("Exception raised:" + e); - ci.println("\tStacktrace:"); - e.printStackTrace(); - } - } else { - ci.println("Cache " + cacheName + " on container " + containerName - + " not existant!"); - } - } - - public void _remove(CommandInterpreter ci) { - ConcurrentMap c; - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - String sKey = ci.nextArgument(); - if (sKey == null) { - ci.println("Key not supplied"); - return; - } - Integer key = null; - try { - key = Integer.valueOf(sKey); - } catch (NumberFormatException nfe) { - ci.println("Key is not a valid integer: " + sKey); - } - c = (ConcurrentMap) this.icluster.getCache( - containerName, cacheName); - if (c != null) { - ci.println("\nDelete key " + key); - c.remove(key); - } else { - ci.println("Cache " + cacheName + " on container " + containerName - + " not existant!"); - } - } - - public void _dumper(CommandInterpreter ci) { - ConcurrentMap c; - String containerName = ci.nextArgument().toLowerCase(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - int count = 0; - c = (ConcurrentMap) this.icluster.getCache(containerName, cacheName); - if (c != null) { - for (Map.Entry e : c.entrySet()) { - Map.Entry entry = e; - Object v = entry.getValue(); - String res = ""; - if (v != null) { - res = v.toString(); - } - ci.println("Element " + entry.getKey() + "(hashCode=" - + entry.getKey().hashCode() + ") has value = (" + res - + ")"); - count++; - } - ci.println("Dumped " + count + " records"); - } else { - ci.println("Cache " + cacheName + " on container " + containerName - + " not existant!"); - } - } - - public void _get(CommandInterpreter ci) { - ConcurrentMap c; - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - String sKey = ci.nextArgument(); - if (sKey == null) { - ci.println("Key not supplied"); - return; - } - Integer key = null; - try { - key = Integer.valueOf(sKey); - } catch (NumberFormatException nfe) { - ci.println("Key is not a valid integer: " + sKey); - } - c = (ConcurrentMap) this.icluster.getCache( - containerName, cacheName); - if (c != null) { - ci.println("\nGet key (" + key + ")=(" + c.get(key) + ")"); - } else { - ci.println("Cache " + cacheName + " on container " + containerName - + " not existant!"); - } - } - - @SuppressWarnings("deprecation") //TODO: remove use of deprecated listenRoleChange - public void _listenActive(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - this.doListen = new DoListenRoleChanged(); - try { - this.icluster.listenRoleChange(this.doListen); - } catch (ListenRoleChangeAddException e) { - ci.println("Exception while registering the listener"); - return; - } - ci.println("Register listenRoleChanges"); - } - - @SuppressWarnings("deprecation") //TODO: remove deprecated call to unlistenRoleChange - public void _unlistenActive(CommandInterpreter ci) { - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - if (this.doListen != null) { - this.icluster.unlistenRoleChange(this.doListen); - ci.println("Unregistered Active notifications"); - } - } - - class DoListenRoleChanged implements IListenRoleChange { - @Override - public void newActiveAvailable() { - logger.debug("New Active is available"); - } - } - - public void _putComplex(CommandInterpreter ci) { - ConcurrentMap c; - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - String key = ci.nextArgument(); - if (key == null) { - ci.println("Key not supplied (String)"); - return; - } - String valueIdentity = ci.nextArgument(); - if (valueIdentity == null) { - ci.println("Value for Identity not supplied (String)"); - return; - } - String sValueState = ci.nextArgument(); - if (sValueState == null) { - ci.println("Value for State not supplied (Integer)"); - return; - } - Integer valueState = null; - try { - valueState = Integer.valueOf(sValueState); - } catch (NumberFormatException nfe) { - ci.println("Value State is not a valid integer: " + sValueState); - return; - } - c = (ConcurrentMap) this.icluster - .getCache(containerName, cacheName); - if (c != null) { - c.put(new StringContainer(key), new ComplexContainer(valueIdentity, - valueState)); - ci.println("\nPut in key (" + key + ")={String:" + valueIdentity - + ",Integer:" + valueState + "}"); - } else { - ci.println("Cache " + cacheName + " on container " + containerName - + " not existant!"); - } - } - - public void _updateComplex(CommandInterpreter ci) { - ConcurrentMap c; - if (this.icluster == null) { - ci.println("\nNo Clustering services available"); - return; - } - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.println("containerName not supplied"); - return; - } - String cacheName = ci.nextArgument(); - if (cacheName == null) { - ci.println("Cache not supplied"); - return; - } - String key = ci.nextArgument(); - if (key == null) { - ci.println("Key not supplied (String)"); - return; - } - String valueIdentity = ci.nextArgument(); - if (valueIdentity == null) { - ci.println("Value for Identity not supplied (String)"); - return; - } - c = (ConcurrentMap) this.icluster - .getCache(containerName, cacheName); - if (c != null) { - StringContainer k = new StringContainer(key); - ComplexContainer v = c.get(k); - if (v != null) { - v.setIdentity(valueIdentity); - ci.println("\nUpdate key (" + key + ")={String:" - + valueIdentity + "}"); - - // IMPORTANT ON UPDATING ANY FIELD OF THE CHILD MAKE - // SURE TO PUT THE NEW VALUE IN THE CACHE ELSE THE - // VALUE WILL NOT PROPAGATE!! - c.put(k, v); - } else { - ci.println("\nCannot Update key (" + key - + ") doesn't exist in the database"); - } - } else { - ci.println("Cache " + cacheName + " on container " + containerName - + " not existant!"); - } - } - - public void setIClusterServices(IClusterServices i) { - this.icluster = i; - logger.debug("IClusterServices set"); - } - - public void unsetIClusterServices(IClusterServices i) { - if (this.icluster == i) { - this.icluster = null; - logger.debug("IClusterServices UNset"); - } - } - - public void startUp() { - logger.debug("Started clustering test plugin"); - } - - public void shutDown() { - logger.debug("Stopped clustering test plugin"); - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---Clustering Service Testing---\n"); - help.append("\tput - Put a key,value in the cache\n"); - help.append("\tremove - Delete a key from the cache\n"); - help.append("\tget - Get a key from the cache\n"); - help.append("\tdumper - Dump the cache\n"); - help - .append("\tcacheinfo - Dump the configuration for a cache\n"); - help.append("\ttbegin - Transaction begin\n"); - help.append("\ttcommit - Transaction Commit\n"); - help.append("\ttrollback - Transaction Rollback\n"); - help.append("\tlistcaches - List all the Caches\n"); - help.append("\tlisten - Listen to cache updates\n"); - help.append("\tunlisten - UNListen to cache updates\n"); - help.append("\tlistenActive - Listen to Active updates\n"); - help.append("\tunlistenActive - UNListen to Active updates\n"); - help.append("\tdestroy - Destroy a cache\n"); - help.append("\tcreate - Create a cache\n"); - help.append("\tmyController - Print this controller's Cluster identifier\n"); - help.append("\tgetClusterNodes - Print all the controllers that make this cluster\n"); - help.append("\tputComplex - Fill a more complex data structure\n"); - help.append("\tupdateComplex - Update the value of a more complex data structure\n"); - help.append("\tgetLogLevel - Get the loglevel for the logger specified\n"); - help.append("\tsetLogLevel - Set the loglevel for the logger specified\n"); - return help.toString(); - } -} diff --git a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/StringContainer.java b/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/StringContainer.java deleted file mode 100644 index 7cdb032988..0000000000 --- a/opendaylight/adsal/clustering/test/src/main/java/org/opendaylight/controller/clustering/test/internal/StringContainer.java +++ /dev/null @@ -1,56 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.test.internal; - -import java.io.Serializable; - -public class StringContainer implements Serializable { - private static final long serialVersionUID = 1L; - private String mystring; - - public StringContainer() { - this.mystring = null; - } - - public StringContainer(String s) { - setMystring(s); - } - - public String getMystring() { - return mystring; - } - - public void setMystring(String mystring) { - this.mystring = mystring; - } - - // Return the hashCode of the containing string - @Override - public int hashCode() { - if (this.mystring != null) { - return this.mystring.hashCode(); - } - return 0; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof StringContainer) { - StringContainer o = (StringContainer) obj; - return this.mystring.equals(o.getMystring()); - } - return false; - } - - @Override - public String toString() { - return "{" + this.mystring + "}"; - } -} diff --git a/opendaylight/adsal/clustering/test/src/test/java/org/opendaylight/controller/clustering/test/internal/TestClusteringTest.java b/opendaylight/adsal/clustering/test/src/test/java/org/opendaylight/controller/clustering/test/internal/TestClusteringTest.java deleted file mode 100644 index d143a5171a..0000000000 --- a/opendaylight/adsal/clustering/test/src/test/java/org/opendaylight/controller/clustering/test/internal/TestClusteringTest.java +++ /dev/null @@ -1,65 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.clustering.test.internal; - - -import org.junit.Assert; -import org.junit.Test; - -public class TestClusteringTest { - - @Test - public void testComplexClass() { - ComplexClass cc = new ComplexClass("cplxc1"); - Assert.assertTrue(cc.whoAmI().equals("ComplexClass_cplxc1")); - cc.IAm("cplxc2"); - Assert.assertTrue(cc.whoAmI().equals("ComplexClass_cplxc2")); - } - - @Test - public void testComplexClass1() { - ComplexClass1 cc1 = new ComplexClass1("cplxc1a"); - Assert.assertTrue(cc1.whoAmI().equals("ComplexClass1_cplxc1a")); - cc1.IAm("cplxc1b"); - Assert.assertTrue(cc1.whoAmI().equals("ComplexClass1_cplxc1b")); - } - - - @Test - public void testComplexContainer() { - ComplexContainer cplxcontnr1 = new ComplexContainer("cct1", 5); - Assert.assertTrue(cplxcontnr1.getIdentity().equals("[ComplexClass_cct1]-[ComplexClass1_cct1]")); - Assert.assertTrue(cplxcontnr1.getState() == 5); - - cplxcontnr1.setIdentity("cct2"); - Assert.assertTrue(cplxcontnr1.getIdentity().equals("[ComplexClass_cct2]-[ComplexClass1_cct2]")); - - Assert.assertTrue(cplxcontnr1.toString().equals( - "{ID:[ComplexClass_cct2]-[ComplexClass1_cct2],STATE:5}")); - } - - @Test - public void testStringContainer() { - StringContainer strcontainer1 = new StringContainer(); - Assert.assertTrue(strcontainer1.getMystring() == null); - Assert.assertTrue(strcontainer1.hashCode() == 0); - - StringContainer strcontainer2 = new StringContainer("foo"); - Assert.assertTrue(strcontainer2.getMystring() != null); - Assert.assertTrue(strcontainer2.hashCode() != 0); - - strcontainer1.setMystring("foo"); - Assert.assertTrue(strcontainer2.equals(strcontainer1)); - - Assert.assertTrue(strcontainer2.toString().equals("{foo}")); - } - - -} diff --git a/opendaylight/adsal/commons/httpclient/pom.xml b/opendaylight/adsal/commons/httpclient/pom.xml deleted file mode 100644 index 16f05e0f38..0000000000 --- a/opendaylight/adsal/commons/httpclient/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - commons.httpclient - 0.3.0-SNAPSHOT - bundle - - - commons-logging - commons-logging - 1.1.3 - - - junit - junit - - - org.apache.httpcomponents - httpclient - 4.3 - - - org.apache.httpcomponents - httpcore - 4.3 - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - javax.crypto, - javax.crypto.spec, - javax.net, - javax.net.ssl, - javax.security.auth.x500, - javax.servlet, - org.apache.log4j, - org.ietf.jgss, - !org.apache.commons.codec.*, - !org.apache.log, - !org.apache.avalon.framework.* - org.opendaylight.controller.commons.httpclient - httpclient,httpcore,commons-logging - false - - ${project.basedir}/META-INF - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - true - controller/checkstyle.xml - - - - org.opendaylight.controller - checkstyle - 0.2.0-SNAPSHOT - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPClient.java b/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPClient.java deleted file mode 100644 index 87664f08a5..0000000000 --- a/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPClient.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.commons.httpclient; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; - -import org.apache.http.Header; -import org.apache.http.HeaderIterator; -import org.apache.http.HttpEntity; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; - -public class HTTPClient { - static public HTTPResponse sendRequest(HTTPRequest request) throws Exception { - - CloseableHttpClient httpclient = HttpClients.createDefault(); - if (httpclient == null) - throw new ClientProtocolException("Couldn't create an HTTP client"); - RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(request.getTimeout()) - .setConnectTimeout(request.getTimeout()).build(); - HttpRequestBase httprequest; - String method = request.getMethod(); - - if (method.equalsIgnoreCase("GET")) { - httprequest = new HttpGet(request.getUri()); - } else if (method.equalsIgnoreCase("POST")) { - httprequest = new HttpPost(request.getUri()); - if (request.getEntity() != null) { - StringEntity sentEntity = new StringEntity(request.getEntity()); - sentEntity.setContentType(request.getContentType()); - ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity); - } - } else if (method.equalsIgnoreCase("PUT")) { - httprequest = new HttpPut(request.getUri()); - if (request.getEntity() != null) { - StringEntity sentEntity = new StringEntity(request.getEntity()); - sentEntity.setContentType(request.getContentType()); - ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity); - } - } else if (method.equalsIgnoreCase("DELETE")) { - httprequest = new HttpDelete(request.getUri()); - } else { - httpclient.close(); - throw new IllegalArgumentException("This profile class only supports GET, POST, PUT, and DELETE methods"); - } - httprequest.setConfig(requestConfig); - - // add request headers - Iterator headerIterator = request.getHeaders().keySet().iterator(); - while (headerIterator.hasNext()) { - String header = headerIterator.next(); - Iterator valueIterator = request.getHeaders().get(header).iterator(); - while (valueIterator.hasNext()) { - httprequest.addHeader(header, valueIterator.next()); - } - } - - CloseableHttpResponse response = httpclient.execute(httprequest); - try { - HttpEntity receivedEntity = response.getEntity(); - int httpResponseCode = response.getStatusLine().getStatusCode(); - HTTPResponse ans = new HTTPResponse(); - HashMap> headerMap = new HashMap>(); - - // copy response headers - HeaderIterator it = response.headerIterator(); - while (it.hasNext()) { - Header h = it.nextHeader(); - String name = h.getName(); - String value = h.getValue(); - if (headerMap.containsKey(name)) - headerMap.get(name).add(value); - else { - List list = new ArrayList(); - list.add(value); - headerMap.put(name, list); - } - } - ans.setHeaders(headerMap); - - if (httpResponseCode > 299) { - ans.setStatus(httpResponseCode); - ans.setEntity(response.getStatusLine().getReasonPhrase()); - return ans; - } - ans.setStatus(response.getStatusLine().getStatusCode()); - if (receivedEntity != null) - ans.setEntity(EntityUtils.toString(receivedEntity)); - else - ans.setEntity(null); - return ans; - } finally { - response.close(); - } - } -} diff --git a/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPRequest.java b/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPRequest.java deleted file mode 100644 index 7e39a78372..0000000000 --- a/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPRequest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.commons.httpclient; - -import java.util.List; -import java.util.Map; - - -public class HTTPRequest { - // the HTTP method to use: currently GET, POST, PUT, and DELETE are supported - String method; - - // the full URI to send to (including protocol) - String uri; - - // the entity body to send - String entity; - - // additional headers (separate from content-type) to include in the request - Map> headers; - - // timeout in milliseconds. Defaults to 3 seconds - int timeout; - - // content type to set. Defaults to application/json - String contentType; - - public HTTPRequest() { - timeout = 3000; - contentType = "application/json"; - } - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getEntity() { - return entity; - } - - public void setEntity(String entity) { - this.entity = entity; - } - - public Map> getHeaders() { - return headers; - } - - public void setHeaders(Map> headers) { - this.headers = headers; - } - - public int getTimeout() { - return timeout; - } - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } -} diff --git a/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPResponse.java b/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPResponse.java deleted file mode 100644 index 096fce2662..0000000000 --- a/opendaylight/adsal/commons/httpclient/src/main/java/org/opendaylight/controller/commons/httpclient/HTTPResponse.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.commons.httpclient; - -import java.util.List; -import java.util.Map; - -public class HTTPResponse { - Integer status; // response status - String entity; // response entity - Map> headers; // http header values - - public HTTPResponse() { - } - - public Integer getStatus() { - return status; - } - - public void setStatus(Integer status) { - this.status = status; - } - - public String getEntity() { - return entity; - } - - public void setEntity(String entity) { - this.entity = entity; - } - - public Map> getHeaders() { - return headers; - } - - public void setHeaders(Map> map) { - this.headers = map; - } -} diff --git a/opendaylight/adsal/commons/integrationtest/pom.xml b/opendaylight/adsal/commons/integrationtest/pom.xml deleted file mode 100644 index fbb1d0ea1d..0000000000 --- a/opendaylight/adsal/commons/integrationtest/pom.xml +++ /dev/null @@ -1,142 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - commons.integrationtest - 0.7.0-SNAPSHOT - pom - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - equinoxSDK381 - org.apache.felix.gogo.command - - - equinoxSDK381 - org.apache.felix.gogo.runtime - - - equinoxSDK381 - org.apache.felix.gogo.shell - - - equinoxSDK381 - org.eclipse.equinox.console - - - equinoxSDK381 - org.eclipse.equinox.ds - - - equinoxSDK381 - org.eclipse.equinox.util - - - equinoxSDK381 - org.eclipse.osgi.services - - - junit - junit - - - org.slf4j - log4j-over-slf4j - - - - org.ops4j.pax.exam - pax-exam-junit4 - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - test - - - org.ops4j.pax.url - pax-url-aether - test - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - true - controller/checkstyle.xml - - - - org.opendaylight.controller - checkstyle - 0.2.0-SNAPSHOT - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - - - - org.codehaus.mojo - properties-maven-plugin - ${propertymavenplugin.version} - - - - set-system-properties - - - - - logback.configurationFile - ${project.parent.parent.basedir}/logback.xml - - - - - - - - org.ops4j.pax.exam - maven-paxexam-plugin - - - generate-config - - generate-depends-file - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/configuration/api/pom.xml b/opendaylight/adsal/configuration/api/pom.xml deleted file mode 100644 index 00591e0fdd..0000000000 --- a/opendaylight/adsal/configuration/api/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - configuration - 0.6.0-SNAPSHOT - bundle - - - org.opendaylight.controller - sal - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.sal.utils - org.opendaylight.controller.configuration - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationEvent.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationEvent.java deleted file mode 100644 index a7e936532b..0000000000 --- a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationEvent.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.configuration; - -public enum ConfigurationEvent { - SAVE("Save"), - BACKUP("Backup"), - RESTORE("Restore"), - DELETE("Delete"); - - private ConfigurationEvent(String name) { - this.name = name; - } - - private String name; - - public String toString() { - return name; - } - - public static ConfigurationEvent fromString(String pName) { - for(ConfigurationEvent p:ConfigurationEvent.values()) { - if (p.toString().equals(pName)) { - return p; - } - } - return null; - } -} diff --git a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationObject.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationObject.java deleted file mode 100644 index 7151e561b1..0000000000 --- a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/ConfigurationObject.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration; - -import java.io.Serializable; - -public abstract class ConfigurationObject implements Serializable { - private static final long serialVersionUID = 1L; - private static final String DEFAULT_REGEX = "^[\\w-=\\+\\*\\.\\(\\)\\[\\]\\@\\|\\:]{1,256}$"; - private static final String REGEX_PROP_NAME = "resourceNameRegularExpression"; - private static String regex; - - static { - String customRegex = System.getProperty(REGEX_PROP_NAME); - regex = (customRegex != null) ? customRegex : DEFAULT_REGEX; - } - - /** - * Checks if the provided resource name matches the controller resource name - * regular expression - * - * @param name - * The resource name to test - * @return true if the resource name is not null and matches the controller - * resource name regular expression, false otherwise - */ - protected boolean isValidResourceName(String name) { - return name != null && name.matches(regex); - } - - /** - * Return the regular expression currently in use for testing the controller - * resource names - * - * @return The regular expression - */ - public static String getRegularExpression() { - return regex; - } -} diff --git a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAware.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAware.java deleted file mode 100644 index 1983b012d6..0000000000 --- a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAware.java +++ /dev/null @@ -1,17 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration; - - -/** - * Listener Interface for receiving Configuration events. - */ -public interface IConfigurationAware extends IConfigurationAwareCommon { -} diff --git a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAwareCommon.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAwareCommon.java deleted file mode 100644 index c909bff4c4..0000000000 --- a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationAwareCommon.java +++ /dev/null @@ -1,25 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration; - -import org.opendaylight.controller.sal.utils.Status; - - -/** - * Listener Interface for receiving Configuration events. - */ -public interface IConfigurationAwareCommon { - /** - * Trigger from Configuration Service or Container Configuration Service to - * persist the configuration state for this component on the local cluster - * node - */ - Status saveConfiguration(); -} diff --git a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerAware.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerAware.java deleted file mode 100644 index f759315ec7..0000000000 --- a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerAware.java +++ /dev/null @@ -1,18 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration; - - -/** - * Listener Interface for receiving Configuration events for components that - * live in a container - */ -public interface IConfigurationContainerAware extends IConfigurationAwareCommon { -} diff --git a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerService.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerService.java deleted file mode 100644 index b8461ce3b3..0000000000 --- a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationContainerService.java +++ /dev/null @@ -1,34 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration; - -/** - * Container configuration service - */ -public interface IConfigurationContainerService extends IConfigurationServiceCommon { - - /** - * This function returns the path to the configuration directory of the - * current container. - * - * @return The path to active container's configuration directory - */ - public String getConfigurationRoot(); - - /** - * Function checks whether there exists a saved configuration for this - * container (This is essentially checking whether the container's root - * configuration directory exists) - * - * @return True iff container config has been saved at least once - */ - public boolean hasBeenSaved(); - -} diff --git a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationService.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationService.java deleted file mode 100644 index d892a59f83..0000000000 --- a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationService.java +++ /dev/null @@ -1,17 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration; - - -/** - * Configuration Service interface - */ -public interface IConfigurationService extends IConfigurationServiceCommon { -} diff --git a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationServiceCommon.java b/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationServiceCommon.java deleted file mode 100644 index bbc9ee1ee8..0000000000 --- a/opendaylight/adsal/configuration/api/src/main/java/org/opendaylight/controller/configuration/IConfigurationServiceCommon.java +++ /dev/null @@ -1,61 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration; - -import java.util.List; - -import org.opendaylight.controller.sal.utils.IObjectReader; -import org.opendaylight.controller.sal.utils.Status; - -/** - * Common configuration interface for Configuration Service and Container - * Configuration Service - */ -public interface IConfigurationServiceCommon { - /** - * Represent the trigger to save the controller configuration cluster wide. - * When called on IConfigurationService, it will trigger a cluster wide save - * configuration event for all the global instance components and all - * components in all containers. When called on - * IContainerConfigurationService, it will trigger a cluster wide save - * configuration event for all components in the current container. - * - * @return the Status object representing the result of the saving request - */ - Status saveConfigurations(); - - /** - * Bundle will call this function to ask Configuration Manager to persist - * their configurations. It is up to the Configuration Manager to decide - * how the configuration will be persisted - * - * @param config - * The bundle configuration as a collection of - * ConfigurationObject - * @param storeName - * The identifier for this configuration - * @return The Status of the operation - */ - Status persistConfiguration(List config, String storeName); - - /** - * Bundle will call this function to ask Configuration Manager to retrieve - * the configuration identified by the passed store name - * - * @param reader - * The reader object for parsing the configuration provided by - * the caller - * @param storeName - * The identifier for the configuration - * @return The retrieved configuration as a collection of - * ConfigurationObject - */ - List retrieveConfiguration(IObjectReader reader, String storeName); -} diff --git a/opendaylight/adsal/configuration/implementation/pom.xml b/opendaylight/adsal/configuration/implementation/pom.xml deleted file mode 100644 index 8ea8997004..0000000000 --- a/opendaylight/adsal/configuration/implementation/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - configuration.implementation - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - sal - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.configuration, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.core, - org.osgi.framework, - org.slf4j, - org.apache.felix.dm - - org.opendaylight.controller.configuration.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/Activator.java b/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/Activator.java deleted file mode 100644 index c798eeb05d..0000000000 --- a/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/Activator.java +++ /dev/null @@ -1,144 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration.internal; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.configuration.IConfigurationAware; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.configuration.IConfigurationService; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @file Activator.java - * - * @brief Component Activator for ConfigurationService Management. - * - * - * - */ -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { ContainerConfigurationService.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(ContainerConfigurationService.class)) { - Dictionary> props = new Hashtable>(); - Set propSet = new HashSet(); - propSet.add(ContainerConfigurationService.CONTAINER_SAVE_EVENT_CACHE); - props.put("cachenames", propSet); - - // export the service - c.setInterface( - new String[] { IConfigurationContainerService.class.getName(), IConfigurationAware.class.getName(), - ICacheUpdateAware.class.getName() }, props); - - c.add(createContainerServiceDependency(containerName).setService( - IConfigurationContainerAware.class).setCallbacks( - "addConfigurationContainerAware", - "removeConfigurationContainerAware").setRequired(false)); - - c.add(createContainerServiceDependency(containerName).setService(IClusterContainerServices.class) - .setCallbacks("setClusterServices", "unsetClusterServices").setRequired(true)); - } - } - - /** - * Method which tells how many Global implementations are - * supported by the bundle. This way we can tune the number of - * components created. This components will be created ONLY at the - * time of bundle startup and will be destroyed only at time of - * bundle destruction, this is the major difference with the - * implementation retrieved via getImplementations where all of - * them are assumed to be in a container! - * - * - * @return The list of implementations the bundle will support, - * in Global version - */ - @Override - protected Object[] getGlobalImplementations() { - Object[] res = { ConfigurationService.class }; - return res; - } - - /** - * Configure the dependency for a given instance Global - * - * @param c Component assigned for this instance, this will be - * what will be used for configuration - * @param imp implementation to be configured - * @param containerName container on which the configuration happens - */ - @Override - protected void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(ConfigurationService.class)) { - Dictionary> props = new Hashtable>(); - Set propSet = new HashSet(); - propSet.add(ConfigurationService.SAVE_EVENT_CACHE); - props.put("cachenames", propSet); - - // export the service - c.setInterface( - new String[] { IConfigurationService.class.getName(), - ICacheUpdateAware.class.getName() }, props); - - c.add(createServiceDependency().setService( - IClusterGlobalServices.class).setCallbacks( - "setClusterServices", "unsetClusterServices").setRequired( - true)); - - c.add(createServiceDependency().setService( - IConfigurationAware.class).setCallbacks( - "addConfigurationAware", "removeConfigurationAware") - .setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ConfigurationService.java b/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ConfigurationService.java deleted file mode 100644 index de7621110e..0000000000 --- a/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ConfigurationService.java +++ /dev/null @@ -1,260 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration.internal; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.configuration.ConfigurationEvent; -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.configuration.IConfigurationAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.configuration.IConfigurationService; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.IObjectReader; -import org.opendaylight.controller.sal.utils.ObjectReader; -import org.opendaylight.controller.sal.utils.ObjectWriter; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @file ConfigurationImpl.java - * - * @brief Backend functionality for all ConfigurationService related tasks. - * - */ - -public class ConfigurationService implements IConfigurationService, ICacheUpdateAware { - private static final Logger logger = LoggerFactory - .getLogger(ConfigurationService.class); - public static final String SAVE_EVENT_CACHE = "config.event.save"; - private static final String ROOT = GlobalConstants.STARTUPHOME.toString(); - private IClusterGlobalServices clusterServices; - private ConcurrentMap configEvent; - private Set configurationAwareList = Collections - .synchronizedSet(new HashSet()); - private ObjectReader objReader; - private ObjectWriter objWriter; - - - public int getConfigurationAwareListSize() { - return this.configurationAwareList.size(); - } - - public void addConfigurationAware(IConfigurationAware configurationAware) { - if (!this.configurationAwareList.contains(configurationAware)) { - this.configurationAwareList.add(configurationAware); - } - } - - public void removeConfigurationAware(IConfigurationAware configurationAware) { - this.configurationAwareList.remove(configurationAware); - } - - public void setClusterServices(IClusterGlobalServices i) { - this.clusterServices = i; - logger.debug("IClusterServices set"); - } - - public void unsetClusterServices(IClusterGlobalServices i) { - if (this.clusterServices == i) { - this.clusterServices = null; - logger.debug("IClusterServices Unset"); - } - } - - public void init() { - logger.info("ConfigurationService Manager init"); - - // Create the default startup directory, so that container unaware apps can initiate save - createContainerDirectory(ROOT + GlobalConstants.DEFAULT.toString()); - } - - public void start() { - allocateCache(); - retrieveCache(); - objReader = new ObjectReader(); - objWriter = new ObjectWriter(); - } - - public void destroy() { - // Clear local states - this.configurationAwareList.clear(); - } - - @Override - public Status saveConfigurations() { - if (configEvent != null) { - configEvent.put(ConfigurationEvent.SAVE.toString(), ""); - } - return saveConfigurationsInternal(); - } - - - private List getContainerDirectoryList() { - List containerList = new ArrayList(); - for (IConfigurationAware configurationAware : this.configurationAwareList) { - if (configurationAware instanceof IConfigurationContainerService) { - String containerFilePath = ((IConfigurationContainerService)configurationAware).getConfigurationRoot(); - containerList.add(containerFilePath); - } - } - return containerList; - } - - private void createContainerDirectory(IConfigurationAware configurationAware) { - String containerFilePath = ((IConfigurationContainerService) configurationAware).getConfigurationRoot(); - createContainerDirectory(containerFilePath); - } - - private void createContainerDirectory(String containerFilePath) { - - try { - if (!new File(containerFilePath).exists()) { - boolean created = new File(containerFilePath).mkdir(); - if (!created) { - logger.error("Failed to create config directory: {}", containerFilePath); - } - } - } catch (Exception e) { - logger.error("Failed to create config directory: {} ({})", containerFilePath, e.getMessage()); - } - } - - private void clearStaleContainerDirectories() { - List activeContainers = getContainerDirectoryList(); - for (File file : new File(ROOT).listFiles()) { - if (file.isDirectory() && !activeContainers.contains(file.toPath() + File.separator)) { - logger.trace("Removing directory for container {}", file.getName()); - for (File innerFile : file.listFiles()) { - innerFile.delete(); - } - boolean removed = file.delete(); - if (!removed) { - logger.warn("Failed to remove stale directory: {}", file.getName()); - } - } - } - } - - - private Status saveConfigurationsInternal() { - boolean success = true; - for (IConfigurationAware configurationAware : configurationAwareList) { - if (configurationAware instanceof IConfigurationContainerService) { - // Create directory for new containers - createContainerDirectory(configurationAware); - } - Status status = configurationAware.saveConfiguration(); - if (!status.isSuccess()) { - success = false; - logger.warn("Failed to save config for {}", configurationAware.getClass().getName()); - } - } - // Remove startup directories of containers that were removed from - // the configuration but not saved - clearStaleContainerDirectories(); - - if (success) { - return new Status(StatusCode.SUCCESS); - } else { - return new Status(StatusCode.INTERNALERROR, "Failed to Save All Configurations"); - } - } - - @Override - public void entryCreated(String key, String cacheName, - boolean originLocal) { - if (originLocal) { - return; - } - } - - @Override - public void entryUpdated(String key, String new_value, - String cacheName, boolean originLocal) { - if (originLocal) { - return; - } - if (key.equals(ConfigurationEvent.SAVE.toString())) { - saveConfigurationsInternal(); - } - } - - @Override - public void entryDeleted(String key, String cacheName, - boolean originLocal) { - if (originLocal) { - return; - } - } - - private void allocateCache() { - if (this.clusterServices == null) { - logger.error("uninitialized clusterServices, can't create cache"); - return; - } - try { - this.clusterServices.createCache(SAVE_EVENT_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheConfigException cce) { - logger.debug("Error creating ConfigurationService cache ", cce); - } catch (CacheExistException cce) { - logger.debug("ConfigurationService Cache already exists, destroy and recreate ", cce); - } - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCache() { - if (this.clusterServices == null) { - logger.error("uninitialized clusterServices, can't retrieve cache"); - return; - } - configEvent = (ConcurrentMap) this.clusterServices.getCache(SAVE_EVENT_CACHE); - if (configEvent == null) { - logger.error("Failed to retrieve configuration Cache"); - } - } - - @Override - public Status persistConfiguration(List config, String fileName) { - String destination = String.format("%s%s", ROOT, fileName); - return objWriter.write(config, destination); - } - - @Override - public List retrieveConfiguration(IObjectReader reader, String fileName) { - if (!clusterServices.amICoordinator()) { - return Collections.emptyList(); - } - String source = String.format("%s%s", ROOT, fileName); - Object obj = objReader.read(reader, source); - if (obj == null) { - return Collections. emptyList(); - } - if (obj instanceof ConcurrentMap) { - return new ArrayList(((ConcurrentMap)obj).values()); - } - return (List) obj; - } -} diff --git a/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ContainerConfigurationService.java b/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ContainerConfigurationService.java deleted file mode 100644 index dcab1f63fb..0000000000 --- a/opendaylight/adsal/configuration/implementation/src/main/java/org/opendaylight/controller/configuration/internal/ContainerConfigurationService.java +++ /dev/null @@ -1,242 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration.internal; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Dictionary; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.configuration.ConfigurationEvent; -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.configuration.IConfigurationAware; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.IObjectReader; -import org.opendaylight.controller.sal.utils.ObjectReader; -import org.opendaylight.controller.sal.utils.ObjectWriter; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @file ConfigurationImpl.java - * - * @brief Backend functionality for all ConfigurationService related tasks. - * - */ - -public class ContainerConfigurationService implements IConfigurationContainerService, - IConfigurationAware, - ICacheUpdateAware { - public static final String CONTAINER_SAVE_EVENT_CACHE = "config.container.event.save"; - private static final Logger logger = LoggerFactory.getLogger(ContainerConfigurationService.class); - private IClusterContainerServices clusterServices; - private ConcurrentMap containerConfigEvent; - // Directory which contains the startup files for this container - private String root; - private Set configurationAwareList = Collections - .synchronizedSet(new HashSet()); - private ObjectReader objReader; - private ObjectWriter objWriter; - private String containerName; - - public void addConfigurationContainerAware( - IConfigurationContainerAware configurationAware) { - if (!this.configurationAwareList.contains(configurationAware)) { - this.configurationAwareList.add(configurationAware); - } - } - - public int getConfigurationAwareListSize() { - return this.configurationAwareList.size(); - } - - public void removeConfigurationContainerAware( - IConfigurationContainerAware configurationAware) { - this.configurationAwareList.remove(configurationAware); - } - - public void setClusterServices(IClusterContainerServices i) { - this.clusterServices = i; - logger.debug("IClusterServices set"); - } - - public void unsetClusterServices(IClusterContainerServices i) { - if (this.clusterServices == i) { - this.clusterServices = null; - logger.debug("IClusterServices Unset"); - } - } - - void init(Component c) { - Dictionary props = c.getServiceProperties(); - containerName = (props != null) ? (String) props.get("containerName") : - GlobalConstants.DEFAULT.toString(); - root = String.format("%s%s/", GlobalConstants.STARTUPHOME.toString(), containerName); - } - - public void start() { - allocateCache(); - retrieveCache(); - objReader = new ObjectReader(); - objWriter = new ObjectWriter(); - } - - public void destroy() { - // Clear local states - this.configurationAwareList.clear(); - } - - /** - * Function called by the dependency manager before Container is Stopped and Destroyed. - */ - public void containerStop() { - // Do nothing - } - - @Override - public String getConfigurationRoot() { - return root; - } - - @Override - public Status saveConfiguration() { - boolean success = true; - - for (IConfigurationContainerAware configurationAware : configurationAwareList) { - logger.trace("Save Config triggered for {}", configurationAware.getClass().getSimpleName()); - - Status status = configurationAware.saveConfiguration(); - if (!status.isSuccess()) { - success = false; - logger.warn("Failed to save config for {} ({})", configurationAware.getClass().getSimpleName(), - status.getDescription()); - } - } - if (success) { - return new Status(StatusCode.SUCCESS); - } else { - return new Status(StatusCode.INTERNALERROR, "Failed to save one or more configurations"); - } - } - - @Override - public Status saveConfigurations() { - containerConfigEvent.put(ConfigurationEvent.SAVE.toString(), ""); - return saveConfiguration(); - } - - @Override - public void entryCreated(String key, String cacheName, - boolean originLocal) { - if (originLocal) { - return; - } - } - - @Override - public void entryUpdated(String key, String new_value, - String cacheName, boolean originLocal) { - if (originLocal) { - return; - } - logger.debug("Processing {} event", key); - if (key.equals(ConfigurationEvent.SAVE.toString())) { - saveConfiguration(); - } - } - - @Override - public void entryDeleted(String key, String cacheName, - boolean originLocal) { - if (originLocal) { - return; - } - } - - private void allocateCache() { - if (this.clusterServices == null) { - logger.error("uninitialized clusterServices, can't create cache"); - return; - } - try { - this.clusterServices.createCache(CONTAINER_SAVE_EVENT_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheConfigException cce) { - logger.debug("Error creating ContainerConfigurationService cache ", cce); - } catch (CacheExistException cce) { - logger.debug("ConfigurationService Cache already exists, destroy and recreate ", cce); - } - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCache() { - if (this.clusterServices == null) { - logger.error("uninitialized clusterServices, can't retrieve cache"); - return; - } - containerConfigEvent = - (ConcurrentMap) this.clusterServices.getCache(CONTAINER_SAVE_EVENT_CACHE); - if (containerConfigEvent == null) { - logger.error("Failed to retrieve configuration Cache"); - } - } - - @Override - public Status persistConfiguration(List config, String fileName) { - if (!hasBeenSaved()) { - return new Status(StatusCode.NOTALLOWED, - String.format("Container %s has not been saved yet", containerName)); - } - String destination = String.format("%s%s", root, fileName); - return objWriter.write(config, destination); - } - - @Override - public List retrieveConfiguration(IObjectReader reader, String fileName) { - if (!clusterServices.amICoordinator()) { - return Collections.emptyList(); - } - String source = String.format("%s%s", root, fileName); - Object obj = objReader.read(reader, source); - if (obj == null) { - return Collections. emptyList(); - } - if (obj instanceof ConcurrentMap) { - return new ArrayList(((ConcurrentMap)obj).values()); - } - return (List) obj; - } - - @Override - public boolean hasBeenSaved() { - try { - File configRoot = new File(this.getConfigurationRoot()); - return configRoot.exists(); - } catch (Exception e) { - return false; - } - - } -} diff --git a/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationAwareTest.java b/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationAwareTest.java deleted file mode 100644 index 185fb17a61..0000000000 --- a/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationAwareTest.java +++ /dev/null @@ -1,32 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration.internal; - -import org.opendaylight.controller.configuration.IConfigurationAware; -import org.opendaylight.controller.sal.utils.Status; - -/** - * @file TestConfigurationAware.java - * - * @brief Test Class to create for jUnit test cases for ConfigurationService Implementation - * - * - */ - -public class ConfigurationAwareTest implements -IConfigurationAware { - - @Override - public Status saveConfiguration() { - return null; - } - - -} diff --git a/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerAwareTest.java b/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerAwareTest.java deleted file mode 100644 index ff627aa13d..0000000000 --- a/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerAwareTest.java +++ /dev/null @@ -1,35 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration.internal; - -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.sal.utils.Status; - -/** - * @file TestConfigurationAware.java - * - * @brief Test Class to create for jUnit test cases for ConfigurationService Implementation - * - * - */ - -public class ConfigurationContainerAwareTest implements - IConfigurationContainerAware { - - - - - @Override - public Status saveConfiguration() { - return null; - } - - -} diff --git a/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerImplTest.java b/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerImplTest.java deleted file mode 100644 index baf30041a6..0000000000 --- a/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationContainerImplTest.java +++ /dev/null @@ -1,65 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration.internal; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; - - - -public class ConfigurationContainerImplTest { - - - @Test - public void testAddRemoveSaveConfiguration() { - - ContainerConfigurationService configurationContainerImpl = new ContainerConfigurationService(); - IConfigurationContainerAware testConfigurationContainerAware = new ConfigurationContainerAwareTest(); - - configurationContainerImpl.addConfigurationContainerAware(testConfigurationContainerAware); - configurationContainerImpl.addConfigurationContainerAware(testConfigurationContainerAware); - - Assert.assertEquals(1, configurationContainerImpl.getConfigurationAwareListSize()); - - IConfigurationContainerAware testConfigurationAware1 = new ConfigurationContainerAwareTest(); - configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware1); - - Assert.assertEquals(2, configurationContainerImpl.getConfigurationAwareListSize()); - - IConfigurationContainerAware testConfigurationAware2 = new ConfigurationContainerAwareTest(); - configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware2); - - Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize()); - - IConfigurationContainerAware testConfigurationAware3 = new ConfigurationContainerAwareTest(); - configurationContainerImpl.addConfigurationContainerAware(testConfigurationAware3); - - Assert.assertEquals(4, configurationContainerImpl.getConfigurationAwareListSize()); - - configurationContainerImpl.removeConfigurationContainerAware(testConfigurationContainerAware); - Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize()); - - configurationContainerImpl.removeConfigurationContainerAware(testConfigurationContainerAware); - Assert.assertEquals(3, configurationContainerImpl.getConfigurationAwareListSize()); - - configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware3); - Assert.assertEquals(2, configurationContainerImpl.getConfigurationAwareListSize()); - - configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware2); - Assert.assertEquals(1, configurationContainerImpl.getConfigurationAwareListSize()); - - configurationContainerImpl.removeConfigurationContainerAware(testConfigurationAware1); - Assert.assertEquals(0, configurationContainerImpl.getConfigurationAwareListSize()); - - - } - -} diff --git a/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationImplTest.java b/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationImplTest.java deleted file mode 100644 index f9811006ce..0000000000 --- a/opendaylight/adsal/configuration/implementation/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationImplTest.java +++ /dev/null @@ -1,63 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.configuration.internal; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.configuration.IConfigurationAware; - -public class ConfigurationImplTest { - - - @Test - public void testAddRemoveSaveConfiguration() { - - ConfigurationService configurationImpl = new ConfigurationService(); - IConfigurationAware testConfigurationAware = new ConfigurationAwareTest(); - - configurationImpl.addConfigurationAware(testConfigurationAware); - configurationImpl.addConfigurationAware(testConfigurationAware); - - Assert.assertEquals(1, configurationImpl.getConfigurationAwareListSize()); - - ConfigurationAwareTest testConfigurationAware1 = new ConfigurationAwareTest(); - configurationImpl.addConfigurationAware(testConfigurationAware1); - - Assert.assertEquals(2, configurationImpl.getConfigurationAwareListSize()); - - ConfigurationAwareTest testConfigurationAware2 = new ConfigurationAwareTest(); - configurationImpl.addConfigurationAware(testConfigurationAware2); - - Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize()); - - ConfigurationAwareTest testConfigurationAware3 = new ConfigurationAwareTest(); - configurationImpl.addConfigurationAware(testConfigurationAware3); - - Assert.assertEquals(4, configurationImpl.getConfigurationAwareListSize()); - - - configurationImpl.removeConfigurationAware(testConfigurationAware); - Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize()); - - configurationImpl.removeConfigurationAware(testConfigurationAware); - Assert.assertEquals(3, configurationImpl.getConfigurationAwareListSize()); - - configurationImpl.removeConfigurationAware(testConfigurationAware3); - Assert.assertEquals(2, configurationImpl.getConfigurationAwareListSize()); - - configurationImpl.removeConfigurationAware(testConfigurationAware1); - Assert.assertEquals(1, configurationImpl.getConfigurationAwareListSize()); - - configurationImpl.removeConfigurationAware(testConfigurationAware2); - Assert.assertEquals(0, configurationImpl.getConfigurationAwareListSize()); - - } - -} diff --git a/opendaylight/adsal/configuration/integrationtest/.gitignore b/opendaylight/adsal/configuration/integrationtest/.gitignore deleted file mode 100644 index f92f36385a..0000000000 --- a/opendaylight/adsal/configuration/integrationtest/.gitignore +++ /dev/null @@ -1 +0,0 @@ -configuration diff --git a/opendaylight/adsal/configuration/integrationtest/pom.xml b/opendaylight/adsal/configuration/integrationtest/pom.xml deleted file mode 100644 index 5ae64e75d7..0000000000 --- a/opendaylight/adsal/configuration/integrationtest/pom.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.integrationtest - 0.7.0-SNAPSHOT - ../../commons/integrationtest - - - configuration.integrationtest - 0.6.0-SNAPSHOT - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - eclipselink - javax.resource - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - clustering.services-implementation - - - org.opendaylight.controller - clustering.stub - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - configuration.implementation - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.it.implementation - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - protocol_plugins.stub - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.implementation - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - switchmanager.implementation - - - org.opendaylight.controller - topologymanager - - - org.slf4j - log4j-over-slf4j - - - junit - junit - test - - - - org.ops4j.pax.exam - pax-exam-container-native - test - - - org.ops4j.pax.exam - pax-exam-junit4 - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - test - - - org.ops4j.pax.url - pax-url-aether - test - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/configuration/integrationtest/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationIT.java b/opendaylight/adsal/configuration/integrationtest/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationIT.java deleted file mode 100644 index eb9ce47507..0000000000 --- a/opendaylight/adsal/configuration/integrationtest/src/test/java/org/opendaylight/controller/configuration/internal/ConfigurationIT.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.configuration.internal; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; -import static org.ops4j.pax.exam.CoreOptions.options; -import static org.ops4j.pax.exam.CoreOptions.systemPackages; -import static org.ops4j.pax.exam.CoreOptions.systemProperty; - -import java.io.File; - -import javax.inject.Inject; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.configuration.IConfigurationService; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.util.PathUtils; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(PaxExam.class) -public class ConfigurationIT { - private final Logger logger = LoggerFactory - .getLogger(ConfigurationIT.class); - // get the OSGI bundle context - @Inject - private BundleContext bc; - private IConfigurationService configService = null; - - // Configure the OSGi container - @Configuration - public Option[] config() { - return options( - systemProperty("logback.configurationFile").value( - "file:" + PathUtils.getBaseDir() - + "/src/test/resources/logback.xml"), - // To start OSGi console for inspection remotely - systemProperty("osgi.console").value("2401"), - // Set the systemPackages (used by clustering) - systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"), - // List framework bundles - mavenBundle("equinoxSDK381", "org.eclipse.equinox.console").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.util").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.osgi.services").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell").versionAsInProject(), - // List logger bundles - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), - mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(), - mavenBundle("org.jboss.spec.javax.transaction", "jboss-transaction-api_1.1_spec").versionAsInProject(), - mavenBundle("eclipselink", "javax.resource").versionAsInProject(), - mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager").versionAsInProject(), - // List all the bundles on which the test case depends - mavenBundle("org.opendaylight.controller", "sal").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "protocol_plugins.stub").versionAsInProject(), - // needed bundles by switchmanager - mavenBundle("org.opendaylight.controller", "containermanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "containermanager.it.implementation").versionAsInProject(), - // needed bundles by configuration - mavenBundle("org.opendaylight.controller", "clustering.services").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "clustering.stub").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "configuration").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "configuration.implementation").versionAsInProject(), - junitBundles()); - } - - private String stateToString(int state) { - switch (state) { - case Bundle.ACTIVE: - return "ACTIVE"; - case Bundle.INSTALLED: - return "INSTALLED"; - case Bundle.RESOLVED: - return "RESOLVED"; - case Bundle.UNINSTALLED: - return "UNINSTALLED"; - default: - return "Not CONVERTED"; - } - } - - @Before - public void areWeReadyForClustering() { - assertNotNull(bc); - boolean debugit = false; - Bundle b[] = bc.getBundles(); - for (int i = 0; i < b.length; i++) { - int state = b[i].getState(); - if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) { - logger.debug("Bundle:" + b[i].getSymbolicName() + " state:" - + stateToString(state)); - debugit = true; - } - } - if (debugit) { - logger.debug("Do some debugging because some bundle is unresolved"); - } - - // Assert if true, if false we are good to go! - assertFalse(debugit); - } - - @Before - public void areWeReadyForConfiguration() { - assertNotNull(bc); - boolean debugit = false; - Bundle b[] = bc.getBundles(); - for (int i = 0; i < b.length; i++) { - int state = b[i].getState(); - if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) { - logger.debug("Bundle:" + b[i].getSymbolicName() + " state:" - + stateToString(state)); - debugit = true; - } - } - if (debugit) { - logger.debug("Do some debugging because some bundle is unresolved"); - } - - // Assert if true, if false we are good to go! - assertFalse(debugit); - ServiceReference r = bc.getServiceReference(IConfigurationService.class - .getName()); - if (r != null) { - this.configService = (IConfigurationService) bc.getService(r); - } - // If StatisticsManager is null, cannot run tests. - assertNotNull(this.configService); - - } - - @Test - public void saveConfiguration() { - File f = new File(GlobalConstants.STARTUPHOME.toString()); - boolean success = f.exists(); - if (!success) { - success = f.mkdirs(); - } - if(success){ - Status status = new Status(StatusCode.SUCCESS, null); - if (this.configService != null) { - status = this.configService.saveConfigurations(); - } - if (status.getCode().equals(StatusCode.SUCCESS)) { - Assert.assertTrue("Successfully saved config for " - + configService.getClass().getSimpleName(), status - .getCode().equals(StatusCode.SUCCESS)); - } else { - Assert.assertFalse("Failed to save config for " - + configService.getClass().getSimpleName(), status - .getCode().equals(StatusCode.INTERNALERROR)); - } - } - } - -} diff --git a/opendaylight/adsal/configuration/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/configuration/integrationtest/src/test/resources/logback.xml deleted file mode 100644 index 2d63ce5744..0000000000 --- a/opendaylight/adsal/configuration/integrationtest/src/test/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/opendaylight/adsal/connectionmanager/api/pom.xml b/opendaylight/adsal/connectionmanager/api/pom.xml deleted file mode 100644 index 21f4df1f9e..0000000000 --- a/opendaylight/adsal/connectionmanager/api/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - connectionmanager - 0.3.0-SNAPSHOT - bundle - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.connection - org.opendaylight.controller.connectionmanager - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/ConnectionMgmtScheme.java b/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/ConnectionMgmtScheme.java deleted file mode 100644 index 49e77b2d1c..0000000000 --- a/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/ConnectionMgmtScheme.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.connectionmanager; - -/** - * Enumeration that represents the Connectivity Scheme / Algorithm for South-Bound nodes - * towards an Active-Active Clustered Controllers. - */ -public enum ConnectionMgmtScheme { - /** - * All the nodes are connected with a Single Controller. - * The SingleControllerScheme algorithm will determine that one controller to which all - * the nodes are connected with. - * This is like Active-Standby model from a South-Bound perspective. - */ - SINGLE_CONTROLLER("All nodes connected with a Single Controller"), - - /** - * Any node can be connected with any controller. But with just 1 master controller. - */ - ANY_CONTROLLER_ONE_MASTER("Nodes can to connect with any controller in the cluster"), - - /** - * Simple Round Robin Scheme that will let the nodes connect with each controller in - * Active-Active cluster in a round robin fashion. - */ - ROUND_ROBIN("Each node is connected with individual Controller in Round-Robin fashion"), - - /** - * Complex Load Balancing scheme that will let the nodes connect with controller based - * on the resource usage in each of the controllers in a cluster. - */ - LOAD_BALANCED("Connect nodes to controllers based on the Controller Load"), - - /** - * Container based scheme will let the nodes connect with controller based - * on the container configuration. - */ - CONTAINER_BASED("Connect nodes to controllers based on Container they belong to"); - - private ConnectionMgmtScheme(String name) { - this.name = name; - } - - private String name; - - public String toString() { - return name; - } - - public static ConnectionMgmtScheme fromString(String pName) { - for(ConnectionMgmtScheme p:ConnectionMgmtScheme.values()) { - if (p.toString().equals(pName)) { - return p; - } - } - return null; - } -} diff --git a/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/IConnectionManager.java b/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/IConnectionManager.java deleted file mode 100644 index c7e7fa4770..0000000000 --- a/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/IConnectionManager.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.connectionmanager; - -import java.net.InetAddress; -import java.util.Map; -import java.util.Set; - -import org.opendaylight.controller.sal.connection.ConnectionConstants; -import org.opendaylight.controller.sal.connection.ConnectionLocality; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.Status; - -/** - * Connection Manager provides south-bound connectivity services. The APIs are - * currently focused towards Active-Active Clustering support wherein the node - * can connect to any of the Active Controller in the Cluster. This component - * can also host the necessary logic for south-bound connectivity when partial - * cluster is identified during Partition scenarios. - * - * This (and its corresponding implementation) component can also be enhanced - * further for more fancy algorithms/criteria for connection acceptance. - */ - -public interface IConnectionManager { - /** - * This method returns Connectivity Algorithm (Scheme) that is currently - * being used. - * - * @return ConnectionMgmtScheme Enum that represents the active scheme. - */ - public ConnectionMgmtScheme getActiveScheme(); - - /** - * Method that will retrieve and return a Set of Nodes that is currently - * connected to the given controller. - * - * @param controller - * InetAddress of the Controller that is currently connected to a - * set of Nodes. - * - * @return Set Set of Nodes connected to a controller. - */ - public Set getNodes(InetAddress controller); - - /** - * Method that will retrieve and return a Set of Nodes that is currently - * connected to the controller on which this method is executed. - * - * @return Set Set of Nodes connected to this controller. - */ - public Set getLocalNodes(); - - /** - * @deprecated Use getLocalityStatus(Node node) instead. - * - * Method to test if a node is local to a controller. - * - * @param node - * The node for which the locality is being tested - * @return true if node is local to this controller.
- * false if either node is not connected to this controller or not - * connected to any other controllers in the cluster. - */ - public boolean isLocal(Node node); - - /** - * getLocalityStatus provides the tri-state connectivity status as opposed - * to the binary status returned by isLocal. ConnectionLocality enum that is - * returned by this method also includes the case of a Node not connected to - * any of the controllers in the cluster. - * - * @param node - * The node for which the locality is being verified - * @return ConnectionLocality - */ - public ConnectionLocality getLocalityStatus(Node node); - - /** - * Disconnect a Node from the controller. - * - * @return Status of the disconnect Operation. - */ - public Status disconnect(Node node); - - /** - * Connect to a node - * - * @param connectionIdentifier - * identifier with which the application would refer to a given - * connection. - * @param params - * Connection Params in Map format. This is entirely handled by - * the south-bound plugins and is an opaque value for SAL or - * Connection Manager. Typical values keyed inside this params - * are Management IP-Address, Username, Password, Security Keys, - * etc... - * - * @return Node Node connected to. - */ - public Node connect(String connectionIdentifier, - Map params); - - /** - * Connect to a node - * - * @param type - * Type of the node representing NodeIDType. - * @param connectionIdentifier - * identifier with which the application would refer to a given - * connection. - * @param params - * Connection Params in Map format. This is entirely handled by - * the south-bound plugins and is an opaque value for SAL or - * Connection Manager. Typical values keyed inside this params - * are Management IP-Address, Username, Password, Security Keys, - * etc... - * - * @return Status of the Connect Operation. - */ - public Node connect(String type, String connectionIdentifier, - Map params); - - /** - * Retrieve list of cluster-members to which Node is connected to - * - * @param node - * Node for which cluster-members to be retrieved - * - * @return Set List of cluster-member addresses to which the - * node is connected - */ - public Set getControllers(Node node); -} diff --git a/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/NodeAccessPermission.java b/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/NodeAccessPermission.java deleted file mode 100644 index c59e297cc4..0000000000 --- a/opendaylight/adsal/connectionmanager/api/src/main/java/org/opendaylight/controller/connectionmanager/NodeAccessPermission.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.connectionmanager; - -/* - * - * This enum enables the options which could be used for querying - * the cluster-members based on the state-change permissions. - * - * SB Plugin or any other means could be used to store this metadata - * against each connection w.r.t. Node - * - * TODO: When connection-manager is enhanced later to store connection - * metadata with permissions, this could be used to query the connections - * based on permission-level of the connection - * - */ - -public enum NodeAccessPermission { - - /* - * This option could be used to retrieve the cluster-members who have rights - * only to read the Node state but are not eligible for modifying the state - * of Node - */ - READONLY_ACCESS, - - /* - * This option could be used to retrieve the cluster-members who have rights - * to read and modify the state of Node - */ - READWRITE_ACCESS - -} diff --git a/opendaylight/adsal/connectionmanager/implementation/pom.xml b/opendaylight/adsal/connectionmanager/implementation/pom.xml deleted file mode 100644 index 0ae29a7a2d..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - connectionmanager.implementation - 0.3.0-SNAPSHOT - bundle - - - equinoxSDK381 - org.eclipse.osgi - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.connectionmanager, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.connection, - org.opendaylight.controller.sal.inventory, - org.eclipse.osgi.framework.console, - org.osgi.framework, - org.slf4j, - org.apache.felix.dm - - org.opendaylight.controller.connectionmanager.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/Activator.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/Activator.java deleted file mode 100644 index 8912aebbf3..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/Activator.java +++ /dev/null @@ -1,95 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.connectionmanager.internal; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; - -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.ICoordinatorChangeAware; -import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.sal.connection.IConnectionListener; -import org.opendaylight.controller.sal.connection.IConnectionService; -import org.apache.felix.dm.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.inventory.IInventoryService; -import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Method which tells how many Global implementations are - * supported by the bundle. This way we can tune the number of - * components created. This components will be created ONLY at the - * time of bundle startup and will be destroyed only at time of - * bundle destruction, this is the major difference with the - * implementation retrieved via getImplementations where all of - * them are assumed to be in a container! - * - * - * @return The list of implementations the bundle will support, - * in Global version - */ - @Override - protected Object[] getGlobalImplementations() { - Object[] res = { ConnectionManager.class }; - return res; - } - - /** - * Configure the dependency for a given instance Global - * - * @param c Component assigned for this instance, this will be - * what will be used for configuration - * @param imp implementation to be configured - * @param containerName container on which the configuration happens - */ - @Override - protected void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(ConnectionManager.class)) { - Dictionary props = new Hashtable(); - Set propSet = new HashSet(); - for (ConnectionMgmtScheme scheme:ConnectionMgmtScheme.values()) { - propSet.add("connectionmanager."+scheme.name()+".nodeconnections"); - } - props.put("cachenames", propSet); - props.put("scope", "Global"); - - // export the service - c.setInterface(new String[] { IConnectionManager.class.getName(), - IConnectionListener.class.getName(), - ICoordinatorChangeAware.class.getName(), - IListenInventoryUpdates.class.getName(), - ICacheUpdateAware.class.getName()}, - props); - - c.add(createServiceDependency() - .setService(IClusterGlobalServices.class) - .setCallbacks("setClusterServices", "unsetClusterServices") - .setRequired(true)); - - c.add(createServiceDependency().setService(IConnectionService.class) - .setCallbacks("setConnectionService", "unsetConnectionService") - .setRequired(true)); - c.add(createServiceDependency().setService(IInventoryService.class, "(scope=Global)") - .setCallbacks("setInventoryService", "unsetInventoryService") - .setRequired(true)); - } - } -} diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionManager.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionManager.java deleted file mode 100644 index d76c094851..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionManager.java +++ /dev/null @@ -1,451 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * Connection Manager provides south-bound connectivity services. - * The APIs are currently focused towards Active-Active Clustering support - * wherein the node can connect to any of the Active Controller in the Cluster. - * This component can also host the necessary logic for south-bound connectivity - * when partial cluster is identified during Partition scenarios. - * - * But this (and its corresponding implementation) component can also be used for - * basic connectivity mechansims for various south-bound plugins. - */ - -package org.opendaylight.controller.connectionmanager.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Collections; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.LinkedBlockingQueue; - -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.ICoordinatorChangeAware; -import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.connectionmanager.scheme.AbstractScheme; -import org.opendaylight.controller.connectionmanager.scheme.SchemeFactory; -import org.opendaylight.controller.sal.connection.ConnectionConstants; -import org.opendaylight.controller.sal.connection.ConnectionLocality; -import org.opendaylight.controller.sal.connection.IConnectionListener; -import org.opendaylight.controller.sal.connection.IConnectionService; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.inventory.IInventoryService; -import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ConnectionManager implements IConnectionManager, - IConnectionListener, ICoordinatorChangeAware, IListenInventoryUpdates, - ICacheUpdateAware>, CommandProvider { - private static final Logger logger = LoggerFactory - .getLogger(ConnectionManager.class); - private ConnectionMgmtScheme activeScheme = ConnectionMgmtScheme.ANY_CONTROLLER_ONE_MASTER; - private IClusterGlobalServices clusterServices; - private ConcurrentMap schemes; - private IConnectionService connectionService; - private Thread connectionEventThread; - private BlockingQueue connectionEvents; - private IInventoryService inventoryService; - - public void setClusterServices(IClusterGlobalServices i) { - this.clusterServices = i; - } - - public void unsetClusterServices(IClusterGlobalServices i) { - if (this.clusterServices == i) { - this.clusterServices = null; - } - } - - public void setConnectionService(IConnectionService i) { - this.connectionService = i; - } - - public void unsetConnectionService(IConnectionService i) { - if (this.connectionService == i) { - this.connectionService = null; - } - } - - public void setInventoryService(IInventoryService service) { - logger.trace("Got inventory service set request {}", service); - this.inventoryService = service; - } - - public void unsetInventoryService(IInventoryService service) { - logger.trace("Got a service UNset request"); - this.inventoryService = null; - } - - private void getInventories() { - Map> nodeProp = this.inventoryService - .getNodeProps(); - for (Map.Entry> entry : nodeProp.entrySet()) { - Node node = entry.getKey(); - logger.debug("getInventories for node:{}", new Object[] { node }); - Map propMap = entry.getValue(); - Set props = new HashSet(); - for (Property property : propMap.values()) { - props.add(property); - } - updateNode(node, UpdateType.ADDED, props); - } - - Map> nodeConnectorProp = this.inventoryService - .getNodeConnectorProps(); - for (Map.Entry> entry : nodeConnectorProp - .entrySet()) { - Map propMap = entry.getValue(); - Set props = new HashSet(); - for (Property property : propMap.values()) { - props.add(property); - } - updateNodeConnector(entry.getKey(), UpdateType.ADDED, props); - } - } - - public void started() { - - connectionEventThread.start(); - - registerWithOSGIConsole(); - notifyClusterViewChanged(); - // Should pull the Inventory updates in case we missed it - getInventories(); - } - - public void init() { - connectionEventThread = new Thread(new EventHandler(), - "ConnectionEvent Thread"); - this.connectionEvents = new LinkedBlockingQueue(); - schemes = new ConcurrentHashMap(); - - String schemeStr = System.getProperty("connection.scheme"); - for (ConnectionMgmtScheme scheme : ConnectionMgmtScheme.values()) { - AbstractScheme schemeImpl = SchemeFactory.getScheme(scheme, clusterServices); - if (schemeImpl != null) { - schemes.put(scheme, schemeImpl); - if (scheme.name().equalsIgnoreCase(schemeStr)) { - activeScheme = scheme; - } - } - } - } - - public void stopping() { - connectionEventThread.interrupt(); - Set localNodes = getLocalNodes(); - if (localNodes != null) { - AbstractScheme scheme = schemes.get(activeScheme); - for (Node localNode : localNodes) { - connectionService.disconnect(localNode); - if (scheme != null) - scheme.removeNode(localNode); - } - } - } - - @Override - public ConnectionMgmtScheme getActiveScheme() { - return activeScheme; - } - - @Override - public Set getNodes(InetAddress controller) { - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme == null) - return null; - return scheme.getNodes(controller); - } - - @Override - public Set getLocalNodes() { - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme == null) - return null; - return scheme.getNodes(); - } - - @Override - public boolean isLocal(Node node) { - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme == null) - return false; - return scheme.isLocal(node); - } - - @Override - public ConnectionLocality getLocalityStatus(Node node) { - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme == null) - return ConnectionLocality.NOT_CONNECTED; - return scheme.getLocalityStatus(node); - } - - @Override - public void updateNode(Node node, UpdateType type, Set props) { - logger.debug("updateNode: {} type {} props {}", node, type, props); - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme == null) - return; - switch (type) { - case ADDED: - scheme.addNode(node); - break; - case REMOVED: - scheme.removeNode(node); - break; - default: - break; - } - } - - @Override - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props) { - logger.debug("updateNodeConnector: {} type {} props {}", nodeConnector, - type, props); - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme == null) - return; - switch (type) { - case ADDED: - scheme.addNode(nodeConnector.getNode()); - break; - default: - break; - } - } - - @Override - public void coordinatorChanged() { - notifyClusterViewChanged(); - } - - @Override - public Node connect(String connectionIdentifier, - Map params) { - if (connectionService == null) - return null; - Node node = connectionService.connect(connectionIdentifier, params); - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme != null && node != null) - scheme.addNode(node); - return node; - } - - @Override - public Node connect(String type, String connectionIdentifier, - Map params) { - if (connectionService == null) - return null; - Node node = connectionService.connect(type, connectionIdentifier, params); - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme != null && node != null) - scheme.addNode(node); - return node; - } - - @Override - public Status disconnect(Node node) { - if (node == null) - return new Status(StatusCode.BADREQUEST); - if (connectionService == null) - return new Status(StatusCode.NOSERVICE); - Status status = connectionService.disconnect(node); - if (status.isSuccess()) { - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme != null) - scheme.removeNode(node); - } - return status; - } - - @Override - public void entryCreated(Node key, String cacheName, boolean originLocal) { - if (originLocal) - return; - } - - /* - * Clustering Services doesn't provide the existing states in the cache - * update callbacks. Hence, using a scratch local cache to maintain the - * existing state. - */ - private ConcurrentMap> existingConnections = new ConcurrentHashMap>(); - - @Override - public void entryUpdated(Node node, Set newControllers, - String cacheName, boolean originLocal) { - if (originLocal) - return; - Set existingControllers = existingConnections.get(node); - if (existingControllers != null) { - logger.debug("Processing Update for : {} NewControllers : {} existingControllers : {}", node, - newControllers.toString(), existingControllers.toString()); - if (newControllers.size() < existingControllers.size()) { - Set removed = new HashSet(existingControllers); - if (removed.removeAll(newControllers)) { - logger.debug("notifyNodeDisconnectFromMaster({})", node); - notifyNodeDisconnectedEvent(node); - } - } - } else { - logger.debug("Ignoring the Update for : {} NewControllers : {}", node, newControllers.toString()); - } - existingConnections.put(node, newControllers); - } - - @Override - public void entryDeleted(Node key, String cacheName, boolean originLocal) { - if (originLocal) - return; - logger.debug("Deleted entry {} from cache : {}", key, cacheName); - notifyNodeDisconnectedEvent(key); - } - - private void enqueueConnectionEvent(ConnectionMgmtEvent event) { - try { - if (!connectionEvents.contains(event)) { - this.connectionEvents.put(event); - } - } catch (InterruptedException e) { - logger.debug( - "enqueueConnectionEvent caught Interrupt Exception for event {}", - event); - } - } - - private void notifyClusterViewChanged() { - ConnectionMgmtEvent event = new ConnectionMgmtEvent( - ConnectionMgmtEventType.CLUSTER_VIEW_CHANGED, null); - enqueueConnectionEvent(event); - } - - private void notifyNodeDisconnectedEvent(Node node) { - ConnectionMgmtEvent event = new ConnectionMgmtEvent( - ConnectionMgmtEventType.NODE_DISCONNECTED_FROM_MASTER, node); - enqueueConnectionEvent(event); - } - - /* - * this thread monitors the connectionEvent queue for new incoming events - * from - */ - private class EventHandler implements Runnable { - @Override - public void run() { - - while (true) { - try { - ConnectionMgmtEvent ev = connectionEvents.take(); - ConnectionMgmtEventType eType = ev.getEvent(); - switch (eType) { - case NODE_DISCONNECTED_FROM_MASTER: - Node node = (Node) ev.getData(); - connectionService.notifyNodeDisconnectFromMaster(node); - break; - case CLUSTER_VIEW_CHANGED: - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme == null) - return; - scheme.handleClusterViewChanged(); - connectionService.notifyClusterViewChanged(); - break; - default: - logger.error("Unknown Connection event {}", - eType.ordinal()); - } - } catch (InterruptedException e) { - connectionEvents.clear(); - return; - } - } - } - } - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, - null); - } - - public void _scheme(CommandInterpreter ci) { - String schemeStr = ci.nextArgument(); - if (schemeStr == null) { - ci.println("Please enter valid Scheme name"); - ci.println("Current Scheme : " + activeScheme.name()); - return; - } - ConnectionMgmtScheme scheme = ConnectionMgmtScheme.valueOf(schemeStr); - if (scheme == null) { - ci.println("Please enter a valid Scheme name"); - return; - } - activeScheme = scheme; - } - - public void _printNodes(CommandInterpreter ci) { - String controller = ci.nextArgument(); - if (controller == null) { - ci.println("Nodes connected to this controller : "); - if (this.getLocalNodes() == null) { - ci.println("None"); - } else { - ci.println(this.getLocalNodes().toString()); - } - return; - } - try { - InetAddress address = InetAddress.getByName(controller); - ci.println("Nodes connected to controller " + controller); - if (this.getNodes(address) == null) { - ci.println("None"); - } else { - ci.println(this.getNodes(address).toString()); - } - } catch (UnknownHostException e) { - logger.error("An error occured", e); - } - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---Connection Manager---\n"); - help.append("\t scheme [] - Print / Set scheme\n"); - help.append("\t printNodes [] - Print connected nodes\n"); - return help.toString(); - } - - @Override - public Set getControllers(Node node) { - AbstractScheme scheme = schemes.get(activeScheme); - if (scheme == null) - return Collections.emptySet(); - return scheme.getControllers(node); - } -} diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEvent.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEvent.java deleted file mode 100644 index bb353ffa08..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.connectionmanager.internal; - -public class ConnectionMgmtEvent { - ConnectionMgmtEventType event; - Object data; - public ConnectionMgmtEvent(ConnectionMgmtEventType event, Object data) { - this.event = event; - this.data = data; - } - public ConnectionMgmtEventType getEvent() { - return event; - } - public Object getData() { - return data; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result + ((event == null) ? 0 : event.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ConnectionMgmtEvent other = (ConnectionMgmtEvent) obj; - if (data == null) { - if (other.data != null) - return false; - } else if (!data.equals(other.data)) - return false; - if (event != other.event) - return false; - return true; - } - @Override - public String toString() { - return "ConnectionMgmtEvent [event=" + event + ", data=" + data + "]"; - } -} diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEventType.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEventType.java deleted file mode 100644 index cefae55fc6..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/internal/ConnectionMgmtEventType.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.connectionmanager.internal; - -public enum ConnectionMgmtEventType { - NODE_DISCONNECTED_FROM_MASTER("Node is disconnected from master"), - CLUSTER_VIEW_CHANGED("Cluster Composition changed"); - - private ConnectionMgmtEventType(String name) { - this.name = name; - } - - private String name; - - public String toString() { - return name; - } - - public static ConnectionMgmtEventType fromString(String pName) { - for(ConnectionMgmtEventType p:ConnectionMgmtEventType.values()) { - if (p.toString().equals(pName)) { - return p; - } - } - return null; - } -} diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AbstractScheme.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AbstractScheme.java deleted file mode 100644 index 68d1b233b2..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AbstractScheme.java +++ /dev/null @@ -1,390 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.connectionmanager.scheme; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme; -import org.opendaylight.controller.sal.connection.ConnectionLocality; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class AbstractScheme { - private static final Logger log = LoggerFactory.getLogger(AbstractScheme.class); - protected IClusterGlobalServices clusterServices = null; - /* - * A more natural Map data-structure is to have a Key=Controller IP-address with value = a set of Nodes. - * But, such a data-structure results in some complex event processing during the Cluster operations - * to sync up the Connection states. - * - * A data-structure with Node as the key and set of controllers provides a good balance - * between the needed functionality and simpler clustering implementation for Connection Manager. - */ - protected ConcurrentMap > nodeConnections; - protected abstract boolean isConnectionAllowedInternal(Node node); - private final String name; - private final String nodeConnectionsCacheName; - - protected AbstractScheme(IClusterGlobalServices clusterServices, ConnectionMgmtScheme type) { - this.clusterServices = clusterServices; - name = (type != null ? type.name() : "UNKNOWN"); - nodeConnectionsCacheName = "connectionmanager."+name+".nodeconnections"; - if (clusterServices != null) { - allocateCaches(); - retrieveCaches(); - } else { - log.error("Couldn't retrieve caches for scheme {}. Clustering service unavailable", name); - } - } - - protected ConcurrentMap > getControllerToNodesMap() { - ConcurrentMap > controllerNodesMap = new ConcurrentHashMap >(); - for (Node node : nodeConnections.keySet()) { - Set controllers = nodeConnections.get(node); - if (controllers == null) continue; - for (InetAddress controller : controllers) { - Set nodes = controllerNodesMap.get(controller); - if (nodes == null) { - nodes = new HashSet(); - } - nodes.add(node); - controllerNodesMap.put(controller, nodes); - } - } - return controllerNodesMap; - } - - public boolean isConnectionAllowed (Node node) { - if (clusterServices == null || nodeConnections == null) { - return false; - } - - return isConnectionAllowedInternal(node); - } - - public void handleClusterViewChanged() { - log.debug("Handling Cluster View changed notification"); - List controllers = clusterServices.getClusteredControllers(); - ConcurrentMap > controllerNodesMap = getControllerToNodesMap(); - List toRemove = new ArrayList(); - for (InetAddress c : controllerNodesMap.keySet()) { - if (!controllers.contains(c)) { - toRemove.add(c); - } - } - - boolean retry = false; - for (InetAddress c : toRemove) { - log.debug("Removing Controller : {} from the Connections table", c); - for (Iterator nodeIterator = nodeConnections.keySet().iterator();nodeIterator.hasNext();) { - Node node = nodeIterator.next(); - Set oldControllers = nodeConnections.get(node); - Set newControllers = new HashSet(oldControllers); - if (newControllers.remove(c)) { - try { - clusterServices.tbegin(); - if (!nodeConnections.replace(node, oldControllers, newControllers)) { - log.debug("Replace Failed for {} ", node.toString()); - retry = true; - clusterServices.trollback(); - break; - } else { - clusterServices.tcommit(); - } - } catch (Exception e) { - log.debug("Exception in replacing nodeConnections ", e); - retry = true; - try { - clusterServices.trollback(); - } catch (Exception e1) {} - break; - } - } - } - } - if (retry) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) {} - handleClusterViewChanged(); - } - } - - public Set getNodes(InetAddress controller) { - ConcurrentMap > controllerNodesMap = getControllerToNodesMap(); - return controllerNodesMap.get(controller); - } - - public Set getNodes() { - return getNodes(clusterServices.getMyAddress()); - } - - public Set getControllers(Node node) { - if (nodeConnections != null) return nodeConnections.get(node); - return Collections.emptySet(); - } - - public ConcurrentMap> getNodeConnections() { - return nodeConnections; - } - - public boolean isLocal(Node node) { - if (nodeConnections == null) return false; - InetAddress myController = clusterServices.getMyAddress(); - Set controllers = nodeConnections.get(node); - return (controllers != null && controllers.contains(myController)); - } - - public ConnectionLocality getLocalityStatus(Node node) { - if (nodeConnections == null) return ConnectionLocality.NOT_CONNECTED; - Set controllers = nodeConnections.get(node); - if (controllers == null || controllers.size() == 0) return ConnectionLocality.NOT_CONNECTED; - InetAddress myController = clusterServices.getMyAddress(); - return controllers.contains(myController) ? ConnectionLocality.LOCAL: - ConnectionLocality.NOT_LOCAL; - } - - public Status removeNode (Node node) { - return removeNodeFromController(node, clusterServices.getMyAddress()); - } - - protected Status removeNodeFromController (Node node, InetAddress controller) { - if (node == null || controller == null) { - return new Status(StatusCode.BADREQUEST, "Invalid Node or Controller Address Specified."); - } - - if (clusterServices == null || nodeConnections == null) { - return new Status(StatusCode.SUCCESS); - } - - Set oldControllers = nodeConnections.get(node); - - if (oldControllers != null && oldControllers.contains(controller)) { - Set newControllers = new HashSet(oldControllers); - if (newControllers.remove(controller)) { - try { - clusterServices.tbegin(); - if (newControllers.size() > 0) { - if (!nodeConnections.replace(node, oldControllers, newControllers)) { - clusterServices.trollback(); - try { - Thread.sleep(100); - } catch ( InterruptedException e) {} - return removeNodeFromController(node, controller); - } - } else { - nodeConnections.remove(node); - } - clusterServices.tcommit(); - } catch (Exception e) { - log.error("Exception in removing Controller from a Node", e); - try { - clusterServices.trollback(); - } catch (Exception e1) { - log.error("Error Rolling back the node Connections Changes ", e); - } - return new Status(StatusCode.INTERNALERROR); - } - - } - } - return new Status(StatusCode.SUCCESS); - - } - - /* - * A few race-conditions were seen with the Clustered caches in putIfAbsent and replace - * functions. Leaving a few debug logs behind to assist in debugging if strange things happen. - */ - private Status putNodeToController (Node node, InetAddress controller) { - if (clusterServices == null || nodeConnections == null) { - return new Status(StatusCode.INTERNALERROR, "Cluster service unavailable, or node connections info missing."); - } - log.debug("Trying to Put {} to {}", controller.getHostAddress(), node.toString()); - - Set oldControllers = nodeConnections.get(node); - Set newControllers = null; - if (oldControllers == null) { - newControllers = new HashSet(); - } else { - if (oldControllers.size() > 0 && !isConnectionAllowed(node)) { - /* - * In certain race conditions, the putIfAbsent fails to be atomic. - * This check is added to identify such cases and report an warning - * for debugging. - */ - log.warn("States Exists for {} : {}", node, oldControllers.toString()); - } - newControllers = new HashSet(oldControllers); - } - newControllers.add(controller); - - try { - clusterServices.tbegin(); - if (nodeConnections.putIfAbsent(node, newControllers) != null) { - log.debug("PutIfAbsent failed {} to {}", controller.getHostAddress(), node.toString()); - /* - * This check is needed again to take care of the case where some schemes - * would not allow nodes to be connected to multiple controllers. - * Hence, if putIfAbsent fails, that means, some other controller is competing - * with this controller to take hold of a Node. - */ - if (isConnectionAllowed(node)) { - if (oldControllers == null || !nodeConnections.replace(node, oldControllers, newControllers)) { - clusterServices.trollback(); - try { - Thread.sleep(100); - } catch ( InterruptedException e) {} - log.debug("Retrying ... {} with {}", controller.getHostAddress(), node.toString()); - return putNodeToController(node, controller); - } else { - log.debug("Replace successful old={} with new={} for {} to {}", oldControllers.toString(), newControllers.toString(), - controller.getHostAddress(), node.toString()); - } - } else { - clusterServices.trollback(); - return new Status(StatusCode.CONFLICT); - } - } else { - log.debug("Added {} to {}", controller.getHostAddress(), node.toString()); - } - clusterServices.tcommit(); - } catch (Exception e) { - log.error("Excepion in adding Controller to a Node", e); - try { - clusterServices.trollback(); - } catch (Exception e1) { - log.error("Error Rolling back the node Connections Changes ", e); - } - return new Status(StatusCode.INTERNALERROR); - } - return new Status(StatusCode.SUCCESS); - } - - public Status addNode (Node node, InetAddress controller) { - if (node == null || controller == null) { - if (node == null) { - log.warn("addNode: node is null"); - } else if (controller == null) { - log.error("Failed to add node {}. The controller address retrieved from clusterServices is null.", node); - } - return new Status(StatusCode.BADREQUEST); - } - if (isLocal(node)) { - return new Status(StatusCode.SUCCESS); - } - if (isConnectionAllowed(node)) { - return putNodeToController(node, controller); - } else { - return new Status(StatusCode.NOTALLOWED); - } - } - - public Status addNode (Node node) { - return addNode(node, clusterServices.getMyAddress()); - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - if (this.clusterServices == null) { - log.error("Un-initialized Cluster Services, can't retrieve caches for scheme: {}", name); - return; - } - - nodeConnections = (ConcurrentMap>) clusterServices.getCache(nodeConnectionsCacheName); - - if (nodeConnections == null) { - log.error("\nFailed to get cache: {}", nodeConnectionsCacheName); - } - } - - private void allocateCaches() { - if (this.clusterServices == null) { - log.error("Un-initialized clusterServices, can't create cache"); - return; - } - - try { - clusterServices.createCache(nodeConnectionsCacheName, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheExistException cee) { - log.debug("\nCache already exists: {}", nodeConnectionsCacheName); - } catch (CacheConfigException cce) { - log.error("\nCache configuration invalid - check cache mode"); - } catch (Exception e) { - log.error("An error occured",e); - } - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((nodeConnections == null) ? 0 : nodeConnections.hashCode()); - result = prime * result + ((nodeConnectionsCacheName == null) ? 0 : nodeConnectionsCacheName.hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof AbstractScheme)) { - return false; - } - AbstractScheme other = (AbstractScheme) obj; - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (nodeConnections == null) { - if (other.nodeConnections != null) { - return false; - } - } else if (!nodeConnections.equals(other.nodeConnections)) { - return false; - } - if (nodeConnectionsCacheName == null) { - if (other.nodeConnectionsCacheName != null) { - return false; - } - } else if (!nodeConnectionsCacheName.equals(other.nodeConnectionsCacheName)) { - return false; - } - return true; - } -} diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AnyControllerScheme.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AnyControllerScheme.java deleted file mode 100644 index a4138c4160..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/AnyControllerScheme.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.connectionmanager.scheme; - -import java.net.InetAddress; -import java.util.Set; - -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme; -import org.opendaylight.controller.sal.core.Node; - -class AnyControllerScheme extends AbstractScheme { - private static AbstractScheme myScheme= null; - - protected AnyControllerScheme(IClusterGlobalServices clusterServices) { - super(clusterServices, ConnectionMgmtScheme.ANY_CONTROLLER_ONE_MASTER); - } - - public static AbstractScheme getScheme(IClusterGlobalServices clusterServices) { - if (myScheme == null) { - myScheme = new AnyControllerScheme(clusterServices); - } - return myScheme; - } - - @Override - public boolean isConnectionAllowedInternal(Node node) { - Set controllers = nodeConnections.get(node); - if (controllers == null || controllers.size() == 0) return true; - return (controllers.size() == 1 && controllers.contains(clusterServices.getMyAddress())); - } -} diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/ControllerConfig.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/ControllerConfig.java deleted file mode 100644 index e186d2b9a1..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/ControllerConfig.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.connectionmanager.scheme; - -import java.net.InetAddress; - -/** - * Configuration object that can be used to prioritize or add weight to a given controller. - * This can be potentially used by the Connection management scheme algorithms. - * - * This is currently not used. - * - */ -public class ControllerConfig { - private InetAddress controllerId; - private int priority; - private int weight; - - public ControllerConfig(InetAddress controllerId, int priority, int weight) { - this.controllerId = controllerId; - this.priority = priority; - this.weight = weight; - } - - public InetAddress getControllerId() { - return controllerId; - } - public int getPriority() { - return priority; - } - public int getWeight() { - return weight; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((controllerId == null) ? 0 : controllerId.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ControllerConfig other = (ControllerConfig) obj; - if (controllerId == null) { - if (other.controllerId != null) - return false; - } else if (!controllerId.equals(other.controllerId)) - return false; - return true; - } - @Override - public String toString() { - return "ControllerConfig [controllerId=" + controllerId + ", priority=" - + priority + ", weight=" + weight + "]"; - } -} diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/LoadBalancedScheme.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/LoadBalancedScheme.java deleted file mode 100644 index 04b6e1bc30..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/LoadBalancedScheme.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.connectionmanager.scheme; - - -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme; -import org.opendaylight.controller.sal.core.Node; - -/** - * Load Balancing scheme will let the nodes connect with controller based - * on the resource usage in each of the controllers in a cluster. - * - * Incomplete and Currently not used. - */ - -class LoadBalancedScheme extends AbstractScheme { - - protected LoadBalancedScheme(IClusterGlobalServices clusterServices) { - super(clusterServices, ConnectionMgmtScheme.LOAD_BALANCED); - } - - public static AbstractScheme getScheme(IClusterGlobalServices clusterServices) { - return null; - } - - @Override - public boolean isConnectionAllowedInternal(Node node) { - return false; - } - -} diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/RoundRobinScheme.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/RoundRobinScheme.java deleted file mode 100644 index eed120b7ec..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/RoundRobinScheme.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.connectionmanager.scheme; - -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme; -import org.opendaylight.controller.sal.core.Node; - -class RoundRobinScheme extends AbstractScheme { - protected RoundRobinScheme(IClusterGlobalServices clusterServices) { - super(clusterServices, ConnectionMgmtScheme.ROUND_ROBIN); - // TODO Auto-generated constructor stub - } - - public static AbstractScheme getScheme(IClusterGlobalServices clusterServices) { - return null; - } - - @Override - public boolean isConnectionAllowedInternal(Node node) { - // TODO Auto-generated method stub - return false; - } - -} diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SchemeFactory.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SchemeFactory.java deleted file mode 100644 index 2a6a91fda3..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SchemeFactory.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.connectionmanager.scheme; - -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme; - -public class SchemeFactory { - public static AbstractScheme getScheme(ConnectionMgmtScheme scheme, IClusterGlobalServices clusterServices) { - if (scheme == ConnectionMgmtScheme.SINGLE_CONTROLLER) { - return SingleControllerScheme.getScheme(clusterServices); - } else if (scheme == ConnectionMgmtScheme.ROUND_ROBIN) { - return RoundRobinScheme.getScheme(clusterServices); - } else if (scheme == ConnectionMgmtScheme.LOAD_BALANCED) { - return LoadBalancedScheme.getScheme(clusterServices); - } else if (scheme == ConnectionMgmtScheme.ANY_CONTROLLER_ONE_MASTER) { - return AnyControllerScheme.getScheme(clusterServices); - } - return null; - } -} diff --git a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SingleControllerScheme.java b/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SingleControllerScheme.java deleted file mode 100644 index 292773a2ed..0000000000 --- a/opendaylight/adsal/connectionmanager/implementation/src/main/java/org/opendaylight/controller/connectionmanager/scheme/SingleControllerScheme.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.connectionmanager.scheme; - -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.connectionmanager.ConnectionMgmtScheme; -import org.opendaylight.controller.sal.core.Node; - -class SingleControllerScheme extends AbstractScheme { - - private static AbstractScheme myScheme = null; - - protected SingleControllerScheme(IClusterGlobalServices clusterServices) { - super(clusterServices, ConnectionMgmtScheme.SINGLE_CONTROLLER); - } - - public static AbstractScheme getScheme(IClusterGlobalServices clusterServices) { - if (myScheme == null) { - myScheme = new SingleControllerScheme(clusterServices); - } - return myScheme; - } - - @Override - public boolean isConnectionAllowedInternal(Node node) { - // Lets make it simple. The Cluster Coordinator is the master - return clusterServices.amICoordinator(); - } -} diff --git a/opendaylight/adsal/containermanager/api/pom.xml b/opendaylight/adsal/containermanager/api/pom.xml deleted file mode 100644 index 20687edb60..0000000000 --- a/opendaylight/adsal/containermanager/api/pom.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - containermanager - 0.7.0-SNAPSHOT - bundle - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - sal - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.configuration, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.reader, - org.slf4j, - javax.xml.bind.annotation, - javax.xml.bind - org.opendaylight.controller.containermanager - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerChangeEvent.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerChangeEvent.java deleted file mode 100644 index 7e040c7852..0000000000 --- a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerChangeEvent.java +++ /dev/null @@ -1,33 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager; - -import java.io.Serializable; - -import org.opendaylight.controller.sal.core.UpdateType; - -public class ContainerChangeEvent implements Serializable { - private static final long serialVersionUID = 1L; - private ContainerConfig config; - private UpdateType update; - - public ContainerChangeEvent(ContainerConfig config, UpdateType update) { - this.config = config; - this.update = update; - } - - public UpdateType getUpdateType() { - return update; - } - - public ContainerConfig getConfig() { - return config; - } -} diff --git a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerConfig.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerConfig.java deleted file mode 100644 index 3c086cbce0..0000000000 --- a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerConfig.java +++ /dev/null @@ -1,645 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; - -/** - * Container Configuration Java Object for Container Manager Represents a container - * configuration information for Container Manager. - * - * Objects of this class are also serialized to and deserialized from binary - * files through java serialization API when saving to/reading from Container - * Manager startup configuration file. - */ -@XmlRootElement(name = "containerConfig") -@XmlAccessorType(XmlAccessType.NONE) -public class ContainerConfig extends ConfigurationObject implements Serializable { - private static final long serialVersionUID = 2L; - private static final String regexName = "^\\w+$"; - private static final String containerProfile = System.getProperty("container.profile") == null ? "Container" - : System.getProperty("container.profile"); - private static final String ADMIN_SUFFIX = "Admin"; - private static final String OPERATOR_SUFFIX = "Operator"; - - @XmlElement - private String container; - - @XmlElement - private String staticVlan; - - @XmlElement(name = "nodeConnectors") - private List ports; - - @XmlElement(name = "flowSpecs") - private List containerFlows; - - public String getContainer() { - return container; - } - - public void setContainer(String container) { - this.container = container; - } - - public String getStaticVlan() { - return staticVlan; - } - - public void setStaticVlan(String staticVlan) { - this.staticVlan = staticVlan; - } - - public List getContainerFlows() { - return containerFlows; - } - - public void setContainerFlows(List containerFlows) { - this.containerFlows = containerFlows; - } - - public static long getSerialversionuid() { - return serialVersionUID; - } - - public static String getRegexname() { - return regexName; - } - - public void setPorts(List ports) { - this.ports = ports; - } - - /** - * Default constructor needed by Gson. - * - * @return a Default ContainerConfig - */ - public ContainerConfig() { - this.container = null; - this.staticVlan = null; - this.ports = new ArrayList(0); - this.containerFlows = new ArrayList(0); - } - - /** - * Constructor for the ContainerConfig. - * - * @param container - * Name of the container in this configuration - * @param vlan - * vlan assigned to this container - * @param nodeName - * the name of the node assigned to the container from this - * configuration - * @param ports - * the list of NodeConnectors on the Node belonging to the container - * @return the constructed object - */ - public ContainerConfig(String container, String vlan, List portList, List containerFlows) { - this.container = container; - this.staticVlan = vlan; - this.ports = (portList == null) ? new ArrayList(0) : new ArrayList(portList); - this.containerFlows = (containerFlows == null) ? new ArrayList(0) - : new ArrayList(containerFlows); - } - - public ContainerConfig(ContainerConfig config) { - this.container = config.container; - this.staticVlan = config.staticVlan; - this.ports = (config.ports == null) ? new ArrayList(0) : new ArrayList(config.ports); - this.containerFlows = (config.containerFlows == null) ? new ArrayList(0) - : new ArrayList(config.containerFlows); - } - - /** - * Returns the container name. - * - * @return the container name - */ - public String getContainerName() { - return container; - } - - /** - * Returns the Vlan tag. - * - * @return the Vlan Tag configured for this container configuration - */ - public String getVlanTag() { - return staticVlan; - } - - /** - * Returns the configured ports. - * - * @return the string with the list of ports associated to the container on this - * configuration - */ - public List getPorts() { - return new ArrayList(ports); - } - - /** - * Returns the list of container flows configured for this container - * - * @return - */ - public List getContainerFlowConfigs() { - return (containerFlows == null || containerFlows.isEmpty()) ? new ArrayList(0) - : new ArrayList(containerFlows); - } - - /** - * Matches container name against passed parameter. - * - * @param name - * name of the container to be matched - * @return true if the passed argument correspond with the container name in the - * configuration - */ - public boolean matchName(String name) { - return this.container.equals(name); - } - - /** - * Parse the port list in several NodeConnector descriptor. - * - * @return the list of NodeConnector corresponding to the ports configured - * on this configuration - */ - public List getPortList() { - List portList = new ArrayList(); - if (ports != null && !ports.isEmpty()) { - for (String portString : ports) { - portList.add(NodeConnector.fromString(portString)); - } - } - return portList; - } - - /** - * Checks if this is a valid container configuration - * - * @return true, if is valid container configuration, false otherwise - */ - public Status validate() { - Status status = validateName(); - if (status.isSuccess()) { - status = validateStaticVlan(); - if (status.isSuccess()) { - status = validatePorts(); - if (status.isSuccess()) { - status = validateContainerFlows(); - } - } - } - return status; - } - - /** - * Checks for valid name. - * - * @return true, if successful - */ - private Status validateName() { - // No Container configuration allowed to container default - return (isValidResourceName(container) && !container.equalsIgnoreCase(GlobalConstants.DEFAULT.toString())) ? - new Status(StatusCode.SUCCESS) : new Status(StatusCode.BADREQUEST, "Invalid container name"); - } - - /** - * Checks for valid ports. - * - * @return true, if successful - */ - private Status validatePorts() { - return validateNodeConnectors(this.ports); - } - - public static Status validateNodeConnectors(List connectorList) { - if (connectorList != null && !connectorList.isEmpty()) { - for (String ncString : connectorList) { - if (NodeConnector.fromString(ncString) == null) { - return new Status(StatusCode.BADREQUEST, "Invalid node connector: " + ncString); - } - } - - } - return new Status(StatusCode.SUCCESS); - } - - public static List nodeConnectorsFromString(List nodeConnectorStrings) { - List list = new ArrayList(nodeConnectorStrings.size()); - for (String str : nodeConnectorStrings) { - list.add(NodeConnector.fromString(str)); - } - return list; - } - - /** - * Checks for valid static vlan. - * - * @return true, if successful - */ - private Status validateStaticVlan() { - if (staticVlan != null && !staticVlan.trim().isEmpty()) { - short vl = 0; - try { - vl = Short.valueOf(staticVlan); - } catch (NumberFormatException e) { - return new Status(StatusCode.BADREQUEST, "Static Vlan Value must be between 1 and 4095"); - } - if ((vl < 1) || (vl > 4095)) { - return new Status(StatusCode.BADREQUEST, "Static Vlan Value must be between 1 and 4095"); - } - } - return new Status(StatusCode.SUCCESS); - } - - private Status validateContainerFlows() { - if (containerFlows != null && !containerFlows.isEmpty()) { - for (ContainerFlowConfig conf : containerFlows) { - Status status = conf.validate(); - if (!status.isSuccess()) { - return new Status(StatusCode.BADREQUEST, "Invalid Flow Spec: " + status.getDescription()); - } - } - } - return new Status(StatusCode.SUCCESS); - } - - /** - * Returns Vlan value in short - * - * @return the Vlan tag - */ - public short getStaticVlanValue() { - if ((staticVlan == null) || (staticVlan.trim().isEmpty())) { - return 0; - } - try { - return Short.valueOf(staticVlan); - } catch (NumberFormatException e) { - return 0; - } - } - - public Status addNodeConnectors(List ncList) { - // Syntax check - Status status = ContainerConfig.validateNodeConnectors(ncList); - if (!status.isSuccess()) { - return status; - } - - // Add ports - ports.addAll(ncList); - return new Status(StatusCode.SUCCESS); - } - - public Status removeNodeConnectors(List ncList) { - // Syntax check - Status status = ContainerConfig.validateNodeConnectors(ncList); - if (!status.isSuccess()) { - return status; - } - // Presence check - if (ports.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "The following node connectors are not part of this container: " - + ncList); - } - List extra = new ArrayList(ncList); - extra.removeAll(ports); - if (!extra.isEmpty()) { - return new Status(StatusCode.CONFLICT, "The following node connectors are not part of this container: " + extra); - } - // Remove ports - ports.removeAll(ncList); - return new Status(StatusCode.SUCCESS); - } - - public Status validateContainerFlowModify(List cFlowConfigs, boolean delete) { - // Sanity Check - if (cFlowConfigs == null || cFlowConfigs.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid Flow Spec configuration(s): null or empty list"); - } - // Validity check - for (ContainerFlowConfig cFlowConf : cFlowConfigs) { - Status status = cFlowConf.validate(); - if (!status.isSuccess()) { - return new Status(StatusCode.BADREQUEST, String.format("Invalid Flow Spec configuration (%s): %s", - cFlowConf.getName(), status.getDescription())); - } - } - // Name conflict check - List existingNames = this.getContainerFlowConfigsNames(); - List proposedNames = this.getContainerFlowConfigsNames(cFlowConfigs); - - // Check for duplicates in the request - if (proposedNames.size() < cFlowConfigs.size()) { - return new Status(StatusCode.BADREQUEST, - "Invalid Flow Spec configuration(s): duplicate name configs present"); - } - - // Check for overflow - if (delete) { - // Raw size check - if (proposedNames.size() > existingNames.size()) { - return new Status(StatusCode.BADREQUEST, - "Invalid request: requested to remove more flow spec configs than available ones"); - } - // Presence check - for (ContainerFlowConfig config : cFlowConfigs) { - if (!this.containerFlows.contains(config)) { - return new Status(StatusCode.BADREQUEST, String.format( - "Invalid request: requested to remove nonexistent flow spec config: %s", - config.getName())); - } - } - } else { - // Check for conflicting names with existing cFlows - List conflicting = new ArrayList(existingNames); - conflicting.retainAll(proposedNames); - if (!conflicting.isEmpty()) { - return new Status(StatusCode.CONFLICT, - "Invalid Flow Spec configuration: flow spec name(s) conflict with existing flow specs: " - + conflicting.toString()); - } - - /* - * Check for conflicting flow spec match (we only check for strict - * equality). Remove this in case (*) is reintroduced - */ - if (this.containerFlows != null && !this.containerFlows.isEmpty()) { - Set existingMatches = new HashSet(); - for (ContainerFlowConfig existing : this.containerFlows) { - existingMatches.addAll(existing.getMatches()); - } - for (ContainerFlowConfig proposed : cFlowConfigs) { - if (existingMatches.removeAll(proposed.getMatches())) { - return new Status(StatusCode.CONFLICT, String.format( - "Invalid Flow Spec configuration: %s conflicts with existing flow spec", - proposed.getName())); - } - } - } - } - - - return new Status(StatusCode.SUCCESS); - } - - public ContainerFlowConfig getContainerFlowConfig(String name) { - if (this.containerFlows != null && !this.containerFlows.isEmpty()) { - for (ContainerFlowConfig conf : this.containerFlows) { - if (conf.getName().equals(name)) { - return new ContainerFlowConfig(conf); - } - } - } - return null; - } - - public List getContainerFlowConfigsNames() { - return getContainerFlowConfigsNames(this.containerFlows); - } - - /** - * Returns the list of unique names for the passed list of - * ContainerFlowConfig objects. the list will not contain duplicates even - * though the passed object list has ContainerFlowConfig objects with same - * names - * - * @param confList - * the list of ContainerFlowConfig objects - * @return the list of correspondent unique container flow names. The return - * list may differ from the passed list in size, if the latter - * contains duplicates - */ - private List getContainerFlowConfigsNames(List confList) { - // Use set to check for duplicates later - Set namesSet = new HashSet(); - if (confList != null) { - for (ContainerFlowConfig conf : confList) { - namesSet.add(conf.getName()); - } - } - return new ArrayList(namesSet); - } - - /** - * Add the proposed list of container flow configurations to this container - * configuration. A validation check on the operation is first run. - * - * @param containerFlowConfigs - * the proposed list of container flow configuration objects to - * add to this container configuration object - * @return the result of this request as Status object - */ - public Status addContainerFlows(List containerFlowConfigs) { - Status status = this.validateContainerFlowModify(containerFlowConfigs, false); - if (!status.isSuccess()) { - return status; - } - if (this.containerFlows.addAll(containerFlowConfigs) == false) { - return new Status(StatusCode.INTERNALERROR, "Unable to update the flow spec configuration(s)"); - } - return new Status(StatusCode.SUCCESS); - } - - public Status removeContainerFlows(List containerFlowConfigs) { - Status status = this.validateContainerFlowModify(containerFlowConfigs, true); - if (!status.isSuccess()) { - return status; - } - if (this.containerFlows.removeAll(containerFlowConfigs) == false) { - return new Status(StatusCode.INTERNALERROR, "Unable to update the flow spec configuration(s)"); - } - return new Status(StatusCode.SUCCESS); - } - - public Status removeContainerFlows(Set names) { - // Sanity check - if (names == null || names.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid flow spec names list"); - } - // Validation check - List present = this.getContainerFlowConfigsNames(); - if (!present.containsAll(names)) { - List notPresent = new ArrayList(names); - notPresent.retainAll(present); - return new Status(StatusCode.BADREQUEST, "Following flow spec(s) are not present: " + notPresent); - } - // Remove - List toDelete = new ArrayList(names.size()); - for (ContainerFlowConfig config : this.containerFlows) { - if (names.contains(config.getName())) { - toDelete.add(config); - } - } - if (this.containerFlows.removeAll(toDelete) == false) { - return new Status(StatusCode.INTERNALERROR, "Unable to remove the flow spec configuration(s)"); - } - return new Status(StatusCode.SUCCESS); - } - - public List getContainerFlowConfigs(Set names) { - List list = new ArrayList(names.size()); - for (String name : names) { - ContainerFlowConfig conf = this.getContainerFlowConfig(name); - if (conf != null) { - list.add(new ContainerFlowConfig(conf)); - } - } - return list; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((containerFlows == null) ? 0 : containerFlows.hashCode()); - result = prime * result + ((ports == null) ? 0 : ports.hashCode()); - result = prime * result + ((container == null) ? 0 : container.hashCode()); - result = prime * result + ((staticVlan == null) ? 0 : staticVlan.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - ContainerConfig other = (ContainerConfig) obj; - if (containerFlows == null) { - if (other.containerFlows != null) { - return false; - } - } else if (!containerFlows.equals(other.containerFlows)) { - return false; - } - if (ports == null) { - if (other.ports != null) { - return false; - } - } else if (!ports.equals(other.ports)) { - return false; - } - if (container == null) { - if (other.container != null) { - return false; - } - } else if (!container.equals(other.container)) { - return false; - } - if (staticVlan == null) { - if (other.staticVlan != null) { - return false; - } - } else if (!staticVlan.equals(other.staticVlan)) { - return false; - } - return true; - } - - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - String vlString = ""; - if (staticVlan != null) { - vlString = staticVlan; - } - return "container=" + container + ((vlString.equals("") ? "" : " static Vlan=" + vlString)) + " ports=" + ports + " flowspecs=" + containerFlows; - } - - /** - * Returns whether this Container configuration object has any ports specified - * - * @return true if any port is specified, false otherwise - */ - public boolean hasNodeConnectors() { - return (ports != null && !ports.isEmpty()); - } - - /** - * Returns whether this Container configuration object has any flow specs specified - * - * @return true if any flow spec is specified, false otherwise - */ - public boolean hasFlowSpecs() { - return (containerFlows != null && !containerFlows.isEmpty()); - } - - public List getContainerFlowSpecs() { - List list = new ArrayList(); - if (containerFlows != null && !containerFlows.isEmpty()) { - for (ContainerFlowConfig flowSpec : containerFlows) { - for (Match match : flowSpec.getMatches()) { - list.add(new ContainerFlow(match)); - } - } - } - return list; - } - - private String getContainerRole(boolean admin) { - return String.format("%s-%s-%s", containerProfile, container, (admin ? ADMIN_SUFFIX : OPERATOR_SUFFIX)); - } - - /** - * Return the well known administrator role for this container - * - * @return The administrator role for this container - */ - public String getContainerAdminRole() { - return getContainerRole(true); - } - - /** - * Return the well known operator role for this container - * - * @return The operator role for this container - */ - public String getContainerOperatorRole() { - return getContainerRole(false); - } - - public String getContainerGroupName() { - return String.format("%s-%s", containerProfile, container); - } -} diff --git a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerData.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerData.java deleted file mode 100644 index 0c8c53162e..0000000000 --- a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerData.java +++ /dev/null @@ -1,239 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; - - -/** - * This Class contains all the configurations pertained to this container - * - */ -public class ContainerData implements Serializable { - private static final long serialVersionUID = 1L; - private String containerAdminRole; - private String containerOperatorRole; - private String name; - private ConcurrentMap> swPorts; - private short staticVlan; - private List cFlowList; - - /** - * Build a ContainerData from container configuration - * - * @param conf configuration from where the ContainerData need to be extracted - * - * @return the constructed containerData - */ - public ContainerData(ContainerConfig conf) { - /* - * Back-end Non-Configuration Classes store names in lower case - */ - name = conf.getContainerName().toLowerCase(Locale.ENGLISH); - swPorts = new ConcurrentHashMap>(); - cFlowList = new ArrayList(); - staticVlan = conf.getStaticVlanValue(); - containerAdminRole = conf.getContainerAdminRole(); - containerOperatorRole = conf.getContainerOperatorRole(); - } - - /** - * getter for containerName - * - * - * @return the container name - */ - public String getContainerName() { - return name; - } - - /** - * getter for static vlan - * - * - * @return attribute static vlan - */ - public short getStaticVlan() { - return staticVlan; - } - - /** - * Check if the static vlan has non-zero value in that case is - * assumed to be assigned - * - * - * @return true if static vlan non-zero - */ - public boolean hasStaticVlanAssigned() { - return (staticVlan != 0); - } - - /** - * retrieve all NodeConnectors on a given switch on the containerName - * used in this object - * - * @param switchId the Node for switch we want to retrieve the list of ports - * - * @return get all the ports in form of a set of nodeconnectors - */ - public Set getPorts(Node switchId) { - Set swpinfo = swPorts.get(switchId); - if (swpinfo != null) { - return swpinfo; - } - return null; - } - - /** - * Returns the DB of all the association Node -> List of - * NodeConnectors composing this container - * - * @return the ConcurrentMap of all the association Node -> List - * of NodeConnectors - */ - public ConcurrentMap> getSwPorts() { - return swPorts; - } - - /** - * Add to the container a NodeConnector, that implicitely means also - * the Node being added - * - * @param port NodeConnector corresponding to the port being added - * in the container - */ - public void addPortToSwitch(NodeConnector port) { - Node switchId = port.getNode(); - if (switchId == null) { - return; - } - Set portSet = swPorts.get(switchId); - if (portSet == null) { - portSet = new HashSet(); - swPorts.put(switchId, portSet); - } - portSet.add(port); - } - - /** - * Remove from the container a NodeConnector, that implicitely means also - * the Node being removed - * - * @param port NodeConnector corresponding to the port being removed - * in the container - */ - public void removePortFromSwitch(NodeConnector port) { - Node switchId = port.getNode(); - if (switchId == null) { - return; - } - Set swpinfo = swPorts.get(switchId); - if (swpinfo != null) { - swpinfo.remove(port); - if (swpinfo.isEmpty()) { - // There are no more ports lets get ride of the switch - swPorts.remove(switchId); - } - } - } - - /** - * Existence check of a Node in a container - * - * @param switchId See if a particular node is part of the container - * - * @return true if the node is in it else false - */ - public boolean isSwitchInContainer(Node switchId) { - if (swPorts.containsKey(switchId)) { - return true; - } else { - return false; - } - } - - /** - * Test for existance of NodeConnectors on a Node in a container - * - * @param switchId Node we are testing for port existance - * - * @return ture if the portset is non-empty - */ - public boolean portListEmpty(Node switchId) { - Set swpinfo = swPorts.get(switchId); - if (swpinfo != null) { - if (!swpinfo.isEmpty()) { - return false; - } - } - return true; - } - - public void deleteFlowSpec(ContainerFlow cFlow) { - cFlowList.remove(cFlow); - } - - public void addFlowSpec(ContainerFlow cFlow) { - cFlowList.add(cFlow); - } - - public boolean isFlowSpecEmpty() { - return (cFlowList.isEmpty()); - - } - - public boolean containsFlowSpec(ContainerFlow cFlow) { - return cFlowList.contains(cFlow); - } - - public int getFlowSpecCount() { - return cFlowList.size(); - } - - public List getContainerFlowSpecs() { - return cFlowList; - } - - public boolean matchName(String name) { - return this.name.equalsIgnoreCase(name); - } - - /** - * Returns all the node connectors part of the container - * @return The node connectors belonging to this container. The returning set is never null. - */ - public Set getNodeConnectors() { - Set set = new HashSet(); - for (Map.Entry> entry : swPorts.entrySet()) { - set.addAll(entry.getValue()); - } - return set; - } - - public String getContainerAdminRole() { - return containerAdminRole; - } - - public String getContainerOperatorRole() { - return containerOperatorRole; - } -} diff --git a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowChangeEvent.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowChangeEvent.java deleted file mode 100644 index 7405a72e7b..0000000000 --- a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowChangeEvent.java +++ /dev/null @@ -1,39 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager; - -import java.io.Serializable; -import java.util.List; - -import org.opendaylight.controller.sal.core.UpdateType; - -public class ContainerFlowChangeEvent implements Serializable { - private static final long serialVersionUID = 1L; - private List configs; - private UpdateType updateType; - - public ContainerFlowChangeEvent(List configs, UpdateType updateType) { - this.configs = configs; - this.updateType = updateType; - } - - public List getConfigList() { - return configs; - } - - public UpdateType getUpdateType() { - return updateType; - } - - @Override - public String toString() { - return "ContainerFlowChangeEvent [configs: " + configs + " updateType: " + updateType + "]"; - } -} diff --git a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowConfig.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowConfig.java deleted file mode 100644 index 6abd1acd40..0000000000 --- a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/ContainerFlowConfig.java +++ /dev/null @@ -1,819 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager; - -import java.io.Serializable; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.packet.BitBufferHelper; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Flow Specification Java Object for Container Manager - * Represents a container flow configuration information for Container Manager. - * - * Objects of this class are serialized to and de-serialized from binary files through - * java serialization API when saving to/reading from Container manager startup - * configuration file. - */ -@XmlRootElement (name = "flow-spec-config") -@XmlAccessorType(XmlAccessType.NONE) -public class ContainerFlowConfig extends ConfigurationObject implements Serializable { - private static Logger log = LoggerFactory.getLogger(ContainerFlowConfig.class); - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = 1L; - - /** Flow Spec name. */ - @XmlElement - private String name; - - /** The vlan. */ - @XmlElement - private String dlVlan; - - /** The network Source. */ - @XmlElement - private String nwSrc; - - /** The network Destination */ - @XmlElement - private String nwDst; - - /** The protocol. */ - @XmlElement - private String protocol; - - /** The transport source */ - @XmlElement - private String tpSrc; - - /** The transport destination */ - @XmlElement - private String tpDst; - - /* unidirectional flag - do not include this flag in equality check - @XmlElement */ - private static boolean unidirectional = false; - - - /** - * Instantiates a new container flow config. - */ - public ContainerFlowConfig() { - } - - /** - * Instantiates a new container flow config. - * - * @param name Flow Spec configuration name - * @param container Container Name - * @param srcIP Source IP Address - * @param dstIP Destination IP Address - * @param proto Protocol - * @param srcPort Source Layer4 Port - * @param dstPort Destination Layer4 Port - */ - public ContainerFlowConfig(String name, String srcIP, String dstIP, String proto, String srcPort, - String dstPort) { - this.name = name; - this.dlVlan = null; - this.nwSrc = srcIP; - this.nwDst = dstIP; - this.protocol = proto; - this.tpSrc = srcPort; - this.tpDst = dstPort; - //this.unidirectional = false; - } - - public ContainerFlowConfig(String name, String dlVlan, String srcIP, String dstIP, String proto, String srcPort, - String dstPort) { - this.name = name; - this.dlVlan = dlVlan; - this.nwSrc = srcIP; - this.nwDst = dstIP; - this.protocol = proto; - this.tpSrc = srcPort; - this.tpDst = dstPort; - } - - - public ContainerFlowConfig(ContainerFlowConfig containerFlowConfig) { - this.name = containerFlowConfig.name; - this.dlVlan = containerFlowConfig.dlVlan; - this.nwSrc = containerFlowConfig.nwSrc; - this.nwDst = containerFlowConfig.nwDst; - this.protocol = containerFlowConfig.protocol; - this.tpSrc = containerFlowConfig.tpSrc; - this.tpDst = containerFlowConfig.tpDst; - //this.unidirectional = containerFlowConfig.unidirectional; - } - - /** - * Returns the name of this Flow Specification - * - * @return the name of the Flow Specification - */ - public String getName() { - // mandatory field - return name; - } - - /** - * Returns the vlan id. - * - * @return the Vlan Id - */ - public String getVlan() { - return (dlVlan == null || dlVlan.isEmpty()) ? null : dlVlan; - } - - /** - * Returns the Source IP Address. - * - * @return the Source IP Address - */ - public String getSrcIP() { - return (nwSrc == null || nwSrc.isEmpty()) ? null : nwSrc; - } - - /** - * Returns the Destination IP Address. - * - * @return the Destination IP Address - */ - public String getDstIP() { - return (nwDst == null || nwDst.isEmpty()) ? null : nwDst; - } - - /** - * Returns the protocol. - * - * @return the protocol - */ - public String getProtocol() { - return protocol; - } - - /** - * Returns Source Layer4 Port. - * - * @return Source Layer4 Port - */ - public String getSrcPort() { - return (tpSrc == null || tpSrc.isEmpty()) ? null : tpSrc; - } - - /** - * Returns Destination Layer4 Port. - * - * @return Destination Layer4 Port - */ - public String getDstPort() { - return (tpDst == null || tpDst.isEmpty()) ? null : tpDst; - } - - /* - * @return the unidirectional flag - */ - public boolean isUnidirectional() { - return unidirectional; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((protocol == null) ? 0 : protocol.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((dlVlan == null) ? 0 : dlVlan.hashCode()); - result = prime * result + ((nwDst == null) ? 0 : nwDst.hashCode()); - result = prime * result + ((tpDst == null) ? 0 : tpDst.hashCode()); - result = prime * result + ((nwSrc == null) ? 0 : nwSrc.hashCode()); - result = prime * result + ((tpSrc == null) ? 0 : tpSrc.hashCode()); - return result; - } - - /* - * For comparison, consider that container flow can have empty fields - */ - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - /* - * Configuration will be stored in collection only if it is valid - * Hence we don't check here for uninitialized fields - */ - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - ContainerFlowConfig other = (ContainerFlowConfig) obj; - if (matchName(other) && matchDlVlan(other) && matchSrcIP(other) - && matchDstIP(other) && matchProtocol(other) - && matchSrcPort(other) && matchDstPort(other)) { - return true; - } - return false; - } - - /** - * Equals by Flow Spec name. - * - * @param name flow spec name for comparison - * @return true, if successful - */ - public boolean equalsByName(String name) { - return this.name.equals(name); - } - - /** - * equalsByMatch - * - * @param that ContainerFlowConfig for comparison - * @return true, if any match is equal - */ - public boolean equalsByMatch(ContainerFlowConfig that) { - // get both matches - // the match is equal if any of the match is equal - List thisMatch = this.getMatches(); - List otherMatch = that.getMatches(); - // both the lists cannot be null - for(Match m1 : thisMatch) { - for(Match m2 : otherMatch) { - if(m1.equals(m2)) { - return true; - } - } - } - // if you have reached here without a match - // being found - // return false - return false; - } - - /** - * Matches the name of this flow spec with that of ContainerFlowConfig parameter's flow spec. - * - * @param o the ContainerFlowConfig parameter - * @return true, if successful - */ - private boolean matchName(ContainerFlowConfig flowSpec) { - if (name == flowSpec.name) { - return true; - } - if (name == null || flowSpec.name == null) { - return false; - } - return name.equals(flowSpec.name); - } - - /** - * Match the set of these vlans with that of flowSpec's vlans. - * - * @param flowSpec - * Flow Specification - * @return true, if successful - */ - private boolean matchDlVlan(ContainerFlowConfig flowSpec) { - if (dlVlan == flowSpec.dlVlan) { - return true; - } - if (dlVlan == null || flowSpec.dlVlan == null) { - return false; - } - - return this.getVlanList().equals(flowSpec.getVlanList()); - } - - /** - * Match Source IP Address. - * - * @param flowSpec Flow Specification - * @return true, if successful - */ - private boolean matchSrcIP(ContainerFlowConfig flowSpec) { - if (nwSrc == flowSpec.nwSrc) { - return true; - } - if (nwSrc == null || flowSpec.nwSrc == null) { - return false; - } - return nwSrc.equals(flowSpec.nwSrc); - } - - /** - * Match Destination IP Address. - * - * @param flowSpec Flow Specification - * @return true, if successful - */ - private boolean matchDstIP(ContainerFlowConfig flowSpec) { - if (nwDst == flowSpec.nwDst) { - return true; - } - if (nwDst == null || flowSpec.nwDst == null) { - return false; - } - return this.nwDst.equals(flowSpec.nwDst); - } - - /** - * Match protocol. - * - * @param flowSpec Flow Specification - * @return true, if successful - */ - private boolean matchProtocol(ContainerFlowConfig flowSpec) { - if (protocol == flowSpec.protocol) { - return true; - } - if (protocol == null || flowSpec.protocol == null) { - return false; - } - return this.protocol.equals(flowSpec.protocol); - } - - /** - * Match Source Layer4 Port. - * - * @param flowSpec Flow Specification - * @return true, if successful - */ - private boolean matchSrcPort(ContainerFlowConfig flowSpec) { - if (tpSrc == flowSpec.tpSrc) { - return true; - } - if (tpSrc == null || flowSpec.tpSrc == null) { - return false; - } - return tpSrc.equals(flowSpec.tpSrc); - } - - /** - * Match Destination Layer4 Port. - * - * @param flowSpec Flow Specification - * @return true, if successful - */ - private boolean matchDstPort(ContainerFlowConfig flowSpec) { - if (tpDst == flowSpec.tpDst) { - return true; - } - if (tpDst == null || flowSpec.tpDst == null) { - return false; - } - return this.tpDst.equals(flowSpec.tpDst); - } - - /** - * Returns the vlan id number for all vlans specified - * - * @return the vlan id number for all vlans specified - */ - public Set getVlanList() { - /* - * example: Vlan = "1,3,5-12" - * elemArray = ["1" "3" "5-12"] - * elem[2] = "5-12" --> limits = ["5" "12"] - * vlanList = [1 3 5 6 7 8 9 10 11 12] - */ - Set vlanList = new HashSet(); - try { - String[] elemArray = dlVlan.split(","); - for (String elem : elemArray) { - if (elem.contains("-")) { - String[] limits = elem.split("-"); - for (short j = Short.valueOf(limits[0]); j <= Short.valueOf(limits[1]); j++) { - vlanList.add(Short.valueOf(j)); - } - } else { - vlanList.add(Short.valueOf(elem)); - } - } - } catch (NumberFormatException e) { - - } - return vlanList; - } - - /** - * Returns the Source IP Address mask length. - * - * @return the Source IP Address mask length - */ - public Short getSrcIPMaskLen() { - Short maskLen = 0; - - if (nwSrc != null && !nwSrc.isEmpty()) { - String[] s = nwSrc.split("/"); - if (s.length == 2) { - try { - maskLen = Short.valueOf(s[1]); - } catch (Exception e) { - // no mask or bad mask - } - } else { - InetAddress ip = this.getSrcIPNum(); - maskLen = (short) ((ip instanceof Inet4Address) ? 32 : 128); - } - } - return maskLen; - } - - /** - * Returns the Destination IP Address mask length. - * - * @return the Destination IP Address mask length - */ - public Short getDstIPMaskLen() { - Short maskLen = 0; - if (nwDst != null && !nwDst.isEmpty()) { - String[] s = nwDst.split("/"); - if (s.length == 2) { - try { - maskLen = Short.valueOf(s[1]); - } catch (Exception e) { - // no mask or bad mask - } - } else { - InetAddress ip = this.getDstIPNum(); - maskLen = (short) ((ip instanceof Inet4Address) ? 32 : 128); - } - } - return maskLen; - } - - /** - * Returns the Source IP Address. - * - * @return the Source IP Address - */ - public InetAddress getSrcIPNum() { - InetAddress ip = null; - if (nwSrc == null || nwSrc.isEmpty()) { - try { - ip = InetAddress.getByAddress(new byte[16]); - return ip; - } catch (UnknownHostException e) { - log.error("", e); - return null; - } - } - try { - ip = InetAddress.getByName(nwSrc.split("/")[0]); - } catch (UnknownHostException e1) { - log.error("", e1); - return null; - } - return ip; - } - - /** - * Returns the Destination IP Address. - * - * @return the Destination IP Address - */ - public InetAddress getDstIPNum() { - InetAddress ip = null; - if (nwDst == null || nwDst.isEmpty()) { - try { - ip = InetAddress.getByAddress(new byte[16]); - return ip; - } catch (UnknownHostException e) { - log.error("",e); - return null; - } - } - try { - ip = InetAddress.getByName(nwDst.split("/")[0]); - } catch (UnknownHostException e1) { - log.error("", e1); - return null; - } - return ip; - } - - /** - * Returns Source Layer4 Port number. - * - * @return Source Layer4 Port number - */ - public Short getSrcPortNum() { - return (tpSrc == null || tpSrc.isEmpty()) ? Short.valueOf((short) 0) - : Short.valueOf(tpSrc); - } - - /** - * Returns Destination Layer4 Port number. - * - * @return Destination Layer4 Port number - */ - public Short getDstPortNum() { - return (tpDst == null || tpDst.isEmpty()) ? Short.valueOf((short) 0) - : Short.valueOf(tpDst); - } - - /** - * Get the IP protocol value - * - * @return the protocol - */ - public Short getProtoNum() { - return protocol == null ? null : IPProtocols.getProtocolNumberShort(protocol); - } - - /** - * Returns whether this container flow overlap with the passed one This is - * true when any two of the resulting matches for the two container flow - * configurations intersect. - * - * @param other - * the other container flow config with which checking the - * overlap - * @return true if the two configurations overlap, false otherwise - */ - public boolean overlap(ContainerFlowConfig other) { - if (other == null) { - return false; - } - List myMathes = this.getMatches(); - List hisMatches = other.getMatches(); - for (Match mine : myMathes) { - for (Match his : hisMatches) { - if (mine.intersetcs(his)) { - return true; - } - } - } - return false; - } - - /** - * Checks if this flow specification configuration is valid. - * - * @return true, if is valid - */ - public Status validate() { - if (!isValidResourceName(name)) { - return new Status(StatusCode.BADREQUEST, "Invalid name"); - } - Status status = validateVlan(); - if (!status.isSuccess()) { - return status; - } - status = validateIPs(); - if (!status.isSuccess()) { - return status; - } - if(!hasValidProtocol()) { - return new Status(StatusCode.BADREQUEST, "Invalid IP protocol"); - } - if (!hasValidPorts()) { - return new Status(StatusCode.BADREQUEST, "Invalid Source or Destination Port"); - } - if (this.getMatches().get(0).getMatches() == 0) { - return new Status(StatusCode.BADREQUEST, "Flow Spec is empty"); - } - return new Status(StatusCode.SUCCESS); - } - - /** - * Validates the vlan number - * - * @return the result of the check as Status object - */ - private Status validateVlan() { - if (dlVlan != null) { - short vlanId = 0; - try { - String[] elemArray = dlVlan.split(","); - for (String elem : elemArray) { - if (elem.contains("-")) { - String[] limits = elem.split("-"); - if (Short.parseShort(limits[0]) < 0 - || Short.parseShort(limits[0]) >= Short.parseShort(limits[1]) - || Short.parseShort(limits[1]) > 0xfff) { - return new Status(StatusCode.BADREQUEST, "Invalid vlan id"); - } - } else { - vlanId = Short.parseShort(elem); - if (vlanId < 0 || vlanId > 0xfff) { - return new Status(StatusCode.BADREQUEST, "Invalid vlan id"); - } - } - } - } catch (NumberFormatException e) { - return new Status(StatusCode.BADREQUEST, "Invalid vlan id"); - } - } - return new Status(StatusCode.SUCCESS); - } - - /** - * Validates the network addresses, checks syntax and semantic - * - * @return the result of the check as Status object, if successful - */ - private Status validateIPs() { - if (nwSrc != null) { - if (!NetUtils.isIPAddressValid(nwSrc)) { - return new Status(StatusCode.BADREQUEST, "Invalid network source address"); - } - byte[] bytePrefix = NetUtils.getSubnetPrefix(this.getSrcIPNum(), this.getSrcIPMaskLen()).getAddress(); - long prefix = BitBufferHelper.getLong(bytePrefix); - if (prefix == 0) { - return new Status(StatusCode.BADREQUEST, "Invalid network source address: subnet zero"); - } - } - if (nwDst != null) { - if (!NetUtils.isIPAddressValid(nwDst)) { - return new Status(StatusCode.BADREQUEST, "Invalid network destination address"); - } - byte[] bytePrefix = NetUtils.getSubnetPrefix(this.getDstIPNum(), this.getDstIPMaskLen()).getAddress(); - long prefix = BitBufferHelper.getLong(bytePrefix); - if (prefix == 0) { - return new Status(StatusCode.BADREQUEST, "Invalid network destination address: subnet zero"); - } - } - return new Status(StatusCode.SUCCESS); - } - - /** - * Validate the protocol field. Either it can be a enum defined in IPProtocols.java - * or a valid IP proto value between 0 and 255, see: - * http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml - * for more details. - * - * @return true if a valid protocol value - */ - private boolean hasValidProtocol() { - IPProtocols p = IPProtocols.fromString(protocol); - return p != null; - } - - /** - * - * @param tpPort - * String representing the transport protocol port number - * @return true if tpPort contains a decimal value between 0 and 65535 - */ - private boolean hasValidPort(String tpPort) { - try { - int port = Integer.decode(tpPort); - return ((port >= 0) && (port <= 0xffff)); - } catch (NumberFormatException e) { - return false; - } - } - - /** - * Validate the transport protocol source and destination ports as - * entered by users. - * - * @return true if ports are defined and are in valid range - */ - private boolean hasValidPorts() { - if (tpSrc !=null && !tpSrc.isEmpty()) { - if (!hasValidPort(tpSrc)) { - return false; - } - } - - if (tpDst !=null && !tpDst.isEmpty()) { - return hasValidPort(tpDst); - } - return true; - } - - /** - * Returns the matches. - * If unidirectional flag is set, there will be only one match per vlan in the list - * If unidirectional flag is unset there will be two matches per vlan in the list, - * only if the specified flow has an intrinsic direction. - * For Ex. if the cFlow only has the protocol field configured, no matter - * if unidirectional flag is set or not, only one match per vlan will be returned - * The client just has to iterate over the returned list - * @return the matches - */ - public List getMatches() { - List matches = new ArrayList(); - - if (this.dlVlan != null && !this.dlVlan.isEmpty()) { - for(Short vlan:getVlanList()){ - Match match = getMatch(vlan); - matches.add(match); - } - } - else{ - Match match = getMatch(null); - matches.add(match); - } - - if (!ContainerFlowConfig.unidirectional) { - List forwardMatches = new ArrayList(matches); - for (Match match : forwardMatches) { - Match reverse = match.reverse(); - if (!match.equals(reverse)) { - matches.add(reverse); - } - } - } - - return matches; - } - - private Match getMatch(Short vlan){ - Match match = new Match(); - - if (vlan != null) { - match.setField(MatchType.DL_VLAN, vlan); - } - if (this.nwSrc != null && !this.nwSrc.trim().isEmpty()) { - String parts[] = this.nwSrc.split("/"); - InetAddress ip = NetUtils.parseInetAddress(parts[0]); - InetAddress mask = null; - int maskLen = 0; - if (parts.length > 1) { - maskLen = Integer.parseInt(parts[1]); - } else { - maskLen = (ip instanceof Inet6Address) ? 128 : 32; - } - mask = NetUtils.getInetNetworkMask(maskLen, ip instanceof Inet6Address); - match.setField(MatchType.NW_SRC, ip, mask); - } - if (this.nwDst != null && !this.nwDst.trim().isEmpty()) { - String parts[] = this.nwDst.split("/"); - InetAddress ip = NetUtils.parseInetAddress(parts[0]); - InetAddress mask = null; - int maskLen = 0; - if (parts.length > 1) { - maskLen = Integer.parseInt(parts[1]); - } else { - maskLen = (ip instanceof Inet6Address) ? 128 : 32; - } - mask = NetUtils.getInetNetworkMask(maskLen, ip instanceof Inet6Address); - match.setField(MatchType.NW_DST, ip, mask); - } - if (IPProtocols.fromString(this.protocol) != IPProtocols.ANY) { - match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(this.protocol)); - } - if (this.tpSrc != null && !this.tpSrc.trim().isEmpty()) { - match.setField(MatchType.TP_SRC, Integer.valueOf(tpSrc).shortValue()); - } - if (this.tpDst != null && !this.tpDst.trim().isEmpty()) { - match.setField(MatchType.TP_DST, Integer.valueOf(tpDst).shortValue()); - } - return match; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "Container Flow={name:" + name + " dlVlan:" + dlVlan + " nwSrc:" + nwSrc + " nwDst:" + nwDst + " " + "protocol:" + protocol - + " tpSrc:" + tpSrc + " tpDst:" + tpDst + "}"; - } -} diff --git a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerAuthorization.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerAuthorization.java deleted file mode 100644 index 6d3d9f877f..0000000000 --- a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerAuthorization.java +++ /dev/null @@ -1,19 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager; - -import org.opendaylight.controller.sal.authorization.IResourceAuthorization; - -/** - * Container groups and container users authorizations - */ -public interface IContainerAuthorization extends IResourceAuthorization { - -} diff --git a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManager.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManager.java deleted file mode 100644 index b2e2a7631b..0000000000 --- a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManager.java +++ /dev/null @@ -1,197 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.opendaylight.controller.sal.utils.Status; - -/** - * Container Manager provides an ability for the Network Administrators to - * partitions a production network into smaller, isolated and manageable - * networks. IContainerManager interface exposes these Container management capabilities - * via the supported APIs - */ -public interface IContainerManager { - - /** - * Create a Container - * - * @param configObject - * ContainerConfig object that carries name of the Container to be - * created - * @return returns the status code of adding a container - */ - public Status addContainer(ContainerConfig configObject); - - /** - * Remove a container - * - * @param configObject - * ContainerConfig object that carries the name of the Container to be - * removed - * @return returns the status code of removing a container - */ - public Status removeContainer(ContainerConfig configObject); - - /** - * Remove a container - * - * @param containerName - * the container name - * @return returns the status code of removing a container - */ - public Status removeContainer(String containerName); - - /** - * Adds resources to a given container. Updates the container data based on new - * resources added - * - * @param configObject - * refer to {@link com.ContainerConfig.csdn.containermanager.ContainerConfig - * ContainerConfig} - * @return returns the status code of adding a container entry - */ - public Status addContainerEntry(String containerName, List portList); - - /** - * Remove a resource from a given container. Updates the container data based on new - * resources removed. - * - * @param configObject - * refer to {@link com.ContainerConfig.csdn.containermanager.ContainerConfig - * ContainerConfig} - * @return returns the status code of removing a container entry - */ - public Status removeContainerEntry(String containerName, List portList); - - /** - * Adds/Removes a container flow - * - * @param configObject - * refer to {@link com.ContainerConfig.csdn.containermanager.ContainerConfig - * ContainerConfig} - * @return returns the status code of adding a container flow - */ - public Status addContainerFlows(String containerName, List configObject); - - /** - * Remove a container flow - * - * @param configObject - * refer to {@link com.ContainerConfig.csdn.containermanager.ContainerConfig - * ContainerConfig} - * @return returns the status of removing a container flow - */ - public Status removeContainerFlows(String containerName, List configObject); - - /** - * Remove a container flow - * - * @param containerName - * the name of the container - * @param name - * the name of the container flow - * @return the status of the request - */ - public Status removeContainerFlows(String containerName, Set name); - - /** - * Get the list of {@link com.ContainerConfig.csdn.containermanager.ContainerConfig - * ContainerConfig} objects representing all the containers that have been - * configured previously. - * - * @return the lsit of {@link com.ContainerConfig.csdn.containermanager.ContainerConfig - * ContainerConfig} objects configured so far - */ - public List getContainerConfigList(); - - /** - * Get the configuration object for the specified container - * - * @param containerName - * the name of the container - * @return a copy of the {@link com.ContainerConfig.csdn.containermanager.ContainerConfig - * ContainerConfig} object for the specified container if present, null - * otherwise - */ - public ContainerConfig getContainerConfig(String containerName); - - /** - * Returns a list of container names that currently exist. - * - * @return array of String container names - */ - public List getContainerNameList(); - - /** - * Check for the existence of a container - * - * @param ContainerId - * Name of the Container - * - * @return true if it exists, false otherwise - */ - public boolean doesContainerExist(String ContainerId); - - /** - * Get an array of ContainerFlowConfig objects representing all the - * container flows that have been configured previously. - * - * @return array of {@link org.opendaylight.controller.containermanager.ContainerFlowConfig - * ContainerFlowConfig} - */ - public Map> getContainerFlows(); - - /** - * Get an array of {@link org.opendaylight.controller.containermanager.ContainerFlowConfig - * ContainerFlowConfig} objects representing all the container flows that - * have been configured previously on the given containerName - * - * @param containerName - * the container name - * @return array of {@link org.opendaylight.controller.containermanager.ContainerFlowConfig - * ContainerFlowConfig} - */ - public List getContainerFlows(String containerName); - - /** - * Get an the list of names of the container flows that have been configured - * previously on the given containerName - * - * @param containerName - * the container name - * @return the array containing the names of the container flows configured - * on the specified container - */ - public List getContainerFlowNameList(String containerName); - - /** - * Returns true if there are any non-default Containers present. - * - * @return true if any non-default container is present false otherwise. - */ - public boolean hasNonDefaultContainer(); - - /** - * Returns a list of the existing containers. - * - * @return List of Container name strings. - */ - public List getContainerNames(); - - /** - * Returns whether the controller is running in container mode - * - * @return true if controller is in container mode, false otherwise - */ - public boolean inContainerMode(); -} diff --git a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManagerShell.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManagerShell.java deleted file mode 100644 index 2024b1855c..0000000000 --- a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/IContainerManagerShell.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.opendaylight.controller.containermanager; - -import java.util.List; - -public interface IContainerManagerShell { - public List psc(); - public List pfc(); - public List psd(); - public List psp(); - public List psm(); - public List addContainer(String arg1, String arg2); - public List createContainer(String arg1, String arg2); - public List removeContainerShell(String arg1); - public List addContainerEntry(String arg1, String arg2, String arg3); - public List removeContainerEntry(String arg1, String arg2, String arg3); - public List addContainerFlow(String arg1, String arg2, String arg3); - public List removeContainerFlow(String arg1, String arg2); - public List containermgrGetRoles(); - public List containermgrGetAuthorizedGroups(String arg1); - public List containermgrGetAuthorizedResources(String arg1); - public List containermgrGetResourcesForGroup(String arg1); - public List containermgrGetUserLevel(String arg1); - public List containermgrGetUserResources(String arg1); - public List saveConfig(); -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/NodeConnectorsChangeEvent.java b/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/NodeConnectorsChangeEvent.java deleted file mode 100644 index 5f992c76de..0000000000 --- a/opendaylight/adsal/containermanager/api/src/main/java/org/opendaylight/controller/containermanager/NodeConnectorsChangeEvent.java +++ /dev/null @@ -1,43 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager; - -import java.io.Serializable; -import java.util.List; - -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.UpdateType; - -/** - * Class that represent the event of a configuration change for a container - */ -public class NodeConnectorsChangeEvent implements Serializable { - private static final long serialVersionUID = 1L; - private List ncList; - private UpdateType updateType; - - public NodeConnectorsChangeEvent(List ncList, UpdateType updateType) { - this.ncList = ncList; - this.updateType = updateType; - } - - public List getNodeConnectors() { - return ncList; - } - - public UpdateType getUpdateType() { - return updateType; - } - - @Override - public String toString() { - return "ContainerConnectorsChangeEvent [ncList: " + ncList + " updateType: " + updateType + "]"; - } -} diff --git a/opendaylight/adsal/containermanager/implementation/pom.xml b/opendaylight/adsal/containermanager/implementation/pom.xml deleted file mode 100644 index 288977973f..0000000000 --- a/opendaylight/adsal/containermanager/implementation/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - containermanager.implementation - 0.7.0-SNAPSHOT - bundle - - - org.opendaylight.controller - appauth - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - topologymanager - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.containermanager, - org.opendaylight.controller.appauth.authorization, - org.opendaylight.controller.configuration, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.reader, - org.opendaylight.controller.topologymanager, - org.eclipse.osgi.framework.console, - org.osgi.framework, - org.slf4j, - org.apache.felix.dm - - org.opendaylight.controller.containermanager.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java b/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java deleted file mode 100644 index 61c8ab6c6e..0000000000 --- a/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java +++ /dev/null @@ -1,163 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager.internal; - -import org.eclipse.osgi.framework.console.CommandProvider; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Set; -import java.util.Hashtable; - -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.containermanager.IContainerManagerShell; -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.configuration.IConfigurationAware; -import org.opendaylight.controller.configuration.IConfigurationService; -import org.opendaylight.controller.containermanager.IContainerAuthorization; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.core.IContainer; -import org.opendaylight.controller.sal.core.IContainerAware; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.opendaylight.controller.sal.core.IContainerLocalListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory.getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the list of - * known implementations for containerd-services - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { ContainerImpl.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies is - * required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - * @param containerName - * The containername being configured, this allow also optional - * per-container different behavior if needed, usually should not be - * the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(ContainerImpl.class)) { - // export the service - c.setInterface(new String[] { IContainer.class.getName() }, null); - - // private interface exported by ContainerManager to retrieve - // internal data, this is mandatory to implement the - // IContainer functionality - c.add(createServiceDependency().setService(IContainerInternal.class) - .setCallbacks("setIContainerInternal", "unsetIContainerInternal") - .setRequired(true)); - } - } - - /** - * Method which tells how many NON-containerd implementations are supported by - * the bundle. This way we can tune the number of components created. This - * components will be created ONLY at the time of bundle startup and will be - * destroyed only at time of bundle destruction, this is the major - * difference with the implementation retrieved via getImplementations where - * all of them are assumed to be containerd! - * - * - * @return The list of implementations the bundle will support, in - * non-containerd version - */ - @Override - protected Object[] getGlobalImplementations() { - Object[] res = { ContainerManager.class }; - return res; - } - - /** - * Configure the dependency for a given instance non-containerd - * - * @param c - * Component assigned for this instance, this will be what will - * be used for configuration - * @param imp - * implementation to be configured - * @param containerName - * container on which the configuration happens - */ - @Override - protected void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(ContainerManager.class)) { - Dictionary> props = new Hashtable>(); - Set propSet = new HashSet(); - propSet.add("containermgr.event.containerChange"); - props.put("cachenames", propSet); - - // export the service - c.setInterface( - new String[] { IContainerManager.class.getName(), - IContainerManager.class.getName(), - IConfigurationAware.class.getName(), - CommandProvider.class.getName(), - IContainerInternal.class.getName(), - IContainerAuthorization.class.getName(), - ICacheUpdateAware.class.getName(), - IContainerManagerShell.class.getName()}, props); - - c.add(createServiceDependency() - .setService(IClusterGlobalServices.class) - .setCallbacks("setClusterServices", "unsetClusterServices") - .setRequired(true)); - - c.add(createServiceDependency().setService( - IConfigurationService.class).setCallbacks( - "setConfigurationService", - "unsetConfigurationService").setRequired(true)); - - // Key kick-starter for container creation in each component - c.add(createServiceDependency().setService(IContainerAware.class) - .setCallbacks("setIContainerAware", "unsetIContainerAware") - .setRequired(false)); - - // Optional interface expected to be exported by the - // protocol plugins to setup proper filtering based on - // slicing events - c.add(createServiceDependency() - .setService(IContainerListener.class) - .setCallbacks("setIContainerListener", "unsetIContainerListener") - .setRequired(false)); - - // Interface expected to be exported by the Functional Modules - c.add(createServiceDependency() - .setService(IContainerLocalListener.class) - .setCallbacks("setIContainerLocalListener", "unsetIContainerLocalListener") - .setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java b/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java deleted file mode 100644 index cb2a289af3..0000000000 --- a/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java +++ /dev/null @@ -1,125 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file ContainerImpl.java - * - * @brief Class that instantiated per-container implements the - * interface IContainer - * - */ -package org.opendaylight.controller.containermanager.internal; - -import java.util.ArrayList; -import java.util.Dictionary; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.containermanager.ContainerData; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.IContainer; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; - -public class ContainerImpl implements IContainer { - private String containerName = null; - private IContainerInternal iContainerInternal = null; - - public void setIContainerInternal(IContainerInternal s) { - this.iContainerInternal = s; - } - - public void unsetIContainerInternal(IContainerInternal s) { - if (this.iContainerInternal == s) { - this.iContainerInternal = null; - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init(Component c) { - Dictionary props = c.getServiceProperties(); - if (props != null) { - this.containerName = (String) props.get("containerName"); - } - } - - @Override - public String getName() { - return this.containerName; - } - - @Override - public List getContainerFlows() { - List list = new ArrayList(); - - ContainerData d = this.iContainerInternal.getContainerData(this.containerName); - if (d != null) { - list.addAll(d.getContainerFlowSpecs()); - } - return list; - } - - @Override - public short getTag(Node n) { - ContainerData d = this.iContainerInternal.getContainerData(this.containerName); - if (d != null) { - return d.getStaticVlan(); - } - // Return 0 because in containerData that means an unassigned tag - return (short) 0; - } - - @Override - public Set getNodeConnectors() { - Set set = new HashSet(); - - ContainerData d = this.iContainerInternal.getContainerData(this.containerName); - if (d != null) { - ConcurrentMap> m = d.getSwPorts(); - if (m != null) { - for (Map.Entry> entry : m.entrySet()) { - set.addAll(entry.getValue()); - } - } - } - return set; - } - - @Override - public Set getNodes() { - Set set = new HashSet(); - - ContainerData d = this.iContainerInternal.getContainerData(this.containerName); - if (d != null) { - ConcurrentMap> m = d.getSwPorts(); - if (m != null) { - set.addAll(m.keySet()); - } - } - return set; - } - - @Override - public String getContainerAdminRole() { - return iContainerInternal.getContainerData(containerName).getContainerAdminRole(); - } - - @Override - public String getContainerOperatorRole() { - return iContainerInternal.getContainerData(containerName).getContainerOperatorRole(); - } -} diff --git a/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java b/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java deleted file mode 100644 index 98378e8135..0000000000 --- a/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java +++ /dev/null @@ -1,1905 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager.internal; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.appauth.authorization.Authorization; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.configuration.IConfigurationAware; -import org.opendaylight.controller.configuration.IConfigurationService; -import org.opendaylight.controller.containermanager.ContainerChangeEvent; -import org.opendaylight.controller.containermanager.ContainerConfig; -import org.opendaylight.controller.containermanager.ContainerData; -import org.opendaylight.controller.containermanager.ContainerFlowChangeEvent; -import org.opendaylight.controller.containermanager.ContainerFlowConfig; -import org.opendaylight.controller.containermanager.IContainerAuthorization; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.containermanager.IContainerManagerShell; -import org.opendaylight.controller.containermanager.NodeConnectorsChangeEvent; -import org.opendaylight.controller.sal.authorization.AppRoleLevel; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.authorization.Resource; -import org.opendaylight.controller.sal.authorization.ResourceGroup; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.IContainerAware; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.opendaylight.controller.sal.core.IContainerLocalListener; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.IObjectReader; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ContainerManager extends Authorization implements IContainerManager, IObjectReader, - CommandProvider, ICacheUpdateAware, IContainerInternal, IContainerAuthorization, - IConfigurationAware, IContainerManagerShell { - private static final Logger logger = LoggerFactory.getLogger(ContainerManager.class); - private static String CONTAINERS_FILE_NAME = "containers.conf"; - private static final String allContainersGroup = "allContainers"; - private IClusterGlobalServices clusterServices; - private IConfigurationService configurationService; - /* - * Collection containing the configuration objects. This is configuration - * world: container names (also the map key) are maintained as they were - * configured by user, same case - */ - private ConcurrentMap containerConfigs; - private ConcurrentMap containerData; - private ConcurrentMap> nodeConnectorToContainers; - private ConcurrentMap> nodeToContainers; - private ConcurrentMap containerChangeEvents; - private final Set iContainerAware = Collections.synchronizedSet(new HashSet()); - private final Set iContainerListener = Collections - .synchronizedSet(new HashSet()); - private final Set iContainerLocalListener = Collections - .synchronizedSet(new HashSet()); - - void setIContainerListener(IContainerListener s) { - if (this.iContainerListener != null) { - this.iContainerListener.add(s); - /* - * At boot with startup, containers are created before listeners have - * joined. Replaying here the first container creation notification for - * the joining listener when containers are already present. Also - * replaying all the node connectors and container flows additions - * to the existing containers. - */ - if (!this.containerData.isEmpty()) { - s.containerModeUpdated(UpdateType.ADDED); - } - for (ConcurrentMap.Entry> entry : nodeConnectorToContainers - .entrySet()) { - NodeConnector port = entry.getKey(); - for (String container : entry.getValue()) { - s.nodeConnectorUpdated(container, port, UpdateType.ADDED); - } - } - for (Map.Entry container : containerData.entrySet()) { - for (ContainerFlow cFlow : container.getValue().getContainerFlowSpecs()) { - s.containerFlowUpdated(container.getKey(), cFlow, cFlow, UpdateType.ADDED); - } - } - } - } - - void unsetIContainerListener(IContainerListener s) { - if (this.iContainerListener != null) { - this.iContainerListener.remove(s); - } - } - - void setIContainerLocalListener(IContainerLocalListener s) { - if (this.iContainerLocalListener != null) { - this.iContainerLocalListener.add(s); - } - } - - void unsetIContainerLocalListener(IContainerLocalListener s) { - if (this.iContainerLocalListener != null) { - this.iContainerLocalListener.remove(s); - } - } - - public void setIContainerAware(IContainerAware iContainerAware) { - if (!this.iContainerAware.contains(iContainerAware)) { - this.iContainerAware.add(iContainerAware); - // Now call the container creation for all the known containers so far - for (String container : getContainerNameList()) { - iContainerAware.containerCreate(container.toLowerCase(Locale.ENGLISH)); - } - } - } - - public void unsetIContainerAware(IContainerAware iContainerAware) { - this.iContainerAware.remove(iContainerAware); - // There is no need to do cleanup of the component when - // unregister because it will be taken care by the Container - // component itself - } - - public void setClusterServices(IClusterGlobalServices i) { - this.clusterServices = i; - logger.debug("IClusterServices set"); - } - - public void unsetClusterServices(IClusterGlobalServices i) { - if (this.clusterServices == i) { - this.clusterServices = null; - logger.debug("IClusterServices Unset"); - } - } - - public void setConfigurationService(IConfigurationService service) { - logger.trace("Got configuration service set request {}", service); - this.configurationService = service; - } - - public void unsetConfigurationService(IConfigurationService service) { - logger.trace("Got configuration service UNset request"); - this.configurationService = null; - } - - private void allocateCaches() { - logger.debug("Container Manager allocating caches"); - - if (clusterServices == null) { - logger.warn("un-initialized Cluster Services, can't allocate caches"); - return; - } - try { - clusterServices.createCache("containermgr.containerConfigs", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterServices.createCache("containermgr.event.containerChange", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterServices.createCache("containermgr.containerData", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterServices.createCache("containermgr.nodeConnectorToContainers", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterServices.createCache("containermgr.nodeToContainers", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterServices.createCache("containermgr.containerGroups", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterServices.createCache("containermgr.containerAuthorizations", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterServices.createCache("containermgr.roles", EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheConfigException cce) { - logger.error("Cache configuration invalid - check cache mode"); - } catch (CacheExistException ce) { - logger.error("Cache already exits - destroy and recreate if needed"); - } - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - logger.debug("Container Manager retrieving caches"); - - if (clusterServices == null) { - logger.warn("un-initialized Cluster Services, can't retrieve caches"); - return; - } - - containerConfigs = (ConcurrentMap) clusterServices.getCache("containermgr.containerConfigs"); - - containerChangeEvents = (ConcurrentMap) clusterServices.getCache("containermgr.event.containerChange"); - - containerData = (ConcurrentMap) clusterServices.getCache("containermgr.containerData"); - - nodeConnectorToContainers = (ConcurrentMap>) clusterServices - .getCache("containermgr.nodeConnectorToContainers"); - - nodeToContainers = (ConcurrentMap>) clusterServices.getCache("containermgr.nodeToContainers"); - - resourceGroups = (ConcurrentMap>) clusterServices.getCache("containermgr.containerGroups"); - - groupsAuthorizations = (ConcurrentMap>) clusterServices - .getCache("containermgr.containerAuthorizations"); - - roles = (ConcurrentMap) clusterServices.getCache("containermgr.roles"); - - if (inContainerMode()) { - for (Map.Entry entry : containerConfigs.entrySet()) { - // Notify global and local listeners about the mode change - notifyContainerChangeInternal(entry.getValue(), UpdateType.ADDED, true); - } - } - } - - @Override - public void entryCreated(String containerName, String cacheName, boolean originLocal) { - - } - - @Override - public void entryUpdated(String key, Object value, String cacheName, boolean originLocal) { - /* - * This is were container manager replays a configuration event that was - * notified by its peer from a cluster node where the configuration - * happened. Only the global listeners, the cluster unaware classes, - * (mainly the shim classes in the sdn protocol plugins) need to receive - * these notifications on this cluster node. The cluster aware classes, - * like the functional modules which reacts on these events, must _not_ - * be notified to avoid parallel computation in the cluster. - */ - if (!originLocal) { - if (value instanceof NodeConnectorsChangeEvent) { - NodeConnectorsChangeEvent event = (NodeConnectorsChangeEvent) value; - List ncList = event.getNodeConnectors(); - notifyContainerEntryChangeInternal(key, ncList, event.getUpdateType(), false); - } else if (value instanceof ContainerFlowChangeEvent) { - ContainerFlowChangeEvent event = (ContainerFlowChangeEvent) value; - notifyCFlowChangeInternal(key, event.getConfigList(), event.getUpdateType(), false); - } else if (value instanceof ContainerChangeEvent) { - ContainerChangeEvent event = (ContainerChangeEvent) value; - notifyContainerChangeInternal(event.getConfig(), event.getUpdateType(), false); - } - } - } - - @Override - public void entryDeleted(String containerName, String cacheName, boolean originLocal) { - } - - public ContainerManager() { - } - - public void init() { - - } - - public void start() { - // Get caches from cluster manager - allocateCaches(); - retrieveCaches(); - - // Allocates default groups and association to default roles - createDefaultAuthorizationGroups(); - - // Read startup configuration and create local database - loadContainerConfig(); - } - - public void destroy() { - // Clear local states - this.iContainerAware.clear(); - this.iContainerListener.clear(); - this.iContainerLocalListener.clear(); - } - - /** - * Adds/Remove the list of flow specs to/from the specified container. This - * function is supposed to be called after all the validation checks have - * already been run on the proposed configuration. - */ - private Status updateContainerFlow(String containerName, List confList, boolean delete) { - ContainerData container = getContainerByName(containerName); - if (container == null) { - return new Status(StatusCode.GONE, "Container not present"); - } - - for (ContainerFlowConfig conf : confList) { - // Validation was fine. Modify the database now. - for (Match match : conf.getMatches()) { - ContainerFlow cFlow = new ContainerFlow(match); - if (delete) { - logger.trace("Removing Flow Spec {} from Container {}", conf.getName(), containerName); - container.deleteFlowSpec(cFlow); - } else { - logger.trace("Adding Flow Spec {} to Container {}", conf.getName(), containerName); - container.addFlowSpec(cFlow); - - } - // Update Database - putContainerDataByName(containerName, container); - } - } - return new Status(StatusCode.SUCCESS); - } - - /** - * Adds/Remove this container to/from the Container database, no updates are going - * to be generated here other that the destroying and creation of the container. - * This function is supposed to be called after all the validation checks - * have already been run on the configuration object - */ - private Status updateContainerDatabase(ContainerConfig containerConf, boolean delete) { - /* - * Back-end world here, container names are all stored in lower case - */ - String containerName = containerConf.getContainerName(); - ContainerData container = getContainerByName(containerName); - if (delete && container == null) { - return new Status(StatusCode.NOTFOUND, "Container is not present"); - } - if (!delete && container != null) { - // A container with the same (lower case) name already exists - return new Status(StatusCode.CONFLICT, "A container with the same name already exists"); - } - if (delete) { - logger.debug("Removing container {}", containerName); - removeNodeToContainersMapping(container); - removeNodeConnectorToContainersMapping(container); - removeContainerDataByName(containerName); - } else { - logger.debug("Adding container {}", containerName); - container = new ContainerData(containerConf); - putContainerDataByName(containerName, container); - - // If flow specs are specified, add them - if (containerConf.hasFlowSpecs()) { - updateContainerFlow(containerName, containerConf.getContainerFlowConfigs(), delete); - } - - // If ports are specified, add them - if (!containerConf.getPortList().isEmpty()) { - updateContainerEntryDatabase(containerName, containerConf.getPortList(), delete); - } - } - return new Status(StatusCode.SUCCESS); - } - - private void removeNodeConnectorToContainersMapping(ContainerData container) { - Iterator>> it = nodeConnectorToContainers.entrySet().iterator(); - String containerName = container.getContainerName(); - for (; it.hasNext();) { - Entry> entry = it.next(); - final NodeConnector nc = entry.getKey(); - final CopyOnWriteArrayList slist = entry.getValue(); - for (final String sdata : slist) { - if (sdata.equalsIgnoreCase(containerName)) { - logger.debug("Removing NodeConnector->Containers mapping, nodeConnector: {}", nc); - slist.remove(containerName); - if (slist.isEmpty()) { - nodeConnectorToContainers.remove(nc); - } else { - nodeConnectorToContainers.put(nc, slist); - } - break; - } - } - } - } - - private void removeNodeToContainersMapping(ContainerData container) { - for (Entry> entry : nodeToContainers.entrySet()) { - Node node = entry.getKey(); - for (String sdata : entry.getValue()) { - if (sdata.equals(container.getContainerName())) { - logger.debug("Removing Node->Containers mapping, node {} container {}", node, sdata); - Set value = nodeToContainers.get(node); - value.remove(sdata); - nodeToContainers.put(node, value); - break; - } - } - } - } - - /** - * Adds/Remove container data to/from the container. This function is supposed to be - * called after all the validation checks have already been run on the - * configuration object - */ - private Status updateContainerEntryDatabase(String containerName, List nodeConnectors, boolean delete) { - ContainerData container = getContainerByName(containerName); - // Presence check - if (container == null) { - return new Status(StatusCode.NOTFOUND, "Container Not Found"); - } - - // Check changes in the portlist - for (NodeConnector port : nodeConnectors) { - Node node = port.getNode(); - if (delete) { - container.removePortFromSwitch(port); - putContainerDataByName(containerName, container); - - /* remove - container mapping */ - if (nodeConnectorToContainers.containsKey(port)) { - nodeConnectorToContainers.remove(port); - } - /* - * If no more ports in the switch, remove switch from container - * Generate switchRemoved Event - */ - if (container.portListEmpty(node)) { - logger.debug("Port List empty for switch {}", node); - putContainerDataByName(containerName, container); - // remove node->containers mapping - Set slist = nodeToContainers.get(node); - if (slist != null) { - logger.debug("Removing container from switch-container list. node{}, container{}", node, containerName); - slist.remove(container.getContainerName()); - nodeToContainers.put(node, slist); - if (slist.isEmpty()) { - logger.debug("Container list empty for switch {}. removing switch-container mapping", node); - nodeToContainers.remove(node); - } - } - } - } else { - if (container.isSwitchInContainer(node) == false) { - Set value = nodeToContainers.get(node); - // Add node->containers mapping - if (value == null) { - value = new HashSet(); - logger.debug("Creating new Container Set for switch {}", node); - } - value.add(container.getContainerName()); - nodeToContainers.put(node, value); - } - container.addPortToSwitch(port); - putContainerDataByName(containerName, container); - - // added nc->containers mapping - CopyOnWriteArrayList slist = nodeConnectorToContainers.get(port); - if (slist == null) { - slist = new CopyOnWriteArrayList(); - } - slist.add(container.getContainerName()); - nodeConnectorToContainers.put(port, slist); - } - } - return new Status(StatusCode.SUCCESS); - } - - private Status validateContainerFlowAddRemoval(String containerName, ContainerFlow cFlow, boolean delete) { - /* - * It used to be the comment below: ~~~~~~~~~~~~~~~~~~~~ If Link Sharing - * at Host facing interfaces, then disallow last ContainerFlow removal - * ~~~~~~~~~~~~~~~~~~~~ But the interface being host facing is a - * condition that can change at runtime and so the final effect will be - * unreliable. So now we will always allow the container flow removal, - * if this is a link host facing and is shared by many that will cause - * issues but that validation should be done not at the configuration - * but in the UI/northbound side. - */ - ContainerData container = this.getContainerByName(containerName); - if (container == null) { - String error = String.format("Cannot validate flow specs for container %s: (Container does not exist)", containerName); - logger.warn(error); - return new Status(StatusCode.BADREQUEST, error); - } - - if (delete) { - Set thisContainerPorts = container.getNodeConnectors(); - // Go through all the installed containers - for (Map.Entry entry : containerData.entrySet()) { - if (containerName.equalsIgnoreCase(entry.getKey())) { - continue; - } - // Derive the common ports - Set commonPorts = entry.getValue().getNodeConnectors(); - commonPorts.retainAll(thisContainerPorts); - if (commonPorts.isEmpty()) { - continue; - } - - // Check if this operation would remove the only flow spec - // assigned to this container - if (container.getFlowSpecCount() == 1) { - if (!container.hasStaticVlanAssigned()) { - // Ports are shared and static vlan is not present: this - // is a failure - // regardless the shared ports are host facing or - // interswitch ports - return new Status(StatusCode.BADREQUEST, "Container shares port with another container: " - + "The only one flow spec assigned to this container cannot be removed," - + "because this container is not assigned any static vlan"); - } - - // Check on host facing port - ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance( - ITopologyManager.class, GlobalConstants.DEFAULT.toString(), this); - if (topologyManager == null) { - return new Status(StatusCode.NOSERVICE, - "Cannot validate the request: Required service is not available"); - } - for (NodeConnector nc : commonPorts) { - /* - * Shared link case : For internal port check if it has - * a vlan configured. If vlan is configured, allow the - * flowspec to be deleted If the port is host-facing, do - * not allow the flowspec to be deleted - */ - if (!topologyManager.isInternal(nc)) { - return new Status(StatusCode.BADREQUEST, String.format( - "Port %s is shared and is host facing port: " - + "The only one flow spec assigned to this container cannot be removed", nc)); - } - } - } - } - } else { - // Adding a new flow spec: need to check if other containers with common - // ports do not have same flow spec - Set thisContainerPorts = container.getNodeConnectors(); - List proposed = new ArrayList(container.getContainerFlowSpecs()); - proposed.add(cFlow); - for (Map.Entry entry : containerData.entrySet()) { - if (containerName.equalsIgnoreCase(entry.getKey())) { - continue; - } - ContainerData otherContainer = entry.getValue(); - Set commonPorts = otherContainer.getNodeConnectors(); - commonPorts.retainAll(thisContainerPorts); - - if (!commonPorts.isEmpty()) { - Status status = checkCommonContainerFlow(otherContainer.getContainerFlowSpecs(), proposed); - if (!status.isSuccess()) { - return new Status(StatusCode.BADREQUEST, String.format( - "Container %s which shares ports with this container has overlapping flow spec: %s", - entry.getKey(), status.getDescription())); - } - } - } - } - - return new Status(StatusCode.SUCCESS); - } - - /** - * Checks if the passed list of node connectors can be safely applied to the - * specified existing container in terms of port sharing with other containers. - * - * @param containerName - * the name of the existing container - * @param portList - * the list of node connectors to be added to the container - * @return the status object representing the result of the check - */ - private Status validatePortSharing(String containerName, List portList) { - ContainerData container = this.getContainerByName(containerName); - if (container == null) { - String error = String - .format("Cannot validate port sharing for container %s: (container does not exist)", containerName); - logger.error(error); - return new Status(StatusCode.BADREQUEST, error); - } - return validatePortSharingInternal(portList, container.getContainerFlowSpecs()); - } - - /** - * Checks if the proposed container configuration is valid to be applied in - * terms of port sharing with other containers. - * - * @param containerConf - * the container configuration object containing the list of node - * connectors - * @return the status object representing the result of the check - */ - private Status validatePortSharing(ContainerConfig containerConf) { - return validatePortSharingInternal(containerConf.getPortList(), containerConf.getContainerFlowSpecs()); - } - - /* - * If any port is shared with an existing container, need flowSpec to be - * configured. If no flowSpec for this or other container, or if containers have any - * overlapping flowspec in common, then let the caller know this - * configuration has to be rejected. - */ - private Status validatePortSharingInternal(List portList, List flowSpecList) { - for (NodeConnector port : portList) { - List slist = nodeConnectorToContainers.get(port); - if (slist != null && !slist.isEmpty()) { - for (String otherContainerName : slist) { - String msg = null; - ContainerData other = containerData.get(otherContainerName); - if (flowSpecList.isEmpty()) { - msg = String.format("Port %s is shared and flow spec is empty for this container", port); - } else if (other.isFlowSpecEmpty()) { - msg = String.format("Port %s is shared and flow spec is empty for the other container", port); - } else if (!checkCommonContainerFlow(flowSpecList, other.getContainerFlowSpecs()).isSuccess()) { - msg = String.format("Port %s is shared and other container has common flow spec", port); - } - if (msg != null) { - logger.debug(msg); - return new Status(StatusCode.BADREQUEST, msg); - } - } - } - } - return new Status(StatusCode.SUCCESS); - } - - /** - * Utility function to check if two lists of container flows share any same - * or overlapping container flows. - * - * @param oneFlowList - * One of the two lists of container flows to test - * @param twoFlowList - * One of the two lists of container flows to test - * @return The status of the check. Either SUCCESS or CONFLICT. In case of - * conflict, the Status will contain the description for the failed - * check. - */ - private Status checkCommonContainerFlow(List oneFlowList, List twoFlowList) { - for (ContainerFlow oneFlow : oneFlowList) { - for (ContainerFlow twoFlow : twoFlowList) { - if (oneFlow.getMatch().intersetcs(twoFlow.getMatch())) { - return new Status(StatusCode.CONFLICT, String.format("Flow Specs overlap: %s %s", - oneFlow.getMatch(), twoFlow.getMatch())); - } - } - } - return new Status(StatusCode.SUCCESS); - } - - /** - * Return the ContainerData object for the passed container name. Given this is a - * backend database, the lower case version of the passed name is used while - * searching for the corresponding ContainerData object. - * - * @param name - * The container name in any case - * @return The corresponding ContainerData object - */ - private ContainerData getContainerByName(String name) { - return containerData.get(name.toLowerCase(Locale.ENGLISH)); - } - - /** - * Add a ContainerData object for the given container name. - * - * @param name - * The container name in any case - * @param sData - * The container data object - */ - private void putContainerDataByName(String name, ContainerData sData) { - containerData.put(name.toLowerCase(Locale.ENGLISH), sData); - } - - /** - * Removes the ContainerData object for the given container name. - * - * @param name - * The container name in any case - */ - private void removeContainerDataByName(String name) { - containerData.remove(name.toLowerCase(Locale.ENGLISH)); - } - - @Override - public List getContainerConfigList() { - return new ArrayList(containerConfigs.values()); - } - - @Override - public ContainerConfig getContainerConfig(String containerName) { - ContainerConfig target = containerConfigs.get(containerName); - return (target == null) ? null : new ContainerConfig(target); - } - - @Override - public List getContainerNameList() { - /* - * Return container names as they were configured by user (case sensitive) - * along with the default container - */ - List containerNameList = new ArrayList(); - containerNameList.add(GlobalConstants.DEFAULT.toString()); - containerNameList.addAll(containerConfigs.keySet()); - return containerNameList; - } - - @Override - public Map> getContainerFlows() { - Map> flowSpecConfig = new HashMap>(); - for (Map.Entry entry : containerConfigs.entrySet()) { - List set = entry.getValue().getContainerFlowConfigs(); - flowSpecConfig.put(entry.getKey(), set); - } - return flowSpecConfig; - } - - private Status saveContainerConfig() { - return saveContainerConfigLocal(); - } - - public Status saveContainerConfigLocal() { - Status status = configurationService.persistConfiguration( - new ArrayList(containerConfigs.values()), CONTAINERS_FILE_NAME); - - if (!status.isSuccess()) { - return new Status(StatusCode.INTERNALERROR, "Failed to save container configurations: " - + status.getDescription()); - } - return status; - } - - /** - * Create and initialize default all resource group and create association - * with default well known users and profiles, if not already learnt from - * another cluster node - */ - private void createDefaultAuthorizationGroups() { - allResourcesGroupName = ContainerManager.allContainersGroup; - - // Add the default container to the all containers group if needed - String defaultContainer = GlobalConstants.DEFAULT.toString(); - Set allContainers = (resourceGroups.containsKey(allResourcesGroupName)) ? resourceGroups - .get(allResourcesGroupName) : new HashSet(); - if (!allContainers.contains(defaultContainer)) { - // Add Default container - allContainers.add(defaultContainer); - // Update cluster - resourceGroups.put(allResourcesGroupName, allContainers); - } - - // Add the controller well known roles, if not known already - if (!roles.containsKey(UserLevel.SYSTEMADMIN.toString())) { - roles.put(UserLevel.SYSTEMADMIN.toString(), AppRoleLevel.APPADMIN); - } - if (!roles.containsKey(UserLevel.NETWORKADMIN.toString())) { - roles.put(UserLevel.NETWORKADMIN.toString(), AppRoleLevel.APPADMIN); - } - if (!roles.containsKey(UserLevel.NETWORKOPERATOR.toString())) { - roles.put(UserLevel.NETWORKOPERATOR.toString(), AppRoleLevel.APPOPERATOR); - } - - /* - * Create and add the all containers user groups and associate them to the - * default well known user roles, if not present already - */ - if (!groupsAuthorizations.containsKey(UserLevel.NETWORKADMIN.toString())) { - Set writeProfile = new HashSet(1); - Set readProfile = new HashSet(1); - writeProfile.add(new ResourceGroup(allResourcesGroupName, Privilege.WRITE)); - readProfile.add(new ResourceGroup(allResourcesGroupName, Privilege.READ)); - groupsAuthorizations.put(UserLevel.SYSTEMADMIN.toString(), writeProfile); - groupsAuthorizations.put(UserLevel.NETWORKADMIN.toString(), writeProfile); - groupsAuthorizations.put(UserLevel.NETWORKOPERATOR.toString(), readProfile); - } - } - - /** - * Until manual configuration is not available, automatically maintain the - * well known resource groups - * - * @param containerName - * @param delete - */ - private void updateResourceGroups(ContainerConfig containerConf, boolean delete) { - // Container Roles and Container Resource Group - String containerName = containerConf.getContainer(); - String groupName = containerConf.getContainerGroupName(); - String containerAdminRole = containerConf.getContainerAdminRole(); - String containerOperatorRole = containerConf.getContainerOperatorRole(); - Set allContainerSet = resourceGroups.get(allResourcesGroupName); - if (delete) { - resourceGroups.remove(groupName); - groupsAuthorizations.remove(containerAdminRole); - groupsAuthorizations.remove(containerOperatorRole); - roles.remove(containerAdminRole); - roles.remove(containerOperatorRole); - // Update the all container group - allContainerSet.remove(containerName); - } else { - Set resources = new HashSet(1); - resources.add(containerName); - resourceGroups.put(groupName, resources); - Set adminGroups = new HashSet(1); - Set operatorGroups = new HashSet(1); - adminGroups.add(new ResourceGroup(groupName, Privilege.WRITE)); - operatorGroups.add(new ResourceGroup(groupName, Privilege.READ)); - groupsAuthorizations.put(containerAdminRole, adminGroups); - groupsAuthorizations.put(containerOperatorRole, operatorGroups); - roles.put(containerAdminRole, AppRoleLevel.APPADMIN); - roles.put(containerOperatorRole, AppRoleLevel.APPOPERATOR); - // Update the all containers resource group - allContainerSet.add(containerName); - } - // Update resource groups in cluster - resourceGroups.put(allResourcesGroupName, allContainerSet); - } - - /** - * Notify ContainerAware listeners of the creation/deletion of the container - * - * @param containerName - * @param delete - * true is container was removed, false otherwise - */ - private void notifyContainerAwareListeners(String containerName, boolean delete) { - // Back-end World: container name forced to lower case - String name = containerName.toLowerCase(Locale.ENGLISH); - - synchronized (this.iContainerAware) { - for (IContainerAware i : this.iContainerAware) { - if (delete) { - i.containerDestroy(name); - } else { - i.containerCreate(name); - } - } - } - } - - /** - * Notify the ContainerListener listeners in case the container mode has - * changed following a container configuration operation Note: this call - * must happen after the configuration db has been updated - * - * @param lastActionDelete - * true if the last container configuration operation was a - * container delete operation - * @param notifyLocal - * if true, the notification is also sent to the - * IContainerLocalListener classes besides the IContainerListener - * classes - */ - private void notifyContainerModeChange(boolean lastActionDelete, boolean notifyLocal) { - if (lastActionDelete == false && containerConfigs.size() == 1) { - logger.trace("First container Creation. Inform listeners"); - synchronized (this.iContainerListener) { - for (IContainerListener i : this.iContainerListener) { - i.containerModeUpdated(UpdateType.ADDED); - } - } - if (notifyLocal) { - synchronized (this.iContainerLocalListener) { - for (IContainerLocalListener i : this.iContainerLocalListener) { - i.containerModeUpdated(UpdateType.ADDED); - } - } - } - } else if (lastActionDelete == true && containerConfigs.isEmpty()) { - logger.trace("Last container Deletion. Inform listeners"); - synchronized (this.iContainerListener) { - for (IContainerListener i : this.iContainerListener) { - i.containerModeUpdated(UpdateType.REMOVED); - } - } - if (notifyLocal) { - synchronized (this.iContainerLocalListener) { - for (IContainerLocalListener i : this.iContainerLocalListener) { - i.containerModeUpdated(UpdateType.REMOVED); - } - } - } - } - } - - private Status addRemoveContainerEntries(String containerName, List nodeConnectorsString, boolean delete) { - // Construct action message - String action = String.format("Node connector(s) %s container %s: %s", delete ? "removal from" : "addition to", - containerName, nodeConnectorsString); - - // Validity Check - if (nodeConnectorsString == null || nodeConnectorsString.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Node connector list is null or empty"); - } - - // Presence check - ContainerConfig entryConf = containerConfigs.get(containerName); - if (entryConf == null) { - String msg = String.format("Container not found: %s", containerName); - String error = String.format("Failed to apply %s: (%s)", action, msg); - logger.warn(error); - return new Status(StatusCode.NOTFOUND, msg); - } - - // Validation check - Status status = ContainerConfig.validateNodeConnectors(nodeConnectorsString); - if (!status.isSuccess()) { - String error = String.format("Failed to apply %s: (%s)", action, status.getDescription()); - logger.warn(error); - return status; - } - - List nodeConnectors = ContainerConfig.nodeConnectorsFromString(nodeConnectorsString); - - // Port sharing check - if (!delete) { - /* - * Check if the ports being added to this container already belong to - * other containers. If so check whether the the appropriate flow specs - * are configured on this container - */ - status = validatePortSharing(containerName, nodeConnectors); - if (!status.isSuccess()) { - String error = String.format("Failed to apply %s: (%s)", action, status.getDescription()); - logger.warn(error); - return status; - } - } - - // Update Database - status = updateContainerEntryDatabase(containerName, nodeConnectors, delete); - if (!status.isSuccess()) { - String error = String.format("Failed to apply %s: (%s)", action, status.getDescription()); - logger.warn(error); - return status; - } - - // Update Configuration - status = (delete) ? entryConf.removeNodeConnectors(nodeConnectorsString) : entryConf - .addNodeConnectors(nodeConnectorsString); - if (!status.isSuccess()) { - String error = String.format("Failed to modify config for %s: (%s)", action, status.getDescription()); - logger.warn(error); - // Revert backend changes - Status statusRevert = updateContainerEntryDatabase(containerName, nodeConnectors, !delete); - if (!statusRevert.isSuccess()) { - // Unlikely - logger.error("Failed to revert changes in database (CRITICAL)"); - } - return status; - } - - // Update cluster Configuration cache - containerConfigs.put(containerName, entryConf); - - // Notify global and local listeners - UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED; - notifyContainerEntryChangeInternal(containerName, nodeConnectors, update, true); - // Trigger cluster notification - containerChangeEvents.put(containerName, new NodeConnectorsChangeEvent(nodeConnectors, update)); - - return status; - } - - private void notifyContainerChangeInternal(ContainerConfig conf, UpdateType update, boolean notifyLocal) { - String containerName = conf.getContainerName(); - logger.trace("Notifying listeners on {} for container {}", update, containerName); - // Back-end World: container name forced to lower case - String container = containerName.toLowerCase(Locale.ENGLISH); - boolean delete = (update == UpdateType.REMOVED); - // Check if a container mode change notification is needed - notifyContainerModeChange(delete, notifyLocal); - // Notify listeners - notifyContainerAwareListeners(container, delete); - } - - private void notifyContainerEntryChangeInternal(String containerName, List ncList, UpdateType update, boolean notifyLocal) { - logger.trace("Notifying listeners on {} for ports {} in container {}", update, ncList, containerName); - // Back-end World: container name forced to lower case - String container = containerName.toLowerCase(Locale.ENGLISH); - for (NodeConnector nodeConnector : ncList) { - // Now signal that the port has been added/removed - synchronized (this.iContainerListener) { - for (IContainerListener i : this.iContainerListener) { - i.nodeConnectorUpdated(container, nodeConnector, update); - } - } - // Check if the Functional Modules need to be notified as well - if (notifyLocal) { - synchronized (this.iContainerLocalListener) { - for (IContainerLocalListener i : this.iContainerLocalListener) { - i.nodeConnectorUpdated(container, nodeConnector, update); - } - } - } - } - } - - private void notifyCFlowChangeInternal(String containerName, List confList, UpdateType update, - boolean notifyLocal) { - logger.trace("Notifying listeners on {} for flow specs {} in container {}", update, confList, containerName); - // Back-end World: container name forced to lower case - String container = containerName.toLowerCase(Locale.ENGLISH); - - for (ContainerFlowConfig conf : confList) { - for (Match match : conf.getMatches()) { - ContainerFlow cFlow = new ContainerFlow(match); - synchronized (this.iContainerListener) { - for (IContainerListener i : this.iContainerListener) { - i.containerFlowUpdated(container, cFlow, cFlow, update); - } - } - // Check if the Functional Modules need to be notified as well - if (notifyLocal) { - synchronized (this.iContainerLocalListener) { - for (IContainerLocalListener i : this.iContainerLocalListener) { - i.containerFlowUpdated(container, cFlow, cFlow, update); - } - } - } - } - } - } - - private Status addRemoveContainerFlow(String containerName, List cFlowConfList, boolean delete) { - // Construct action message - String action = String.format("Flow spec(s) %s container %s: %s", delete ? "removal from" : "addition to", - containerName, cFlowConfList); - - // Presence check - ContainerConfig containerConfig = this.containerConfigs.get(containerName); - if (containerConfig == null) { - String msg = String.format("Container not found: %s", containerName); - String error = String.format("Failed to apply %s: (%s)", action, msg); - logger.warn(error); - return new Status(StatusCode.NOTFOUND, "Container not present"); - } - - // Validity check, check for overlaps on current container configuration - Status status = containerConfig.validateContainerFlowModify(cFlowConfList, delete); - if (!status.isSuccess()) { - String msg = status.getDescription(); - String error = String.format("Failed to apply %s: (%s)", action, msg); - logger.warn(error); - return new Status(StatusCode.BADREQUEST, msg); - } - - // Validate the operation in terms to the port sharing with other containers - for (ContainerFlowConfig conf : cFlowConfList) { - for (Match match : conf.getMatches()) { - ContainerFlow cFlow = new ContainerFlow(match); - status = validateContainerFlowAddRemoval(containerName, cFlow, delete); - if (!status.isSuccess()) { - String msg = "Validation failed: " + status.getDescription(); - String error = String.format("Failed to apply %s: (%s)", action, msg); - logger.warn(error); - return new Status(StatusCode.BADREQUEST, msg); - } - } - } - - // Update Database - status = updateContainerFlow(containerName, cFlowConfList, delete); - if (!status.isSuccess()) { - String error = String.format("Failed to apply %s: (%s)", action, status.getDescription()); - logger.error(error); - return status; - } - - // Update Configuration - status = (delete) ? containerConfig.removeContainerFlows(cFlowConfList) : containerConfig - .addContainerFlows(cFlowConfList); - if (!status.isSuccess()) { - String error = String.format("Failed to modify config for %s: (%s)", action, status.getDescription()); - logger.error(error); - // Revert backend changes - Status statusRevert = updateContainerFlow(containerName, cFlowConfList, !delete); - if (!statusRevert.isSuccess()) { - // Unlikely - logger.error("Failed to revert changes in database (CRITICAL)"); - } - return status; - } - // Update cluster cache - this.containerConfigs.put(containerName, containerConfig); - - // Notify global and local listeners - UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED; - notifyCFlowChangeInternal(containerName, cFlowConfList, update, true); - // Trigger cluster notification - containerChangeEvents.put(containerName, new ContainerFlowChangeEvent(cFlowConfList, update)); - - return status; - } - - private Status addRemoveContainer(ContainerConfig containerConf, boolean delete) { - // Construct action message - String action = String.format("Container %s", delete ? "removal" : "creation"); - - // Valid configuration check - Status status = null; - String error = (containerConfigs == null) ? String.format("Invalid %s configuration: (null config object)", action) - : (!(status = containerConf.validate()).isSuccess()) ? String.format("Invalid %s configuration: (%s)", - action, status.getDescription()) : null; - if (error != null) { - logger.warn(error); - return new Status(StatusCode.BADREQUEST, error); - } - - // Configuration presence check - String containerName = containerConf.getContainerName(); - if (delete) { - if (!containerConfigs.containsKey(containerName)) { - String msg = String.format("%s Failed: (Container does not exist: %s)", action, containerName); - logger.warn(msg); - return new Status(StatusCode.NOTFOUND, msg); - } - } else { - if (containerConfigs.containsKey(containerName)) { - String msg = String.format("%s Failed: (Container already exist: %s)", action, containerName); - logger.warn(msg); - return new Status(StatusCode.CONFLICT, msg); - } - } - - /* - * The proposed container configuration could be a complex one containing - * both ports and flow spec. If so, check if it has shared ports with - * other existing containers. If that is the case verify flow spec isolation - * is in place. No need to check on flow spec validation first. This - * would take care of both - */ - if (!delete) { - status = validatePortSharing(containerConf); - if (!status.isSuccess()) { - error = String.format("%s Failed: (%s)", action, status.getDescription()); - logger.error(error); - return status; - } - } - - // Update Database - status = updateContainerDatabase(containerConf, delete); - - // Abort and exit here if back-end database update failed - if (!status.isSuccess()) { - return status; - } - - /* - * Update Configuration: This will trigger the notifications on cache - * update callback locally and on the other cluster nodes - */ - if (delete) { - this.containerConfigs.remove(containerName); - } else { - this.containerConfigs.put(containerName, containerConf); - } - - // Automatically create and populate user and resource groups - updateResourceGroups(containerConf, delete); - - // Notify global and local listeners - UpdateType update = (delete) ? UpdateType.REMOVED : UpdateType.ADDED; - notifyContainerChangeInternal(containerConf, update, true); - - // Trigger cluster notification - containerChangeEvents.put(containerName, new ContainerChangeEvent(containerConf, update)); - - if (update == UpdateType.ADDED) { - if (containerConf.hasFlowSpecs()) { - List specList = containerConf.getContainerFlowConfigs(); - // Notify global and local listeners about flow spec addition - notifyCFlowChangeInternal(containerName, specList, update, true); - - // Trigger cluster notification - containerChangeEvents.put(containerName, new ContainerFlowChangeEvent(specList, update)); - } - - if (containerConf.hasNodeConnectors()) { - List ncList = containerConf.getPortList(); - // Notify global and local listeners about port(s) addition - notifyContainerEntryChangeInternal(containerName, ncList, update, true); - // Trigger cluster notification - containerChangeEvents.put(containerName, new NodeConnectorsChangeEvent(ncList, update)); - } - } - - if (delete) { - clusterServices.removeContainerCaches(containerName); - } - return status; - } - - @Override - public Status addContainer(ContainerConfig containerConf) { - return addRemoveContainer(containerConf, false); - } - - @Override - public Status removeContainer(ContainerConfig containerConf) { - return addRemoveContainer(containerConf, true); - } - - @Override - public Status removeContainer(String containerName) { - // Construct action message - String action = String.format("Container removal: %s", containerName); - - ContainerConfig containerConf = containerConfigs.get(containerName); - if (containerConf == null) { - String msg = String.format("Container not found"); - String error = String.format("Failed to apply %s: (%s)", action, msg); - logger.warn(error); - return new Status(StatusCode.NOTFOUND, msg); - } - return addRemoveContainer(containerConf, true); - } - - @Override - public Status addContainerEntry(String containerName, List nodeConnectors) { - return addRemoveContainerEntries(containerName, nodeConnectors, false); - } - - @Override - public Status removeContainerEntry(String containerName, List nodeConnectors) { - return addRemoveContainerEntries(containerName, nodeConnectors, true); - } - - @Override - public Status addContainerFlows(String containerName, List fSpecConf) { - return addRemoveContainerFlow(containerName, fSpecConf, false); - } - - @Override - public Status removeContainerFlows(String containerName, List fSpecConf) { - return addRemoveContainerFlow(containerName, fSpecConf, true); - } - - @Override - public Status removeContainerFlows(String containerName, Set names) { - // Construct action message - String action = String.format("Flow spec(s) removal from container %s: %s", containerName, names); - - // Presence check - ContainerConfig sc = containerConfigs.get(containerName); - if (sc == null) { - String msg = String.format("Container not found: %s", containerName); - String error = String.format("Failed to apply %s: (%s)", action, msg); - logger.warn(error); - return new Status(StatusCode.NOTFOUND, msg); - } - List list = sc.getContainerFlowConfigs(names); - if (list.isEmpty() || list.size() != names.size()) { - String msg = String.format("Cannot find all the specified flow specs"); - String error = String.format("Failed to apply %s: (%s)", action, msg); - logger.warn(error); - return new Status(StatusCode.BADREQUEST, msg); - } - return addRemoveContainerFlow(containerName, list, true); - } - - @Override - public List getContainerFlows(String containerName) { - ContainerConfig sc = containerConfigs.get(containerName); - return (sc == null) ? new ArrayList(0) : sc.getContainerFlowConfigs(); - } - - @Override - public List getContainerFlowNameList(String containerName) { - ContainerConfig sc = containerConfigs.get(containerName); - return (sc == null) ? new ArrayList(0) : sc.getContainerFlowConfigsNames(); - } - - @Override - public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException { - // Perform the class deserialization locally, from inside the package - // where the class is defined - return ois.readObject(); - } - - private void loadContainerConfig() { - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, CONTAINERS_FILE_NAME)) { - addContainer((ContainerConfig) conf); - } - } - - public void _psc(CommandInterpreter ci) { - for (Map.Entry entry : containerConfigs.entrySet()) { - ContainerConfig sc = entry.getValue(); - ci.println(String.format("%s: %s", sc.getContainerName(), sc.toString())); - } - ci.println("Total number of containers: " + containerConfigs.entrySet().size()); - } - - public void _pfc(CommandInterpreter ci) { - for (Map.Entry entry : containerConfigs.entrySet()) { - ContainerConfig sc = entry.getValue(); - ci.println(String.format("%s: %s", sc.getContainerName(), sc.getContainerFlowConfigs())); - } - } - - public void _psd(CommandInterpreter ci) { - for (String containerName : containerData.keySet()) { - ContainerData sd = containerData.get(containerName); - for (Node sid : sd.getSwPorts().keySet()) { - Set s = sd.getSwPorts().get(sid); - ci.println("\t" + sid + " : " + s); - } - - for (ContainerFlow s : sd.getContainerFlowSpecs()) { - ci.println("\t" + s.toString()); - } - } - } - - public void _psp(CommandInterpreter ci) { - for (NodeConnector sp : nodeConnectorToContainers.keySet()) { - ci.println(nodeConnectorToContainers.get(sp)); - } - } - - public void _psm(CommandInterpreter ci) { - for (Node sp : nodeToContainers.keySet()) { - ci.println(nodeToContainers.get(sp)); - } - } - - public void _addContainer(CommandInterpreter ci) { - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.print("Container Name not specified"); - return; - } - String staticVlan = ci.nextArgument(); - ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, null, null); - ci.println(this.addRemoveContainer(containerConfig, false)); - } - - public void _createContainer(CommandInterpreter ci) { - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.print("Container Name not specified"); - return; - } - String staticVlan = ci.nextArgument(); - if (staticVlan == null) { - ci.print("Static Vlan not specified"); - return; - } - List ports = new ArrayList(); - for (long l = 1L; l < 10L; l++) { - ports.add(NodeConnectorCreator.createOFNodeConnector((short) 1, NodeCreator.createOFNode(l)).toString()); - } - List cFlowList = new ArrayList(); - cFlowList.add(this.createSampleContainerFlowConfig("tcp", true)); - ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, ports, cFlowList); - ci.println(this.addRemoveContainer(containerConfig, false)); - } - - public void _removeContainer(CommandInterpreter ci) { - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.print("Container Name not specified"); - return; - } - ContainerConfig containerConfig = new ContainerConfig(containerName, "", null, null); - ci.println(this.addRemoveContainer(containerConfig, true)); - } - - public void _addContainerEntry(CommandInterpreter ci) { - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.print("Container Name not specified"); - return; - } - String nodeId = ci.nextArgument(); - if (nodeId == null) { - ci.print("Node Id not specified"); - return; - } - String portId = ci.nextArgument(); - if (portId == null) { - ci.print("Port not specified"); - return; - } - Node node = NodeCreator.createOFNode(Long.valueOf(nodeId)); - Short port = Short.valueOf(portId); - NodeConnector nc = NodeConnectorCreator.createOFNodeConnector(port, node); - List portList = new ArrayList(1); - portList.add(nc.toString()); - ci.println(this.addRemoveContainerEntries(containerName, portList, false)); - } - - public void _removeContainerEntry(CommandInterpreter ci) { - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.print("Container Name not specified"); - return; - } - String nodeId = ci.nextArgument(); - if (nodeId == null) { - ci.print("Node Id not specified"); - return; - } - String portId = ci.nextArgument(); - if (portId == null) { - ci.print("Port not specified"); - return; - } - Node node = NodeCreator.createOFNode(Long.valueOf(nodeId)); - Short port = Short.valueOf(portId); - NodeConnector nc = NodeConnectorCreator.createOFNodeConnector(port, node); - List portList = new ArrayList(1); - portList.add(nc.toString()); - ci.println(this.addRemoveContainerEntries(containerName, portList, true)); - } - - private ContainerFlowConfig createSampleContainerFlowConfig(String cflowName, boolean boolUnidirectional) { - ContainerFlowConfig cfg = new ContainerFlowConfig(cflowName, "9.9.1.0/24", "19.9.1.2", "TCP", "1234", "25"); - return cfg; - } - - public void _addContainerFlow(CommandInterpreter ci) { - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.print("Container Name not specified"); - return; - } - String cflowName = ci.nextArgument(); - if (cflowName == null) { - ci.print("cflowName not specified"); - return; - } - String unidirectional = ci.nextArgument(); - boolean boolUnidirectional = Boolean.parseBoolean(unidirectional); - List list = new ArrayList(); - list.add(createSampleContainerFlowConfig(cflowName, boolUnidirectional)); - ci.println(this.addRemoveContainerFlow(containerName, list, false)); - } - - public void _removeContainerFlow(CommandInterpreter ci) { - String containerName = ci.nextArgument(); - if (containerName == null) { - ci.print("Container Name not specified"); - return; - } - String cflowName = ci.nextArgument(); - if (cflowName == null) { - ci.print("cflowName not specified"); - return; - } - Set set = new HashSet(1); - set.add(cflowName); - ci.println(this.removeContainerFlows(containerName, set)); - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---ContainerManager Testing---\n"); - help.append("\tpsc - Print ContainerConfigs\n"); - help.append("\tpfc - Print FlowSpecConfigs\n"); - help.append("\tpsd - Print ContainerData\n"); - help.append("\tpsp - Print nodeConnectorToContainers\n"); - help.append("\tpsm - Print nodeToContainers\n"); - help.append("\t addContainer \n"); - help.append("\t removeContainer \n"); - help.append("\t addContainerEntry \n"); - help.append("\t removeContainerEntry \n"); - help.append("\t addContainerFlow \n"); - help.append("\t removeContainerFlow \n"); - return help.toString(); - } - - @Override - public boolean doesContainerExist(String containerName) { - // Test for default container - if (GlobalConstants.DEFAULT.toString().equalsIgnoreCase(containerName)) { - return true; - } - // Test for non-default one - return (getContainerByName(containerName) != null); - } - - @Override - public ContainerData getContainerData(String containerName) { - return (getContainerByName(containerName)); - } - - @Override - public Status saveConfiguration() { - return saveContainerConfig(); - } - - public void _containermgrGetRoles(CommandInterpreter ci) { - ci.println("Configured roles for Container Mgr:"); - List list = this.getRoles(); - for (String role : list) { - ci.println(role + "\t" + roles.get(role)); - } - } - - public void _containermgrGetAuthorizedGroups(CommandInterpreter ci) { - String roleName = ci.nextArgument(); - if (roleName == null || roleName.trim().isEmpty()) { - ci.println("Invalid argument"); - ci.println("mmGetAuthorizedGroups "); - return; - } - ci.println("Resource Groups associated to role " + roleName + ":"); - List list = this.getAuthorizedGroups(roleName); - for (ResourceGroup group : list) { - ci.println(group.toString()); - } - } - - public void _containermgrGetAuthorizedResources(CommandInterpreter ci) { - String roleName = ci.nextArgument(); - if (roleName == null || roleName.trim().isEmpty()) { - ci.println("Invalid argument"); - ci.println("mmGetAuthorizedResources "); - return; - } - ci.println("Resource associated to role " + roleName + ":"); - List list = this.getAuthorizedResources(roleName); - for (Resource resource : list) { - ci.println(resource.toString()); - } - } - - public void _containermgrGetResourcesForGroup(CommandInterpreter ci) { - String groupName = ci.nextArgument(); - if (groupName == null || groupName.trim().isEmpty()) { - ci.println("Invalid argument"); - ci.println("containermgrResourcesForGroup "); - return; - } - ci.println("Group " + groupName + " contains the following resources:"); - List resources = this.getResources(groupName); - for (Object resource : resources) { - ci.println(resource.toString()); - } - } - - public void _containermgrGetUserLevel(CommandInterpreter ci) { - String userName = ci.nextArgument(); - if (userName == null || userName.trim().isEmpty()) { - ci.println("Invalid argument"); - ci.println("containermgrGetUserLevel "); - return; - } - ci.println("User " + userName + " has level: " + this.getUserLevel(userName)); - } - - public void _containermgrGetUserResources(CommandInterpreter ci) { - String userName = ci.nextArgument(); - if (userName == null || userName.trim().isEmpty()) { - ci.println("Invalid argument"); - ci.println("containermgrGetUserResources "); - return; - } - ci.println("User " + userName + " owns the following resources: "); - Set resources = this.getAllResourcesforUser(userName); - for (Resource resource : resources) { - ci.println(resource.toString()); - } - } - - /* - * For scalability testing where as of now controller gui is unresponsive - * providing here an osgi hook to trigger the save config so that DT do not - * have to reaply the scalable configuration each time they restart the - * controller - */ - // TODO: remove when no longer needed - public void _saveConfig(CommandInterpreter ci) { - Status status = new Status(StatusCode.NOSERVICE, "Configuration service not reachable"); - - IConfigurationService configService = (IConfigurationService) ServiceHelper.getGlobalInstance( - IConfigurationService.class, this); - if (configService != null) { - status = configService.saveConfigurations(); - } - ci.println(status.toString()); - } - - @Override - public List getContainerNames() { - return getContainerNameList(); - } - - @Override - public boolean hasNonDefaultContainer() { - return !containerConfigs.keySet().isEmpty(); - } - - @Override - public boolean inContainerMode() { - return this.containerConfigs.size() > 0; - } - - public List psc() { - List result = new ArrayList(); - for (Map.Entry entry : containerConfigs.entrySet()) { - ContainerConfig sc = entry.getValue(); - result.add(String.format("%s: %s", sc.getContainerName(), sc.toString())); - } - result.add("Total number of containers: " + containerConfigs.entrySet().size()); - return result; - } - - public List pfc() { - List result = new ArrayList(); - for (Map.Entry entry : containerConfigs.entrySet()) { - ContainerConfig sc = entry.getValue(); - result.add(String.format("%s: %s", sc.getContainerName(), sc.getContainerFlowConfigs())); - } - return result; - } - - public List psd() { - List result = new ArrayList(); - for (String containerName : containerData.keySet()) { - ContainerData sd = containerData.get(containerName); - for (Node sid : sd.getSwPorts().keySet()) { - Set s = sd.getSwPorts().get(sid); - result.add("\t" + sid + " : " + s); - } - - for (ContainerFlow s : sd.getContainerFlowSpecs()) { - result.add("\t" + s.toString()); - } - } - return result; - } - - public List psp() { - List result = new ArrayList(); - for (NodeConnector sp : nodeConnectorToContainers.keySet()) { - result.add(nodeConnectorToContainers.get(sp).toString()); - } - return result; - } - - public List psm() { - List result = new ArrayList(); - for (Node sp : nodeToContainers.keySet()) { - result.add(nodeToContainers.get(sp).toString()); - } - return result; - } - - public List addContainer(String arg1, String arg2) { - List result = new ArrayList(); - String containerName = arg1; - if (containerName == null) { - result.add("Container Name not specified"); - return result; - } - String staticVlan = arg2; - ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, null, null); - result.add((this.addRemoveContainer(containerConfig, false)).toString()); - return result; - } - - public List createContainer(String arg1, String arg2) { - List result = new ArrayList(); - String containerName = arg1; - if (containerName == null) { - result.add("Container Name not specified"); - return result; - } - String staticVlan = arg2; - if (staticVlan == null) { - result.add("Static Vlan not specified"); - return result; - } - List ports = new ArrayList(); - for (long l = 1L; l < 10L; l++) { - ports.add(NodeConnectorCreator.createOFNodeConnector((short) 1, NodeCreator.createOFNode(l)).toString()); - } - List cFlowList = new ArrayList(); - cFlowList.add(this.createSampleContainerFlowConfig("tcp", true)); - ContainerConfig containerConfig = new ContainerConfig(containerName, staticVlan, ports, cFlowList); - result.add((this.addRemoveContainer(containerConfig, false)).toString()); - return result; - } - - public List removeContainerShell(String arg1) { - List result = new ArrayList(); - String containerName = arg1; - if (containerName == null) { - result.add("Container Name not specified"); - return result; - } - ContainerConfig containerConfig = new ContainerConfig(containerName, "", null, null); - result.add((this.addRemoveContainer(containerConfig, true)).toString()); - return result; - } - - public List addContainerEntry(String arg1, String arg2, String arg3) { - List result = new ArrayList(); - String containerName = arg1; - if (containerName == null) { - result.add("Container Name not specified"); - return result; - } - String nodeId = arg2; - if (nodeId == null) { - result.add("Node Id not specified"); - return result; - } - String portId = arg3; - if (portId == null) { - result.add("Port not specified"); - return result; - } - Node node = NodeCreator.createOFNode(Long.valueOf(nodeId)); - Short port = Short.valueOf(portId); - NodeConnector nc = NodeConnectorCreator.createOFNodeConnector(port, node); - List portList = new ArrayList(1); - portList.add(nc.toString()); - result.add((this.addRemoveContainerEntries(containerName, portList, false)).toString()); - return result; - } - - public List removeContainerEntry(String arg1, String arg2, String arg3) { - List result = new ArrayList(); - String containerName = arg1; - if (containerName == null) { - result.add("Container Name not specified"); - return result; - } - String nodeId = arg2; - if (nodeId == null) { - result.add("Node Id not specified"); - return result; - } - String portId = arg3; - if (portId == null) { - result.add("Port not specified"); - return result; - } - Node node = NodeCreator.createOFNode(Long.valueOf(nodeId)); - Short port = Short.valueOf(portId); - NodeConnector nc = NodeConnectorCreator.createOFNodeConnector(port, node); - List portList = new ArrayList(1); - portList.add(nc.toString()); - result.add((this.addRemoveContainerEntries(containerName, portList, true)).toString()); - return result; - } - public List addContainerFlow(String arg1, String arg2, String arg3) { - List result = new ArrayList(); - String containerName = arg1; - if (containerName == null) { - result.add("Container Name not specified"); - return result; - } - String cflowName = arg2; - if (cflowName == null) { - result.add("cflowName not specified"); - return result; - } - String unidirectional = arg3; - boolean boolUnidirectional = Boolean.parseBoolean(unidirectional); - List list = new ArrayList(); - list.add(createSampleContainerFlowConfig(cflowName, boolUnidirectional)); - result.add((this.addRemoveContainerFlow(containerName, list, false)).toString()); - return result; - } - - public List removeContainerFlow(String arg1, String arg2) { - List result = new ArrayList(); - String containerName = arg1; - if (containerName == null) { - result.add("Container Name not specified"); - return result; - } - String cflowName = arg2; - if (cflowName == null) { - result.add("cflowName not specified"); - return result; - } - Set set = new HashSet(1); - set.add(cflowName); - result.add((this.removeContainerFlows(containerName, set)).toString()); - return result; - } - - public List containermgrGetRoles() { - List result = new ArrayList(); - result.add("Configured roles for Container Mgr:"); - List list = this.getRoles(); - for (String role : list) { - result.add(role + "\t" + roles.get(role)); - } - return result; - } - - public List containermgrGetAuthorizedGroups(String arg1) { - List result = new ArrayList(); - String roleName = arg1; - if (roleName == null || roleName.trim().isEmpty()) { - result.add("Invalid argument"); - result.add("mmGetAuthorizedGroups "); - return result; - } - result.add("Resource Groups associated to role " + roleName + ":"); - List list = this.getAuthorizedGroups(roleName); - for (ResourceGroup group : list) { - result.add(group.toString()); - } - return result; - } - public List containermgrGetAuthorizedResources(String arg1) { - List result = new ArrayList(); - String roleName = arg1; - if (roleName == null || roleName.trim().isEmpty()) { - result.add("Invalid argument"); - result.add("mmGetAuthorizedResources "); - return result; - } - result.add("Resource associated to role " + roleName + ":"); - List list = this.getAuthorizedResources(roleName); - for (Resource resource : list) { - result.add(resource.toString()); - } - return result; - } - public List containermgrGetResourcesForGroup(String arg1) { - List result = new ArrayList(); - String groupName = arg1; - if (groupName == null || groupName.trim().isEmpty()) { - result.add("Invalid argument"); - result.add("containermgrResourcesForGroup "); - return result; - } - result.add("Group " + groupName + " contains the following resources:"); - List resources = this.getResources(groupName); - for (Object resource : resources) { - result.add(resource.toString()); - } - return result; - } - public List containermgrGetUserLevel(String arg1) { - List result = new ArrayList(); - String userName = arg1; - if (userName == null || userName.trim().isEmpty()) { - result.add("Invalid argument"); - result.add("containermgrGetUserLevel "); - return result; - } - result.add("User " + userName + " has level: " + this.getUserLevel(userName)); - return result; - } - public List containermgrGetUserResources(String arg1) { - List result = new ArrayList(); - String userName = arg1; - if (userName == null || userName.trim().isEmpty()) { - result.add("Invalid argument"); - result.add("containermgrGetUserResources "); - return result; - } - result.add("User " + userName + " owns the following resources: "); - Set resources = this.getAllResourcesforUser(userName); - for (Resource resource : resources) { - result.add(resource.toString()); - } - return result; - } - public List saveConfig() { - List result = new ArrayList(); - Status status = new Status(StatusCode.NOSERVICE, "Configuration service not reachable"); - - IConfigurationService configService = (IConfigurationService) ServiceHelper.getGlobalInstance( - IConfigurationService.class, this); - if (configService != null) { - status = configService.saveConfigurations(); - } - result.add(status.toString()); - return result; - } -} diff --git a/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/IContainerInternal.java b/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/IContainerInternal.java deleted file mode 100644 index 555f37a4a4..0000000000 --- a/opendaylight/adsal/containermanager/implementation/src/main/java/org/opendaylight/controller/containermanager/internal/IContainerInternal.java +++ /dev/null @@ -1,33 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager.internal; - -import org.opendaylight.controller.containermanager.ContainerData; - -/** - * @file IContainerInternal.java - * - * @brief Interface to export internal container manager data to friend classes - * - * Interface to export internal container manager data to friend classes - */ - -interface IContainerInternal { - /** - * Return a reference to containerData if available so a friend class - * can extract all the data and cook them up. - * - * @param containerName ContainerName for which we want to export the data - * - * @return null if containerName doesn't exist or a reference to - * ContainerData if exists - */ - ContainerData getContainerData(String containerName); -} diff --git a/opendaylight/adsal/containermanager/it.implementation/pom.xml b/opendaylight/adsal/containermanager/it.implementation/pom.xml deleted file mode 100644 index 241d9fbb87..0000000000 --- a/opendaylight/adsal/containermanager/it.implementation/pom.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - containermanager.it.implementation - 0.7.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.containermanager, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.reader, - org.eclipse.osgi.framework.console, - org.osgi.framework, - org.slf4j, - org.apache.felix.dm - - org.opendaylight.controller.containermanager.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java b/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java deleted file mode 100644 index bc0bba8dc2..0000000000 --- a/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/Activator.java +++ /dev/null @@ -1,114 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager.internal; - -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.sal.core.IContainerAware; -import org.opendaylight.controller.sal.core.IContainer; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.apache.felix.dm.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - public Object[] getImplementations() { - Object[] res = { ContainerImpl.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(ContainerImpl.class)) { - // export the service - c.setInterface(new String[] { IContainer.class.getName() }, null); - } - } - - /** - * Method which tells how many Global implementations are - * supported by the bundle. This way we can tune the number of - * components created. This components will be created ONLY at the - * time of bundle startup and will be destroyed only at time of - * bundle destruction, this is the major difference with the - * implementation retrieved via getImplementations where all of - * them are assumed to be in a container! - * - * - * @return The list of implementations the bundle will support, - * in Global version - */ - protected Object[] getGlobalImplementations() { - Object[] res = { ContainerManager.class }; - return res; - } - - /** - * Configure the dependency for a given instance Global - * - * @param c Component assigned for this instance, this will be - * what will be used for configuration - * @param imp implementation to be configured - * @param containerName container on which the configuration happens - */ - protected void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(ContainerManager.class)) { - - // export the service - c.setInterface(new String[] { IContainerManager.class.getName() }, - null); - - c.add(createServiceDependency().setService( - IClusterGlobalServices.class).setCallbacks( - "setClusterServices", "unsetClusterServices").setRequired( - true)); - - // Key kick-starter for container creation in each component - c.add(createServiceDependency().setService(IContainerAware.class) - .setCallbacks("setIContainerAware", "unsetIContainerAware") - .setRequired(false)); - - // Optional interface expected to be exported by the - // protocol plugins to setup proper filtering based on - // slicing events - c.add(createServiceDependency() - .setService(IContainerListener.class).setCallbacks( - "setIContainerListener", "unsetIContainerListener") - .setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java b/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java deleted file mode 100644 index 27874dc336..0000000000 --- a/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerImpl.java +++ /dev/null @@ -1,80 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file ContainerImpl.java - * - * @brief Class that instantiated per-container implements the - * interface IContainer - * - * - */ -package org.opendaylight.controller.containermanager.internal; - -import java.util.Dictionary; -import org.apache.felix.dm.Component; -import org.opendaylight.controller.sal.core.NodeConnector; -import java.util.Set; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.ContainerFlow; -import java.util.List; -import org.opendaylight.controller.sal.core.IContainer; - -public class ContainerImpl implements IContainer { - private String containerName = null; - private String containerAdminRole; - private String containerOperatorRole; - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init(Component c) { - Dictionary props = c.getServiceProperties(); - if (props != null) { - this.containerName = (String) props.get("containerName"); - } - } - - @Override - public String getName() { - return this.containerName; - } - - @Override - public List getContainerFlows() { - return null; - } - - @Override - public short getTag(Node n) { - return (short) 0; - } - - @Override - public Set getNodeConnectors() { - return null; - } - - @Override - public Set getNodes() { - return null; - } - - @Override - public String getContainerAdminRole() { - return containerAdminRole; - } - - @Override - public String getContainerOperatorRole() { - return containerOperatorRole; - } -} diff --git a/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java b/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java deleted file mode 100644 index f2219e53b8..0000000000 --- a/opendaylight/adsal/containermanager/it.implementation/src/main/java/org/opendaylight/controller/containermanager/internal/ContainerManager.java +++ /dev/null @@ -1,222 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file ContainerManager.java - * - * @brief Manage one or many Containers - * - * - */ -package org.opendaylight.controller.containermanager.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.containermanager.ContainerConfig; -import org.opendaylight.controller.containermanager.ContainerFlowConfig; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.sal.core.IContainerAware; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.Status; - -public class ContainerManager implements IContainerManager { - private static final Logger logger = LoggerFactory - .getLogger(ContainerManager.class); - private IClusterGlobalServices clusterServices; - /* - * Collection containing the configuration objects. - * This is configuration world: container names (also the map key) - * are maintained as they were configured by user, same case - */ - private Set iContainerAware = Collections - .synchronizedSet(new HashSet()); - private Set iContainerListener = Collections - .synchronizedSet(new HashSet()); - - void setIContainerListener(IContainerListener s) { - if (this.iContainerListener != null) { - this.iContainerListener.add(s); - } - } - - void unsetIContainerListener(IContainerListener s) { - if (this.iContainerListener != null) { - this.iContainerListener.remove(s); - } - } - - public void setIContainerAware(IContainerAware iContainerAware) { - if (!this.iContainerAware.contains(iContainerAware)) { - this.iContainerAware.add(iContainerAware); - // Now call the container creation for all the known containers so - // far - List containerDB = getContainerNames(); - if (containerDB != null) { - for (int i = 0; i < containerDB.size(); i++) { - iContainerAware.containerCreate(containerDB.get(i)); - } - } - } - } - - public void unsetIContainerAware(IContainerAware iContainerAware) { - this.iContainerAware.remove(iContainerAware); - // There is no need to do cleanup of the component when - // unregister because it will be taken care by the Containerd - // component itself - } - - public void setClusterServices(IClusterGlobalServices i) { - this.clusterServices = i; - logger.debug("IClusterServices set"); - } - - public void unsetClusterServices(IClusterGlobalServices i) { - if (this.clusterServices == i) { - this.clusterServices = null; - logger.debug("IClusterServices Unset"); - } - } - - public void init() { - logger.info("ContainerManager startup...."); - } - - public void destroy() { - // Clear local states - this.iContainerAware.clear(); - this.iContainerListener.clear(); - - logger.info("ContainerManager Shutdown...."); - } - - @Override - public List getContainerNames() { - /* - * Return container names as they were configured by user (case sensitive) - * along with the default container - */ - List containerNameList = new ArrayList(); - containerNameList.add(GlobalConstants.DEFAULT.toString()); - return containerNameList; - } - - @Override - public boolean hasNonDefaultContainer() { - return false; - } - - @Override - public Status addContainer(ContainerConfig configObject) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Status removeContainer(ContainerConfig configObject) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Status removeContainer(String containerName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Status addContainerEntry(String containerName, List portList) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Status removeContainerEntry(String containerName, - List portList) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Status addContainerFlows(String containerName, - List configObject) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Status removeContainerFlows(String containerName, - List configObject) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Status removeContainerFlows(String containerName, Set name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getContainerConfigList() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ContainerConfig getContainerConfig(String containerName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getContainerNameList() { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean doesContainerExist(String ContainerId) { - return GlobalConstants.DEFAULT.toString().equalsIgnoreCase(ContainerId); - } - - @Override - public Map> getContainerFlows() { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getContainerFlows(String containerName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getContainerFlowNameList(String containerName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean inContainerMode() { - // TODO Auto-generated method stub - return false; - } - -} diff --git a/opendaylight/adsal/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerImplTest.java b/opendaylight/adsal/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerImplTest.java deleted file mode 100644 index cea81dbe6d..0000000000 --- a/opendaylight/adsal/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerImplTest.java +++ /dev/null @@ -1,61 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager.internal; - -import org.apache.felix.dm.impl.ComponentImpl; -import org.junit.Test; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.NodeCreator; - -import java.util.Hashtable; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertEquals; - -public class ContainerImplTest { - - @Test - public void test() { - - ContainerImpl container1 = new ContainerImpl(); - - //Create Component for init - ComponentImpl component1 = new ComponentImpl(null, null, null); - component1.setInterface("serviceTestName", null); - - //container1 does not have name yet - container1.init(component1); - assertNull(container1.getName()); - - //Sets container1 name to TestName - Hashtable properties = new Hashtable(); - properties.put("dummyKey", "dummyValue"); - properties.put("containerName", "TestName"); - component1.setInterface("serviceTestName", properties); - - container1.init(component1); - assertEquals("TestName", container1.getName()); - - //getContainerFlows always returns null for now - assertNull(container1.getContainerFlows()); - - //getTag always returns 0 for now - Node n = NodeCreator.createOFNode(1L); - assertEquals(0, container1.getTag(n)); - - //getNodeConnectors always returns null for now - assertNull(container1.getNodeConnectors()); - - //getNodes always returns null for now - assertNull(container1.getNodes()); - - } - -} diff --git a/opendaylight/adsal/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerManagerTest.java b/opendaylight/adsal/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerManagerTest.java deleted file mode 100644 index 53f19dee73..0000000000 --- a/opendaylight/adsal/containermanager/it.implementation/src/test/java/org/opendaylight/controller/containermanager/internal/ContainerManagerTest.java +++ /dev/null @@ -1,40 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager.internal; - - -import org.junit.Test; -import org.opendaylight.controller.sal.utils.GlobalConstants; - -import java.util.ArrayList; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - - -public class ContainerManagerTest { - - @Test - public void test() { - ContainerManager cm = new ContainerManager(); - - cm.init(); - - ArrayList names = (ArrayList) cm.getContainerNames(); - assertEquals(1, names.size()); - assertEquals(GlobalConstants.DEFAULT.toString(), names.get(0)); - - assertFalse(cm.hasNonDefaultContainer()); - - cm.destroy(); - - } - -} diff --git a/opendaylight/adsal/containermanager/shell/pom.xml b/opendaylight/adsal/containermanager/shell/pom.xml deleted file mode 100644 index aa3c457694..0000000000 --- a/opendaylight/adsal/containermanager/shell/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - containermanager.shell - ${containermanager.shell.version} - bundle - - - junit - junit - - - org.apache.karaf.shell - org.apache.karaf.shell.console - ${karaf.shell.version} - - - org.mockito - mockito-all - - - org.opendaylight.controller - containermanager - ${containermanager.version} - - - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - - - org.apache.felix.service.command, - org.apache.karaf.shell.commands, - org.apache.karaf.shell.console, - * - - - - - - - diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainer.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainer.java deleted file mode 100644 index 2b75d54e30..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainer.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "addcontainer", description="Add Container") -public class AddContainer extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="containerName", description="container name", required=true, multiValued=false) - String containerName = null; - - @Argument(index=1, name="staticVlan", description="staticVlan", required=true, multiValued=false) - String staticVlan = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.addContainer(containerName, staticVlan)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerEntry.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerEntry.java deleted file mode 100644 index 936e1d5e3b..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerEntry.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "AddContainerEntry", description="add container entry") -public class AddContainerEntry extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="containerName", description="container name", required=true, multiValued=false) - String containerName = null; - - @Argument(index=1, name="nodeId", description="node ID", required=true, multiValued=false) - String nodeId = null; - - @Argument(index=2, name="portId", description="portId", required=true, multiValued=false) - String portId = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.addContainerEntry(containerName, nodeId, portId)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerFlow.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerFlow.java deleted file mode 100644 index bbfbc2fe7c..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/AddContainerFlow.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "addContainerFlow", description="adds container flow") -public class AddContainerFlow extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="containerName", description="container name", required=true, multiValued=false) - String containerName = null; - - @Argument(index=1, name="cflowName", description="c Flow name", required=true, multiValued=false) - String cflowName = null; - - @Argument(index=2, name="unidirectional", description="unidirectional", required=true, multiValued=false) - String unidirectional = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.addContainerFlow(containerName, cflowName, unidirectional)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedGroups.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedGroups.java deleted file mode 100644 index 72f82fdc47..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedGroups.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "containermgrGetAuthorizedGroups", description="Get authorized groups") -public class ContainermgrGetAuthorizedGroups extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="roleName", description="role name", required=true, multiValued=false) - String roleName = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.containermgrGetAuthorizedGroups(roleName)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedResources.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedResources.java deleted file mode 100644 index d625d09cc8..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetAuthorizedResources.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "containermgrGetAuthorizedResources", description="Get authorized resources") -public class ContainermgrGetAuthorizedResources extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="roleName", description="role name", required=true, multiValued=false) - String roleName = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.containermgrGetAuthorizedResources(roleName)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetResourcesForGroup.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetResourcesForGroup.java deleted file mode 100644 index e21eed6563..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetResourcesForGroup.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "containermgrGetResourcesForGroup", description="Get resources for group") -public class ContainermgrGetResourcesForGroup extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="groupName", description="group name", required=true, multiValued=false) - String groupName = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.containermgrGetResourcesForGroup(groupName)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetRoles.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetRoles.java deleted file mode 100644 index 4f8fa140a7..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetRoles.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "containermgrGetRoles", description="Get container mgr roles") -public class ContainermgrGetRoles extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.containermgrGetRoles()) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserLevel.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserLevel.java deleted file mode 100644 index e47cc12ecd..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserLevel.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "containermgrGetUserLevel", description="Get user level") -public class ContainermgrGetUserLevel extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="userName", description="user name", required=true, multiValued=false) - String userName = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.containermgrGetUserLevel(userName)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserResources.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserResources.java deleted file mode 100644 index da1949976c..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/ContainermgrGetUserResources.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "containermgrGetUserResources", description="Get user resources") -public class ContainermgrGetUserResources extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="userName", description="user name", required=true, multiValued=false) - String userName = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.containermgrGetUserResources(userName)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/CreateContainer.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/CreateContainer.java deleted file mode 100644 index 0f74d40c95..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/CreateContainer.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "createcontainer", description="create container") -public class CreateContainer extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="containerName", description="container name", required=true, multiValued=false) - String containerName = null; - - @Argument(index=1, name="staticVlan", description="staticVlan", required=true, multiValued=false) - String staticVlan = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.createContainer(containerName, staticVlan)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Pfc.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Pfc.java deleted file mode 100644 index 72ee7f22a0..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Pfc.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "pfc", description="Display pfc") -public class Pfc extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.pfc()) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psc.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psc.java deleted file mode 100644 index 6604748d1a..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psc.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "psc", description="Display ") -public class Psc extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.psc()) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psd.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psd.java deleted file mode 100644 index c6370487d7..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psd.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "psd", description="Display psd") -public class Psd extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.psd()) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psm.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psm.java deleted file mode 100644 index ca5d96b75d..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psm.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "psm", description="Display psm") -public class Psm extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.psm()) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psp.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psp.java deleted file mode 100644 index a38c5ab1c7..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/Psp.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "psp", description="Display psp") -public class Psp extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.psp()) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainer.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainer.java deleted file mode 100644 index 0c6322ae0d..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainer.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "removecontainer", description="remove container") -public class RemoveContainer extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="containerName", description="container name", required=true, multiValued=false) - String containerName = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.removeContainerShell(containerName)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerEntry.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerEntry.java deleted file mode 100644 index c126a03bfc..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerEntry.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "removeContainerEntry", description="remove container entry") -public class RemoveContainerEntry extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="containerName", description="container name", required=true, multiValued=false) - String containerName = null; - - @Argument(index=1, name="nodeId", description="node ID", required=true, multiValued=false) - String nodeId = null; - - @Argument(index=2, name="portId", description="portId", required=true, multiValued=false) - String portId = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.removeContainerEntry(containerName, nodeId, portId)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerFlow.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerFlow.java deleted file mode 100644 index 8ba532a68d..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/RemoveContainerFlow.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "removeContainerFlow", description="removes container flow") -public class RemoveContainerFlow extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Argument(index=0, name="containerName", description="container name", required=true, multiValued=false) - String containerName = null; - - @Argument(index=1, name="cflowName", description="c Flow name", required=true, multiValued=false) - String cflowName = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.removeContainerFlow(containerName, cflowName)) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/SaveConfig.java b/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/SaveConfig.java deleted file mode 100644 index c4b7a9cbf7..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/java/org/opendaylight/controller/containermanager/shell/SaveConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - -@Command(scope = "containermanager", name = "saveConfig", description="Save config") -public class SaveConfig extends OsgiCommandSupport{ - private IContainerManagerShell containerManager; - - @Override - protected Object doExecute() throws Exception { - for(String p : containerManager.saveConfig()) { - System.out.println(p); - } - return null; - } - - public void setContainerManager(IContainerManagerShell containerManager){ - this.containerManager = containerManager; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/containermanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/opendaylight/adsal/containermanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml deleted file mode 100644 index e7e01f8eb1..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/containermanager/shell/src/test/java/org/opendaylight/controller/containermanager/shell/ContainerManagerShellTest.java b/opendaylight/adsal/containermanager/shell/src/test/java/org/opendaylight/controller/containermanager/shell/ContainerManagerShellTest.java deleted file mode 100644 index f11d1da6da..0000000000 --- a/opendaylight/adsal/containermanager/shell/src/test/java/org/opendaylight/controller/containermanager/shell/ContainerManagerShellTest.java +++ /dev/null @@ -1,368 +0,0 @@ -package org.opendaylight.controller.containermanager.shell; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.lang.reflect.Field; - -import org.junit.Assert; -import org.junit.Test; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import org.opendaylight.controller.containermanager.IContainerManagerShell; - - -public class ContainerManagerShellTest { - private IContainerManagerShell containerManager; - - @Test - public void testAddContainer() throws Exception { - String containerName = "test", staticVlan = "1234"; - AddContainer addConTest = new AddContainer(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - List result2 = new ArrayList(Arrays.asList("Container Name not specified")); - when(containerManager.addContainer(containerName, staticVlan)).thenReturn(result); - when(containerManager.addContainer(null, null)).thenReturn(result2); - - Field cNField = addConTest.getClass().getDeclaredField("containerName"); - cNField.setAccessible(true); - Field sVField = addConTest.getClass().getDeclaredField("staticVlan"); - sVField.setAccessible(true); - - cNField.set(addConTest, "test"); - sVField.set(addConTest, "1234"); - - addConTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - addConTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - baos.reset(); - - cNField.set(addConTest, null); - sVField.set(addConTest, null); - addConTest.doExecute(); - Assert.assertEquals("Container Name not specified\n", baos.toString()); - } - - @Test - public void testAddContainerEntry() throws Exception { - String containerName = "test", nodeId = "1234", portId = "5678"; - AddContainerEntry addConEntTest = new AddContainerEntry(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.addContainerEntry(containerName, nodeId, portId)).thenReturn(result); - - Field cNField = addConEntTest.getClass().getDeclaredField("containerName"); - cNField.setAccessible(true); - Field nIField = addConEntTest.getClass().getDeclaredField("nodeId"); - nIField.setAccessible(true); - Field pIField = addConEntTest.getClass().getDeclaredField("portId"); - pIField.setAccessible(true); - - cNField.set(addConEntTest, "test"); - nIField.set(addConEntTest, "1234"); - pIField.set(addConEntTest, "5678"); - - addConEntTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - addConEntTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testAddContainerFlow() throws Exception { - String containerName = "test", cflowName = "1234", unidirectional = "5678"; - AddContainerFlow addConFlowTest = new AddContainerFlow(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.addContainerFlow(containerName, cflowName, unidirectional)).thenReturn(result); - - Field cNField = addConFlowTest.getClass().getDeclaredField("containerName"); - cNField.setAccessible(true); - Field cfField = addConFlowTest.getClass().getDeclaredField("cflowName"); - cfField.setAccessible(true); - Field unField = addConFlowTest.getClass().getDeclaredField("unidirectional"); - unField.setAccessible(true); - - cNField.set(addConFlowTest, "test"); - cfField.set(addConFlowTest, "1234"); - unField.set(addConFlowTest, "5678"); - - addConFlowTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - addConFlowTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testContainermgrGetAuthorizedGroups() throws Exception { - String roleName = "test"; - ContainermgrGetAuthorizedGroups contmgrGTest = new ContainermgrGetAuthorizedGroups(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.containermgrGetAuthorizedGroups(roleName)).thenReturn(result); - - Field rNField = contmgrGTest.getClass().getDeclaredField("roleName"); - rNField.setAccessible(true); - - rNField.set(contmgrGTest, "test"); - - contmgrGTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - contmgrGTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testContainermgrGetAuthorizedResources() throws Exception { - String roleName = "test"; - ContainermgrGetAuthorizedResources contmgrRTest = new ContainermgrGetAuthorizedResources(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.containermgrGetAuthorizedResources(roleName)).thenReturn(result); - - Field rNField = contmgrRTest.getClass().getDeclaredField("roleName"); - rNField.setAccessible(true); - - rNField.set(contmgrRTest, "test"); - - contmgrRTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - contmgrRTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testContainermgrGetResourcesForGroup() throws Exception { - String groupName = "test"; - ContainermgrGetResourcesForGroup contmgrRTest = new ContainermgrGetResourcesForGroup(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.containermgrGetResourcesForGroup(groupName)).thenReturn(result); - - Field gNField = contmgrRTest.getClass().getDeclaredField("groupName"); - gNField.setAccessible(true); - - gNField.set(contmgrRTest, groupName); - - contmgrRTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - contmgrRTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testContainermgrGetRoles() throws Exception { - ContainermgrGetRoles contmgrRTest = new ContainermgrGetRoles(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.containermgrGetRoles()).thenReturn(result); - - contmgrRTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - contmgrRTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testContainermgrGetUserLevel() throws Exception { - String userName = "test"; - ContainermgrGetUserLevel contmgrUTest = new ContainermgrGetUserLevel(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.containermgrGetUserLevel(userName)).thenReturn(result); - - Field gNField = contmgrUTest.getClass().getDeclaredField("userName"); - gNField.setAccessible(true); - - gNField.set(contmgrUTest, userName); - - contmgrUTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - contmgrUTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testContainermgrGetUserResources() throws Exception { - String userName = "test"; - ContainermgrGetUserResources contmgrUTest = new ContainermgrGetUserResources(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.containermgrGetUserResources(userName)).thenReturn(result); - - Field gNField = contmgrUTest.getClass().getDeclaredField("userName"); - gNField.setAccessible(true); - - gNField.set(contmgrUTest, userName); - - contmgrUTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - contmgrUTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testPfc() throws Exception { - Pfc pfc = new Pfc(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.pfc()).thenReturn(result); - - pfc.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - pfc.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testPsc() throws Exception { - Psc psc = new Psc(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.psc()).thenReturn(result); - - psc.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - psc.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testPsd() throws Exception { - Psd psd = new Psd(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.psd()).thenReturn(result); - - psd.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - psd.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testPsm() throws Exception { - Psm psm = new Psm(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.psm()).thenReturn(result); - - psm.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - psm.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testPsp() throws Exception { - Psp psp = new Psp(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.psp()).thenReturn(result); - - psp.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - psp.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testRemoveContainer() throws Exception { - String containerName = "test"; - RemoveContainer remConTest = new RemoveContainer(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.removeContainerShell(containerName)).thenReturn(result); - - Field cNField = remConTest.getClass().getDeclaredField("containerName"); - cNField.setAccessible(true); - cNField.set(remConTest, "test"); - - remConTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - remConTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testRemoveContainerEntry() throws Exception { - String containerName = "test", nodeId = "1234", portId = "5678"; - RemoveContainerEntry remConEntTest = new RemoveContainerEntry(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.removeContainerEntry(containerName, nodeId, portId)).thenReturn(result); - - Field cNField = remConEntTest.getClass().getDeclaredField("containerName"); - cNField.setAccessible(true); - Field nIField = remConEntTest.getClass().getDeclaredField("nodeId"); - nIField.setAccessible(true); - Field pIField = remConEntTest.getClass().getDeclaredField("portId"); - pIField.setAccessible(true); - - cNField.set(remConEntTest, "test"); - nIField.set(remConEntTest, "1234"); - pIField.set(remConEntTest, "5678"); - - remConEntTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - remConEntTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testRemoveContainerFlow() throws Exception { - String containerName = "test", cflowName = "1234"; - RemoveContainerFlow remConFlowTest = new RemoveContainerFlow(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.removeContainerFlow(containerName, cflowName)).thenReturn(result); - - Field cNField = remConFlowTest.getClass().getDeclaredField("containerName"); - cNField.setAccessible(true); - Field cfField = remConFlowTest.getClass().getDeclaredField("cflowName"); - cfField.setAccessible(true); - - cNField.set(remConFlowTest, "test"); - cfField.set(remConFlowTest, "1234"); - - remConFlowTest.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - remConFlowTest.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } - - @Test - public void testSaveConfig() throws Exception { - SaveConfig saveConfig = new SaveConfig(); - containerManager = mock(IContainerManagerShell.class); - List result = new ArrayList(Arrays.asList("status")); - when(containerManager.saveConfig()).thenReturn(result); - - saveConfig.setContainerManager(containerManager); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - saveConfig.doExecute(); - Assert.assertEquals("status\n", baos.toString()); - } -} \ No newline at end of file diff --git a/opendaylight/adsal/dummy-console/README b/opendaylight/adsal/dummy-console/README deleted file mode 100644 index 09974d5e54..0000000000 --- a/opendaylight/adsal/dummy-console/README +++ /dev/null @@ -1,2 +0,0 @@ -This bundle is temporary only and should be removed as soon as possible -it is only for compatibility layer in Karaf. diff --git a/opendaylight/adsal/dummy-console/pom.xml b/opendaylight/adsal/dummy-console/pom.xml deleted file mode 100644 index 76aa58f058..0000000000 --- a/opendaylight/adsal/dummy-console/pom.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../commons/opendaylight - - dummy-console - 1.3.0-SNAPSHOT - bundle - Dummy Console Interfaces for Equinox-specific CLI - - - - org.apache.felix - maven-bundle-plugin - true - - - * - org.eclipse.osgi.framework.console - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandInterpreter.java b/opendaylight/adsal/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandInterpreter.java deleted file mode 100644 index 29e9fc931b..0000000000 --- a/opendaylight/adsal/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandInterpreter.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright(c)2014 Inocybe Technologies, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - */ -package org.eclipse.osgi.framework.console; - -/** Empty tag interface for Command Interpreter **/ -public interface CommandInterpreter {} diff --git a/opendaylight/adsal/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandProvider.java b/opendaylight/adsal/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandProvider.java deleted file mode 100644 index a781f6f908..0000000000 --- a/opendaylight/adsal/dummy-console/src/main/java/org/eclipse/osgi/framework/console/CommandProvider.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright(c)2014 Inocybe Technologies, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - */ -package org.eclipse.osgi.framework.console; - -/** Empty tag interface for Command Provider **/ -public interface CommandProvider {} diff --git a/opendaylight/adsal/features/adsal/pom.xml b/opendaylight/adsal/features/adsal/pom.xml deleted file mode 100644 index 9ae56739b3..0000000000 --- a/opendaylight/adsal/features/adsal/pom.xml +++ /dev/null @@ -1,150 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../opendaylight/commons/opendaylight - - features-adsal - ${sal.version} - jar - Features :: AD-SAL Features - AD-SAL Features POM - - features.xml - - - - org.opendaylight.controller - features-base - features - xml - - - - org.opendaylight.odlparent - features-test - - - - org.opendaylight.controller - opendaylight-karaf-empty - 1.6.0-SNAPSHOT - zip - - - - org.opendaylight.controller - dummy-console - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller - sal.connection.implementation - - - org.opendaylight.controller - sal.implementation - - - org.opendaylight.controller - sal.networkconfiguration - - - org.opendaylight.controller - sal.networkconfiguration.implementation - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - clustering.services-implementation - - - org.opendaylight.controller - clustering.stub - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - configuration.implementation - - - org.opendaylight.controller - logging.bridge - - - - - - true - src/main/resources - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - org.opendaylight.controller - opendaylight-karaf-empty - ${commons.opendaylight.version} - - - org.opendaylight.odlparent:features-test - - - - - - diff --git a/opendaylight/adsal/features/adsal/src/main/resources/features.xml b/opendaylight/adsal/features/adsal/src/main/resources/features.xml deleted file mode 100644 index 397a05e10b..0000000000 --- a/opendaylight/adsal/features/adsal/src/main/resources/features.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - mvn:org.opendaylight.controller/features-base/${commons.opendaylight.version}/xml/features - - odl-adsal-core - odl-adsal-networkconfiguration - odl-adsal-connection - odl-adsal-clustering - odl-adsal-configuration - - - odl-base-felix-dm - odl-base-dummy-console - odl-adsal-thirdparty - mvn:org.apache.commons/commons-lang3/${commons.lang3.version} - - mvn:org.opendaylight.controller/sal/${sal.version} - mvn:org.opendaylight.controller/sal.implementation/${sal.implementation.version} - - - odl-adsal-core - mvn:org.opendaylight.controller/sal.networkconfiguration/${sal.networkconfiguration.version} - mvn:org.opendaylight.controller/sal.networkconfiguration.implementation/${sal.networkconfiguration.version} - - - odl-adsal-core - mvn:org.opendaylight.controller/sal.connection/${sal.connection.version} - mvn:org.opendaylight.controller/sal.connection.implementation/${sal.connection.version} - - - transaction - odl-base-felix-dm - odl-base-eclipselink-persistence - odl-adsal-core - mvn:org.opendaylight.controller/clustering.services/${clustering.services.version} - mvn:org.opendaylight.controller/clustering.services-implementation/${clustering.services_implementation.version} - - - odl-adsal-core - odl-adsal-clustering - mvn:org.opendaylight.controller/configuration/${configuration.version} - mvn:org.opendaylight.controller/configuration.implementation/${configuration.implementation.version} - - - - - diff --git a/opendaylight/adsal/features/base/pom.xml b/opendaylight/adsal/features/base/pom.xml deleted file mode 100644 index 3042b6abe3..0000000000 --- a/opendaylight/adsal/features/base/pom.xml +++ /dev/null @@ -1,532 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../opendaylight/commons/opendaylight - - features-base - jar - ${project.artifactId} - Base Features POM - - features.xml - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - org.opendaylight.controller - dummy-console - - - org.opendaylight.controller - karaf-tomcat-security - - - com.fasterxml.jackson.core - jackson-annotations - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.core - jackson-databind - - - com.fasterxml.jackson.datatype - jackson-datatype-json-org - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-base - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - - - com.fasterxml.jackson.module - jackson-module-jaxb-annotations - - - com.google.code.gson - gson - - - com.google.guava - guava - - - com.sun.jersey - jersey-client - - - - com.sun.jersey - jersey-core - - - com.sun.jersey - jersey-server - - - commons-codec - commons-codec - - - commons-fileupload - commons-fileupload - - - commons-io - commons-io - - - commons-net - commons-net - - - eclipselink - javax.persistence - - - eclipselink - javax.resource - - - equinoxSDK381 - javax.servlet - - - equinoxSDK381 - javax.servlet.jsp - - - equinoxSDK381 - org.apache.felix.gogo.command - - - equinoxSDK381 - org.apache.felix.gogo.runtime - - - equinoxSDK381 - org.apache.felix.gogo.shell - - - equinoxSDK381 - org.eclipse.equinox.cm - - - equinoxSDK381 - org.eclipse.equinox.console - - - equinoxSDK381 - org.eclipse.equinox.ds - - - equinoxSDK381 - org.eclipse.equinox.launcher - - - equinoxSDK381 - org.eclipse.equinox.util - - - equinoxSDK381 - org.eclipse.osgi - - - equinoxSDK381 - org.eclipse.osgi.services - - - - geminiweb - org.eclipse.gemini.web.core - - - geminiweb - org.eclipse.gemini.web.extender - - - geminiweb - org.eclipse.gemini.web.tomcat - - - geminiweb - org.eclipse.virgo.kernel.equinox.extensions - - - geminiweb - org.eclipse.virgo.util.common - - - geminiweb - org.eclipse.virgo.util.io - - - geminiweb - org.eclipse.virgo.util.math - - - geminiweb - org.eclipse.virgo.util.osgi - - - geminiweb - org.eclipse.virgo.util.osgi.manifest - - - geminiweb - org.eclipse.virgo.util.parser.manifest - - - io.netty - netty-buffer - - - io.netty - netty-codec - - - io.netty - netty-codec-http - - - io.netty - netty-common - - - - - io.netty - netty-handler - - - io.netty - netty-transport - - - orbit - javax.activation - - - orbit - javax.annotation - - - orbit - javax.ejb - - - orbit - javax.el - - - orbit - javax.mail.glassfish - - - orbit - javax.servlet.jsp.jstl - - - orbit - javax.servlet.jsp.jstl.impl - - - orbit - javax.xml.rpc - - - orbit - org.apache.catalina - - - orbit - org.apache.catalina.ha - - - orbit - org.apache.catalina.tribes - - - orbit - org.apache.coyote - - - orbit - org.apache.el - - - orbit - org.apache.jasper - - - orbit - org.apache.juli.extras - - - orbit - org.apache.tomcat.api - - - orbit - org.apache.tomcat.util - - - org.aopalliance - com.springsource.org.aopalliance - - - org.apache.commons - commons-lang3 - - - org.apache.felix - org.apache.felix.dependencymanager - - - org.apache.felix - org.apache.felix.dependencymanager.shell - - - org.apache.felix - org.apache.felix.fileinstall - - - - org.apache.felix - org.apache.felix.webconsole - all - - - - org.codehaus.jettison - jettison - - - - org.eclipse.equinox.http - servlet - - - org.eclipse.persistence - org.eclipse.persistence.antlr - - - org.eclipse.persistence - org.eclipse.persistence.core - - - org.eclipse.persistence - org.eclipse.persistence.moxy - - - org.javassist - javassist - - - org.jboss.spec.javax.transaction - jboss-transaction-api_1.1_spec - - - org.jolokia - jolokia-osgi - - - - org.json - json - - - - org.ow2.asm - asm-all - - - - org.ow2.chameleon.management - chameleon-mbeans - - - - - org.slf4j - jcl-over-slf4j - - - org.slf4j - log4j-over-slf4j - - - org.slf4j - slf4j-api - - - org.springframework - org.springframework.aop - - - - org.springframework - org.springframework.asm - - - org.springframework - org.springframework.beans - - - org.springframework - org.springframework.context - - - org.springframework - org.springframework.context.support - - - org.springframework - org.springframework.core - - - org.springframework - org.springframework.expression - - - org.springframework - org.springframework.transaction - - - org.springframework - org.springframework.web - - - org.springframework - org.springframework.web.servlet - - - - org.springframework.security - spring-security-config - - - org.springframework.security - spring-security-core - - - org.springframework.security - spring-security-taglibs - - - org.springframework.security - spring-security-web - - - virgomirror - org.eclipse.jdt.core.compiler.batch - - - - - org.opendaylight.odlparent - features-test - - - - org.opendaylight.controller - opendaylight-karaf-empty - 1.6.0-SNAPSHOT - zip - - - - - - true - src/main/resources - - - - - org.apache.karaf.tooling - karaf-maven-plugin - ${karaf.version} - true - - - features-create-kar - - features-create-kar - - - ${project.build.directory}/classes/${features.file} - - - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - org.opendaylight.controller - opendaylight-karaf-empty - ${commons.opendaylight.version} - - - org.opendaylight.odlparent:features-test - - - - - - diff --git a/opendaylight/adsal/features/base/src/main/resources/features.xml b/opendaylight/adsal/features/base/src/main/resources/features.xml deleted file mode 100644 index 182c047595..0000000000 --- a/opendaylight/adsal/features/base/src/main/resources/features.xml +++ /dev/null @@ -1,155 +0,0 @@ - - - - - http - transaction - odl-base-felix-dm - odl-base-aries-spi-fly - odl-base-dummy-console - odl-base-apache-commons - odl-base-eclipselink-persistence - odl-base-gemini-web - odl-base-tomcat - odl-base-netty - odl-base-jersey - odl-base-jackson - odl-base-spring-security - - - mvn:org.opendaylight.controller/dummy-console/1.3.0-SNAPSHOT - - - mvn:org.osgi/org.osgi.compendium/${osgi.compendium.version} - mvn:org.apache.felix/org.apache.felix.dependencymanager/${felix.dependencymanager.version} - mvn:org.apache.felix/org.apache.felix.dependencymanager.shell/${felix.dependencymanager.shell.version} - - - mvn:org.apache.aries/org.apache.aries.util/1.1.0 - mvn:org.apache.aries.spifly/org.apache.aries.spifly.dynamic.bundle/${spifly.version} - mvn:org.ow2.asm/asm-all/4.0 - - - wrap:mvn:io.netty/netty-buffer/${netty.version} - wrap:mvn:io.netty/netty-codec/${netty.version} - wrap:mvn:io.netty/netty-transport/${netty.version} - wrap:mvn:io.netty/netty-common/${netty.version} - wrap:mvn:io.netty/netty-handler/${netty.version} - wrap:mvn:io.netty/netty-codec-http/${netty.version} - - - odl-base-gemini-web - mvn:com.sun.jersey/jersey-server/${jersey.version} - mvn:com.sun.jersey/jersey-core/${jersey.version} - mvn:com.sun.jersey/jersey-client/${jersey.version} - mvn:com.sun.jersey/jersey-servlet/${jersey.version} - - - http - mvn:com.eclipsesource.jaxrs/jersey-all/${jersey2.version} - mvn:com.eclipsesource.jaxrs/publisher/${jersey2.publisher.version} - mvn:javax.ws.rs/javax.ws.rs-api/${jsr311.v2.api.version} - mvn:javax.annotation/javax.annotation-api/${javax.annotation.version} - - - mvn:com.sun.jersey/jersey-core/${jersey.version} - mvn:com.sun.jersey/jersey-client/${jersey.version} - mvn:com.fasterxml.jackson.core/jackson-annotations/${jackson.version} - mvn:com.fasterxml.jackson.core/jackson-core/${jackson.version} - mvn:com.fasterxml.jackson.core/jackson-databind/${jackson.version} - mvn:org.codehaus.jettison/jettison/${jettison.version} - mvn:com.fasterxml.jackson.module/jackson-module-jaxb-annotations/${jackson.version} - mvn:com.fasterxml.jackson.jaxrs/jackson-jaxrs-base/${jackson.version} - mvn:com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider/${jackson.version} - - - mvn:org.slf4j/slf4j-jdk14/1.7.2 - mvn:org.slf4j/slf4j-nop/1.7.2 - mvn:org.slf4j/slf4j-simple/1.7.2 - mvn:org.slf4j/slf4j-api/1.7.2 - - - mvn:com.google.guava/guava/${guava.version} - mvn:org.javassist/javassist/${javassist.version} - mvn:commons-io/commons-io/${commons.io.version} - mvn:commons-codec/commons-codec/${commons.codec.version} - mvn:org.apache.commons/commons-lang3/${commons.lang3.version} - mvn:commons-net/commons-net/${commons.net.version} - - - mvn:eclipselink/javax.persistence/2.0.4.v201112161009 - mvn:eclipselink/javax.resource/1.5.0.v200906010428 - mvn:org.eclipse.persistence/org.eclipse.persistence.antlr/2.5.0 - mvn:org.eclipse.persistence/org.eclipse.persistence.moxy/2.5.0 - mvn:org.eclipse.persistence/org.eclipse.persistence.core/2.5.0 - - - http - transaction - odl-base-slf4j - odl-base-felix-dm - odl-base-jackson - odl-base-apache-commons - mvn:com.google.code.gson/gson/${gson.version} - mvn:commons-fileupload/commons-fileupload/${commons.fileupload.version} - mvn:geminiweb/org.eclipse.gemini.web.core/${geminiweb.version} - mvn:geminiweb/org.eclipse.gemini.web.extender/${geminiweb.version} - mvn:geminiweb/org.eclipse.virgo.util.common/${virgo.version} - mvn:geminiweb/org.eclipse.virgo.util.io/${virgo.version} - mvn:geminiweb/org.eclipse.virgo.util.math/${virgo.version} - mvn:geminiweb/org.eclipse.virgo.util.osgi/${virgo.version} - mvn:geminiweb/org.eclipse.virgo.util.osgi.manifest/${virgo.version} - mvn:geminiweb/org.eclipse.virgo.util.parser.manifest/${virgo.version} - mvn:org.apache.felix/org.apache.felix.fileinstall/3.1.6 - mvn:orbit/javax.activation/1.1.0.v201211130549 - mvn:orbit/javax.annotation/1.1.0.v201209060031 - mvn:orbit/javax.ejb/3.1.1.v201204261316 - mvn:orbit/javax.el/2.2.0.v201108011116 - mvn:orbit/javax.mail.glassfish/1.4.1.v201108011116 - mvn:orbit/javax.xml.rpc/1.1.0.v201005080400 - mvn:org.eclipse.jetty.orbit/javax.servlet.jsp/2.2.0.v201112011158 - mvn:orbit/javax.servlet.jsp.jstl/1.2.0.v201105211821 - mvn:orbit/javax.servlet.jsp.jstl.impl/1.2.0.v201210211230 - - - odl-base-gemini-web - odl-base-eclipselink-persistence - mvn:orbit/org.apache.catalina/${commons.catalina} - mvn:geminiweb/org.eclipse.gemini.web.tomcat/${geminiweb.version} - mvn:orbit/org.apache.catalina.ha/${commons.catalina.ha} - mvn:orbit/org.apache.catalina.tribes/${commons.catalina.tribes} - mvn:orbit/org.apache.coyote/${commons.coyote} - mvn:orbit/org.apache.el/${commons.el} - mvn:orbit/org.apache.jasper/${commons.jasper} - mvn:orbit/org.apache.juli.extras/${commons.juli.version} - mvn:orbit/org.apache.tomcat.api/${commons.tomcat.api} - mvn:orbit/org.apache.tomcat.util/${commons.tomcat.util} - mvn:org.opendaylight.controller/karaf-tomcat-security/${karaf.security.version} - wrap:mvn:virgomirror/org.eclipse.jdt.core.compiler.batch/${eclipse.jdt.core.compiler.batch.version} - - - mvn:org.ow2.asm/asm-all/${asm.version} - mvn:org.aopalliance/com.springsource.org.aopalliance/${aopalliance.version} - mvn:org.springframework/org.springframework.aop/${spring.version} - mvn:org.springframework/org.springframework.asm/${spring.version} - mvn:org.springframework/org.springframework.beans/${spring.version} - mvn:org.springframework/org.springframework.context/${spring.version} - mvn:org.springframework/org.springframework.context.support/${spring.version} - mvn:org.springframework/org.springframework.core/${spring.version} - mvn:org.springframework/org.springframework.expression/${spring.version} - mvn:org.springframework/org.springframework.transaction/${spring.version} - - - odl-base-spring - odl-base-gemini-web - mvn:org.springframework/org.springframework.web/${spring.version} - mvn:org.springframework/org.springframework.web.servlet/${spring.version} - - - odl-base-spring-web - mvn:org.springframework.security/spring-security-config/${spring-security.version} - mvn:org.springframework.security/spring-security-core/${spring-security.version} - mvn:org.springframework.security/spring-security-taglibs/${spring-security.version} - mvn:org.springframework.security/spring-security-web/${spring-security.version} - - diff --git a/opendaylight/adsal/features/controller/pom.xml b/opendaylight/adsal/features/controller/pom.xml deleted file mode 100644 index c92e0bc69e..0000000000 --- a/opendaylight/adsal/features/controller/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../opendaylight/commons/opendaylight - - controller-features - pom - ${project.artifactId} - Features POM - - features.xml - - - - - true - src/main/resources - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - - diff --git a/opendaylight/adsal/features/controller/src/main/resources/features.xml b/opendaylight/adsal/features/controller/src/main/resources/features.xml deleted file mode 100644 index 1ae210ac20..0000000000 --- a/opendaylight/adsal/features/controller/src/main/resources/features.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - odl-clustering - odl-managers - odl-sal - mvn:org.opendaylight.controller/hosttracker/${hosttracker.api.version} - mvn:org.opendaylight.controller/hosttracker.implementation/${hosttracker.implementation.version} - - - base-felix-dm - mvn:org.apache.commons/commons-lang3/${commons.lang.version} - mvn:org.osgi/org.osgi.compendium/${osgi.compendium.version} - mvn:org.apache.felix/org.apache.felix.dependencymanager/${felix.dependencymanager.version} - mvn:org.opendaylight.controller/sal/${sal.version} - - mvn:org.opendaylight.controller/sal.implementation/${sal.implementation.version} - mvn:org.opendaylight.controller/sal.networkconfiguration/${sal.networkconfiguration.version} - mvn:org.opendaylight.controller/sal.networkconfiguration.implementation/${sal.networkconfiguration.version} - mvn:org.opendaylight.controller/sal.connection/${sal.connection.version} - mvn:org.opendaylight.controller/sal.connection.implementation/${sal.connection.version} - - - transaction - base-felix-dm - base-eclipselink-persistence - odl-sal - mvn:org.opendaylight.controller/clustering.services/${clustering.services.version} - mvn:org.opendaylight.controller/clustering.services-implementation/${clustering.services_implementation.version} - mvn:org.opendaylight.controller/clustering.stub/${clustering.stub.version} - - - odl-sal - mvn:org.opendaylight.controller/configuration/${configuration.version} - mvn:org.opendaylight.controller/configuration.implementation/${configuration.implementation.version} - - - - mvn:org.opendaylight.controller/config-api/${config.version} - mvn:org.opendaylight.controller/config-manager/${config.version} - mvn:org.opendaylight.controller/config-netconf-connector/${netconf.version} - mvn:org.opendaylight.controller/config-persister-api/${config.version} - mvn:org.opendaylight.controller/config-persister-directory-xml-adapter/${config.version} - mvn:org.opendaylight.controller/config-persister-file-xml-adapter/${config.version} - mvn:org.opendaylight.controller/config-persister-impl/${netconf.version} - mvn:org.opendaylight.controller/yang-jmx-generator/${yang-jmx-generator.version} - - - odl-legacy-configuration - base-spring-security - base-felix-dm - odl-clustering - mvn:org.opendaylight.controller.thirdparty/net.sf.jung2/2.0.1 - mvn:org.opendaylight.controller/appauth/${appauth.version} - mvn:org.opendaylight.controller/hosttracker/${hosttracker.api.version} - mvn:org.opendaylight.controller/hosttracker.implementation/${hosttracker.implementation.version} - mvn:org.opendaylight.controller/switchmanager/${switchmanager.api.version} - mvn:org.opendaylight.controller/switchmanager.implementation/${switchmanager.implementation.version} - mvn:org.opendaylight.controller/statisticsmanager/${statisticsmanager.version} - mvn:org.opendaylight.controller/statisticsmanager.implementation/${statisticsmanager.implementation.version} - mvn:org.opendaylight.controller/forwardingrulesmanager/${forwardingrulesmanager.version} - mvn:org.opendaylight.controller/forwardingrulesmanager.implementation/${forwardingrulesmanager.implementation.version} - mvn:org.opendaylight.controller/usermanager/${usermanager.version} - mvn:org.opendaylight.controller/usermanager.implementation/${usermanager.version} - mvn:org.opendaylight.controller/containermanager/${containermanager.version} - mvn:org.opendaylight.controller/containermanager.implementation/${containermanager.version} - mvn:org.opendaylight.controller/topologymanager/${topologymanager.version} - mvn:org.opendaylight.controller/forwarding.staticrouting - mvn:org.opendaylight.controller/routing.dijkstra_implementation - mvn:org.opendaylight.controller/connectionmanager - mvn:org.opendaylight.controller/connectionmanager.implementation - - diff --git a/opendaylight/adsal/features/extras/pom.xml b/opendaylight/adsal/features/extras/pom.xml deleted file mode 100644 index f8e04d1e1a..0000000000 --- a/opendaylight/adsal/features/extras/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../opendaylight/commons/opendaylight - - extras-features - kar - ${project.artifactId} - Base Features POM - - features.xml - 3.9.2.Final - - - - - true - src/main/resources - - - - - org.apache.karaf.tooling - karaf-maven-plugin - ${karaf.version} - true - - - features-create-kar - - features-create-kar - - - ${project.build.directory}/classes/${features.file} - - - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - - diff --git a/opendaylight/adsal/features/extras/src/main/resources/features.xml b/opendaylight/adsal/features/extras/src/main/resources/features.xml deleted file mode 100644 index 3be66d9a6e..0000000000 --- a/opendaylight/adsal/features/extras/src/main/resources/features.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - mvn:org.osgi/org.osgi.compendium/${osgi.compendium.version} - - - - mvn:org.scala-lang/scala-library/${scala.version}.${scala.micro.version} - mvn:org.scala-lang/scala-reflect/${scala.version}.${scala.micro.version} - - - - odl-extras-scala - mvn:com.typesafe/config/${typesafe.config.version} - mvn:com.typesafe.akka/akka-actor_${scala.version}/${akka.version} - mvn:com.typesafe.akka/akka-slf4j_${scala.version}/${akka.version} - mvn:com.typesafe.akka/akka-osgi_${scala.version}/${akka.version} - - - - odl-extras-akka-system - wrap:mvn:org.uncommons.maths/uncommons-maths/${uncommons.maths.version} - mvn:com.google.protobuf/protobuf-java/${protobuf.version} - wrap:mvn:io.netty/netty/${netty3.version} - mvn:com.typesafe.akka/akka-remote_${scala.version}/${akka.version} - mvn:com.typesafe.akka/akka-cluster_${scala.version}/${akka.version} - - - - wrap:mvn:org.iq80.leveldb/leveldb/${leveldb.version} - wrap:mvn:org.fusesource.leveldbjni/leveldbjni-all/${leveldbjni.version} - - diff --git a/opendaylight/adsal/features/nsf/pom.xml b/opendaylight/adsal/features/nsf/pom.xml deleted file mode 100644 index 150196f4fc..0000000000 --- a/opendaylight/adsal/features/nsf/pom.xml +++ /dev/null @@ -1,327 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../opendaylight/commons/opendaylight - - features-nsf - ${nsf.version} - jar - OpenDaylight :: Features :: Network Service Functions - Feature for Network Service Functions - - features.xml - - - - - org.opendaylight.odlparent - features-test - - - - org.opendaylight.controller - opendaylight-karaf-empty - 1.6.0-SNAPSHOT - zip - - - - org.opendaylight.controller - features-adsal - ${sal.version} - features - xml - - - org.opendaylight.controller - features-base - features - ${commons.opendaylight.version} - xml - - - - org.opendaylight.controller - appauth - - - org.opendaylight.controller - arphandler - - - org.opendaylight.controller - bundlescanner - - - org.opendaylight.controller - bundlescanner.implementation - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - configuration.implementation - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - connectionmanager.implementation - - - org.opendaylight.controller - connectionmanager.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.implementation - - - org.opendaylight.controller - containermanager.shell - - - org.opendaylight.controller - containermanager.northbound - - - org.opendaylight.controller - controllermanager.northbound - - - org.opendaylight.controller - devices.web - - - org.opendaylight.controller - flowprogrammer.northbound - - - org.opendaylight.controller - flows.web - - - org.opendaylight.controller - routing.dijkstra_implementation - - - org.opendaylight.controller - forwarding.staticrouting - - - org.opendaylight.controller - forwarding.staticrouting.northbound - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - forwardingrulesmanager.implementation - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - hosttracker.shell - - - org.opendaylight.controller - hosttracker.implementation - - - org.opendaylight.controller - hosttracker.northbound - - - org.opendaylight.controller - httpservice-bridge - - - org.opendaylight.controller - jolokia-bridge - - - org.opendaylight.controller - logging.bridge - - - org.opendaylight.controller - networkconfig.bridgedomain.northbound - - - org.opendaylight.controller - osgi-brandfragment.web - - - org.opendaylight.controller - samples.loadbalancer - - - org.opendaylight.controller - samples.loadbalancer.northbound - - - org.opendaylight.controller - samples.simpleforwarding - - - org.opendaylight.controller - security - - - org.opendaylight.controller - statistics.northbound - - - org.opendaylight.controller - statisticsmanager - - - org.opendaylight.controller - statisticsmanager.implementation - - - org.opendaylight.controller - subnets.northbound - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - switchmanager.implementation - - - org.opendaylight.controller - switchmanager.northbound - - - org.opendaylight.controller - topology.northbound - - - org.opendaylight.controller - topology.web - - - org.opendaylight.controller - topologymanager - - - org.opendaylight.controller - topologymanager.shell - - - org.opendaylight.controller - troubleshoot.web - - - org.opendaylight.controller - usermanager - - - org.opendaylight.controller - usermanager.implementation - - - org.opendaylight.controller - usermanager.northbound - - - org.opendaylight.controller.thirdparty - net.sf.jung2 - - - org.eclipse.persistence - org.eclipse.persistence.antlr - - - org.eclipse.persistence - org.eclipse.persistence.core - - - org.eclipse.persistence - org.eclipse.persistence.moxy - - - - - - true - src/main/resources - - - - - org.apache.maven.plugins - maven-resources-plugin - - - filter - - resources - - generate-resources - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${project.build.directory}/classes/${features.file} - xml - features - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - org.opendaylight.controller - opendaylight-karaf-empty - ${commons.opendaylight.version} - - - org.opendaylight.odlparent:features-test - - - - - - diff --git a/opendaylight/adsal/features/nsf/src/main/resources/features.xml b/opendaylight/adsal/features/nsf/src/main/resources/features.xml deleted file mode 100644 index 56271eb699..0000000000 --- a/opendaylight/adsal/features/nsf/src/main/resources/features.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - mvn:org.opendaylight.controller/features-base/${commons.opendaylight.version}/xml/features - mvn:org.opendaylight.controller/features-adsal/${sal.version}/xml/features - - odl-adsal-all - odl-nsf-managers - odl-adsal-northbound - - - - - odl-adsal-all - odl-nsf-managers - odl-adsal-northbound - - - - odl-base-all - odl-adsal-all - mvn:org.opendaylight.controller/usermanager/${usermanager.version} - mvn:org.opendaylight.controller/usermanager.implementation/${usermanager.version} - - mvn:org.opendaylight.controller/appauth/${appauth.version} - - mvn:org.opendaylight.controller/connectionmanager/${connectionmanager.version} - mvn:org.opendaylight.controller/connectionmanager.implementation/${connectionmanager.version} - - mvn:org.opendaylight.controller/containermanager/${containermanager.version} - mvn:org.opendaylight.controller/containermanager.implementation/${containermanager.version} - - mvn:org.opendaylight.controller/statisticsmanager/${statisticsmanager.version} - mvn:org.opendaylight.controller/statisticsmanager.implementation/${statisticsmanager.implementation.version} - - mvn:org.opendaylight.controller/switchmanager/${switchmanager.api.version} - mvn:org.opendaylight.controller/switchmanager.implementation/${switchmanager.implementation.version} - - mvn:org.opendaylight.controller/forwardingrulesmanager/${forwardingrulesmanager.version} - mvn:org.opendaylight.controller/forwardingrulesmanager.implementation/${forwardingrulesmanager.implementation.version} - - mvn:org.opendaylight.controller/topologymanager/${topologymanager.version} - mvn:org.opendaylight.controller/topologymanager.shell/${topologymanager.shell.version} - - mvn:org.opendaylight.controller/hosttracker/${hosttracker.api.version} - mvn:org.opendaylight.controller/hosttracker.implementation/${hosttracker.implementation.version} - mvn:org.opendaylight.controller/hosttracker.shell/${hosttracker.shell.version} - - mvn:org.opendaylight.controller/forwarding.staticrouting/${forwarding.staticrouting} - - mvn:org.opendaylight.controller.thirdparty/net.sf.jung2/2.0.1 - mvn:org.opendaylight.controller/routing.dijkstra_implementation/${routing.dijkstra_implementation.version} - - - - odl-base-all - odl-nsf-managers - mvn:org.ow2.asm/asm-all/${asm.version} - - mvn:org.opendaylight.controller/bundlescanner/${bundlescanner.api.version} - mvn:org.opendaylight.controller/bundlescanner.implementation/${bundlescanner.implementation.version} - mvn:org.opendaylight.controller/commons.northbound/${northbound.commons.version} - mvn:org.opendaylight.controller/connectionmanager.northbound/${connectionmanager.version} - mvn:org.opendaylight.controller/flowprogrammer.northbound/${flowprogrammer.northbound.version} - mvn:org.opendaylight.controller/hosttracker.northbound/${hosttracker.northbound.version} - mvn:org.opendaylight.controller/networkconfig.bridgedomain.northbound/${networkconfig.bridgedomain.northbound.version} - mvn:org.eclipse.persistence/org.eclipse.persistence.antlr/${eclipse.persistence.version} - mvn:org.eclipse.persistence/org.eclipse.persistence.core/${eclipse.persistence.version} - mvn:org.eclipse.persistence/org.eclipse.persistence.moxy/${eclipse.persistence.version} - mvn:org.opendaylight.controller/forwarding.staticrouting.northbound/${forwarding.staticrouting.northbound.version} - mvn:org.opendaylight.controller/statistics.northbound/${statistics.northbound.version} - mvn:org.opendaylight.controller/subnets.northbound/${subnets.northbound.version} - mvn:org.opendaylight.controller/switchmanager.northbound/${switchmanager.northbound.version} - mvn:org.opendaylight.controller/topology.northbound/${topology.northbound.version} - mvn:org.opendaylight.controller/usermanager.northbound/${usermanager.northbound.version} - - diff --git a/opendaylight/adsal/forwarding/staticrouting/pom.xml b/opendaylight/adsal/forwarding/staticrouting/pom.xml deleted file mode 100644 index d14b31235a..0000000000 --- a/opendaylight/adsal/forwarding/staticrouting/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - forwarding.staticrouting - 0.7.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - sal - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.sal.packet.address, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.configuration, - org.opendaylight.controller.hosttracker, - org.opendaylight.controller.hosttracker.hostAware, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.routing, - org.eclipse.osgi.framework.console, - org.osgi.framework, - org.slf4j, - org.apache.felix.dm - org.opendaylight.controller.forwarding.staticrouting - org.opendaylight.controller.forwarding.staticrouting.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IForwardingStaticRouting.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IForwardingStaticRouting.java deleted file mode 100644 index 03d9453126..0000000000 --- a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IForwardingStaticRouting.java +++ /dev/null @@ -1,56 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting; - -import java.net.InetAddress; -import java.util.concurrent.ConcurrentMap; -/** - * - * This interface provides APIs to configure and manage static routes. - * - */ -import org.opendaylight.controller.sal.utils.Status; - -/** - * - * This Interface provides APIs to manage and query the static routes - * - */ -public interface IForwardingStaticRouting { - - /** - * Retrieves the StaticRoute that has the longest prefix matching the ipAddress. - * @param ipAddress (InetAddress) the IP address - * @return StaticRoute - */ - StaticRoute getBestMatchStaticRoute(InetAddress ipAddress); - - /** - * Returns all the StaticRouteConfig - * @return all the StaticRouteConfig - */ - ConcurrentMap getStaticRouteConfigs(); - - /** - * Adds a StaticRouteConfig - * @param config: the StaticRouteConfig to be added - * @return a text string indicating the result of the operation.. - * If the operation is successful, the return string will be "SUCCESS" - */ - Status addStaticRoute(StaticRouteConfig config); - - /** - * Removes the named StaticRouteConfig - * @param name: the name of the StaticRouteConfig to be removed - * @return a text string indicating the result of the operation. - * If the operation is successful, the return string will be "SUCCESS" - */ - Status removeStaticRoute(String name); -} diff --git a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IStaticRoutingAware.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IStaticRoutingAware.java deleted file mode 100644 index fb4863b1e0..0000000000 --- a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/IStaticRoutingAware.java +++ /dev/null @@ -1,25 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting; - -/** - * Interface that will be implemented by the modules that want to - * know when a Static Route is added or deleted. - * - */ -public interface IStaticRoutingAware { - - /** - * This method is called when a StaticRoute has added or deleted. - * @param s: StaticRoute - * @param added: boolean true if the static route is added, - */ - void staticRouteUpdate(StaticRoute s, boolean added); -} diff --git a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRoute.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRoute.java deleted file mode 100644 index f4df24304f..0000000000 --- a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRoute.java +++ /dev/null @@ -1,322 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting; - -import java.io.Serializable; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.nio.ByteBuffer; -import java.util.Map; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.packet.BitBufferHelper; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class defines a static route object. - */ -public class StaticRoute implements Serializable{ - private static final long serialVersionUID = 1L; - protected static final Logger logger = LoggerFactory - .getLogger(StaticRoute.class); - - /** - * This Enum defines the possible types for the next hop address. - */ - public enum NextHopType implements Serializable { - IPADDRESS("nexthop-ip"), SWITCHPORT("nexthop-interface"); - private NextHopType(String name) { - this.name = name; - } - - private String name; - - public String toString() { - return name; - } - - public static NextHopType fromString(String str) { - if (str == null) - return IPADDRESS; - if (str.equals(IPADDRESS.toString())) - return IPADDRESS; - if (str.equals(SWITCHPORT.toString())) - return SWITCHPORT; - return IPADDRESS; - } - } - - InetAddress networkAddress; - InetAddress mask; - NextHopType type; - InetAddress nextHopAddress; - Node node; - NodeConnector port; - HostNodeConnector host; - - /** - * Create a static route object with no specific information. - */ - public StaticRoute() { - - } - - /** - * Create a static route object from the StaticRouteConfig. - * @param: config: StaticRouteConfig - */ - public StaticRoute(StaticRouteConfig config) { - networkAddress = config.getStaticRouteIP(); - mask = StaticRoute.getV4AddressMaskFromDecimal(config - .getStaticRouteMask()); - type = NextHopType.fromString(config.getNextHopType()); - nextHopAddress = config.getNextHopIP(); - Map switchPort = config.getNextHopSwitchPorts(); - if ((switchPort != null) && (switchPort.size() == 1)) { - node = NodeCreator.createOFNode((Long) switchPort.keySet() - .toArray()[0]); - port = NodeConnectorCreator.createOFNodeConnector( - (Short) switchPort.values().toArray()[0], node); - } - } - - /** - * Get the IP address portion of the sub-network of the static route. - * @return InetAddress: the IP address portion of the sub-network of the static route - */ - public InetAddress getNetworkAddress() { - return networkAddress; - } - - /** - * Set the IP address portion of the sub-network of the static route. - * @param networkAddress The IP address (InetAddress) to be set - */ - public void setNetworkAddress(InetAddress networkAddress) { - this.networkAddress = networkAddress; - } - - /** - * Get the mask of the sub-network of the static route. - * @return mask: the mask (InetAddress) of the sub-network of the static route - */ - public InetAddress getMask() { - return mask; - } - - /** - * Set the sub-network's mask of the static route. - * @param mask The mask (InetAddress) to be set - */ - public void setMask(InetAddress mask) { - this.mask = mask; - } - - /** - * Get the NextHopeType of the static route. - * @return type: NextHopeType - */ - public NextHopType getType() { - return type; - } - - /** - * Set the nextHopType. - * @param type The NextHopType to be set - */ - public void setType(NextHopType type) { - this.type = type; - } - - /** - * Get the next hop IP address. - * @return: nextHopAddress (InetAddress) - */ - public InetAddress getNextHopAddress() { - return nextHopAddress; - } - - /** - * Set the next hop IP address. - * @param nextHopAddress The IP address (InetAddress) to be set - */ - public void setNextHopAddress(InetAddress nextHopAddress) { - this.nextHopAddress = nextHopAddress; - } - - /** - * Get the Node associated with the static route. - * @return: Node - */ - public Node getNode() { - return node; - } - - /** - * Set the node associated to the static route. - * @param node: The node to be set - */ - public void setNode(Node node) { - this.node = node; - } - - /** - * Set the port associated to the static route. - * @param port The port (NodeConnector) to be set - */ - public void setPort(NodeConnector port) { - this.port = port; - } - - /** - * Get the port associated to the static route. - * @return port: The port (NodeConnector) - */ - public NodeConnector getPort() { - return port; - } - - /** - * Get the Host associated to static route. - * @return host: The host (HostNodeConnector) - */ - public HostNodeConnector getHost() { - return host; - } - - /** - * Set the host associated to the static route. - * @param host: (HostNodeConnector) to be set - */ - public void setHost(HostNodeConnector host) { - this.host = host; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((mask == null) ? 0 : mask.hashCode()); - result = prime * result - + ((networkAddress == null) ? 0 : networkAddress.hashCode()); - result = prime * result - + ((nextHopAddress == null) ? 0 : nextHopAddress.hashCode()); - result = prime * result + ((port == null) ? 0 : port.hashCode()); - result = prime * result + ((node == null) ? 0 : node.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - - @Override - public String toString() { - return "StaticRoute [networkAddress=" + networkAddress + ", mask=" - + mask + ", type=" + type.toString() + ", nextHopAddress=" - + nextHopAddress + ", swid=" + node + ", port=" + port - + ", host=" + host + "]"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StaticRoute other = (StaticRoute) obj; - if (!networkAddress.equals(other.networkAddress)) - return false; - if (!mask.equals(other.mask)) - return false; - return true; - } - - private static InetAddress getV4AddressMaskFromDecimal(int mask) { - int netmask = 0; - for (int i = 0; i < mask; i++) { - netmask |= (1 << 31 - i); - } - - try { - return InetAddress.getByAddress(BitBufferHelper - .toByteArray(netmask)); - } catch (Exception e) { - logger.error("",e); - return null; - } - } - - private void applyV4MaskOnByteBuffer(ByteBuffer bb, ByteBuffer bbMask) { - for (int i = 0; i < bb.array().length; i++) { - bb.put(i, (byte) (bb.get(i) & bbMask.get(i))); - } - } - - /** - * Compute and return the IP address with longest prefix match from the static route based on the - * destNetworkAddress. Currently it only take IPv4 address format (Inet4Address) - * @param destNetworkAddress: the IP address to be based on - * @return: InetAddress: the IPv4 address with the longest prefix matching the static route. - * If the destNetworkkAddress is not IPv4 format, it will return null. - */ - public InetAddress longestPrefixMatch(InetAddress destNetworkAddress) { - if (destNetworkAddress instanceof Inet4Address) { - ByteBuffer bbdest = ByteBuffer - .wrap(destNetworkAddress.getAddress()); - ByteBuffer bbself = ByteBuffer.wrap(networkAddress.getAddress()); - - ByteBuffer bbMask = ByteBuffer.wrap(mask.getAddress()); - - applyV4MaskOnByteBuffer(bbdest, bbMask); - applyV4MaskOnByteBuffer(bbself, bbMask); - - if (bbdest.equals(bbself)) { - try { - return InetAddress.getByAddress(bbself.array()); - } catch (Exception e) { - logger.error("",e); - } - } - } - return null; - } - - /** - * Compare the static route with another static route. It only handles(for now) IPv4Address. - * @param s: the other StaticRoute - * @return: 0 if they are the same - */ - public int compareTo(StaticRoute s) { - if (s == null) - return 1; - if ((networkAddress instanceof Inet6Address) - || (s.getNetworkAddress() instanceof Inet6Address)) { - // HANDLE IPv6 Later - return 1; - } - - ByteBuffer bbchallenger = ByteBuffer.wrap(s.getNetworkAddress() - .getAddress()); - ByteBuffer bbself = ByteBuffer.wrap(networkAddress.getAddress()); - ByteBuffer bbChallengerMask = ByteBuffer.wrap(s.getMask().getAddress()); - ByteBuffer bbSelfMask = ByteBuffer.wrap(getMask().getAddress()); - - applyV4MaskOnByteBuffer(bbchallenger, bbChallengerMask); - applyV4MaskOnByteBuffer(bbself, bbSelfMask); - return bbself.compareTo(bbchallenger); - } -} \ No newline at end of file diff --git a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfig.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfig.java deleted file mode 100644 index 7726c0f4e7..0000000000 --- a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfig.java +++ /dev/null @@ -1,384 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting; - -import java.io.Serializable; -import java.lang.reflect.Field; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.sal.utils.GUIField; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; - -/** - * This class defines all the necessary configuration information for a static route. - */ -public class StaticRouteConfig extends ConfigurationObject implements Serializable { - private static final long serialVersionUID = 1L; - private static final String regexSubnet = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." - + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." - + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." - + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])[/](\\d|[12]\\d|3[0-2])$"; - private static final String regexIP = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." - + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." - + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." - + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; - private static final String regexDatapathID = "^([0-9a-fA-F]{1,2}[:-]){7}[0-9a-fA-F]{1,2}$"; - private static final String regexDatapathIDLong = "^[0-9a-fA-F]{1,16}$"; - private static final String prettyFields[] = { GUIField.NAME.toString(), - GUIField.STATICROUTE.toString(), GUIField.NEXTHOP.toString() }; - private transient String nextHopType; // Ignoring NextHopType for now. Supporting just the next-hop IP-Address feature for now. - // Order matters: JSP file expects following fields in the following order - private String name; - private String staticRoute; // A.B.C.D/MM Where A.B.C.D is the Default Gateway IP (L3) or ARP Querier IP (L2) - private String nextHop; // NextHop IP-Address (or) datapath ID/port list: xx:xx:xx:xx:xx:xx:xx:xx/a,b,c-m,r-t,y - - /** - * Create a static route configuration with no specific information. - */ - public StaticRouteConfig() { - super(); - nextHopType = StaticRoute.NextHopType.IPADDRESS.toString(); - } - - /** - * Create a static route configuration with all the information. - * @param name The name (String) of the static route config - * @param staticRoute The string representation of the route. e.g. 192.168.1.1/24 - * @param nextHop The string representation of the next hop IP address. e.g. 10.10.1.1 - */ - public StaticRouteConfig(String name, String staticRoute, String nextHop) { - super(); - this.name = name; - this.staticRoute = staticRoute; - this.nextHop = nextHop; - } - - /** - * Get the name of the StaticRouteConfig. - * @return: The name - */ - public String getName() { - return name; - } - - /** - * Set the name of the StaticRouteConfig. - * @param name The name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * Get the string representation of the static route. - * @return The string representation of the static route - */ - public String getStaticRoute() { - return staticRoute; - } - - /** - * Set the static route of the StaticRouteConfig. - * @param staticRoute The string representation of the static route - */ - public void setStaticRoute(String staticRoute) { - this.staticRoute = staticRoute; - } - - /** - * Get the string representation of the next hop address type. - * @return The string representation of the next hop address type - */ - public String getNextHopType() { - if (nextHopType == null) { - return StaticRoute.NextHopType.IPADDRESS.toString(); - } - return nextHopType; - } - - /** - * Set the next hop address type. - * @param nextHopType The string representation of the next hop address type - */ - public void setNextHopType(String nextHopType) { - this.nextHopType = nextHopType; - } - - /** - * Get all the supported next hop address types. - * @return The list of supported next hop address types - */ - public static List getSupportedNextHopTypes() { - List s = new ArrayList(); - for (StaticRoute.NextHopType nh : StaticRoute.NextHopType.values()) { - s.add(nh.toString()); - } - return s; - } - - /** - * Get the next hop address - * @return The string represenation of the next hop address - */ - public String getNextHop() { - return nextHop; - } - - /** - * Set the next hop address. - * @param nextHop: The string representation of the next hop address to be set - */ - public void setNextHop(String nextHop) { - this.nextHop = nextHop; - } - - /** - * Return a string with text indicating if the config is valid. - * @return SUCCESS if the config is valid - */ - public Status isValid() { - if (!isValidResourceName(name)) { - return new Status(StatusCode.BADREQUEST, - "Invalid Static Route name"); - } - if (!isValidStaticRouteEntry()) { - return new Status(StatusCode.BADREQUEST, - "Invalid Static Route entry. Please use the " + - "IPAddress/mask format. Default gateway " + - "(0.0.0.0/0) is NOT supported."); - } - if (!isValidNextHop()) { - return new Status(StatusCode.BADREQUEST, - "Invalid NextHop IP Address configuration. " + - "Please use the X.X.X.X format."); - } - - return new Status(StatusCode.SUCCESS, null); - } - - private boolean isValidAddress(String address) { - if ((address != null) && address.matches(regexIP)) { - return true; - } - return false; - } - - private boolean isValidStaticRouteEntry() { - if ((staticRoute != null) && staticRoute.matches(regexSubnet)) { - return true; - } - return false; - } - - private boolean isValidNextHop() { - if (getNextHopType().equalsIgnoreCase( - StaticRoute.NextHopType.IPADDRESS.toString())) { - return isValidNextHopIP(); - } else if (getNextHopType().equalsIgnoreCase( - StaticRoute.NextHopType.SWITCHPORT.toString())) { - return isValidSwitchId(); - } - return false; - } - - private boolean isValidNextHopIP() { - return isValidAddress(nextHop); - } - - private boolean isValidSwitchId(String switchId) { - return (switchId != null && (switchId.matches(regexDatapathID) || switchId - .matches(regexDatapathIDLong))); - } - - private boolean isValidSwitchId() { - if (getNextHopType().equalsIgnoreCase( - StaticRoute.NextHopType.SWITCHPORT.toString())) { - String pieces[] = nextHop.split("/"); - if (pieces.length < 2) { - return false; - } - return isValidSwitchId(pieces[0]); - } - return false; - } - - /** - * Return the IP address of the static route. - * @return The IP address - */ - public InetAddress getStaticRouteIP() { - if (!isValidStaticRouteEntry()) { - return null; - } - InetAddress ip = null; - try { - ip = InetAddress.getByName(staticRoute.split("/")[0]); - } catch (UnknownHostException e1) { - return null; - } - return ip; - } - - /** - * Return the bit-mask length of the static route. - * @return The bit-mask length - */ - public Short getStaticRouteMask() { - Short maskLen = 0; - if (isValidStaticRouteEntry()) { - String[] s = staticRoute.split("/"); - maskLen = (s.length == 2) ? Short.valueOf(s[1]) : 32; - } - return maskLen; - } - - /** - * Return the IP address of the next hop. - * @return the IP address - */ - public InetAddress getNextHopIP() { - if ((getNextHopType() - .equalsIgnoreCase(StaticRoute.NextHopType.IPADDRESS.toString())) - && isValidNextHopIP()) { - InetAddress ip = null; - try { - ip = InetAddress.getByName(nextHop); - } catch (UnknownHostException e1) { - return null; - } - return ip; - } - return null; - } - -/** - * Return the switch ID and the port ID of the next hop address. - * @return The switchID (Long) and PortID (Short) in the map - */ - public Map getNextHopSwitchPorts() { - // codedSwitchPorts = xx:xx:xx:xx:xx:xx:xx:xx/port-number - if (getNextHopType().equalsIgnoreCase( - StaticRoute.NextHopType.SWITCHPORT.toString())) { - Map sp = new HashMap(1); - String pieces[] = nextHop.split("/"); - sp.put(getSwitchIDLong(pieces[0]), Short.valueOf(pieces[1])); - return sp; - } - return null; - } - - private long getSwitchIDLong(String switchId) { - int radix = 16; - String switchString = "0"; - - if (isValidSwitchId(switchId)) { - if (switchId.contains(":")) { - // Handle the 00:00:AA:BB:CC:DD:EE:FF notation - switchString = switchId.replace(":", ""); - } else if (switchId.contains("-")) { - // Handle the 00-00-AA-BB-CC-DD-EE-FF notation - switchString = switchId.replace("-", ""); - } else { - // Handle the 0123456789ABCDEF notation - switchString = switchId; - } - } - return Long.parseLong(switchString, radix); - } - - /** - * Return all the field names of the config. - * @return The list containing all the field names - */ - public static List getFieldsNames() { - List fieldList = new ArrayList(); - for (Field fld : StaticRouteConfig.class.getDeclaredFields()) { - fieldList.add(fld.getName()); - } - //remove the 6 static fields + NextHopType - for (short i = 0; i < 7; i++) { - fieldList.remove(0); - } - return fieldList; - } - - /** - * Return all the GUI field names of the config. - * @return The list containing all the GUI field names - */ - public static List getGuiFieldsNames() { - List fieldList = new ArrayList(); - for (String str : prettyFields) { - fieldList.add(str); - } - return fieldList; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((nextHop == null) ? 0 : nextHop.hashCode()); - result = prime * result - + ((staticRoute == null) ? 0 : staticRoute.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - StaticRouteConfig other = (StaticRouteConfig) obj; - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (nextHop == null) { - if (other.nextHop != null) { - return false; - } - } else if (!nextHop.equals(other.nextHop)) { - return false; - } - if (staticRoute == null) { - if (other.staticRoute != null) { - return false; - } - } else if (!staticRoute.equals(other.staticRoute)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "StaticRouteConfig [name=" + name + ", staticRoute=" - + staticRoute + ", nextHopType=" + nextHopType + ", nextHop=" - + nextHop + "]"; - } -} diff --git a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/Activator.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/Activator.java deleted file mode 100644 index 7be9c23677..0000000000 --- a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/Activator.java +++ /dev/null @@ -1,87 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting.internal; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.forwarding.staticrouting.IForwardingStaticRouting; -import org.opendaylight.controller.forwarding.staticrouting.IStaticRoutingAware; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.IfNewHostNotify; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { StaticRoutingImplementation.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(StaticRoutingImplementation.class)) { - c.setInterface(new String[] { - IForwardingStaticRouting.class.getName(), - IfNewHostNotify.class.getName(), - IConfigurationContainerAware.class.getName() }, null); - - c.add(createContainerServiceDependency(containerName).setService( - IClusterContainerServices.class).setCallbacks( - "setClusterContainerService", - "unsetClusterContainerService").setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - IfIptoHost.class).setCallbacks("setHostTracker", - "unsetHostTracker").setRequired(true)); - - // Static routing aware there could be many - c.add(createContainerServiceDependency(containerName).setService( - IStaticRoutingAware.class).setCallbacks( - "setStaticRoutingAware", "unsetStaticRoutingAware") - .setRequired(false)); - - c.add(createContainerServiceDependency(containerName).setService( - IConfigurationContainerService.class).setCallbacks( - "setConfigurationContainerService", - "unsetConfigurationContainerService").setRequired(true)); - } - } -} diff --git a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementation.java b/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementation.java deleted file mode 100644 index fedf5541d0..0000000000 --- a/opendaylight/adsal/forwarding/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementation.java +++ /dev/null @@ -1,484 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting.internal; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.net.Inet4Address; -import java.net.InetAddress; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Dictionary; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.forwarding.staticrouting.IForwardingStaticRouting; -import org.opendaylight.controller.forwarding.staticrouting.IStaticRoutingAware; -import org.opendaylight.controller.forwarding.staticrouting.StaticRoute; -import org.opendaylight.controller.forwarding.staticrouting.StaticRouteConfig; -import org.opendaylight.controller.hosttracker.HostIdFactory; -import org.opendaylight.controller.hosttracker.IHostId; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.IfNewHostNotify; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.utils.IObjectReader; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Static Routing feature provides the bridge between SDN and Non-SDN networks. - */ -public class StaticRoutingImplementation implements IfNewHostNotify, IForwardingStaticRouting, IObjectReader, - IConfigurationContainerAware { - private static Logger log = LoggerFactory.getLogger(StaticRoutingImplementation.class); - private static final String STATIC_ROUTES_FILE_NAME = "staticRouting.conf"; - ConcurrentMap staticRoutes; - ConcurrentMap staticRouteConfigs; - private IfIptoHost hostTracker; - private Timer gatewayProbeTimer; - private IClusterContainerServices clusterContainerService = null; - private IConfigurationContainerService configurationService; - private Set staticRoutingAware = Collections - .synchronizedSet(new HashSet()); - private ExecutorService executor; - - void setStaticRoutingAware(IStaticRoutingAware s) { - if (this.staticRoutingAware != null) { - this.staticRoutingAware.add(s); - } - } - - void unsetStaticRoutingAware(IStaticRoutingAware s) { - if (this.staticRoutingAware != null) { - this.staticRoutingAware.remove(s); - } - } - - public void setHostTracker(IfIptoHost hostTracker) { - log.debug("Setting HostTracker"); - this.hostTracker = hostTracker; - } - - public void unsetHostTracker(IfIptoHost hostTracker) { - if (this.hostTracker == hostTracker) { - this.hostTracker = null; - } - } - - public void setConfigurationContainerService(IConfigurationContainerService service) { - log.trace("Got configuration service set request {}", service); - this.configurationService = service; - } - - public void unsetConfigurationContainerService(IConfigurationContainerService service) { - log.trace("Got configuration service UNset request"); - this.configurationService = null; - } - - @Override - public ConcurrentMap getStaticRouteConfigs() { - return staticRouteConfigs; - } - - @Override - public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException { - // Perform the class deserialization locally, from inside the package - // where the class is defined - return ois.readObject(); - } - - - private void loadConfiguration() { - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, STATIC_ROUTES_FILE_NAME)) { - addStaticRoute((StaticRouteConfig) conf); - } - } - - private Status saveConfig() { - return saveConfigInternal(); - } - - public Status saveConfigInternal() { - Status status = configurationService.persistConfiguration( - new ArrayList(staticRouteConfigs.values()), STATIC_ROUTES_FILE_NAME); - - if (status.isSuccess()) { - return status; - } else { - return new Status(StatusCode.INTERNALERROR, "Save failed"); - } - } - - private void allocateCaches() { - if (this.clusterContainerService == null) { - log.trace("un-initialized clusterContainerService, can't create cache"); - return; - } - - try { - clusterContainerService.createCache("forwarding.staticrouting.routes", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache("forwarding.staticrouting.configs", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheExistException cee) { - log.error("\nCache already exists - destroy and recreate if needed"); - } catch (CacheConfigException cce) { - log.error("\nCache configuration invalid - check cache mode"); - } - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - if (this.clusterContainerService == null) { - log.warn("un-initialized clusterContainerService, can't retrieve cache"); - return; - } - - staticRoutes = (ConcurrentMap) clusterContainerService - .getCache("forwarding.staticrouting.routes"); - if (staticRoutes == null) { - log.error("\nFailed to get rulesDB handle"); - } - - staticRouteConfigs = (ConcurrentMap) clusterContainerService - .getCache("forwarding.staticrouting.configs"); - if (staticRouteConfigs == null) { - log.error("\nFailed to get rulesDB handle"); - } - } - - private void notifyStaticRouteUpdate(StaticRoute s, boolean update) { - if (this.staticRoutingAware != null) { - log.trace("Invoking StaticRoutingAware listeners"); - synchronized (this.staticRoutingAware) { - for (IStaticRoutingAware ra : this.staticRoutingAware) { - try { - ra.staticRouteUpdate(s, update); - } catch (Exception e) { - log.error("", e); - } - } - } - } - } - - private class NotifyStaticRouteWorker implements Callable { - - private String name; - private StaticRoute staticRoute; - private boolean added; - - public NotifyStaticRouteWorker(String name, StaticRoute s, boolean update) { - this.name = name; - this.staticRoute = s; - this.added = update; - } - - @Override - public Object call() throws Exception { - if (!added || (staticRoute.getType() == StaticRoute.NextHopType.SWITCHPORT)) { - notifyStaticRouteUpdate(staticRoute, added); - } else { - InetAddress nh = staticRoute.getNextHopAddress(); - // HostTracker hosts db key scheme implementation - IHostId id = HostIdFactory.create(nh, null); - HostNodeConnector host = hostTracker.hostQuery(id); - if (host == null) { - log.debug("Next hop {} is not present, try to discover it", nh.getHostAddress()); - Future future = hostTracker.discoverHost(id); - if (future != null) { - try { - host = future.get(); - } catch (InterruptedException ioe) { - log.trace("Thread interrupted {}", ioe); - } catch (Exception e) { - log.error("", e); - } - } - } - if (host != null) { - log.debug("Next hop {} is found", nh.getHostAddress()); - staticRoute.setHost(host); - // static route object has changed - // put the changed object back in the cache - // for it to sync - staticRoutes.put(name, staticRoute); - notifyStaticRouteUpdate(staticRoute, added); - } else { - log.debug("Next hop {} is still not present, try again later", nh.getHostAddress()); - } - } - return null; - } - } - - private void checkAndUpdateListeners(String name, StaticRoute staticRoute, boolean added) { - NotifyStaticRouteWorker worker = new NotifyStaticRouteWorker(name, staticRoute, added); - try { - executor.submit(worker); - } catch (Exception e) { - log.error("got Exception ", e); - } - } - - private void notifyHostUpdate(HostNodeConnector host, boolean added) { - if (host == null) { - return; - } - for (Map.Entry s : staticRoutes.entrySet()) { - StaticRoute route = s.getValue(); - if (route.getType() == StaticRoute.NextHopType.SWITCHPORT) { - continue; - } - if (route.getNextHopAddress().equals(host.getNetworkAddress())) { - if (added) { - route.setHost(host); - } else { - route.setHost(null); - } - // static route object has changed - // put the changed object back in the cache - // for it to sync - staticRoutes.put(s.getKey(), route); - notifyStaticRouteUpdate(route, added); - } - } - } - - @Override - public void notifyHTClient(HostNodeConnector host) { - notifyHostUpdate(host, true); - } - - @Override - public void notifyHTClientHostRemoved(HostNodeConnector host) { - notifyHostUpdate(host, false); - } - - public boolean isIPv4AddressValid(String cidr) { - if (cidr == null) { - return false; - } - - String values[] = cidr.split("/"); - Pattern ipv4Pattern = Pattern - .compile("(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])"); - Matcher mm = ipv4Pattern.matcher(values[0]); - if (!mm.matches()) { - log.debug("IPv4 source address {} is not valid", cidr); - return false; - } - if (values.length >= 2) { - int prefix = Integer.valueOf(values[1]); - if ((prefix < 0) || (prefix > 32)) { - log.debug("prefix {} is not valid", prefix); - return false; - } - } - return true; - } - - public static short getUnsignedByte(ByteBuffer bb, int position) { - return ((short) (bb.get(position) & (short) 0xff)); - } - - public static int compareByteBuffers(ByteBuffer buf1, ByteBuffer buf2) { - for (int i = 0; i < buf1.array().length; i++) { - if (getUnsignedByte(buf1, i) > getUnsignedByte(buf2, i)) { - return 1; - } else if (getUnsignedByte(buf1, i) < getUnsignedByte(buf2, i)) { - return -1; - } - } - - return 0; - } - - @Override - public StaticRoute getBestMatchStaticRoute(InetAddress ipAddress) { - ByteBuffer bblongestPrefix = null; - try { - bblongestPrefix = ByteBuffer.wrap(InetAddress.getByName("0.0.0.0").getAddress()); - } catch (Exception e) { - return null; - } - - if (staticRoutes == null) { - return null; - } - - StaticRoute longestPrefixRoute = null; - for (StaticRoute s : staticRoutes.values()) { - InetAddress prefix = s.longestPrefixMatch(ipAddress); - if ((prefix != null) && (prefix instanceof Inet4Address)) { - ByteBuffer bbtmp = ByteBuffer.wrap(prefix.getAddress()); - if (compareByteBuffers(bbtmp, bblongestPrefix) > 0) { - bblongestPrefix = bbtmp; - longestPrefixRoute = s; - } - } - } - return longestPrefixRoute; - } - - @Override - public Status addStaticRoute(StaticRouteConfig config) { - Status status = config.isValid(); - if (!status.isSuccess()) { - return status; - } - if (staticRouteConfigs.get(config.getName()) != null) { - return new Status(StatusCode.CONFLICT, "A valid Static Route configuration with this name " - + "already exists. Please use a different name"); - } - - // Update database - StaticRoute sRoute = new StaticRoute(config); - - for (Map.Entry entry : staticRoutes.entrySet()) { - if (entry.getValue().compareTo(sRoute) == 0) { - return new Status(StatusCode.CONFLICT, "This conflicts with an existing Static Route " - + "Configuration. Please check the configuration " + "and try again"); - } - } - staticRoutes.put(config.getName(), sRoute); - - // Update config databse - staticRouteConfigs.put(config.getName(), config); - - // Notify - checkAndUpdateListeners(config.getName(), sRoute, true); - return status; - } - - @Override - public Status removeStaticRoute(String name) { - staticRouteConfigs.remove(name); - StaticRoute sRoute = staticRoutes.remove(name); - if (sRoute != null) { - checkAndUpdateListeners(name, sRoute, false); - return new Status(StatusCode.SUCCESS, null); - } - return new Status(StatusCode.NOTFOUND, "Static Route with name " + name + " is not found"); - } - - void setClusterContainerService(IClusterContainerServices s) { - log.debug("Cluster Service set"); - this.clusterContainerService = s; - } - - void unsetClusterContainerService(IClusterContainerServices s) { - if (this.clusterContainerService == s) { - log.debug("Cluster Service removed!"); - this.clusterContainerService = null; - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init(Component c) { - String containerName = null; - Dictionary props = c.getServiceProperties(); - if (props != null) { - containerName = (String) props.get("containerName"); - } else { - // In the Global instance case the containerName is empty - containerName = ""; - } - - log.debug("forwarding.staticrouting starting on container {}", containerName); - allocateCaches(); - retrieveCaches(); - this.executor = Executors.newFixedThreadPool(1); - loadConfiguration(); - - /* - * Slow probe to identify any gateway that might have silently appeared - * after the Static Routing Configuration. - */ - gatewayProbeTimer = new Timer(); - gatewayProbeTimer.schedule(new TimerTask() { - @Override - public void run() { - for (Map.Entry s : staticRoutes.entrySet()) { - StaticRoute route = s.getValue(); - if ((route.getType() == StaticRoute.NextHopType.IPADDRESS) && route.getHost() == null) { - checkAndUpdateListeners(s.getKey(), route, true); - } - } - } - }, 60 * 1000, 60 * 1000); - - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - log.debug("Destroy all the Static Routing Rules given we are " + "shutting down"); - - gatewayProbeTimer.cancel(); - - // Clear the listener so to be ready in next life - this.staticRoutingAware.clear(); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - executor.shutdown(); - } - - @Override - public Status saveConfiguration() { - return this.saveConfig(); - } - -} diff --git a/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfigTest.java b/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfigTest.java deleted file mode 100644 index 7cd085f896..0000000000 --- a/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteConfigTest.java +++ /dev/null @@ -1,110 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting; - - -import java.net.InetAddress; -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.forwarding.staticrouting.StaticRoute.NextHopType; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; - -public class StaticRouteConfigTest { - - @Test - public void testStaticRouteSetGet() { - StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig(); - staticRouteConfig1.setName("route"); - staticRouteConfig1.setStaticRoute("10.1.1.2/32"); - staticRouteConfig1.setNextHop("200.2.2.2"); - staticRouteConfig1.setNextHopType(NextHopType.IPADDRESS.toString()); - StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route", "10.1.1.2/32", "200.2.2.2"); - - Assert.assertEquals(staticRouteConfig2.getName(), staticRouteConfig1.getName()); - Assert.assertEquals(staticRouteConfig2.getStaticRoute(), staticRouteConfig1.getStaticRoute()); - Assert.assertEquals(staticRouteConfig2.getNextHop(), staticRouteConfig1.getNextHop()); - Assert.assertEquals("nexthop-ip", staticRouteConfig1.getNextHopType()); - } - - @Test - public void testStaticRouteisValid() { - StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1.1"); - Status receivedResponse1 = staticRouteConfig1.isValid(); - Status expectedResponse1 = new Status(StatusCode.SUCCESS, null); - Assert.assertEquals(expectedResponse1.toString(), receivedResponse1.toString()); - - StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("", "", "100.1.1.1"); - Status receivedResponse2 = staticRouteConfig2.isValid(); - Status expectedResponse2 = new Status(StatusCode.BADREQUEST, - "Invalid Static Route name"); - Assert.assertEquals(expectedResponse2.toString(), receivedResponse2.toString()); - - StaticRouteConfig staticRouteConfig3 = new StaticRouteConfig("route1", "10.1.1.254", "100.1.1.1"); - Status receivedResponse3 = staticRouteConfig3.isValid(); - Status expectedResponse3 = new Status(StatusCode.BADREQUEST, - "Invalid Static Route entry. Please use the " + - "IPAddress/mask format. Default gateway " + - "(0.0.0.0/0) is NOT supported."); - Assert.assertEquals(expectedResponse3.toString(), receivedResponse3.toString()); - - StaticRouteConfig staticRouteConfig4 = new StaticRouteConfig("route1", "289.1.1.254/24", "100.1.1.1"); - Status receivedResponse4 = staticRouteConfig4.isValid(); - Status expectedResponse4 = new Status(StatusCode.BADREQUEST, - "Invalid Static Route entry. Please use the " + - "IPAddress/mask format. Default gateway " + - "(0.0.0.0/0) is NOT supported."); - Assert.assertEquals(expectedResponse4.toString(), receivedResponse4.toString()); - - StaticRouteConfig staticRouteConfig5 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1"); - Status receivedResponse5 = staticRouteConfig5.isValid(); - Status expectedResponse5 = new Status(StatusCode.BADREQUEST, - "Invalid NextHop IP Address configuration. " + - "Please use the X.X.X.X format."); - Assert.assertEquals(expectedResponse5.toString(), receivedResponse5.toString()); - } - - @Test - public void testGetStaticRouteIP() { - StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.0/24", "100.1.1.1"); - InetAddress ip1 = staticRouteConfig1.getStaticRouteIP(); - Assert.assertEquals("10.1.1.0", ip1.getHostAddress()); - - StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.0/80", "100.1.1.1"); - InetAddress ip2 = staticRouteConfig2.getStaticRouteIP(); - Assert.assertEquals(null, ip2); - - } - - @Test - public void testGetStaticRouteMask() { - StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.0/24", "100.1.1.1"); - Short receivedMaskLen1 = staticRouteConfig1.getStaticRouteMask(); - Short expectedMaskLen1 = 24; - Assert.assertEquals(expectedMaskLen1, receivedMaskLen1); - - StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.0/40", "100.1.1.1"); - Short receivedMaskLen2 = staticRouteConfig2.getStaticRouteMask(); - Short expectedMaskLen2 = 0; - Assert.assertEquals(expectedMaskLen2, receivedMaskLen2); - } - - @Test - public void testGetNextHopIP() { - StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1.1"); - InetAddress ip1 = staticRouteConfig1.getNextHopIP(); - Assert.assertEquals("100.1.1.1", ip1.getHostAddress()); - - StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1"); - InetAddress ip2 = staticRouteConfig2.getNextHopIP(); - Assert.assertEquals(null, ip2); - } - -} diff --git a/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteTest.java b/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteTest.java deleted file mode 100644 index acfa22363c..0000000000 --- a/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/StaticRouteTest.java +++ /dev/null @@ -1,111 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.forwarding.staticrouting.StaticRoute.NextHopType; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -import static org.junit.Assert.fail; - -public class StaticRouteTest { - - @Test - public void testStaticRouteGetSet() { - StaticRoute staticRoute = new StaticRoute(); - InetAddress networkAddress = null; - InetAddress mask = null; - InetAddress nextHopAddress = null; - try { - networkAddress = InetAddress.getByName("10.1.1.0"); - mask = InetAddress.getByName("255.255.255.0"); - nextHopAddress = InetAddress.getByName("200.0.0.1"); - - } catch (UnknownHostException e) { - fail("Failed due to unknown host " + e.getMessage()); - } - staticRoute.setNetworkAddress(networkAddress); - Assert.assertEquals(networkAddress.getHostAddress(), staticRoute.getNetworkAddress().getHostAddress()); - staticRoute.setMask(mask); - Assert.assertEquals(mask.getHostAddress(), staticRoute.getMask().getHostAddress()); - staticRoute.setType(NextHopType.IPADDRESS); - Assert.assertEquals("nexthop-ip", staticRoute.getType().toString()); - staticRoute.setNextHopAddress(nextHopAddress); - Assert.assertEquals(nextHopAddress.getHostAddress(), staticRoute.getNextHopAddress().getHostAddress()); - Node node = NodeCreator.createOFNode(((long)10)); - staticRoute.setNode(node); - Assert.assertEquals(node, staticRoute.getNode()); - NodeConnector nc0 = NodeConnectorCreator.createOFNodeConnector((short)20, node); - staticRoute.setPort(nc0); - Assert.assertEquals(nc0, staticRoute.getPort()); - InetAddress ip1 = null; - HostNodeConnector h1 = null; - try { - ip1 = InetAddress.getByName("192.1.1.1"); - } catch (UnknownHostException e) { - fail("Failed due to unknown host " + e.getMessage()); - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - fail("Failed to construct host " + e.getMessage()); - } - staticRoute.setHost(h1); - Assert.assertEquals(h1, staticRoute.getHost()); - } - - @Test - public void testStaticRouteComparison() { - StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.0/24", "100.1.1.1"); - StaticRouteConfig staticRouteConfig2 = new StaticRouteConfig("route2", "10.1.1.0/24", "100.2.1.1"); - StaticRouteConfig staticRouteConfig3 = new StaticRouteConfig("route3", "10.2.1.0/24", "100.3.1.1"); - StaticRouteConfig staticRouteConfig4 = new StaticRouteConfig("route4", "10.1.1.0/31", ""); - StaticRoute staticRoute1 = new StaticRoute(staticRouteConfig1); - StaticRoute staticRoute2 = new StaticRoute(staticRouteConfig2); - StaticRoute staticRoute3 = new StaticRoute(staticRouteConfig3); - StaticRoute staticRoute4 = new StaticRoute(staticRouteConfig4); - - Assert.assertTrue(staticRoute1.equals(staticRoute2)); - Assert.assertFalse(staticRoute1.equals(staticRoute3)); - Assert.assertFalse(staticRoute1.equals(staticRoute4)); - - Assert.assertTrue(staticRoute1.compareTo(staticRoute2) == 0); - Assert.assertFalse(staticRoute1.compareTo(staticRoute3) == 0); - Assert.assertTrue(staticRoute1.compareTo(staticRoute4) == 0); - - } - - @Test - public void testLongestPrefixMatch() { - StaticRouteConfig staticRouteConfig1 = new StaticRouteConfig("route1", "10.1.1.254/24", "100.1.1.1"); - StaticRoute staticRoute1 = new StaticRoute(staticRouteConfig1); - InetAddress ip1 = null; - InetAddress ip2 = null; - try { - ip1 = InetAddress.getByName("10.1.0.2"); - ip2 = InetAddress.getByName("10.1.1.2"); - } catch (UnknownHostException e) { - fail("Test failed due to unknown host " + e.getMessage()); - } - InetAddress rxdIp1 = staticRoute1.longestPrefixMatch(ip1); - InetAddress rxdIp2 = staticRoute1.longestPrefixMatch(ip2); - Assert.assertNull(rxdIp1); - Assert.assertEquals("10.1.1.0", rxdIp2.getHostAddress()); - } -} diff --git a/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementationTest.java b/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementationTest.java deleted file mode 100644 index 4c9d4ab1f3..0000000000 --- a/opendaylight/adsal/forwarding/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/internal/StaticRoutingImplementationTest.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting.internal; - -import org.junit.Assert; -import org.junit.Test; - -public class StaticRoutingImplementationTest { - - @Test - public void isIPv4AddressValidTest() { - StaticRoutingImplementation staticRouteImpl = new StaticRoutingImplementation(); - Assert.assertTrue(staticRouteImpl.isIPv4AddressValid("192.168.100.0/24")); - Assert.assertFalse(staticRouteImpl.isIPv4AddressValid("192.168.100.0/36")); - Assert.assertFalse(staticRouteImpl.isIPv4AddressValid("192.168.300.0/32")); - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/api/pom.xml b/opendaylight/adsal/forwardingrulesmanager/api/pom.xml deleted file mode 100644 index b9a46f52a0..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/pom.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - forwardingrulesmanager - 0.8.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.forwardingrulesmanager - org.opendaylight.controller.configuration, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.packet, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.felix.dm, - org.apache.commons.lang3.builder, - org.osgi.service.component, - org.slf4j, - org.eclipse.osgi.framework.console, - org.osgi.framework - org.opendaylight.controller.hosttracker - - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowConfig.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowConfig.java deleted file mode 100644 index e2b6642501..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowConfig.java +++ /dev/null @@ -1,1187 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager; - -import java.io.Serializable; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.ActionType; -import org.opendaylight.controller.sal.action.Controller; -import org.opendaylight.controller.sal.action.Drop; -import org.opendaylight.controller.sal.action.Enqueue; -import org.opendaylight.controller.sal.action.Flood; -import org.opendaylight.controller.sal.action.FloodAll; -import org.opendaylight.controller.sal.action.HwPath; -import org.opendaylight.controller.sal.action.Loopback; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.action.PopVlan; -import org.opendaylight.controller.sal.action.SetDlDst; -import org.opendaylight.controller.sal.action.SetDlSrc; -import org.opendaylight.controller.sal.action.SetNextHop; -import org.opendaylight.controller.sal.action.SetNwDst; -import org.opendaylight.controller.sal.action.SetNwSrc; -import org.opendaylight.controller.sal.action.SetNwTos; -import org.opendaylight.controller.sal.action.SetTpDst; -import org.opendaylight.controller.sal.action.SetTpSrc; -import org.opendaylight.controller.sal.action.SetVlanId; -import org.opendaylight.controller.sal.action.SetVlanPcp; -import org.opendaylight.controller.sal.action.SwPath; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Configuration Java Object which represents a flow configuration information - * for Forwarding Rules Manager. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class FlowConfig extends ConfigurationObject implements Serializable { - private static final long serialVersionUID = 1L; - private static final Logger log = LoggerFactory.getLogger(FlowConfig.class); - public static final String STATICFLOWGROUP = "__StaticFlows__"; - public static final String INTERNALSTATICFLOWGROUP = "__InternalStaticFlows__"; - public static final String INTERNALSTATICFLOWBEGIN = "__"; - public static final String INTERNALSTATICFLOWEND = "__"; - private boolean dynamic; - private String status; - - /* - * The order of the object data defined below is used directly in the UI - * built using JSP. Hence try to keep the order in a more logical way. - */ - @XmlElement - private String installInHw; - @XmlElement - private String name; - @XmlElement - private Node node; - @XmlElement - private String ingressPort; - private String portGroup; - @XmlElement - private String priority; - @XmlElement - private String etherType; - @XmlElement - private String vlanId; - @XmlElement - private String vlanPriority; - @XmlElement - private String dlSrc; - @XmlElement - private String dlDst; - @XmlElement - private String nwSrc; - @XmlElement - private String nwDst; - @XmlElement - private String protocol; - @XmlElement - private String tosBits; - @XmlElement - private String tpSrc; - @XmlElement - private String tpDst; - @XmlElement - private String cookie; - @XmlElement - private String idleTimeout; - @XmlElement - private String hardTimeout; - @XmlElement - private List actions; - - private enum EtherIPType { - ANY, V4, V6; - }; - - public FlowConfig() { - } - - public FlowConfig(String installInHw, String name, Node node, String priority, String cookie, String ingressPort, - String portGroup, String vlanId, String vlanPriority, String etherType, String srcMac, String dstMac, - String protocol, String tosBits, String srcIP, String dstIP, String tpSrc, String tpDst, - String idleTimeout, String hardTimeout, List actions) { - super(); - this.installInHw = installInHw; - this.name = name; - this.node = node; - this.priority = priority; - this.cookie = cookie; - this.ingressPort = ingressPort; - this.portGroup = portGroup; - this.vlanId = vlanId; - this.vlanPriority = vlanPriority; - this.etherType = etherType; - this.dlSrc = srcMac; - this.dlDst = dstMac; - this.protocol = protocol; - this.tosBits = tosBits; - this.nwSrc = srcIP; - this.nwDst = dstIP; - this.tpSrc = tpSrc; - this.tpDst = tpDst; - this.idleTimeout = idleTimeout; - this.hardTimeout = hardTimeout; - this.actions = actions; - this.status = StatusCode.SUCCESS.toString(); - } - - public FlowConfig(FlowConfig from) { - this.installInHw = from.installInHw; - this.name = from.name; - this.node = from.node; - this.priority = from.priority; - this.cookie = from.cookie; - this.ingressPort = from.ingressPort; - this.portGroup = from.portGroup; - this.vlanId = from.vlanId; - this.vlanPriority = from.vlanPriority; - this.etherType = from.etherType; - this.dlSrc = from.dlSrc; - this.dlDst = from.dlDst; - this.protocol = from.protocol; - this.tosBits = from.tosBits; - this.nwSrc = from.nwSrc; - this.nwDst = from.nwDst; - this.tpSrc = from.tpSrc; - this.tpDst = from.tpDst; - this.idleTimeout = from.idleTimeout; - this.hardTimeout = from.hardTimeout; - this.actions = new ArrayList(from.actions); - } - - public boolean installInHw() { - if (installInHw == null) { - // backward compatibility - installInHw = Boolean.toString(true); - } - return Boolean.valueOf(installInHw); - } - - public void setInstallInHw(boolean inHw) { - installInHw = String.valueOf(inHw); - } - - public String getInstallInHw() { - return installInHw; - } - - public boolean isInternalFlow() { - return (this.name != null && - this.name.startsWith(FlowConfig.INTERNALSTATICFLOWBEGIN) && - this.name.endsWith(FlowConfig.INTERNALSTATICFLOWEND)); - } - - public String getName() { - return name; - } - - public void setName(String name) { - if (name == null) { - return; - } - this.name = name; - } - - public Node getNode() { - return this.node; - } - - public void setNode(Node node) { - this.node = node; - } - - public String getPriority() { - return priority; - } - - public void setPriority(String priority) { - this.priority = priority; - } - - public String getCookie() { - return cookie; - } - - public void setCookie(String cookie) { - this.cookie = cookie; - } - - public String getIngressPort() { - return ingressPort; - } - - public void setIngressPort(String ingressPort) { - this.ingressPort = ingressPort; - } - - public String getPortGroup() { - return portGroup; - } - - @Override - public String toString() { - return "FlowConfig [dynamic=" + dynamic + ", status=" + status + ", installInHw=" + installInHw + ", name=" - + name + ", switchId=" + node + ", ingressPort=" + ingressPort + ", portGroup=" + portGroup - + ", etherType=" + etherType + ", priority=" + priority + ", vlanId=" + vlanId + ", vlanPriority=" - + vlanPriority + ", dlSrc=" + dlSrc + ", dlDst=" + dlDst + ", nwSrc=" + nwSrc + ", nwDst=" + nwDst - + ", protocol=" + protocol + ", tosBits=" + tosBits + ", tpSrc=" + tpSrc + ", tpDst=" + tpDst - + ", cookie=" + cookie + ", idleTimeout=" + idleTimeout + ", hardTimeout=" + hardTimeout + ", actions=" - + actions + "]"; - } - - public void setPortGroup(String portGroup) { - this.portGroup = portGroup; - } - - public String getVlanId() { - return vlanId; - } - - public void setVlanId(String vlanId) { - this.vlanId = vlanId; - } - - public String getVlanPriority() { - return vlanPriority; - } - - public void setVlanPriority(String vlanPriority) { - this.vlanPriority = vlanPriority; - } - - public String getEtherType() { - return etherType; - } - - public void setEtherType(String etherType) { - this.etherType = etherType; - } - - public String getSrcMac() { - return dlSrc; - } - - public void setSrcMac(String srcMac) { - this.dlSrc = srcMac; - } - - public String getDstMac() { - return dlDst; - } - - public void setDstMac(String dstMac) { - this.dlDst = dstMac; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public String getTosBits() { - return tosBits; - } - - public void setTosBits(String tos_bits) { - this.tosBits = tos_bits; - } - - public String getSrcIp() { - return nwSrc; - } - - public void setSrcIp(String src_ip) { - this.nwSrc = src_ip; - } - - public String getDstIp() { - return nwDst; - } - - public void setDstIp(String dst_ip) { - this.nwDst = dst_ip; - } - - public String getSrcPort() { - return tpSrc; - } - - public void setSrcPort(String src_port) { - this.tpSrc = src_port; - } - - public String getDstPort() { - return tpDst; - } - - public void setDstPort(String dst_port) { - this.tpDst = dst_port; - } - - public String getIdleTimeout() { - return idleTimeout; - } - - public void setIdleTimeout(String idleTimeout) { - this.idleTimeout = idleTimeout; - } - - public String getHardTimeout() { - return hardTimeout; - } - - public void setHardTimeout(String hardTimeout) { - this.hardTimeout = hardTimeout; - } - - public boolean isIPv6() { - return NetUtils.isIPv6AddressValid(this.getSrcIp()) || NetUtils.isIPv6AddressValid(this.getDstIp()); - } - - public List getActions() { - return actions; - } - - public void setActions(List actions) { - this.actions = actions; - } - - public boolean isPortGroupEnabled() { - return (portGroup != null); - } - - public boolean isDynamic() { - return dynamic; - } - - public void setDynamic(boolean dynamic) { - this.dynamic = dynamic; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public boolean isStatusSuccessful() { - return status.equals(StatusCode.SUCCESS.toString()); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((actions == null) ? 0 : actions.hashCode()); - result = prime * result + ((cookie == null) ? 0 : cookie.hashCode()); - result = prime * result + ((dlDst == null) ? 0 : dlDst.hashCode()); - result = prime * result + ((dlSrc == null) ? 0 : dlSrc.hashCode()); - result = prime * result + (dynamic ? 1231 : 1237); - result = prime * result + ((etherType == null) ? 0 : etherType.hashCode()); - result = prime * result + ((ingressPort == null) ? 0 : ingressPort.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((nwDst == null) ? 0 : nwDst.hashCode()); - result = prime * result + ((nwSrc == null) ? 0 : nwSrc.hashCode()); - result = prime * result + ((portGroup == null) ? 0 : portGroup.hashCode()); - result = prime * result + ((priority == null) ? 0 : priority.hashCode()); - result = prime * result + ((protocol == null) ? 0 : protocol.hashCode()); - result = prime * result + ((node == null) ? 0 : node.hashCode()); - result = prime * result + ((tosBits == null) ? 0 : tosBits.hashCode()); - result = prime * result + ((tpDst == null) ? 0 : tpDst.hashCode()); - result = prime * result + ((tpSrc == null) ? 0 : tpSrc.hashCode()); - result = prime * result + ((vlanId == null) ? 0 : vlanId.hashCode()); - result = prime * result + ((vlanPriority == null) ? 0 : vlanPriority.hashCode()); - result = prime * result + ((idleTimeout == null) ? 0 : idleTimeout.hashCode()); - result = prime * result + ((hardTimeout == null) ? 0 : hardTimeout.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - FlowConfig other = (FlowConfig) obj; - if (actions == null) { - if (other.actions != null) { - return false; - } - } else if (!actions.equals(other.actions)) { - return false; - } - if (cookie == null) { - if (other.cookie != null) { - return false; - } - } else if (!cookie.equals(other.cookie)) { - return false; - } - if (dlDst == null) { - if (other.dlDst != null) { - return false; - } - } else if (!dlDst.equals(other.dlDst)) { - return false; - } - if (dlSrc == null) { - if (other.dlSrc != null) { - return false; - } - } else if (!dlSrc.equals(other.dlSrc)) { - return false; - } - if (dynamic != other.dynamic) { - return false; - } - if (etherType == null) { - if (other.etherType != null) { - return false; - } - } else if (!etherType.equals(other.etherType)) { - return false; - } - if (ingressPort == null) { - if (other.ingressPort != null) { - return false; - } - } else if (!ingressPort.equals(other.ingressPort)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (nwDst == null) { - if (other.nwDst != null) { - return false; - } - } else if (!nwDst.equals(other.nwDst)) { - return false; - } - if (nwSrc == null) { - if (other.nwSrc != null) { - return false; - } - } else if (!nwSrc.equals(other.nwSrc)) { - return false; - } - if (portGroup == null) { - if (other.portGroup != null) { - return false; - } - } else if (!portGroup.equals(other.portGroup)) { - return false; - } - if (priority == null) { - if (other.priority != null) { - return false; - } - } else if (!priority.equals(other.priority)) { - return false; - } - if (protocol == null) { - if (other.protocol != null) { - return false; - } - } else if (!protocol.equals(other.protocol)) { - return false; - } - if (node == null) { - if (other.node != null) { - return false; - } - } else if (!node.equals(other.node)) { - return false; - } - if (tosBits == null) { - if (other.tosBits != null) { - return false; - } - } else if (!tosBits.equals(other.tosBits)) { - return false; - } - if (tpDst == null) { - if (other.tpDst != null) { - return false; - } - } else if (!tpDst.equals(other.tpDst)) { - return false; - } - if (tpSrc == null) { - if (other.tpSrc != null) { - return false; - } - } else if (!tpSrc.equals(other.tpSrc)) { - return false; - } - if (vlanId == null) { - if (other.vlanId != null) { - return false; - } - } else if (!vlanId.equals(other.vlanId)) { - return false; - } - if (vlanPriority == null) { - if (other.vlanPriority != null) { - return false; - } - } else if (!vlanPriority.equals(other.vlanPriority)) { - return false; - } - if (idleTimeout == null) { - if (other.idleTimeout != null) { - return false; - } - } else if (!idleTimeout.equals(other.idleTimeout)) { - return false; - } - if (hardTimeout == null) { - if (other.hardTimeout != null) { - return false; - } - } else if (!hardTimeout.equals(other.hardTimeout)) { - return false; - } - return true; - } - - public boolean isL2AddressValid(String mac) { - if (mac == null) { - return false; - } - - Pattern macPattern = Pattern.compile("([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}"); - Matcher mm = macPattern.matcher(mac); - if (!mm.matches()) { - log.debug("Ethernet address {} is not valid. Example: 00:05:b9:7c:81:5f", mac); - return false; - } - return true; - } - - public boolean isVlanIdValid(String vlanId) { - int vlan = Integer.decode(vlanId); - return ((vlan >= 0) && (vlan < 4096)); - } - - public boolean isVlanPriorityValid(String vlanPriority) { - int pri = Integer.decode(vlanPriority); - return ((pri >= 0) && (pri < 8)); - } - - public boolean isTOSBitsValid(String tosBits) { - int tos = Integer.decode(tosBits); - return ((tos >= 0) && (tos < 64)); - } - - public boolean isTpPortValid(String tpPort) { - int port = Integer.decode(tpPort); - return ((port >= 0) && (port <= 0xffff)); - } - - public boolean isTimeoutValid(String timeout) { - int to = Integer.decode(timeout); - return ((to >= 0) && (to <= 0xffff)); - } - - public boolean isProtocolValid(String protocol) { - IPProtocols proto = IPProtocols.fromString(protocol); - return (proto != null); - } - - public Status validate() { - EtherIPType etype = EtherIPType.ANY; - EtherIPType ipsrctype = EtherIPType.ANY; - EtherIPType ipdsttype = EtherIPType.ANY; - - try { - // Flow name cannot be internal flow signature - if (!isValidResourceName(name) || isInternalFlow()) { - return new Status(StatusCode.BADREQUEST, "Invalid name"); - } - - if (node == null) { - return new Status(StatusCode.BADREQUEST, "Node is null"); - } - - if (priority != null) { - if (Integer.decode(priority) < 0 || (Integer.decode(priority) > 65535)) { - return new Status(StatusCode.BADREQUEST, String.format("priority %s is not in the range 0 - 65535", - priority)); - } - } - - // make sure it's a valid number - if (cookie != null) { - Long.decode(cookie); - } - - if (ingressPort != null && ingressPort.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid ingress port"); - } - - if ((vlanId != null) && !isVlanIdValid(vlanId)) { - return new Status(StatusCode.BADREQUEST, String.format("Vlan ID %s is not in the range 0 - 4095", - vlanId)); - } - - if ((vlanPriority != null) && !isVlanPriorityValid(vlanPriority)) { - return new Status(StatusCode.BADREQUEST, String.format("Vlan priority %s is not in the range 0 - 7", - vlanPriority)); - } - if (etherType != null) { - int type = Integer.decode(etherType); - if ((type < 0) || (type > 0xffff)) { - return new Status(StatusCode.BADREQUEST, String.format("Ethernet type %s is not valid", etherType)); - } else { - if (type == 0x800) { - etype = EtherIPType.V4; - } else if (type == 0x86dd) { - etype = EtherIPType.V6; - } - } - } - - if ((protocol != null) && !isProtocolValid(protocol)) { - return new Status(StatusCode.BADREQUEST, String.format("Protocol %s is not valid", protocol)); - } - - if ((tosBits != null) && !isTOSBitsValid(tosBits)) { - return new Status(StatusCode.BADREQUEST, String.format("IP ToS bits %s is not in the range 0 - 63", - tosBits)); - } - - if ((tpSrc != null) && !isTpPortValid(tpSrc)) { - return new Status(StatusCode.BADREQUEST, String.format("Transport source port %s is not valid", tpSrc)); - } - - if ((tpDst != null) && !isTpPortValid(tpDst)) { - return new Status(StatusCode.BADREQUEST, String.format("Transport destination port %s is not valid", - tpDst)); - } - - if ((dlSrc != null) && !isL2AddressValid(dlSrc)) { - return new Status(StatusCode.BADREQUEST, String.format( - "Ethernet source address %s is not valid. Example: 00:05:b9:7c:81:5f", dlSrc)); - } - - if ((dlDst != null) && !isL2AddressValid(dlDst)) { - return new Status(StatusCode.BADREQUEST, String.format( - "Ethernet destination address %s is not valid. Example: 00:05:b9:7c:81:5f", dlDst)); - } - - if (nwSrc != null) { - if (NetUtils.isIPv4AddressValid(nwSrc)) { - ipsrctype = EtherIPType.V4; - } else if (NetUtils.isIPv6AddressValid(nwSrc)) { - ipsrctype = EtherIPType.V6; - } else { - return new Status(StatusCode.BADREQUEST, String.format("IP source address %s is not valid", nwSrc)); - } - } - - if (nwDst != null) { - if (NetUtils.isIPv4AddressValid(nwDst)) { - ipdsttype = EtherIPType.V4; - } else if (NetUtils.isIPv6AddressValid(nwDst)) { - ipdsttype = EtherIPType.V6; - } else { - return new Status(StatusCode.BADREQUEST, String.format("IP destination address %s is not valid", - nwDst)); - } - } - - if (etype != EtherIPType.ANY) { - if ((ipsrctype != EtherIPType.ANY) && (ipsrctype != etype)) { - return new Status(StatusCode.BADREQUEST, String.format("Type mismatch between Ethernet & Src IP")); - } - if ((ipdsttype != EtherIPType.ANY) && (ipdsttype != etype)) { - return new Status(StatusCode.BADREQUEST, String.format("Type mismatch between Ethernet & Dst IP")); - } - } - if (ipsrctype != ipdsttype) { - if (!((ipsrctype == EtherIPType.ANY) || (ipdsttype == EtherIPType.ANY))) { - return new Status(StatusCode.BADREQUEST, String.format("IP Src Dest Type mismatch")); - } - } - - if ((idleTimeout != null) && !isTimeoutValid(idleTimeout)) { - return new Status(StatusCode.BADREQUEST, String.format("Idle Timeout value %s is not valid", - idleTimeout)); - } - - if ((hardTimeout != null) && !isTimeoutValid(hardTimeout)) { - return new Status(StatusCode.BADREQUEST, String.format("Hard Timeout value %s is not valid", - hardTimeout)); - } - - Matcher sstr; - if (actions == null || actions.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Actions value is null or empty"); - } - for (String actiongrp : actions) { - // Check src IP - sstr = Pattern.compile(ActionType.SET_NW_SRC.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - if (!NetUtils.isIPv4AddressValid(sstr.group(1))) { - return new Status(StatusCode.BADREQUEST, String.format("IP source address %s is not valid", - sstr.group(1))); - } - continue; - } - // Check dst IP - sstr = Pattern.compile(ActionType.SET_NW_DST.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - if (!NetUtils.isIPv4AddressValid(sstr.group(1))) { - return new Status(StatusCode.BADREQUEST, String.format( - "IP destination address %s is not valid", sstr.group(1))); - } - continue; - } - - sstr = Pattern.compile(ActionType.SET_VLAN_ID.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - if ((sstr.group(1) != null) && !isVlanIdValid(sstr.group(1))) { - return new Status(StatusCode.BADREQUEST, String.format( - "Vlan ID %s is not in the range 0 - 4095", sstr.group(1))); - } - continue; - } - - sstr = Pattern.compile(ActionType.ENQUEUE + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - for (String t : sstr.group(1).split(",")) { - if (t != null) { - String parts[] = t.split(":"); - String nc = String.format("%s|%s@%s", node.getType(), parts[0], node.toString()); - if (NodeConnector.fromString(nc) == null) { - return new Status(StatusCode.BADREQUEST, String.format("Enqueue port is not valid")); - } - if (parts.length > 1) { - try { - Integer.parseInt(parts[1]); - } catch (NumberFormatException e) { - return new Status(StatusCode.BADREQUEST, String.format("Enqueue %s is not in the range 0 - 2147483647", parts[1])); - } - } - } - } - continue; - } - - sstr = Pattern.compile(ActionType.SET_VLAN_PCP.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - if ((sstr.group(1) != null) && !isVlanPriorityValid(sstr.group(1))) { - return new Status(StatusCode.BADREQUEST, String.format( - "Vlan priority %s is not in the range 0 - 7", sstr.group(1))); - } - continue; - } - - sstr = Pattern.compile(ActionType.SET_DL_SRC.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - if ((sstr.group(1) != null) && !isL2AddressValid(sstr.group(1))) { - return new Status(StatusCode.BADREQUEST, String.format( - "Ethernet source address %s is not valid. Example: 00:05:b9:7c:81:5f", - sstr.group(1))); - } - continue; - } - sstr = Pattern.compile(ActionType.SET_DL_DST.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - if ((sstr.group(1) != null) && !isL2AddressValid(sstr.group(1))) { - return new Status(StatusCode.BADREQUEST, String.format( - "Ethernet destination address %s is not valid. Example: 00:05:b9:7c:81:5f", - sstr.group(1))); - } - continue; - } - - sstr = Pattern.compile(ActionType.SET_NW_TOS.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - if ((sstr.group(1) != null) && !isTOSBitsValid(sstr.group(1))) { - return new Status(StatusCode.BADREQUEST, String.format( - "IP ToS bits %s is not in the range 0 - 63", sstr.group(1))); - } - continue; - } - - sstr = Pattern.compile(ActionType.SET_TP_SRC.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - if ((sstr.group(1) != null) && !isTpPortValid(sstr.group(1))) { - return new Status(StatusCode.BADREQUEST, String.format( - "Transport source port %s is not valid", sstr.group(1))); - } - continue; - } - - sstr = Pattern.compile(ActionType.SET_TP_DST.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - if ((sstr.group(1) != null) && !isTpPortValid(sstr.group(1))) { - return new Status(StatusCode.BADREQUEST, String.format( - "Transport destination port %s is not valid", sstr.group(1))); - } - continue; - } - - sstr = Pattern.compile(ActionType.SET_NEXT_HOP.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - if (!NetUtils.isIPAddressValid(sstr.group(1))) { - return new Status(StatusCode.BADREQUEST, String.format( - "IP destination address %s is not valid", sstr.group(1))); - } - continue; - } - - sstr = Pattern.compile(ActionType.OUTPUT + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - continue; - } - - sstr = Pattern.compile(ActionType.DROP.toString()).matcher(actiongrp); - if (sstr.matches()) { - continue; - } - - sstr = Pattern.compile(ActionType.LOOPBACK.toString()).matcher(actiongrp); - if (sstr.matches()) { - continue; - } - - sstr = Pattern.compile(ActionType.FLOOD.toString()).matcher(actiongrp); - if (sstr.matches()) { - continue; - } - - sstr = Pattern.compile(ActionType.FLOOD_ALL.toString()).matcher(actiongrp); - if (sstr.matches()) { - continue; - } - - sstr = Pattern.compile(ActionType.SW_PATH.toString()).matcher(actiongrp); - if (sstr.matches()) { - continue; - } - - sstr = Pattern.compile(ActionType.HW_PATH.toString()).matcher(actiongrp); - if (sstr.matches()) { - continue; - } - - sstr = Pattern.compile(ActionType.CONTROLLER.toString()).matcher(actiongrp); - if (sstr.matches()) { - continue; - } - - sstr = Pattern.compile(ActionType.POP_VLAN.toString()).matcher(actiongrp); - if (sstr.matches()) { - continue; - } - - // If execution reached here, it means there is an Action - // which is not recognized by the controller. Return error - - return new Status(StatusCode.BADREQUEST, String.format("%s is an UnSupported Action", actiongrp)); - } - } catch (NumberFormatException e) { - return new Status(StatusCode.BADREQUEST, String.format("Invalid number format %s", e.getMessage())); - } - - return new Status(StatusCode.SUCCESS); - } - - public FlowEntry getFlowEntry() { - String group = this.isInternalFlow() ? FlowConfig.INTERNALSTATICFLOWGROUP : FlowConfig.STATICFLOWGROUP; - return new FlowEntry(group, this.name, this.getFlow(), this.getNode()); - } - - public Flow getFlow() { - Match match = new Match(); - - if (this.ingressPort != null) { - match.setField(MatchType.IN_PORT, - NodeConnector.fromString(String.format("%s|%s@%s", node.getType(), ingressPort, node.toString()))); - } - if (this.dlSrc != null) { - match.setField(MatchType.DL_SRC, HexEncode.bytesFromHexString(this.dlSrc)); - } - if (this.dlDst != null) { - match.setField(MatchType.DL_DST, HexEncode.bytesFromHexString(this.dlDst)); - } - if (this.etherType != null) { - match.setField(MatchType.DL_TYPE, Integer.decode(etherType).shortValue()); - } - if (this.vlanId != null) { - match.setField(MatchType.DL_VLAN, Short.parseShort(this.vlanId)); - } - if (this.vlanPriority != null) { - match.setField(MatchType.DL_VLAN_PR, Byte.parseByte(this.vlanPriority)); - } - if (this.nwSrc != null) { - String parts[] = this.nwSrc.split("/"); - InetAddress ip = NetUtils.parseInetAddress(parts[0]); - InetAddress mask = null; - int maskLen = 0; - if (parts.length > 1) { - maskLen = Integer.parseInt(parts[1]); - } else { - maskLen = (ip instanceof Inet6Address) ? 128 : 32; - } - mask = NetUtils.getInetNetworkMask(maskLen, ip instanceof Inet6Address); - match.setField(MatchType.NW_SRC, ip, mask); - } - if (this.nwDst != null) { - String parts[] = this.nwDst.split("/"); - InetAddress ip = NetUtils.parseInetAddress(parts[0]); - InetAddress mask = null; - int maskLen = 0; - if (parts.length > 1) { - maskLen = Integer.parseInt(parts[1]); - } else { - maskLen = (ip instanceof Inet6Address) ? 128 : 32; - } - mask = NetUtils.getInetNetworkMask(maskLen, ip instanceof Inet6Address); - match.setField(MatchType.NW_DST, ip, mask); - } - if (IPProtocols.fromString(this.protocol) != IPProtocols.ANY) { - match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(this.protocol)); - } - if (this.tosBits != null) { - match.setField(MatchType.NW_TOS, Byte.parseByte(this.tosBits)); - } - if (this.tpSrc != null) { - match.setField(MatchType.TP_SRC, Integer.valueOf(this.tpSrc).shortValue()); - } - if (this.tpDst != null) { - match.setField(MatchType.TP_DST, Integer.valueOf(this.tpDst).shortValue()); - } - - Flow flow = new Flow(match, getActionList()); - - if (this.cookie != null) { - flow.setId(Long.parseLong(cookie)); - } - if (this.hardTimeout != null) { - flow.setHardTimeout(Short.parseShort(this.hardTimeout)); - } - if (this.idleTimeout != null) { - flow.setIdleTimeout(Short.parseShort(idleTimeout)); - } - if (this.priority != null) { - flow.setPriority(Integer.decode(this.priority).shortValue()); - } - - - return flow; - } - - public boolean isByNameAndNodeIdEqual(FlowConfig that) { - return (this.name.equals(that.name) && this.node.equals(that.node)); - } - - public boolean isByNameAndNodeIdEqual(String name, Node node) { - return (this.name.equals(name) && this.node.equals(node)); - } - - public boolean onNode(Node node) { - return this.node.equals(node); - } - - public void toggleInstallation() { - installInHw = (installInHw == null) ? Boolean.toString(false) : Boolean.toString(!Boolean.valueOf(installInHw)); - } - - /* - * Parses the actions string and return the List of SAL Action No syntax - * check run, as this function will be called when the config validation - * check has already been performed - */ - private List getActionList() { - List actionList = new ArrayList(); - - if (actions != null) { - Matcher sstr; - for (String actiongrp : actions) { - sstr = Pattern.compile(ActionType.OUTPUT + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - for (String t : sstr.group(1).split(",")) { - if (t != null) { - String nc = String.format("%s|%s@%s", node.getType(), t, node.toString()); - actionList.add(new Output(NodeConnector.fromString(nc))); - } - } - continue; - } - - sstr = Pattern.compile(ActionType.ENQUEUE + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - for (String t : sstr.group(1).split(",")) { - if (t != null) { - String parts[] = t.split(":"); - String nc = String.format("%s|%s@%s", node.getType(), parts[0], node.toString()); - if (parts.length == 1) { - actionList.add(new Enqueue(NodeConnector.fromString(nc))); - } else { - actionList - .add(new Enqueue(NodeConnector.fromString(nc), Integer.parseInt(parts[1]))); - } - } - } - continue; - } - - sstr = Pattern.compile(ActionType.DROP.toString()).matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new Drop()); - continue; - } - - sstr = Pattern.compile(ActionType.LOOPBACK.toString()).matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new Loopback()); - continue; - } - - sstr = Pattern.compile(ActionType.FLOOD.toString()).matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new Flood()); - continue; - } - - sstr = Pattern.compile(ActionType.FLOOD_ALL.toString()).matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new FloodAll()); - continue; - } - - sstr = Pattern.compile(ActionType.SW_PATH.toString()).matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SwPath()); - continue; - } - - sstr = Pattern.compile(ActionType.HW_PATH.toString()).matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new HwPath()); - continue; - } - - sstr = Pattern.compile(ActionType.CONTROLLER.toString()).matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new Controller()); - continue; - } - - sstr = Pattern.compile(ActionType.SET_VLAN_ID.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SetVlanId(Short.parseShort(sstr.group(1)))); - continue; - } - - sstr = Pattern.compile(ActionType.SET_VLAN_PCP.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SetVlanPcp(Byte.parseByte(sstr.group(1)))); - continue; - } - - sstr = Pattern.compile(ActionType.POP_VLAN.toString()).matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new PopVlan()); - continue; - } - - sstr = Pattern.compile(ActionType.SET_DL_SRC.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SetDlSrc(HexEncode.bytesFromHexString(sstr.group(1)))); - continue; - } - - sstr = Pattern.compile(ActionType.SET_DL_DST.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SetDlDst(HexEncode.bytesFromHexString(sstr.group(1)))); - continue; - } - sstr = Pattern.compile(ActionType.SET_NW_SRC.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SetNwSrc(NetUtils.parseInetAddress(sstr.group(1)))); - continue; - } - sstr = Pattern.compile(ActionType.SET_NW_DST.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SetNwDst(NetUtils.parseInetAddress(sstr.group(1)))); - continue; - } - - sstr = Pattern.compile(ActionType.SET_NW_TOS.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SetNwTos(Byte.parseByte(sstr.group(1)))); - continue; - } - - sstr = Pattern.compile(ActionType.SET_TP_SRC.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SetTpSrc(Integer.valueOf(sstr.group(1)))); - continue; - } - - sstr = Pattern.compile(ActionType.SET_TP_DST.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SetTpDst(Integer.valueOf(sstr.group(1)))); - continue; - } - - sstr = Pattern.compile(ActionType.SET_NEXT_HOP.toString() + "=(.*)").matcher(actiongrp); - if (sstr.matches()) { - actionList.add(new SetNextHop(NetUtils.parseInetAddress(sstr.group(1)))); - continue; - } - } - } - return actionList; - } - -} diff --git a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntry.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntry.java deleted file mode 100644 index d9a0891c2a..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntry.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager; - -import java.io.Serializable; -import java.util.Date; - -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Represents a flow applications request Forwarding Rules Manager to install on - * a network node. A FlowEntry is constituted of a flow (match + actions), the - * target network node, and the flow name. It also includes a group name. For - * instance the flows constituting a policy all share the same group name. - */ -public class FlowEntry implements Cloneable, Serializable { - protected static final Logger logger = LoggerFactory.getLogger(FlowEntry.class); - private static final long serialVersionUID = 1L; - private static final Logger log = LoggerFactory.getLogger(FlowEntry.class); - private String groupName; // group name - private String flowName; // flow name (may be null) - private Node node; // network node where to install the flow - private Flow flow; // match + action - - public FlowEntry(String groupName, String flowName, Flow flow, Node node) { - this.groupName = groupName; - this.flow = flow; - this.node = node; - this.flowName = (flowName != null) ? flowName : constructFlowName(); - } - - public String getGroupName() { - return groupName; - } - - public void setGroupName(String name) { - this.groupName = name; - } - - /** - * Return the actual Flow contained in this entry - * - * @return the flow - */ - public Flow getFlow() { - return flow; - } - - public Node getNode() { - return node; - } - - public void setNode(Node n) { - this.node = n; - } - - public String getFlowName() { - return flowName; - } - - public void setFlowName(String n) { - this.flowName = n; - } - - @Override - public FlowEntry clone() { - FlowEntry cloned = null; - try { - cloned = (FlowEntry) super.clone(); - cloned.flow = this.flow.clone(); - } catch (CloneNotSupportedException e) { - log.warn("exception in clone", e); - } - return cloned; - } - - /* - * Only accounts fields which uniquely identify a flow for collision - * purposes: node, match and priority - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((node == null) ? 0 : node.hashCode()); - result = prime * result + ((flow == null) ? 0 : (int) flow.getPriority()); - result = prime * result + ((flow == null || flow.getMatch() == null) ? 0 : flow.getMatch().hashCode()); - - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - FlowEntry other = (FlowEntry) obj; - - if (node == null) { - if (other.node != null) { - return false; - } - } else if (!node.equals(other.node)) { - return false; - } - - if (flow == null) { - return other.flow == null; - } else if (other.flow == null) { - return false; - } - if (flow.getPriority() != other.flow.getPriority()) { - return false; - } - if (flow.getMatch() == null) { - if (other.flow.getMatch() != null) { - return false; - } - } else if (!flow.getMatch().equals(other.flow.getMatch())) { - return false; - } - - return true; - } - - @Override - public String toString() { - return "FlowEntry[flowName = " + flowName + ", groupName = " + groupName + ", node = " + node + ", flow = " - + flow + "]"; - } - - private String constructFlowName() { - return this.groupName + "_" + new Date().toString(); - } - - public boolean equalsByNodeAndName(Node node, String flowName) { - return this.node.equals(node) && this.flowName.equals(flowName); - } - - /** - * Merges the current Flow with the passed Container Flow - * - * Note: Container Flow merging is not an injective function. Be m1 and m2 - * two different matches, and be f() the flow merge function, such that y1 = - * f(m1) and y2 = f(m2) are the two merged matches, we may have: y1 = y2 - * - * - * @param containerFlow - * @return this merged FlowEntry - */ - public FlowEntry mergeWith(ContainerFlow containerFlow) { - Match myMatch = flow.getMatch(); - - Match filter = containerFlow.getMatch(); - - // Merge - Match merge = myMatch.mergeWithFilter(filter); - - // Replace this Flow's match with merged version - flow.setMatch(merge); - - return this; - } - - /** - * Returns whether this entry is the result of an internal generated static - * flow - * - * @return true if internal generated static flow, false otherwise - */ - public boolean isInternal() { - return flowName.startsWith(FlowConfig.INTERNALSTATICFLOWBEGIN) - && flowName.endsWith(FlowConfig.INTERNALSTATICFLOWEND); - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntryInstall.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntryInstall.java deleted file mode 100644 index 1318c97ce2..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/FlowEntryInstall.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager; - -import java.io.Serializable; - -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.Node; - -/** - * The flow database object representing the flow entry to install on the - * network node. It contains the original flow entry FRM was requested to - * install, the container flow with which that entry had to be merged and the - * resultant merged flow entry, which is the one that was eventually installed - * on the network node - * - * Note: If the container flow is null, the install entry will be a clone of the - * original entry - */ -public class FlowEntryInstall implements Serializable { - private static final long serialVersionUID = 1L; - private final FlowEntry original; - private final ContainerFlow cFlow; - private final FlowEntry install; - private transient long requestId; // async request id - private transient boolean deletePending; - - public FlowEntryInstall(FlowEntry original, ContainerFlow cFlow) { - this.original = original; - this.cFlow = cFlow; - this.install = (cFlow == null) ? original.clone() : original.clone().mergeWith(cFlow); - deletePending = false; - requestId = 0; - } - - /* - * Given FlowEntryInstall is used as key for FRM map which contains the - * software view of installed entries, having its hashcode tied to the one - * of the installed FlowEntry which takes into account the fields which - * uniquely identify a flow from switch point of view: node, match and - * priority. - */ - @Override - public int hashCode() { - return install.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - FlowEntryInstall other = (FlowEntryInstall) obj; - if (install == null) { - if (other.install != null) { - return false; - } - } else if (!install.equals(other.install)) { - return false; - } - return true; - } - - public String getFlowName() { - return original.getFlowName(); - } - - public String getGroupName() { - return original.getGroupName(); - } - - public Node getNode() { - return original.getNode(); - } - - public boolean equalsByNodeAndName(Node node, String flowName) { - return original.equalsByNodeAndName(node, flowName); - } - - public FlowEntry getOriginal() { - return original; - } - - public ContainerFlow getContainerFlow() { - return cFlow; - } - - public FlowEntry getInstall() { - return install; - } - - public boolean isDeletePending() { - return deletePending; - } - - public void toBeDeleted() { - this.deletePending = true; - } - - public void setRequestId(long rid) { - this.requestId = rid; - } - - public long getRequestId() { - return requestId; - } - - /** - * Returns whether this entry is the result of an internal generated static - * flow - * - * @return true if internal generated static flow, false otherwise - */ - public boolean isInternal() { - return original.isInternal(); - } - - @Override - public String toString() { - return "[Install = " + install + " Original = " + original + " cFlow = " + cFlow + " rid = " + requestId + "]"; - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManager.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManager.java deleted file mode 100644 index 070e8c4998..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManager.java +++ /dev/null @@ -1,491 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager; - -import java.util.List; -import java.util.Map; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.Status; - -/** - * Interface that describes methods for installing or removing forwarding rules - * and to access to the flows database. - */ -public interface IForwardingRulesManager { - - /** - * It requests FRM to install the passed Flow Entry. FRM will request the - * SDN protocol plugin to install the flow on the network node. Based on the - * result of this operation FRM will update its database accordingly and - * will return the proper {@code Status} code. - * - * @param flow - * the flow entry to install - * @return the {@code Status} object indicating the result of this action. - */ - public Status installFlowEntry(FlowEntry flow); - - /** - * It requests FRM to remove the passed Flow Entry. FRM will request the SDN - * protocol plugin to uninstall the flow from the network node. Based on the - * result of this operation FRM will update its database accordingly and - * will return the proper {@code Status} code. - * - * @param flow - * the flow entry to uninstall - * @return the {@code Status} object indicating the result of this action - */ - public Status uninstallFlowEntry(FlowEntry flow); - - /** - * It requests FRM to remove all the Flow Entry that are part of the - * specified group. FRM will request the SDN protocol plugin to uninstall - * the flows from the network node one by one. Based on the result of this - * operation FRM will update its database accordingly and will return the - * proper {@code Status} code. - * - * @param groupName - * the group name - * @return the {@code Status} object indicating the result of this action - */ - public Status uninstallFlowEntryGroup(String groupName); - - /** - * It requests FRM to replace the currently installed Flow Entry with the - * new one. It is up to the SDN protocol plugin to decide how to convey this - * message to the network node. It could be a delete + add or a single - * modify message depending on the SDN protocol specifications If the - * current flow is equal to the new one it will be a no op and success code - * is returned. - * - * @param current - * the current flow entry to modify - * @param newone - * the new flow entry which will replace the current one - * @return the {@code Status} object indicating the result of this action - */ - public Status modifyFlowEntry(FlowEntry current, FlowEntry newone); - - /** - * It requests the FRM to replace the currently installed Flow Entry with - * the new one. The currently installed entry is derived by the Match - * portion of the passed Flow. FRM looks in its database for a previously - * installed FlowEntry which Match equals the Match of the passed Flow. If - * it finds it, it will request the SDN protocol plugin to replace the - * existing flow with the new one on the network node. If it does not find - * it, it will request plugin to add the new flow. If the passed entry is - * not valid an error code is returned. If the existing flow is equal to the - * passed one it will be a no op and success code is returned. - * - * @param newone - * the new flow entry to install - * @return the {@code Status} object indicating the result of this action - */ - public Status modifyOrAddFlowEntry(FlowEntry newone); - - /** - * It requests FRM to install the passed Flow Entry through an asynchronous - * call. A unique request id is returned to the caller. FRM will request the - * SDN protocol plugin to install the flow on the network node. As immediate - * result of this asynchronous call, FRM will update its flow database as if - * the flow was successfully installed. - * - * @param flow - * the flow entry to install - * @return the status of this request containing the request id associated - * to this asynchronous request - */ - public Status installFlowEntryAsync(FlowEntry flow); - - /** - * It requests FRM to remove the passed Flow Entry through an asynchronous - * call. A unique request id is returned to the caller. FRM will request the - * SDN protocol plugin to uninstall the flow from the network node. As - * immediate result of this asynchronous call, FRM will update its flow - * database as if the flow was successfully removed. - * - * @param flow - * the flow entry to uninstall - * @return the status of this request containing the unique id associated to - * this asynchronous request - */ - public Status uninstallFlowEntryAsync(FlowEntry flow); - - /** - * It requests FRM to remove all the Flow Entry that are part of the - * specified group through an asynchronous call. FRM will request the SDN - * protocol plugin to uninstall the flows from the network node one by one. - * As immediate result of this asynchronous call, FRM will update its flow - * database as if the flow was successfully removed. - * - * @param groupName - * the group name - * @return the {@code Status} object indicating the result of this action - */ - public Status uninstallFlowEntryGroupAsync(String groupName); - - /** - * It requests FRM to replace the currently installed Flow Entry with the - * new one through an asynchronous call. A unique request id is returned to - * the caller. It is up to the SDN protocol plugin to decide how to convey - * this message to the network node. It could be a delete + add or a single - * modify message depending on the SDN protocol specifications. If the - * current flow is equal to the new one it will be a no op. - * - * @param current - * the current flow entry to modify - * @param newone - * the new flow entry which will replace the current one - * @return the status of this request containing the request id associated - * to this asynchronous request - */ - public Status modifyFlowEntryAsync(FlowEntry current, FlowEntry newone); - - /** - * It requests the FRM to replace the currently installed Flow Entry with - * the new one through an asynchronous call. A unique request id is returned - * to the caller. The currently installed entry is derived by the Match - * portion of the passed Flow. FRM looks in its database for a previously - * installed FlowEntry which Match equals the Match of the passed Flow. If - * it finds it, it will request the SDN protocol plugin to replace the - * existing flow with the new one on the network node. If it does not find - * it, it will request plugin to add the new flow. If the passed entry is - * not valid a zero request id is returned. If the existing flow is equal to - * the passed one it will be a no op. - * - * @param newone - * the new flow entry to install - * @return the unique id associated to this request. In case of not - * acceptable request -1 will be returned. - */ - public Status modifyOrAddFlowEntryAsync(FlowEntry newone); - - /** - * Requests ForwardingRulesManager to solicit the network node to inform us - * about the status of its execution on the asynchronous requests that were - * sent to it so far. It is a way for an application to poke the network - * node in order to get a feedback asap on the asynchronous requests - * generated by the application. The caller may decide if this is a blocking - * or non-blocking operation. If blocking is set to true, the caller will be - * blocked until the solicitation response is received from the network node - * or receive timeout. Otherwise, it is a non-blocking call and does not - * guarantee the node will respond in any given time. - * - * @param node - * The network node to solicit a response - * @param blocking - * The blocking mode - * @return the status of this request containing the request id associated - * to this asynchronous request - */ - public Status solicitStatusResponse(Node node, boolean blocking); - - /** - * Check whether the passed flow entry conflicts with the Container flows - * - * @param flow - * the flow entry to test - * @return true if conflicts, false otherwise - */ - public boolean checkFlowEntryConflict(FlowEntry flow); - - /** - * Returns the list of Flow entries across network nodes which are part of - * the same flow group, policy. This list contains the flows as they were - * requested to be installed by the applications, before any merging with - * container flow is done. - * - * @param group - * the group name - * @return the original list of flow entries belonging to the specified group - */ - public List getFlowEntriesForGroup(String group); - - /** - * Returns the list of Flow entries installed in network nodes which are part of - * the same flow group, policy. This list contains the effective flows installed - * on the nodes after the merging with any possible container flow was performed. - * If no container flow are specified, this method returns the same list returned - * by getFlowEntriesForGroup(String group). - * - * @param group - * the group name - * @return the list of container flow merged flow entries belonging to the specified group - */ - public List getInstalledFlowEntriesForGroup(String policyName); - - /** - * Add a list of output port to the flow with the specified name on the - * specified network node - * - * @param node - * the network node - * @param flowName - * the flow name - * @param dstPort - * the list of ports to be added to the flow output actions - */ - public void addOutputPort(Node node, String flowName, List dstPort); - - /** - * Remove a list of output port from the flow with the specified name on the - * specified network node - * - * @param node - * the network node - * @param flowName - * the flow name - * @param dstPortthe - * list of ports to be removed from the flow output actions - */ - public void removeOutputPort(Node node, String flowName, List dstPort); - - /** - * Replace the current output port in the specified flow with the specified - * one - * - * @param node - * the network node - * @param groupName - * the group name - * @param flowName - * the flow name - * @param dstPort - * the new output action port - */ - public void replaceOutputPort(Node node, String flowName, NodeConnector outPort); - - /** - * Returns the output port configured on the specified flow - * - * @param node - * the network node - * @param flowName - * the flow name - * @return the output action port for the specified flow - */ - public NodeConnector getOutputPort(Node node, String flowName); - - /** - * Returns all the troubleshooting information that applications have set - * along with the policy they have configured through forwarding rules - * manger. - * - * @return the collection of troubleshooting objects - */ - public Map getTSPolicyData(); - - /** - * Set the troubleshooting information for the policy - * - * @param policyname - * the flow group name - * @param o - * the object containing the troubleshooting information - * @param add - * true for adding, false for removing - */ - public void setTSPolicyData(String policyName, Object o, boolean add); - - /** - * Returns the troubleshooting information that was set for the specified - * policy - * - * @param groupName - * the flows group name - * @return the troubleshooting info object - */ - public Object getTSPolicyData(String policyName); - - /** - * Returns the specifications of all the flows configured for all the - * switches on the current container - * - * @return the list of flow configurations present in the database - */ - public List getStaticFlows(); - - /** - * Returns the specifications of all the flows configured for the given - * switch on the current container - * - * @param node - * the network node identifier - * @return the list of {@code FlowConfig} objects - */ - public List getStaticFlows(Node node); - - /** - * Returns the specification of the flow configured for the given network - * node on the current container - * - * @param name - * the flow name - * @param n - * the network node identifier - * @return the {@code FlowConfig} object - */ - public FlowConfig getStaticFlow(String name, Node n); - - /** - * Returns the list of names of flows configured for the given Network node - * on the current container - * - * @param node - * the network node identifier - * @return the list of flow names - */ - public List getStaticFlowNamesForNode(Node node); - - /** - * Returns the list of Node(s) for which a static flow has been configured - * - * @return the list of network nodes - */ - public List getListNodeWithConfiguredFlows(); - - /** - * Save the flow configured so far to file - * - * @return the {@code Status} object indicating the result of this action. - */ - public Status saveConfig(); - - /** - * Add a flow specified by the {@code FlowConfig} object on the current - * container - * - * @param config - * the {@code FlowConfig} object representing the static flow - * @return the {@code Status} object indicating the result of this action. - */ - public Status addStaticFlow(FlowConfig config); - - /** - * Add a flow specified by the {@code FlowConfig} object on the current - * container, through an asynchronous call. - * - * @param config - * the {@code FlowConfig} object representing the static flow - * @return the {@code Status} object indicating the result of this action. - */ - public Status addStaticFlowAsync(FlowConfig config); - - /** - * Remove a flow specified by the {@code FlowConfig} object on the current - * container - * - * @param config - * the {@code FlowConfig} object representing the static flow - * @return the {@code Status} object indicating the result of this action - */ - public Status removeStaticFlow(FlowConfig config); - - /** - * Remove a flow specified by the {@code FlowConfig} object on the current - * container, through an asynchronous call. - * - * @param config - * the {@code FlowConfig} object representing the static flow - * @return the {@code Status} object indicating the result of this action - */ - public Status removeStaticFlowAsync(FlowConfig config); - - /** - * Replace the flow identified by the {@code FlowConfig.name} name for the - * {@code FlowConfig.node} network node with the new flow specified by - * {@code FlowConfig} object - * - * @param config - * the {@code FlowConfig} object - * @return the {@code Status} object indicating the result of this action - */ - public Status modifyStaticFlow(FlowConfig config); - - /** - * Remove the flow specified by name on the passed network node - * - * @param name - * for the static flow - * @param node - * on which the flow is attached - * @return the {@code Status} object indicating the result of this action - */ - public Status removeStaticFlow(String name, Node node); - - /** - * Remove the flow specified by name on the passed network node via an - * asynchronous call - * - * @param name - * for the static flow - * @param node - * on which the flow is attached - * @return the {@code Status} object indicating the result of this action - */ - public Status removeStaticFlowAsync(String name, Node node); - - /** - * Toggle the installation status of the specified configured flow If the - * flow configuration status is active, this call will change the flow - * status to inactive and vice-versa - * - * @param configObject - * the {@code FlowConfig} object - * @return the {@code Status} object indicating the result of this action - */ - public Status toggleStaticFlowStatus(FlowConfig configObject); - - /** - * Toggle the installation status of the specified configured flow If the - * flow configuration status is active, this call will change the flow - * status to inactive and vice-versa - * - * @param name - * for the static flow - * @param node - * on which the flow is attached - * @return the {@code Status} object indicating the result of this action - */ - public Status toggleStaticFlowStatus(String name, Node node); - - public Map getPortGroupConfigs(); - - public boolean addPortGroupConfig(String name, String regex, boolean load); - - public boolean delPortGroupConfig(String name); - - public PortGroupProvider getPortGroupProvider(); - - /** - * Returns the list of Flow entries for a network node. - * This list contains the flows as they were - * requested to be installed by the applications, before any merging with - * container flow is done. - * - * @param node - * @return the original list of flow entries belonging to the specified node - */ - public List getFlowEntriesForNode(Node node); - - /** - * Returns the list of Flow entries installed in a network node. - * This list contains the effective flows installed - * on the nodes after the merging with any possible container flow was performed. - * If no container flow are specified, this method returns the same list as returned - * by getFlowEntriesForNode(Node node). - * - * @param node - * @return the list of container flow merged flow entries belonging to the specified node - */ - public List getInstalledFlowEntriesForNode(Node node); - -} diff --git a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManagerAware.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManagerAware.java deleted file mode 100644 index 31e1ea199b..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/IForwardingRulesManagerAware.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager; - -/** - * The interface which describes the methods forwarding rules manager will call - * for notifying the listeners of policy installation updates. - */ -public interface IForwardingRulesManagerAware { - - /** - * Inform the listeners that a troubleshooting information was added or - * removed for the specified policy. - * - * @param policyName - * the policy affected - * @param add - * true if the troubleshooting information was added, false - * otherwise - */ - public void policyUpdate(String policyName, boolean add); - - /** - * Inform listeners that the network node has notified us about a failure in - * executing the controller generated asynchronous request identified by the - * passed unique id. - * - * @param requestId - * the unique id associated with the request which failed to be - * executed on the network node - * @param error - * the string describing the error reported by the network node - */ - public void requestFailed(long requestId, String error); - -} diff --git a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroup.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroup.java deleted file mode 100644 index b05091a4d7..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroup.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager; - -import java.util.HashSet; -import java.util.Set; - -/** - * PortGroup is a simple data-structure to represent any arbitrary group of - * ports on a Switch (that is represented using its switch-ID). - * - * PortGroup is used by PortGroupProvider application to signal a set of ports - * that represent a configured PortGroupConfig. - */ -public class PortGroup { - private long matrixSwitchId; - private Set ports; - - /** - * PortGroup Constructor using Switch and Ports. - * - * @param matrixSwitchId - * Switch Id that represents an openflow Switch - * @param ports - * Set of short values representing openflow port-ids. - */ - public PortGroup(long matrixSwitchId, Set ports) { - super(); - this.matrixSwitchId = matrixSwitchId; - this.ports = ports; - } - - /** - * PortGroup Constructor using Switch. - * - * @param matrixSwitchId - * Switch-Id that represents an openflow Switch - */ - public PortGroup(long matrixSwitchId) { - this.matrixSwitchId = matrixSwitchId; - this.ports = new HashSet(); - } - - /** - * Returns the switchId representing the Switch that makes this PortGroup. - * - * @return long switchId - */ - public long getMatrixSwitchId() { - return matrixSwitchId; - } - - /** - * Assigns a Switch to this PortGroup - * - * @param matrixSwitchId - * Switch-Id that represents an openflow Switch - */ - public void setMatrixSwitchId(long matrixSwitchId) { - this.matrixSwitchId = matrixSwitchId; - } - - /** - * Returns the Set of Ports that makes this PortGroup. - * - * @return Set of short values representing openflow port-ids. - */ - public Set getPorts() { - return ports; - } - - /** - * Assigns a set of openflow ports to this PortGroup - * - * @param ports - * Set of short values representing openflow port-ids. - */ - public void setPorts(Set ports) { - this.ports = ports; - } - - /** - * Adds a port to this PortGroup - * - * @param port - * Short value of a openflow port. - */ - public void addPort(short port) { - ports.add(port); - } - - @Override - public String toString() { - return "PortGroup [matrixSwitchId=" + matrixSwitchId + ", ports=" + ports + "]"; - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupChangeListener.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupChangeListener.java deleted file mode 100644 index 5f28608338..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupChangeListener.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager; - -import java.util.Map; - -import org.opendaylight.controller.sal.core.Node; - -/** - * PortGroupChangeListener listens to the PortGroup updates provided by the - * PortGroupProvider. - * - * - */ -public interface PortGroupChangeListener { - /** - * This method is invoked by PortGroupProvider whenever it detects a change - * in PortGroup membership for a given PortGroupConfig. - * - * @param config - * Port Group Configuration - * @param portGroupData - * HashMap of Node id to PortGroup that represents the updated - * ports as detected by PortGroupProvider. - * @param add - * true indicates that the PortGroup is added. False indicates - * that the PortGroup is removed. - */ - void portGroupChanged(PortGroupConfig config, Map portGroupData, boolean add); -} diff --git a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupConfig.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupConfig.java deleted file mode 100644 index d0878f982c..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupConfig.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager; - -import java.io.Serializable; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; - -import org.opendaylight.controller.configuration.ConfigurationObject; - -/** - * PortGroupConfig class represents the User's Configuration with a Opaque - * Regular Expression String that is parsed and handled by PortGroupProvider. - * - * Typically, the opaque matchString will be a Regular Expression String - * supported by a particular PortGroupProvider based on Customer requirements. - * - * - * - */ -public class PortGroupConfig extends ConfigurationObject implements Serializable { - private static final long serialVersionUID = 1L; - private static final String prettyFields[] = { "Name", "Match Criteria" }; - - private String name; - private String matchString; - - /** - * Default Constructor with regular expression string defaulted to ".*" - */ - public PortGroupConfig() { - name = "default"; - matchString = ".*"; - } - - /** - * Constructor to create a Port Group Configuration using a Group Name and - * an Opaque String that is managed by PortGroupProvider. - * - * @param name - * Group Name representing a Port Group configuration - * @param matchString - * An Opaque String managed by PortGroupProvider - */ - public PortGroupConfig(String name, String matchString) { - super(); - this.name = name; - this.matchString = matchString; - } - - /** - * Returns the user configured PortGroup Configuration name. - * - * @return Configuration Name - */ - public String getName() { - return name; - } - - /** - * Assigns a name to the configuration - * - * @param name - * configuration name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the Opaque string - * - * @return - */ - public String getMatchString() { - return matchString; - } - - /** - * Assigns an opaque String to the Configuration. - * - * @param matchString - * Opaque string handled by PortGroupProvider - */ - public void setMatchString(String matchString) { - this.matchString = matchString; - } - - /** - * Returns the names of all the configurable fields in PortGroupConfig. This - * method is typically used by NorthBound apis. - * - * @return List of Field names that can be configured. - */ - public static List getFieldsNames() { - List fieldList = new ArrayList(); - for (Field fld : PortGroupConfig.class.getDeclaredFields()) { - fieldList.add(fld.getName()); - } - // remove static field(s) - fieldList.remove(0); - fieldList.remove(0); - - return fieldList; - } - - /** - * Returns the names of all the configurable fields in PortGroupConfig in - * human readable format for UI purposes. This method is typically used by - * Web/UI apis. - * - * @return List of Human readable Strings that corresponds to the - * configurable field names. - */ - public static List getPrettyFieldsNames() { - List fieldList = new ArrayList(); - for (String str : prettyFields) { - fieldList.add(str); - } - return fieldList; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((matchString == null) ? 0 : matchString.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PortGroupConfig other = (PortGroupConfig) obj; - if (matchString == null) { - if (other.matchString != null) { - return false; - } - } else if (!matchString.equals(other.matchString)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "PortGroupConfig [name=" + name + ", matchString=" + matchString + "]"; - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupProvider.java b/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupProvider.java deleted file mode 100644 index dc4f13f497..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/src/main/java/org/opendaylight/controller/forwardingrulesmanager/PortGroupProvider.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager; - -import java.util.Map; - -import org.opendaylight.controller.sal.core.Node; - -/** - * PortGroupProvider interface provides all the necessary blueprint for a custom - * application to implement in order to provide Port Grouping Service. Custom - * Application that implements this interface will have to handle the opaque - * match criteria passed to it via PortGroupConfig. - * - * - * - */ -public interface PortGroupProvider { - /** - * This method is invoked by the Controller towards the Provider when a new - * port group is configured. - * - * @param config - * New PortGroupConfig object created by user Configuration. - * @return true if successful. false otherwise. - */ - boolean createPortGroupConfig(PortGroupConfig config); - - /** - * This method is invoked by the Controller towards the Provider when an - * existing port group is deleted. - * - * @param config - * Existing Port Group Configuration deleted by the user. - * @return true if successful. false otherwise. - */ - boolean deletePortGroupConfig(PortGroupConfig config); - - /** - * Returns the complete mapping database corresponds to a PortGroup - * Configuration. Its the PortGroupProvider Application's responsibility to - * manage the Switches & the Set of its Ports that correspond to each of the - * Configuration and return it to the Controller when requested. - * - * @param config - * User Configuration - * @see PortGroupConfig - * @return Database of Switch-Id to PortGroup mapping that corresponds to - * the Port Group User Configuration. - */ - Map getPortGroupData(PortGroupConfig config); - - /** - * Returns PortGroup data for a given Switch and user Configuration. Its the - * PortGroupProvider Application's responsibility to manage the Switches & - * the Set of its Ports that correspond to each of the Configuration and - * return it to the Controller when requested. - * - * @param config - * User Configuration - * @param matrixSwitchId - * Switch Id that represents an openflow Switch - * @see PortGroupConfig - * @return PortGroup data for a given Openflow switch. - * @see PortGroup - */ - PortGroup getPortGroupData(PortGroupConfig config, long matrixSwitchId); - - /** - * Registers a Listener for Port Group membership changes based on Custom - * application algorithm. - * - * @param listener - * A Controller module that listens to events from the Custom - * Port Grouping Application. - */ - void registerPortGroupChange(PortGroupChangeListener listener); - - /** - * Application returns an Usage string for the Match Criteria User - * Configuration. Controller provides an opportunity for application to - * implement Custom Algorithm for Port Grouping. This method exposes the - * custom algorithm to the user so that the user can configure the - * matchString regular expression in PortGroupConfig appropriately. - * - * @return Usage string. - */ - String getApplicationDrivenMatchCriteriaUsage(); - - /** - * Returns the name of the Custom Application that implements - * PortGroupProvider interface. - * - * @return Provider Name - */ - String getProviderName(); - - /** - * Controller uses this method to check with the Provider supports the - * matchCriteria String configured by the User. - * - * @param matchCriteria - * @return true if the Provider supports the matchCriteria String. false - * otherwise. - */ - boolean isMatchCriteriaSupported(String matchCriteria); -} diff --git a/opendaylight/adsal/forwardingrulesmanager/api/src/test/java/org/opendaylight/controller/forwardingrulesmanager/frmTest.java b/opendaylight/adsal/forwardingrulesmanager/api/src/test/java/org/opendaylight/controller/forwardingrulesmanager/frmTest.java deleted file mode 100644 index 3c367b9af4..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/api/src/test/java/org/opendaylight/controller/forwardingrulesmanager/frmTest.java +++ /dev/null @@ -1,822 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.ActionType; -import org.opendaylight.controller.sal.action.Controller; -import org.opendaylight.controller.sal.action.Flood; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.action.PopVlan; -import org.opendaylight.controller.sal.action.SetDlDst; -import org.opendaylight.controller.sal.action.SetNwDst; -import org.opendaylight.controller.sal.action.SetVlanId; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.utils.Status; - -public class frmTest { - - @Test - public void testFlowEntryInstall() throws UnknownHostException { - Node node = NodeCreator.createOFNode(1L); - FlowEntry pol = new FlowEntry("polTest", null, getSampleFlowV6(node), node); - FlowEntry pol2 = new FlowEntry("polTest2", null, getSampleFlowV6(node), node); - FlowEntryInstall fei = new FlowEntryInstall(pol.clone(), null); - FlowEntryInstall fei2 = new FlowEntryInstall(pol.clone(), null); - FlowEntryInstall fei3 = new FlowEntryInstall(pol2.clone(), null); - Assert.assertTrue(fei.getOriginal().equals(pol)); - Assert.assertTrue(fei.getInstall().equals(pol)); - Assert.assertTrue(fei.getFlowName().equals(pol.getFlowName())); - Assert.assertTrue(fei.getGroupName().equals(pol.getGroupName())); - Assert.assertTrue(fei.getNode().equals(pol.getNode())); - Assert.assertFalse(fei.isDeletePending()); - fei.toBeDeleted(); - Assert.assertTrue(fei.isDeletePending()); - Assert.assertNull(fei.getContainerFlow()); - Assert.assertTrue(fei.equalsByNodeAndName(pol.getNode(), pol.getFlowName())); - - Assert.assertTrue(fei.equals(fei2)); - Assert.assertFalse(fei.equals(null)); - Assert.assertTrue(fei.equals(fei3)); - - } - - @Test - public void testFlowEntryCreation() throws UnknownHostException { - Node node = NodeCreator.createOFNode(1L); - FlowEntry pol = new FlowEntry("polTest", null, getSampleFlowV6(node), node); - Assert.assertTrue(pol.getFlow().equals(getSampleFlowV6(node))); - } - - @Test - public void testFlowEntrySetGet() throws UnknownHostException { - Node node = NodeCreator.createOFNode(1L); - Node node2 = NodeCreator.createOFNode(2L); - FlowEntry pol = new FlowEntry("polTest", null, getSampleFlowV6(node), node); - pol.setGroupName("polTest2"); - pol.setFlowName("flowName"); - Assert.assertTrue(pol.getFlowName().equals("flowName")); - Assert.assertTrue(pol.getGroupName().equals("polTest2")); - pol.setNode(node2); - Assert.assertTrue(pol.getNode().equals(node2)); - Assert.assertTrue(pol.equalsByNodeAndName(node2, "flowName")); - } - - @Test - public void testFlowEntryEquality() throws UnknownHostException { - Node node = NodeCreator.createOFNode(1L); - Node node2 = NodeCreator.createOFNode(1L); - FlowEntry pol = new FlowEntry("polTest", null, getSampleFlowV6(node), node); - FlowEntry pol2 = new FlowEntry("polTest", null, getSampleFlowV6(node), node2); - Assert.assertTrue(pol.equals(pol2)); - } - - @Test - public void testFlowEntryCollision() throws UnknownHostException { - // Create 2 equal FlowEntry objects - Node node1 = NodeCreator.createOFNode(1L); - Node node2 = NodeCreator.createOFNode(1L); - FlowEntry fe1 = new FlowEntry("Junit", "flow1", getSampleFlowV6(node1), node1); - FlowEntry fe2 = new FlowEntry("Junit", "flow2", getSampleFlowV6(node2), node1); - - // Check equality in FlowEntry and parameters - Assert.assertTrue(fe1.getFlow().getMatch().equals(fe2.getFlow().getMatch())); - Assert.assertTrue(fe1.getFlow().getMatch().getMatches() == fe2.getFlow().getMatch().getMatches()); - Assert.assertTrue(fe1.getFlow().getMatch().hashCode() == fe2.getFlow().getMatch().hashCode()); - Assert.assertTrue(fe1.getFlow().hashCode() == fe2.getFlow().hashCode()); - Assert.assertTrue(fe1.equals(fe2)); - Assert.assertTrue(fe1.hashCode() == fe2.hashCode()); - - // Change priority field for fe2, verify inequality - fe2.getFlow().setPriority((short)1000); - - // Verify FlowEntry works as key in collection - ConcurrentMap map = new ConcurrentHashMap(); - Assert.assertTrue(null == map.put(fe1, fe1)); - Assert.assertTrue(fe1.clone().equals(map.put(fe1.clone(), fe1.clone()))); - Assert.assertTrue(map.get(fe1.clone()).equals(fe1.clone())); - Assert.assertTrue(map.keySet().contains(fe1.clone())); - Assert.assertTrue(map.containsKey(fe1)); - - // Remove key - map.remove(fe1); - Assert.assertTrue(map.isEmpty()); - Assert.assertFalse(map.containsKey(fe1)); - - // Verify cloned object as key - map.put(fe1.clone(), fe1.clone()); - Assert.assertTrue(map.containsKey(fe1)); - - // Verify different key is not present - Assert.assertFalse(map.containsKey(fe2)); - - // Add different key - map.put(fe2.clone(), fe2.clone()); - Assert.assertTrue(map.size() == 2); - Assert.assertTrue(map.containsKey(fe1)); - Assert.assertTrue(map.containsKey(fe2)); - - // Make fe2 equal to fe1 again - fe2.getFlow().setPriority((short)300); - Assert.assertTrue(fe2.equals(fe1)); - Assert.assertTrue(map.containsKey(fe2)); - - // Clean up - map.clear(); - } - - @Test - public void testFlowEntryInstallCollision() throws UnknownHostException { - // Create 2 equal FlowEntryInstall objects - Node node1 = NodeCreator.createOFNode(1L); - Node node2 = NodeCreator.createOFNode(1L); - FlowEntry fe1 = new FlowEntry("Junit", "flow1", getSampleFlowV6(node1), node1); - FlowEntry fe2 = new FlowEntry("Junit", "flow2", getSampleFlowV6(node2), node1); - ContainerFlow cf1 = null; - ContainerFlow cf2 = null; - FlowEntryInstall fei1 = new FlowEntryInstall(fe1, cf1); - FlowEntryInstall fei2 = new FlowEntryInstall(fe2, cf2); - - // Check equality in FlowEntry and parameters - Assert.assertTrue(fei1.equals(fei2)); - Assert.assertTrue(fei1.hashCode() == fei2.hashCode()); - - // Verify FlowEntryInstall works as key in collection - ConcurrentMap map = - new ConcurrentHashMap(); - Assert.assertTrue(null == map.put(fei1, fei1)); - Assert.assertTrue(map.get(fei1).equals(fei2)); - Assert.assertTrue(map.keySet().contains(fei1)); - Assert.assertTrue(map.keySet().contains(fei2)); - Assert.assertTrue(map.containsKey(fei1)); - - // Remove key - map.remove(fei1); - Assert.assertTrue(map.isEmpty()); - Assert.assertFalse(map.containsKey(fei1)); - - // Verify cloned object as key - map.put(fei1, fei1); - Assert.assertTrue(map.containsKey(fei1)); - - // Change fei2, change relevant hashcode info - fei2.getInstall().getFlow().setPriority((short)301); - Assert.assertFalse(fei1.equals(fei2)); - Assert.assertFalse(fei1.hashCode() == fei2.hashCode()); - - - // Verify different key is not present - Assert.assertFalse(map.containsKey(fei2)); - - // Add different key - map.put(fei2, fei2); - Assert.assertTrue(map.size() == 2); - Assert.assertTrue(map.containsKey(fei1)); - Assert.assertTrue(map.containsKey(fei2)); - - // Make fei2 equal to fei1 again - fei2.getInstall().getFlow().setPriority((short)300); - Assert.assertTrue(fei2.equals(fei1)); - Assert.assertTrue(map.containsKey(fei2)); - - // Clean up - map.clear(); - } - - @Test - public void testFlowEntryCloning() throws UnknownHostException { - Node node = NodeCreator.createOFNode(1L); - FlowEntry pol = new FlowEntry("polTest", null, getSampleFlowV6(node), node); - FlowEntry pol2 = pol.clone(); - Assert.assertTrue(pol.equals(pol2)); - } - - @Test - public void testFlowEntrySet() throws UnknownHostException { - Set set = new HashSet(); - - Node node1 = NodeCreator.createOFNode(1L); - Node node2 = NodeCreator.createOFNode(2L); - Node node3 = NodeCreator.createOFNode(3L); - - Match match = new Match(); - match.setField(MatchType.NW_SRC, InetAddress.getAllByName("1.1.1.1")); - match.setField(MatchType.NW_DST, InetAddress.getAllByName("2.2.2.2")); - match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue()); - - List actionList = new ArrayList(); - // actionList.add(new Drop()); - - Flow flow = new Flow(match, actionList); - FlowEntry pol1 = new FlowEntry("m1", "same", flow, node1); - FlowEntry pol2 = new FlowEntry("m2", "same", flow, node2); - FlowEntry pol3 = new FlowEntry("m3", "same", flow, node3); - - set.add(pol1); - set.add(pol2); - set.add(pol3); - - Assert.assertTrue(set.contains(pol1)); - Assert.assertTrue(set.contains(pol2)); - Assert.assertTrue(set.contains(pol3)); - - Assert.assertTrue(set.contains(pol1.clone())); - Assert.assertTrue(set.contains(pol2.clone())); - Assert.assertTrue(set.contains(pol3.clone())); - - } - - @Test - public void testInternalFlow() { - FlowConfig flowConfig = new FlowConfig(); - Assert.assertFalse(flowConfig.isInternalFlow()); - flowConfig.setName("__Internal__"); - Status status = flowConfig.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("name")); - Assert.assertTrue(flowConfig.isInternalFlow()); - flowConfig.setName("External"); - Assert.assertFalse(flowConfig.isInternalFlow()); - } - - @Test - public void testFlowConfigCreateSet() throws UnknownHostException { - FlowConfig frmC = new FlowConfig(); - FlowConfig frmC3 = new FlowConfig(); - Node node = NodeCreator.createOFNode(1L); - FlowEntry entry = new FlowEntry("polTest", null, getSampleFlowV6(node), node); - - // testing equal function - Assert.assertFalse(frmC.equals(null)); - Assert.assertTrue(frmC.equals(frmC)); - Assert.assertTrue(frmC.equals(frmC3)); - Assert.assertFalse(frmC.equals(entry)); - FlowConfig flowC = createSampleFlowConfig(); - Assert.assertFalse(frmC.equals(flowC)); - // testing installInHW - Assert.assertTrue(frmC.installInHw()); - frmC.setInstallInHw(false); - Assert.assertFalse(frmC.installInHw()); - frmC.setInstallInHw(true); - Assert.assertTrue(frmC.installInHw()); - - // testing general set and get methods - ArrayList actions = createSampleActionList(); - frmC.setActions(actions); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setActions(actions); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setCookie("0"); - Assert.assertTrue(frmC.getCookie().equals("0")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setCookie("0"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setDstMac("00:A0:C9:22:AB:11"); - Assert.assertTrue(frmC.getDstMac().equals("00:A0:C9:22:AB:11")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setDstMac("00:A0:C9:22:AB:11"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setSrcMac("00:A0:C9:14:C8:29"); - Assert.assertTrue(frmC.getSrcMac().equals("00:A0:C9:14:C8:29")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setSrcMac("00:A0:C9:14:C8:29"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setDynamic(true); - Assert.assertTrue(frmC.isDynamic()); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setDynamic(true); - flowC.setDynamic(true); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setEtherType("0x0800"); - Assert.assertTrue(frmC.getEtherType().equals("0x0800")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setEtherType("0x0800"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setIngressPort("60"); - Assert.assertTrue(frmC.getIngressPort().equals("60")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setIngressPort("60"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setName("Config1"); - Assert.assertTrue(frmC.getName().equals("Config1")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setName("Config1"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setDstIp("2.2.2.2"); - Assert.assertTrue(frmC.getDstIp().equals("2.2.2.2")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setDstIp("2.2.2.2"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setSrcIp("1.2.3.4"); - Assert.assertTrue(frmC.getSrcIp().equals("1.2.3.4")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setSrcIp("1.2.3.4"); - - Assert.assertFalse(frmC.equals(flowC)); - Assert.assertFalse(frmC.isPortGroupEnabled()); - frmC.setPortGroup("2"); - Assert.assertTrue(frmC.isPortGroupEnabled()); - Assert.assertTrue(frmC.getPortGroup().equals("2")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setPortGroup("2"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setPriority("100"); - Assert.assertTrue(frmC.getPriority().equals("100")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setPriority("100"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setProtocol(IPProtocols.TCP.toString()); - Assert.assertTrue(frmC.getProtocol().equals(IPProtocols.TCP.toString())); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setProtocol(IPProtocols.TCP.toString()); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setNode(Node.fromString(Node.NodeIDType.OPENFLOW, "1")); - Assert.assertTrue(frmC.getNode().equals(Node.fromString(Node.NodeIDType.OPENFLOW, "1"))); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setNode(Node.fromString(Node.NodeIDType.OPENFLOW, "1")); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setTosBits("0"); - Assert.assertTrue(frmC.getTosBits().equals("0")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setTosBits("0"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setDstPort("100"); - Assert.assertTrue(frmC.getDstPort().equals("100")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setDstPort("100"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setSrcPort("8080"); - Assert.assertTrue(frmC.getSrcPort().equals("8080")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setSrcPort("8080"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setVlanId("100"); - Assert.assertTrue(frmC.getVlanId().equals("100")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setVlanId("100"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setVlanPriority("0"); - Assert.assertTrue(frmC.getVlanPriority().equals("0")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setVlanPriority("0"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setIdleTimeout("300"); - Assert.assertTrue(frmC.getIdleTimeout().equals("300")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setIdleTimeout("300"); - - Assert.assertFalse(frmC.equals(flowC)); - frmC.setHardTimeout("1000"); - Assert.assertTrue(frmC.getHardTimeout().equals("1000")); - Assert.assertFalse(frmC.equals(frmC3)); - frmC3.setHardTimeout("1000"); - - // Assert.assertFalse(frmC.equals(flowC)); - Assert.assertTrue(actions.equals(frmC.getActions())); - - FlowConfig frmC2 = new FlowConfig(frmC); - - Assert.assertFalse(frmC2.equals(frmC)); - frmC2.setDynamic(false); - Assert.assertFalse(frmC2.equals(frmC)); - frmC2.setDynamic(true); - Assert.assertTrue(frmC2.equals(frmC)); - // Assert.assertFalse(frmC2.equals(frmC3)); - flowC.setDynamic(true); - Assert.assertTrue(flowC.equals(frmC)); - Assert.assertTrue(flowC.isStatusSuccessful()); - flowC.setStatus("Invalid"); - Assert.assertFalse(flowC.isStatusSuccessful()); - - flowC.getActions().add(ActionType.DROP.toString()); - Assert.assertFalse(flowC.equals(frmC)); - Assert.assertFalse(flowC.isIPv6()); - flowC.setDstIp("2001:420:281:1004:407a:57f4:4d15:c355"); - Assert.assertTrue(flowC.isIPv6()); - flowC.setSrcIp("2001:420:281:1004:407a:57f4:4d15:c355"); - Assert.assertTrue(flowC.isIPv6()); - - Long id = (Long) flowC.getNode().getID(); - Assert.assertTrue(id.toString().equals("1")); - - } - - @Test - public void testFlowConfigEqualities() throws UnknownHostException { - FlowConfig fc = new FlowConfig(); - FlowConfig fc2 = new FlowConfig(); - fc.setName("flow1"); - fc.setNode(Node.fromString(Node.NodeIDType.OPENFLOW, "1")); - Assert.assertFalse(fc.onNode(Node.fromString(Node.NodeIDType.OPENFLOW, "0"))); - Assert.assertTrue(fc.onNode(Node.fromString(Node.NodeIDType.OPENFLOW, "1"))); - - Assert.assertTrue(fc.isByNameAndNodeIdEqual("flow1", Node.fromString(Node.NodeIDType.OPENFLOW, "1"))); - Assert.assertFalse(fc.isByNameAndNodeIdEqual("flow1", Node.fromString(Node.NodeIDType.OPENFLOW, "0"))); - Assert.assertFalse(fc.isByNameAndNodeIdEqual("flow2", Node.fromString(Node.NodeIDType.OPENFLOW, "1"))); - - Assert.assertFalse(fc.isByNameAndNodeIdEqual(fc2)); - fc2.setName("flow1"); - Assert.assertFalse(fc.isByNameAndNodeIdEqual(fc2)); - fc2.setNode(Node.fromString(Node.NodeIDType.OPENFLOW, "0")); - Assert.assertFalse(fc.isByNameAndNodeIdEqual(fc2)); - fc2.setNode(Node.fromString(Node.NodeIDType.OPENFLOW, "1")); - Assert.assertTrue(fc.isByNameAndNodeIdEqual(fc2)); - } - - @Test - public void testStatusToggle() throws UnknownHostException { - // default is install in Hw - FlowConfig fc = new FlowConfig(); - fc.toggleInstallation(); - Assert.assertFalse(fc.installInHw()); - fc.toggleInstallation(); - Assert.assertTrue(fc.installInHw()); - fc.toggleInstallation(); - Assert.assertFalse(fc.installInHw()); - - } - - @Test - public void testGetFlowEntry() throws UnknownHostException { - FlowConfig fc2 = createSampleFlowConfig(); - FlowEntry fe = fc2.getFlowEntry(); - Assert.assertNotNull(fe); - } - - @Test - public void testGetFlow() throws UnknownHostException { - FlowConfig fc = new FlowConfig(); - fc.setActions(createSampleActionList()); - Flow flow = fc.getFlow(); - Assert.assertNotNull(flow); - } - - @Test - public void testL2AddressValid() { - FlowConfig fc = new FlowConfig(); - Assert.assertFalse(fc.isL2AddressValid(null)); - Assert.assertFalse(fc.isL2AddressValid("11")); - Assert.assertFalse(fc.isL2AddressValid("00:A0:C9:14:C8:")); - Assert.assertFalse(fc.isL2AddressValid("000:A01:C9:14:C8:211")); - - Assert.assertTrue(fc.isL2AddressValid("00:A0:C9:14:C8:29")); - } - - @Test - public void testValid() throws UnknownHostException { - FlowConfig fc2 = createSampleFlowConfig(); - Assert.assertTrue(fc2.validate().isSuccess()); - - FlowConfig fc = new FlowConfig(); - Status status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Invalid name")); - - fc.setName("Config"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Node is null")); - - fc.setNode(Node.fromString(Node.NodeIDType.OPENFLOW, "1")); - Assert.assertFalse(fc.validate().isSuccess()); - List actions = new ArrayList(); - fc.setActions(actions); - Assert.assertFalse(fc.validate().isSuccess()); - actions.add("OUTPUT=2"); - fc.setActions(actions); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setPriority("-1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("is not in the range 0 - 65535")); - - fc.setPriority("100000"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("is not in the range 0 - 65535")); - - fc.setPriority("2000"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setCookie("100"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setIngressPort("100"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setVlanId(("-1")); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("is not in the range 0 - 4095")); - - fc.setVlanId("5000"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("is not in the range 0 - 4095")); - - fc.setVlanId("100"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setVlanPriority("-1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("is not in the range 0 - 7")); - - fc.setVlanPriority("9"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("is not in the range 0 - 7")); - - fc.setVlanPriority("5"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setEtherType("-1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Ethernet type")); - - fc.setEtherType("0xfffff"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Ethernet type")); - - fc.setEtherType("0x800"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setTosBits("-1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("IP ToS bits")); - - fc.setTosBits("65"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("IP ToS bits")); - - fc.setTosBits("60"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setSrcPort("-1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Transport source port")); - - fc.setSrcPort("0xfffff"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Transport source port")); - - fc.setSrcPort("0"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setSrcPort("0x00ff"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setSrcPort("0xffff"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setDstPort("-1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Transport destination port")); - - fc.setDstPort("0xfffff"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Transport destination port")); - - fc.setDstPort("0"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setDstPort("0x00ff"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setDstPort("0xffff"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setSrcMac("abc"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Ethernet source address")); - - fc.setSrcMac("00:A0:C9:14:C8:29"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setDstMac("abc"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Ethernet destination address")); - - fc.setDstMac("00:A0:C9:22:AB:11"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setSrcIp("-1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("IP source address")); - - fc.setSrcIp("2001:420:281:1004:407a:57f4:4d15:c355"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Type mismatch between Ethernet & Src IP")); - - fc.setEtherType("0x86dd"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setSrcIp("1.1.1.1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Type mismatch between Ethernet & Src IP")); - - fc.setEtherType("0x800"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setDstIp("-1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("IP destination address")); - - fc.setDstIp("2001:420:281:1004:407a:57f4:4d15:c355"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Type mismatch between Ethernet & Dst IP")); - - fc.setEtherType("0x86dd"); - fc.setSrcIp("2001:420:281:1004:407a:57f4:4d15:c355"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setDstIp("2.2.2.2"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Type mismatch between Ethernet & Dst IP")); - - fc.setEtherType("0x800"); - fc.setSrcIp("1.1.1.1"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setEtherType(null); - fc.setSrcIp("2001:420:281:1004:407a:57f4:4d15:c355"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("IP Src Dest Type mismatch")); - - fc.setSrcIp("1.1.1.1"); - fc.setIdleTimeout("-1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Idle Timeout value")); - - fc.setIdleTimeout("0xfffff"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Idle Timeout value")); - - fc.setIdleTimeout("10"); - Assert.assertTrue(fc.validate().isSuccess()); - - fc.setHardTimeout("-1"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Hard Timeout value")); - - fc.setHardTimeout("0xfffff"); - status = fc.validate(); - Assert.assertFalse(status.isSuccess()); - Assert.assertTrue(status.getDescription().contains("Hard Timeout value")); - - fc.setHardTimeout("10"); - Assert.assertTrue(fc.validate().isSuccess()); - - } - - private FlowConfig createSampleFlowConfig() throws UnknownHostException { - ArrayList actions; - actions = createSampleActionList(); - // actions.add(ActionType.CONTROLLER.toString()); - FlowConfig flowConfig = new FlowConfig("true", "Config1", Node.fromString(Node.NodeIDType.OPENFLOW, "1"), - "100", "0", "60", "2", "100", "0", "0x0800", "00:A0:C9:14:C8:29", "00:A0:C9:22:AB:11", - IPProtocols.TCP.toString(), "0", "1.2.3.4", "2.2.2.2", "8080", "100", "300", "1000", actions); - return flowConfig; - - } - - private ArrayList createSampleActionList() { - ArrayList actions = new ArrayList(); - actions.add(ActionType.DROP.toString()); - actions.add(ActionType.LOOPBACK.toString()); - actions.add(ActionType.FLOOD.toString()); - actions.add(ActionType.SW_PATH.toString()); - actions.add(ActionType.HW_PATH.toString()); - actions.add(ActionType.SET_VLAN_PCP.toString() + "=1"); - actions.add(ActionType.SET_VLAN_ID.toString() + "=1"); - actions.add(ActionType.POP_VLAN.toString()); - actions.add(ActionType.SET_DL_SRC.toString() + "=00:A0:C1:AB:22:11"); - actions.add(ActionType.SET_DL_DST.toString() + "=00:B1:C1:00:AA:BB"); - actions.add(ActionType.SET_NW_SRC.toString() + "=1.1.1.1"); - actions.add(ActionType.SET_NW_DST.toString() + "=2.2.2.2"); - actions.add(ActionType.CONTROLLER.toString()); - actions.add(ActionType.SET_NW_TOS.toString() + "=1"); - actions.add(ActionType.SET_TP_SRC.toString() + "=60"); - actions.add(ActionType.SET_TP_DST.toString() + "=8080"); - actions.add(ActionType.SET_NEXT_HOP.toString() + "=1.1.1.1"); - - return actions; - } - - private Flow getSampleFlowV6(Node node) throws UnknownHostException { - NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node); - NodeConnector oport = NodeConnectorCreator.createOFNodeConnector((short) 30, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - byte newMac[] = { (byte) 0x11, (byte) 0xaa, (byte) 0xbb, (byte) 0x34, (byte) 0x9a, (byte) 0xee }; - InetAddress srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMask = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - InetAddress ipMask2 = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - InetAddress newIP = InetAddress.getByName("2056:650::a1b0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27; - byte vlanPr = (byte) 3; - Byte tos = 4; - byte proto = IPProtocols.UDP.byteValue(); - short src = (short) 5500; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(MatchType.IN_PORT, port); - match.setField(MatchType.DL_SRC, srcMac); - match.setField(MatchType.DL_DST, dstMac); - match.setField(MatchType.DL_TYPE, ethertype); - match.setField(MatchType.DL_VLAN, vlan); - match.setField(MatchType.DL_VLAN_PR, vlanPr); - match.setField(MatchType.NW_SRC, srcIP, ipMask); - match.setField(MatchType.NW_DST, dstIP, ipMask2); - match.setField(MatchType.NW_TOS, tos); - match.setField(MatchType.NW_PROTO, proto); - match.setField(MatchType.TP_SRC, src); - match.setField(MatchType.TP_DST, dst); - - List actions = new ArrayList(); - actions.add(new Controller()); - actions.add(new SetVlanId(5)); - actions.add(new SetDlDst(newMac)); - actions.add(new SetNwDst(newIP)); - actions.add(new Output(oport)); - actions.add(new PopVlan()); - actions.add(new Flood()); - - Flow flow = new Flow(match, actions); - flow.setPriority((short) 300); - flow.setHardTimeout((short) 240); - - return flow; - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/implementation/pom.xml b/opendaylight/adsal/forwardingrulesmanager/implementation/pom.xml deleted file mode 100644 index d51b98bfe7..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/implementation/pom.xml +++ /dev/null @@ -1,98 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - forwardingrulesmanager.implementation - 0.6.0-SNAPSHOT - bundle - - - equinoxSDK381 - org.apache.felix.gogo.runtime - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller - switchmanager - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.forwardingrulesmanager.implementation.data - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.configuration, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.connection, - org.opendaylight.controller.forwardingrulesmanager, - org.opendaylight.controller.connectionmanager, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.felix.dm, - org.apache.felix.service.command, - org.osgi.service.component, - org.slf4j, - org.osgi.framework - org.opendaylight.controller.forwardingrulesmanager.internal.Activator - org.opendaylight.controller.hosttracker - - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/implementation/data/FlowEntryDistributionOrder.java b/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/implementation/data/FlowEntryDistributionOrder.java deleted file mode 100644 index b55a7e372b..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/implementation/data/FlowEntryDistributionOrder.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * Class used by the FRM to distribute the forwarding rules programming in the - * cluster and to collect back the results of the programming - */ -package org.opendaylight.controller.forwardingrulesmanager.implementation.data; - -import java.io.Serializable; -import java.net.InetAddress; - -import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall; -import org.opendaylight.controller.sal.core.UpdateType; - -/** - * Class used by the FRM to distribute the forwarding rules programming in the - * cluster and to collect back the results of the programming - */ -public final class FlowEntryDistributionOrder implements Serializable { - /** - * Serialization UID - */ - private static final long serialVersionUID = 416280377113255147L; - private final FlowEntryInstall entry; - private final UpdateType upType; - private final InetAddress requestorController; - - /** - * @return the entry - */ - public FlowEntryInstall getEntry() { - return entry; - } - - /** - * @return the upType - */ - public UpdateType getUpType() { - return upType; - } - - /** - * @return the requestorController - */ - public InetAddress getRequestorController() { - return requestorController; - } - - /** - * @param entry - * FlowEntryInstall key value - * @param upType - * UpdateType key value - * @param requestorController - * identifier of the controller that initiated the request - */ - - public FlowEntryDistributionOrder(FlowEntryInstall entry, UpdateType upType, InetAddress requestorController) { - super(); - this.entry = entry; - this.upType = upType; - this.requestorController = requestorController; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + ((entry == null) ? 0 : entry.hashCode()); - result = (prime * result) + ((requestorController == null) ? 0 : requestorController.hashCode()); - result = (prime * result) + ((upType == null) ? 0 : upType.calculateConsistentHashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof FlowEntryDistributionOrder)) { - return false; - } - FlowEntryDistributionOrder other = (FlowEntryDistributionOrder) obj; - if (entry == null) { - if (other.entry != null) { - return false; - } - } else if (!entry.equals(other.entry)) { - return false; - } - if (requestorController == null) { - if (other.requestorController != null) { - return false; - } - } else if (!requestorController.equals(other.requestorController)) { - return false; - } - if (upType != other.upType) { - return false; - } - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("FlowEntryDistributionOrder ["); - if (entry != null) { - builder.append("entry=") - .append(entry) - .append(", "); - } - if (upType != null) { - builder.append("upType=") - .append(upType) - .append(", "); - } - if (requestorController != null) { - builder.append("requestorController=") - .append(requestorController); - } - builder.append("]"); - return builder.toString(); - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/Activator.java b/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/Activator.java deleted file mode 100644 index a53ea111d2..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/Activator.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager.internal; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.core.IContainer; -import org.opendaylight.controller.sal.core.IContainerLocalListener; -import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener; -import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.ISwitchManagerAware; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory.getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the list of - * known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { ForwardingRulesManager.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies is - * required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - * @param containerName - * The containerName being configured, this allow also optional - * per-container different behavior if needed, usually should not - * be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(ForwardingRulesManager.class)) { - String interfaces[] = null; - Dictionary props = new Hashtable(); - Set propSet = new HashSet(); - propSet.add(ForwardingRulesManager.WORK_STATUS_CACHE); - propSet.add(ForwardingRulesManager.WORK_ORDER_CACHE); - propSet.add(ForwardingRulesManager.INSTALLED_SW_VIEW_CACHE); - props.put("cachenames", propSet); - - // export the service - interfaces = new String[] { IContainerLocalListener.class.getName(), ISwitchManagerAware.class.getName(), - IForwardingRulesManager.class.getName(), IInventoryListener.class.getName(), - IConfigurationContainerAware.class.getName(), ICacheUpdateAware.class.getName(), - IFlowProgrammerListener.class.getName() }; - - c.setInterface(interfaces, props); - - c.add(createContainerServiceDependency(containerName).setService(IFlowProgrammerService.class) - .setCallbacks("setFlowProgrammerService", "unsetFlowProgrammerService").setRequired(true)); - c.add(createContainerServiceDependency(containerName).setService(IClusterContainerServices.class) - .setCallbacks("setClusterContainerService", "unsetClusterContainerService").setRequired(true)); - c.add(createContainerServiceDependency(containerName).setService(ISwitchManager.class) - .setCallbacks("setSwitchManager", "unsetSwitchManager").setRequired(true)); - c.add(createContainerServiceDependency(containerName).setService(IForwardingRulesManagerAware.class) - .setCallbacks("setFrmAware", "unsetFrmAware").setRequired(false)); - c.add(createContainerServiceDependency(containerName).setService(IContainer.class) - .setCallbacks("setIContainer", "unsetIContainer").setRequired(true)); - c.add(createServiceDependency().setService(IConnectionManager.class) - .setCallbacks("setIConnectionManager", "unsetIConnectionManager").setRequired(true)); - c.add(createContainerServiceDependency(containerName).setService( - IConfigurationContainerService.class).setCallbacks( - "setConfigurationContainerService", - "unsetConfigurationContainerService").setRequired(true)); - if (GlobalConstants.DEFAULT.toString().equals(containerName)) { - c.add(createServiceDependency().setService(IContainerManager.class) - .setCallbacks("setIContainerManager", "unsetIContainerManager").setRequired(true)); - } - } - } - - @Override - protected Object[] getGlobalImplementations() { - final Object[] res = { ForwardingRulesManagerCLI.class }; - return res; - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/FlowEntryDistributionOrderFutureTask.java b/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/FlowEntryDistributionOrderFutureTask.java deleted file mode 100644 index b8c2d1db55..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/FlowEntryDistributionOrderFutureTask.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * Class which will monitor the completion of a FlowEntryDistributionOrder it - * implements a Future interface so it can be inspected by who is waiting for - * it. - */ -package org.opendaylight.controller.forwardingrulesmanager.internal; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class which will monitor the completion of a FlowEntryDistributionOrder it - * implements a Future interface so it can be inspected by who is waiting for - * it. - */ -final class FlowEntryDistributionOrderFutureTask implements Future { - private final FlowEntryDistributionOrder order; - private boolean amICancelled; - private CountDownLatch waitingLatch; - private Status retStatus; - private static final Logger logger = LoggerFactory.getLogger(FlowEntryDistributionOrderFutureTask.class); - // Don't wait forever to program, rather timeout if there are issues, and - // log an error - private long timeout; - private static final Long DEFAULTTIMEOUT = 30000L; - - /** - * @param order - * for which we are monitoring the execution - */ - FlowEntryDistributionOrderFutureTask(FlowEntryDistributionOrder order) { - // Order being monitored - this.order = order; - this.amICancelled = false; - // We need to wait for one completion to happen - this.waitingLatch = new CountDownLatch(1); - // No return status yet! - this.retStatus = new Status(StatusCode.UNDEFINED); - // Set the timeout - String strTimeout = System.getProperty("FlowEntryDistributionOrderFutureTask.timeout", - DEFAULTTIMEOUT.toString()); - try { - timeout = Long.parseLong(strTimeout); - } catch (Exception e) { - timeout = DEFAULTTIMEOUT; - } - } - - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - if (this.waitingLatch.getCount() != 0L) { - this.retStatus = new Status(StatusCode.GONE); - this.waitingLatch.countDown(); - logger.trace("Cancelled the workOrder"); - return true; - } - return false; - } - - @Override - public Status get() throws InterruptedException, ExecutionException { - boolean didFinish = false; - logger.trace("Getting status for order {}", this.order); - // If i'm done lets return the status as many times as caller wants - if (this.waitingLatch.getCount() == 0L) { - logger.trace("get returns the status without waiting"); - return retStatus; - } - - logger.trace("Start waiting for status to come back"); - // Wait till someone signal that we are done - didFinish = this.waitingLatch.await(this.timeout, TimeUnit.MILLISECONDS); - - if (didFinish) { - logger.trace("Waiting for the status of order {} is over, returning it", this.order); - // Return the known status - return retStatus; - } else { - logger.error("Timing out, the workStatus for order {} has not come back in time!, it's hashcode is {}", - this.order, this.order.hashCode()); - return new Status(StatusCode.TIMEOUT); - } - } - - @Override - public Status get(long timeout, TimeUnit unit) throws InterruptedException, - ExecutionException, TimeoutException { - boolean didFinish = false; - logger.trace("Getting status for order {}", this.order); - // If i'm done lets return the status as many times as caller wants - if (this.waitingLatch.getCount() == 0L) { - logger.trace("get returns the status without waiting"); - return retStatus; - } - - logger.trace("Start waiting for status to come back"); - // Wait till someone signal that we are done - didFinish = this.waitingLatch.await(timeout, unit); - - if (didFinish) { - logger.trace("Waiting for the status is over, returning it"); - // Return the known status, could also be null if didn't return - return retStatus; - } else { - // No need to bark here as long as this routine could indeed - // timeout - logger.trace("Timing out, the workStatus for order {} has not come back in time!", this.order); - return new Status(StatusCode.TIMEOUT); - } - } - - @Override - public boolean isCancelled() { - return this.amICancelled; - } - - @Override - public boolean isDone() { - return (this.waitingLatch.getCount() == 0L); - } - - /** - * Used by the thread that gets back the status for the order so can unblock - * an eventual caller waiting on the result to comes back - * - * @param order - * @param retStatus - */ - void gotStatus(FlowEntryDistributionOrder order, Status retStatus) { - logger.trace("Got status for order:{} \n Status:{}", order, retStatus); - if (!order.equals(this.order)) { - logger.error("Didn't get a result for an order we did issue order expected:{}, order received:{}", - this.order, order); - // Weird we got a call for an order we didn't make - return; - } - this.retStatus = retStatus; - // Now we are not waiting any longer - this.waitingLatch.countDown(); - logger.trace("Unlocked the Future"); - } - - /** - * Getter for the workOrder for which the order is waiting for - * @return the order - */ - public FlowEntryDistributionOrder getOrder() { - return order; - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManager.java b/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManager.java deleted file mode 100644 index 46008b24c6..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManager.java +++ /dev/null @@ -1,3273 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwardingrulesmanager.internal; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; - -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.forwardingrulesmanager.FlowConfig; -import org.opendaylight.controller.forwardingrulesmanager.FlowEntry; -import org.opendaylight.controller.forwardingrulesmanager.FlowEntryInstall; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManagerAware; -import org.opendaylight.controller.forwardingrulesmanager.PortGroup; -import org.opendaylight.controller.forwardingrulesmanager.PortGroupChangeListener; -import org.opendaylight.controller.forwardingrulesmanager.PortGroupConfig; -import org.opendaylight.controller.forwardingrulesmanager.PortGroupProvider; -import org.opendaylight.controller.forwardingrulesmanager.implementation.data.FlowEntryDistributionOrder; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.ActionType; -import org.opendaylight.controller.sal.action.Enqueue; -import org.opendaylight.controller.sal.action.Flood; -import org.opendaylight.controller.sal.action.FloodAll; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.connection.ConnectionLocality; -import org.opendaylight.controller.sal.core.Config; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.IContainer; -import org.opendaylight.controller.sal.core.IContainerLocalListener; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener; -import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.IObjectReader; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.ISwitchManagerAware; -import org.opendaylight.controller.switchmanager.Subnet; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class that manages forwarding rule installation and removal per container of - * the network. It also maintains the central repository of all the forwarding - * rules installed on the network nodes. - */ -public class ForwardingRulesManager implements - IForwardingRulesManager, - PortGroupChangeListener, - IContainerLocalListener, - ISwitchManagerAware, - IConfigurationContainerAware, - IInventoryListener, - IObjectReader, - ICacheUpdateAware, - IFlowProgrammerListener { - - private static final Logger log = LoggerFactory.getLogger(ForwardingRulesManager.class); - private static final Logger logsync = LoggerFactory.getLogger("FRMsync"); - private static final String PORT_REMOVED = "Port removed"; - private static final String NODE_DOWN = "Node is Down"; - private static final String INVALID_FLOW_ENTRY = "Invalid FlowEntry"; - private static final String STATIC_FLOWS_FILE_NAME = "frm_staticflows.conf"; - private static final String PORT_GROUP_FILE_NAME = "portgroup.conf"; - private ConcurrentMap staticFlows; - private ConcurrentMap staticFlowsOrdinal; - private ConcurrentMap portGroupConfigs; - private ConcurrentMap> portGroupData; - private ConcurrentMap TSPolicies; - private IContainerManager containerManager; - private IConfigurationContainerService configurationService; - private boolean inContainerMode; // being used by global instance only - protected boolean stopping; - - /* - * Flow database. It's the software view of what was requested to install - * and what is installed on the switch. It is indexed by the entry itself. - * The entry's hashcode resumes the network node index, the flow's priority - * and the flow's match. The value element is a class which contains the - * flow entry pushed by the applications modules and the respective - * container flow merged version. In absence of container flows, the two - * flow entries are the same. - */ - private ConcurrentMap originalSwView; - private ConcurrentMap installedSwView; - /* - * Per node and per group indexing - */ - private ConcurrentMap> nodeFlows; - private ConcurrentMap> groupFlows; - - /* - * Inactive flow list. This is for the global instance of FRM It will - * contain all the flow entries which were installed on the global container - * when the first container is created. - */ - private ConcurrentMap inactiveFlows; - - private IContainer container; - private Set frmAware = - Collections.synchronizedSet(new HashSet()); - private PortGroupProvider portGroupProvider; - private IFlowProgrammerService programmer; - private IClusterContainerServices clusterContainerService = null; - private ISwitchManager switchManager; - private Thread frmEventHandler; - protected BlockingQueue pendingEvents; - - // Distributes FRM programming in the cluster - private IConnectionManager connectionManager; - - /* - * Name clustered caches used to support FRM entry distribution these are by - * necessity non-transactional as long as need to be able to synchronize - * states also while a transaction is in progress - */ - static final String WORK_ORDER_CACHE = "frm.workOrder"; - static final String WORK_STATUS_CACHE = "frm.workStatus"; - static final String ORIGINAL_SW_VIEW_CACHE = "frm.originalSwView"; - static final String INSTALLED_SW_VIEW_CACHE = "frm.installedSwView"; - - /* - * Data structure responsible for distributing the FlowEntryInstall requests - * in the cluster. The key value is entry that is being either Installed or - * Updated or Delete. The value field is the same of the key value in case - * of Installation or Deletion, it's the new entry in case of Modification, - * this because the clustering caches don't allow null values. - * - * The logic behind this data structure is that the controller that initiate - * the request will place the order here, someone will pick it and then will - * remove from this data structure because is being served. - * - * TODO: We need to have a way to cleanup this data structure if entries are - * not picked by anyone, which is always a case can happen especially on - * Node disconnect cases. - */ - protected ConcurrentMap workOrder; - - /* - * Data structure responsible for retrieving the results of the workOrder - * submitted to the cluster. - * - * The logic behind this data structure is that the controller that has - * executed the order will then place the result in workStatus signaling - * that there was a success or a failure. - * - * TODO: The workStatus entries need to have a lifetime associated in case - * of requestor controller leaving the cluster. - */ - protected ConcurrentMap workStatus; - - /* - * Local Map used to hold the Future which a caller can use to monitor for - * completion - */ - private ConcurrentMap workMonitor = - new ConcurrentHashMap(); - - /* - * Max pool size for the executor - */ - private static final int maxPoolSize = 10; - - /** - * @param e - * Entry being installed/updated/removed - * @param u - * New entry will be placed after the update operation. Valid - * only for UpdateType.CHANGED, null for all the other cases - * @param t - * Type of update - * @return a Future object for monitoring the progress of the result, or - * null in case the processing should take place locally - */ - private FlowEntryDistributionOrderFutureTask distributeWorkOrder(FlowEntryInstall e, FlowEntryInstall u, - UpdateType t) { - // A null entry it's an unexpected condition, anyway it's safe to keep - // the handling local - if (e == null) { - return null; - } - - Node n = e.getNode(); - if (connectionManager.getLocalityStatus(n) == ConnectionLocality.NOT_LOCAL) { - // Create the work order and distribute it - FlowEntryDistributionOrder fe = - new FlowEntryDistributionOrder(e, t, clusterContainerService.getMyAddress()); - // First create the monitor job - FlowEntryDistributionOrderFutureTask ret = new FlowEntryDistributionOrderFutureTask(fe); - logsync.trace("Node {} not local so sending fe {}", n, fe); - workMonitor.put(fe, ret); - if (t.equals(UpdateType.CHANGED)) { - // Then distribute the work - workOrder.put(fe, u); - } else { - // Then distribute the work - workOrder.put(fe, e); - } - logsync.trace("WorkOrder requested"); - // Now create an Handle to monitor the execution of the operation - return ret; - } - - logsync.trace("Node {} could be local. so processing Entry:{} UpdateType:{}", n, e, t); - return null; - } - - /** - * Checks if the FlowEntry targets are valid for this container - * - * @param flowEntry - * The flow entry to test - * @return a Status object representing the result of the validation - */ - private Status validateEntry(FlowEntry flowEntry) { - // Node presence check - Node node = flowEntry.getNode(); - if (!switchManager.getNodes().contains(node)) { - return new Status(StatusCode.BADREQUEST, String.format("Node %s is not present in this container", node)); - } - - // Ports and actions validation check - Flow flow = flowEntry.getFlow(); - Match match = flow.getMatch(); - if (match.isPresent(MatchType.IN_PORT)) { - NodeConnector inputPort = (NodeConnector)match.getField(MatchType.IN_PORT).getValue(); - if (!switchManager.getNodeConnectors(node).contains(inputPort)) { - String msg = String.format("Ingress port %s is not present on this container", inputPort); - return new Status(StatusCode.BADREQUEST, msg); - } - } - for (Action action : flow.getActions()) { - if (action instanceof Flood && !GlobalConstants.DEFAULT.toString().equals(getContainerName())) { - return new Status(StatusCode.BADREQUEST, String.format("Flood is only allowed in default container")); - } - if (action instanceof FloodAll && !GlobalConstants.DEFAULT.toString().equals(getContainerName())) { - return new Status(StatusCode.BADREQUEST, String.format("FloodAll is only allowed in default container")); - } - if (action instanceof Output) { - Output out = (Output)action; - NodeConnector outputPort = out.getPort(); - if (!switchManager.getNodeConnectors(node).contains(outputPort)) { - String msg = String.format("Output port %s is not present on this container", outputPort); - return new Status(StatusCode.BADREQUEST, msg); - } - } - if (action instanceof Enqueue) { - Enqueue out = (Enqueue)action; - NodeConnector outputPort = out.getPort(); - if (!switchManager.getNodeConnectors(node).contains(outputPort)) { - String msg = String.format("Enqueue port %s is not present on this container", outputPort); - return new Status(StatusCode.BADREQUEST, msg); - } - } - } - return new Status(StatusCode.SUCCESS); - } - - /** - * Adds a flow entry onto the network node It runs various validity checks - * and derive the final container flows merged entries that will be - * attempted to be installed - * - * @param flowEntry - * the original flow entry application requested to add - * @param async - * the flag indicating if this is a asynchronous request - * @return the status of this request. In case of asynchronous call, it will - * contain the unique id assigned to this request - */ - private Status addEntry(FlowEntry flowEntry, boolean async) { - - // Sanity Check - if (flowEntry == null || flowEntry.getNode() == null || flowEntry.getFlow() == null) { - String logMsg = INVALID_FLOW_ENTRY + ": {}"; - log.warn(logMsg, flowEntry); - return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY); - } - - // Operational check: input, output and queue ports presence check and - // action validation for this container - Status status = validateEntry(flowEntry); - if (!status.isSuccess()) { - String msg = String.format("%s: %s", INVALID_FLOW_ENTRY, status.getDescription()); - log.warn("{}: {}", msg, flowEntry); - return new Status(StatusCode.NOTACCEPTABLE, msg); - } - - /* - * Redundant Check: Check if the request is a redundant one from the - * same application the flowEntry is equal to an existing one. Given we - * do not have an application signature in the requested FlowEntry yet, - * we are here detecting the above condition by comparing the flow - * names, if set. If they are equal to the installed flow, most likely - * this is a redundant installation request from the same application - * and we can silently return success - * - * TODO: in future a sort of application reference list mechanism will - * be added to the FlowEntry so that exact flow can be used by different - * applications. - */ - FlowEntry present = this.originalSwView.get(flowEntry); - if (present != null) { - boolean sameFlow = present.getFlow().equals(flowEntry.getFlow()); - boolean sameApp = present.getFlowName() != null && present.getFlowName().equals(flowEntry.getFlowName()); - if (sameFlow && sameApp) { - log.trace("Skipping redundant request for flow {} on node {}", flowEntry.getFlowName(), - flowEntry.getNode()); - return new Status(StatusCode.SUCCESS, "Entry is already present"); - } - } - - /* - * Derive the container flow merged entries to install In presence of N - * container flows, we may end up with N different entries to install... - */ - List toInstallList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows()); - - // Container Flow conflict Check - if (toInstallList.isEmpty()) { - String msg = "Flow Entry conflicts with all Container Flows"; - String logMsg = msg + ": {}"; - log.warn(logMsg, flowEntry); - return new Status(StatusCode.CONFLICT, msg); - } - - // Derive the list of entries good to be installed - List toInstallSafe = new ArrayList(); - for (FlowEntryInstall entry : toInstallList) { - // Conflict Check: Verify new entry would not overwrite existing - // ones - if (this.installedSwView.containsKey(entry)) { - log.warn("Operation Rejected: A flow with same match and priority exists on the target node"); - log.trace("Aborting to install {}", entry); - continue; - } - toInstallSafe.add(entry); - } - - // Declare failure if all the container flow merged entries clash with - // existing entries - if (toInstallSafe.size() == 0) { - String msg = "A flow with same match and priority exists on the target node"; - String logMsg = msg + ": {}"; - log.warn(logMsg, flowEntry); - return new Status(StatusCode.CONFLICT, msg); - } - - // Try to install an entry at the time - Status error = new Status(null, null); - Status succeded = null; - boolean oneSucceded = false; - for (FlowEntryInstall installEntry : toInstallSafe) { - - // Install and update database - Status ret = addEntryInternal(installEntry, async); - - if (ret.isSuccess()) { - oneSucceded = true; - /* - * The first successful status response will be returned For the - * asynchronous call, we can discard the container flow - * complication for now and assume we will always deal with one - * flow only per request - */ - succeded = ret; - } else { - error = ret; - log.trace("Failed to install the entry: {}. The failure is: {}", installEntry, ret.getDescription()); - } - } - - return (oneSucceded) ? succeded : error; - } - - /** - * Given a flow entry and the list of container flows, it returns the list - * of container flow merged flow entries good to be installed on this - * container. If the list of container flows is null or empty, the install - * entry list will contain only one entry, the original flow entry. If the - * flow entry is congruent with all the N container flows, then the output - * install entry list will contain N entries. If the output list is empty, - * it means the passed flow entry conflicts with all the container flows. - * - * @param cFlowList - * The list of container flows - * @return the list of container flow merged entries good to be installed on - * this container - */ - private List deriveInstallEntries(FlowEntry request, List cFlowList) { - List toInstallList = new ArrayList(1); - - if (container.getContainerFlows() == null || container.getContainerFlows().isEmpty()) { - // No container flows => entry good to be installed unchanged - toInstallList.add(new FlowEntryInstall(request.clone(), null)); - } else { - // Create the list of entries to be installed. If the flow entry is - // not congruent with any container flow, no install entries will be - // created - for (ContainerFlow cFlow : container.getContainerFlows()) { - if (cFlow.allowsFlow(request.getFlow())) { - toInstallList.add(new FlowEntryInstall(request.clone(), cFlow)); - } - } - } - return toInstallList; - } - - /** - * Modify a flow entry with a new one It runs various validity check and - * derive the final container flows merged flow entries to work with - * - * @param currentFlowEntry - * @param newFlowEntry - * @param async - * the flag indicating if this is a asynchronous request - * @return the status of this request. In case of asynchronous call, it will - * contain the unique id assigned to this request - */ - private Status modifyEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry, boolean async) { - Status retExt; - - // Sanity checks - if (currentFlowEntry == null || currentFlowEntry.getNode() == null || newFlowEntry == null - || newFlowEntry.getNode() == null || newFlowEntry.getFlow() == null) { - String msg = "Modify: " + INVALID_FLOW_ENTRY; - String logMsg = msg + ": {} or {}"; - log.warn(logMsg, currentFlowEntry, newFlowEntry); - return new Status(StatusCode.NOTACCEPTABLE, msg); - } - if (!currentFlowEntry.getNode().equals(newFlowEntry.getNode()) - || !currentFlowEntry.getFlowName().equals(newFlowEntry.getFlowName())) { - String msg = "Modify: Incompatible Flow Entries"; - String logMsg = msg + ": {} and {}"; - log.warn(logMsg, currentFlowEntry, newFlowEntry); - return new Status(StatusCode.NOTACCEPTABLE, msg); - } - - // Equality Check - if (currentFlowEntry.getFlow().equals(newFlowEntry.getFlow())) { - String msg = "Modify skipped as flows are the same"; - String logMsg = msg + ": {} and {}"; - log.debug(logMsg, currentFlowEntry, newFlowEntry); - return new Status(StatusCode.SUCCESS, msg); - } - - // Operational check: input, output and queue ports presence check and - // action validation for this container - Status status = validateEntry(newFlowEntry); - if (!status.isSuccess()) { - String msg = String.format("Modify: %s: %s", INVALID_FLOW_ENTRY, status.getDescription()); - log.warn("{}: {}", msg, newFlowEntry); - return new Status(StatusCode.NOTACCEPTABLE, msg); - } - - /* - * Conflict Check: Verify the new entry would not conflict with an - * existing one. This is a loose check on the previous original flow - * entry requests. No check on the container flow merged flow entries - * (if any) yet - */ - FlowEntry sameMatchOriginalEntry = originalSwView.get(newFlowEntry); - if (sameMatchOriginalEntry != null && !sameMatchOriginalEntry.equals(currentFlowEntry)) { - String msg = "Operation Rejected: Another flow with same match and priority exists on the target node"; - String logMsg = msg + ": {}"; - log.warn(logMsg, currentFlowEntry); - return new Status(StatusCode.CONFLICT, msg); - } - - // Derive the installed and toInstall entries - List installedList = deriveInstallEntries(currentFlowEntry.clone(), - container.getContainerFlows()); - List toInstallList = deriveInstallEntries(newFlowEntry.clone(), container.getContainerFlows()); - - if (toInstallList.isEmpty()) { - String msg = "Modify Operation Rejected: The new entry conflicts with all the container flows"; - String logMsg = msg + ": {}"; - log.warn(logMsg, newFlowEntry); - log.warn(msg); - return new Status(StatusCode.CONFLICT, msg); - } - - /* - * If the two list sizes differ, it means the new flow entry does not - * satisfy the same number of container flows the current entry does. - * This is only possible when the new entry and current entry have - * different match. In this scenario the modification would ultimately - * be handled as a remove and add operations in the protocol plugin. - * - * Also, if any of the new flow entries would clash with an existing - * one, we cannot proceed with the modify operation, because it would - * fail for some entries and leave stale entries on the network node. - * Modify path can be taken only if it can be performed completely, for - * all entries. - * - * So, for the above two cases, to simplify, let's decouple the modify - * in: 1) remove current entries 2) install new entries - */ - Status succeeded = null; - boolean decouple = false; - if (installedList.size() != toInstallList.size()) { - log.trace("Modify: New flow entry does not satisfy the same " - + "number of container flows as the original entry does"); - decouple = true; - } - List toInstallSafe = new ArrayList(); - for (FlowEntryInstall installEntry : toInstallList) { - /* - * Conflict Check: Verify the new entry would not overwrite another - * existing one - */ - FlowEntryInstall sameMatchEntry = installedSwView.get(installEntry); - if (sameMatchEntry != null && !sameMatchEntry.getOriginal().equals(currentFlowEntry)) { - log.trace("Modify: new container flow merged flow entry clashes with existing flow"); - decouple = true; - } else { - toInstallSafe.add(installEntry); - } - } - - if (decouple) { - // Remove current entries - for (FlowEntryInstall currEntry : installedList) { - this.removeEntryInternal(currEntry, async); - } - // Install new entries - for (FlowEntryInstall newEntry : toInstallSafe) { - succeeded = this.addEntryInternal(newEntry, async); - } - } else { - /* - * The two list have the same size and the entries to install do not - * clash with any existing flow on the network node. We assume here - * (and might be wrong) that the same container flows that were - * satisfied by the current entries are the same that are satisfied - * by the new entries. Let's take the risk for now. - * - * Note: modification has to be complete. If any entry modification - * fails, we need to stop, restore the already modified entries, and - * declare failure. - */ - Status retModify = null; - int i = 0; - int size = toInstallList.size(); - while (i < size) { - // Modify and update database - retModify = modifyEntryInternal(installedList.get(i), toInstallList.get(i), async); - if (retModify.isSuccess()) { - i++; - } else { - break; - } - } - // Check if uncompleted modify - if (i < size) { - log.warn("Unable to perform a complete modify for all the container flows merged entries"); - // Restore original entries - int j = 0; - while (j < i) { - log.info("Attempting to restore initial entries"); - retExt = modifyEntryInternal(toInstallList.get(i), installedList.get(i), async); - if (retExt.isSuccess()) { - j++; - } else { - break; - } - } - // Fatal error, recovery failed - if (j < i) { - String msg = "Flow recovery failed ! Unrecoverable Error"; - log.error(msg); - return new Status(StatusCode.INTERNALERROR, msg); - } - } - succeeded = retModify; - } - /* - * The first successful status response will be returned. For the - * asynchronous call, we can discard the container flow complication for - * now and assume we will always deal with one flow only per request - */ - return succeeded; - } - - /** - * This is the function that modifies the final container flows merged - * entries on the network node and update the database. It expects that all - * the validity checks are passed. - * This function is supposed to be called only on the controller on which - * the IFRM call is executed. - * - * @param currentEntries - * @param newEntries - * @param async - * the flag indicating if this is a asynchronous request - * @return the status of this request. In case of asynchronous call, it will - * contain the unique id assigned to this request - */ - private Status modifyEntryInternal(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) { - Status status = new Status(StatusCode.UNDEFINED); - FlowEntryDistributionOrderFutureTask futureStatus = - distributeWorkOrder(currentEntries, newEntries, UpdateType.CHANGED); - if (futureStatus != null) { - try { - status = futureStatus.get(); - if (status.getCode() - .equals(StatusCode.TIMEOUT)) { - // A timeout happened, lets cleanup the workMonitor - workMonitor.remove(futureStatus.getOrder()); - } - } catch (InterruptedException e) { - log.error("", e); - } catch (ExecutionException e) { - log.error("", e); - } - } else { - // Modify the flow on the network node - status = modifyEntryInHw(currentEntries, newEntries, async); - } - - if (!status.isSuccess()) { - log.trace("{} SDN Plugin failed to program the flow: {}. The failure is: {}", - (futureStatus != null) ? "Remote" : "Local", newEntries.getInstall(), status.getDescription()); - return status; - } - - log.trace("Modified {} => {}", currentEntries.getInstall(), newEntries.getInstall()); - - // Update DB - newEntries.setRequestId(status.getRequestId()); - updateSwViews(currentEntries, false); - updateSwViews(newEntries, true); - - return status; - } - - private Status modifyEntryInHw(FlowEntryInstall currentEntries, FlowEntryInstall newEntries, boolean async) { - return async ? programmer.modifyFlowAsync(currentEntries.getNode(), currentEntries.getInstall().getFlow(), - newEntries.getInstall().getFlow()) : programmer.modifyFlow(currentEntries.getNode(), currentEntries - .getInstall().getFlow(), newEntries.getInstall().getFlow()); - } - - /** - * Remove a flow entry. If the entry is not present in the software view - * (entry or node not present), it return successfully - * - * @param flowEntry - * the flow entry to remove - * @param async - * the flag indicating if this is a asynchronous request - * @return the status of this request. In case of asynchronous call, it will - * contain the unique id assigned to this request - */ - private Status removeEntry(FlowEntry flowEntry, boolean async) { - Status error = new Status(null, null); - - // Sanity Check - if (flowEntry == null || flowEntry.getNode() == null || flowEntry.getFlow() == null) { - String logMsg = INVALID_FLOW_ENTRY + ": {}"; - log.warn(logMsg, flowEntry); - return new Status(StatusCode.NOTACCEPTABLE, INVALID_FLOW_ENTRY); - } - - // Derive the container flows merged installed entries - List installedList = deriveInstallEntries(flowEntry.clone(), container.getContainerFlows()); - - Status succeeded = null; - boolean atLeastOneRemoved = false; - for (FlowEntryInstall entry : installedList) { - if (!installedSwView.containsKey(entry)) { - String logMsg = "Removal skipped (not present in software view) for flow entry: {}"; - log.debug(logMsg, flowEntry); - if (installedList.size() == 1) { - // If we had only one entry to remove, we are done - return new Status(StatusCode.SUCCESS); - } else { - continue; - } - } - - // Remove and update DB - Status ret = removeEntryInternal(entry, async); - - if (!ret.isSuccess()) { - error = ret; - log.trace("Failed to remove the entry: {}. The failure is: {}", entry.getInstall(), ret.getDescription()); - if (installedList.size() == 1) { - // If we had only one entry to remove, this is fatal failure - return error; - } - } else { - succeeded = ret; - atLeastOneRemoved = true; - } - } - - /* - * No worries if full removal failed. Consistency checker will take care - * of removing the stale entries later, or adjusting the software - * database if not in sync with hardware - */ - return (atLeastOneRemoved) ? succeeded : error; - } - - /** - * This is the function that removes the final container flows merged entry - * from the network node and update the database. It expects that all the - * validity checks are passed - * This function is supposed to be called only on the controller on which - * the IFRM call is executed. - * - * @param entry - * the flow entry to remove - * @param async - * the flag indicating if this is a asynchronous request - * @return the status of this request. In case of asynchronous call, it will - * contain the unique id assigned to this request - */ - private Status removeEntryInternal(FlowEntryInstall entry, boolean async) { - Status status = new Status(StatusCode.UNDEFINED); - FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.REMOVED); - if (futureStatus != null) { - try { - status = futureStatus.get(); - if (status.getCode().equals(StatusCode.TIMEOUT)) { - // A timeout happened, lets cleanup the workMonitor - workMonitor.remove(futureStatus.getOrder()); - } - } catch (InterruptedException e) { - log.error("", e); - } catch (ExecutionException e) { - log.error("", e); - } - } else { - // Mark the entry to be deleted (for CC just in case we fail) - entry.toBeDeleted(); - - // Remove from node - status = removeEntryInHw(entry, async); - } - - if (!status.isSuccess()) { - log.trace("{} SDN Plugin failed to remove the flow: {}. The failure is: {}", - (futureStatus != null) ? "Remote" : "Local", entry.getInstall(), status.getDescription()); - return status; - } - - log.trace("Removed {}", entry.getInstall()); - - // Update DB - updateSwViews(entry, false); - - return status; - } - - private Status removeEntryInHw(FlowEntryInstall entry, boolean async) { - return async ? programmer.removeFlowAsync(entry.getNode(), entry.getInstall().getFlow()) : programmer - .removeFlow(entry.getNode(), entry.getInstall().getFlow()); - } - - /** - * This is the function that installs the final container flow merged entry - * on the network node and updates the database. It expects that all the - * validity and conflict checks are passed. That means it does not check - * whether this flow would conflict or overwrite an existing one. - * This function is supposed to be called only on the controller on which - * the IFRM call is executed. - * - * @param entry - * the flow entry to install - * @param async - * the flag indicating if this is a asynchronous request - * @return the status of this request. In case of asynchronous call, it will - * contain the unique id assigned to this request - */ - private Status addEntryInternal(FlowEntryInstall entry, boolean async) { - Status status = new Status(StatusCode.UNDEFINED); - FlowEntryDistributionOrderFutureTask futureStatus = distributeWorkOrder(entry, null, UpdateType.ADDED); - if (futureStatus != null) { - try { - status = futureStatus.get(); - if (status.getCode().equals(StatusCode.TIMEOUT)) { - // A timeout happened, lets cleanup the workMonitor - workMonitor.remove(futureStatus.getOrder()); - } - } catch (InterruptedException e) { - log.error("", e); - } catch (ExecutionException e) { - log.error("", e); - } - } else { - status = addEntryInHw(entry, async); - } - - if (!status.isSuccess()) { - log.trace("{} SDN Plugin failed to program the flow: {}. The failure is: {}", - (futureStatus != null) ? "Remote" : "Local", entry.getInstall(), status.getDescription()); - return status; - } - - log.trace("Added {}", entry.getInstall()); - - // Update DB - entry.setRequestId(status.getRequestId()); - updateSwViews(entry, true); - - return status; - } - - private Status addEntryInHw(FlowEntryInstall entry, boolean async) { - // Install the flow on the network node - return async ? programmer.addFlowAsync(entry.getNode(), entry.getInstall().getFlow()) : programmer.addFlow( - entry.getNode(), entry.getInstall().getFlow()); - } - - /** - * Returns true if the flow conflicts with all the container's flows. This - * means that if the function returns true, the passed flow entry is - * congruent with at least one container flow, hence it is good to be - * installed on this container. - * - * @param flowEntry - * @return true if flow conflicts with all the container flows, false - * otherwise - */ - private boolean entryConflictsWithContainerFlows(FlowEntry flowEntry) { - List cFlowList = container.getContainerFlows(); - - // Validity check and avoid unnecessary computation - // Also takes care of default container where no container flows are - // present - if (cFlowList == null || cFlowList.isEmpty()) { - return false; - } - - for (ContainerFlow cFlow : cFlowList) { - if (cFlow.allowsFlow(flowEntry.getFlow())) { - // Entry is allowed by at least one container flow: good to go - return false; - } - } - return true; - } - - private ConcurrentMap.Entry getStaticFlowEntry(String name, Node node) { - for (ConcurrentMap.Entry flowEntry : staticFlows.entrySet()) { - FlowConfig flowConfig = flowEntry.getValue(); - if (flowConfig.isByNameAndNodeIdEqual(name, node)) { - return flowEntry; - } - } - return null; - } - - private void updateIndexDatabase(FlowEntryInstall entry, boolean add) { - // Update node indexed flow database - updateNodeFlowsDB(entry, add); - - // Update group indexed flow database - updateGroupFlowsDB(entry, add); - } - - /* - * Update the node mapped flows database - */ - private void updateSwViews(FlowEntryInstall flowEntries, boolean add) { - if (add) { - originalSwView.put(flowEntries.getOriginal(), flowEntries.getOriginal()); - installedSwView.put(flowEntries, flowEntries); - } else { - originalSwView.remove(flowEntries.getOriginal()); - installedSwView.remove(flowEntries); - } - } - - /* - * Update the node mapped flows database - */ - private void updateNodeFlowsDB(FlowEntryInstall flowEntries, boolean add) { - Node node = flowEntries.getNode(); - - List nodeIndeces = this.nodeFlows.get(node); - if (nodeIndeces == null) { - if (!add) { - return; - } else { - nodeIndeces = new ArrayList(); - } - } - - if (add) { - // there may be an already existing entry. - // remove it before adding the new one. - // This is necessary since we have observed that in some cases - // Infinispan does aggregation for operations (eg:- remove and then put a different value) - // related to the same key within the same transaction. - // Need this defensive code as the new FlowEntryInstall may be different - // than the old one even though the equals method returns true. This is because - // the equals method does not take into account the action list. - if(nodeIndeces.contains(flowEntries)) { - nodeIndeces.remove(flowEntries); - } - nodeIndeces.add(flowEntries); - } else { - nodeIndeces.remove(flowEntries); - } - - // Update cache across cluster - if (nodeIndeces.isEmpty()) { - this.nodeFlows.remove(node); - } else { - this.nodeFlows.put(node, nodeIndeces); - } - } - - /* - * Update the group name mapped flows database - */ - private void updateGroupFlowsDB(FlowEntryInstall flowEntries, boolean add) { - String groupName = flowEntries.getGroupName(); - - // Flow may not be part of a group - if (groupName == null) { - return; - } - - List indices = this.groupFlows.get(groupName); - if (indices == null) { - if (!add) { - return; - } else { - indices = new ArrayList(); - } - } - - if (add) { - // same comments in the similar code section in - // updateNodeFlowsDB method apply here too - if(indices.contains(flowEntries)) { - indices.remove(flowEntries); - } - indices.add(flowEntries); - } else { - indices.remove(flowEntries); - } - - // Update cache across cluster - if (indices.isEmpty()) { - this.groupFlows.remove(groupName); - } else { - this.groupFlows.put(groupName, indices); - } - } - - /** - * Remove a flow entry that has been added previously First checks if the - * entry is effectively present in the local database - */ - @SuppressWarnings("unused") - private Status removeEntry(Node node, String flowName) { - FlowEntryInstall target = null; - - // Find in database - for (FlowEntryInstall entry : installedSwView.values()) { - if (entry.equalsByNodeAndName(node, flowName)) { - target = entry; - break; - } - } - - // If it is not there, stop any further processing - if (target == null) { - return new Status(StatusCode.SUCCESS, "Entry is not present"); - } - - // Remove from node - Status status = programmer.removeFlow(target.getNode(), target.getInstall().getFlow()); - - // Update DB - if (status.isSuccess()) { - updateSwViews(target, false); - } else { - // log the error - log.trace("SDN Plugin failed to remove the flow: {}. The failure is: {}", target.getInstall(), - status.getDescription()); - } - - return status; - } - - @Override - public Status installFlowEntry(FlowEntry flowEntry) { - Status status; - if (isContainerModeAllowed(flowEntry)) { - status = addEntry(flowEntry, false); - } else { - String msg = "Controller in container mode: Install Refused"; - String logMsg = msg + ": {}"; - status = new Status(StatusCode.NOTACCEPTABLE, msg); - log.warn(logMsg, flowEntry); - } - return status; - } - - @Override - public Status installFlowEntryAsync(FlowEntry flowEntry) { - Status status; - if (isContainerModeAllowed(flowEntry)) { - status = addEntry(flowEntry, true); - } else { - String msg = "Controller in container mode: Install Refused"; - status = new Status(StatusCode.NOTACCEPTABLE, msg); - log.warn(msg); - } - return status; - } - - @Override - public Status uninstallFlowEntry(FlowEntry flowEntry) { - Status status; - if (isContainerModeAllowed(flowEntry)) { - status = removeEntry(flowEntry, false); - } else { - String msg = "Controller in container mode: Uninstall Refused"; - String logMsg = msg + ": {}"; - status = new Status(StatusCode.NOTACCEPTABLE, msg); - log.warn(logMsg, flowEntry); - } - return status; - } - - @Override - public Status uninstallFlowEntryAsync(FlowEntry flowEntry) { - Status status; - if (isContainerModeAllowed(flowEntry)) { - status = removeEntry(flowEntry, true); - } else { - String msg = "Controller in container mode: Uninstall Refused"; - status = new Status(StatusCode.NOTACCEPTABLE, msg); - log.warn(msg); - } - return status; - } - - @Override - public Status modifyFlowEntry(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) { - Status status = null; - if (isContainerModeAllowed(currentFlowEntry)) { - status = modifyEntry(currentFlowEntry, newFlowEntry, false); - } else { - String msg = "Controller in container mode: Modify Refused"; - String logMsg = msg + ": {}"; - status = new Status(StatusCode.NOTACCEPTABLE, msg); - log.warn(logMsg, newFlowEntry); - } - return status; - } - - @Override - public Status modifyFlowEntryAsync(FlowEntry currentFlowEntry, FlowEntry newFlowEntry) { - Status status = null; - if (isContainerModeAllowed(currentFlowEntry)) { - status = modifyEntry(currentFlowEntry, newFlowEntry, true); - } else { - String msg = "Controller in container mode: Modify Refused"; - status = new Status(StatusCode.NOTACCEPTABLE, msg); - log.warn(msg); - } - return status; - } - - /** - * Returns whether the specified flow entry is allowed to be - * installed/removed/modified based on the current container mode status. - * This call always returns true in the container instance of forwarding - * rules manager. It is meant for the global instance only (default - * container) of forwarding rules manager. Idea is that for assuring - * container isolation of traffic, flow installation in default container is - * blocked when in container mode (containers are present). The only flows - * that are allowed in container mode in the default container are the - * proactive flows, the ones automatically installed on the network node - * which forwarding mode has been configured to "proactive". These flows are - * needed by controller to discover the nodes topology and to discover the - * attached hosts for some SDN switches. - * - * @param flowEntry - * The flow entry to be installed/removed/modified - * @return true if not in container mode or if flowEntry is internally - * generated - */ - private boolean isContainerModeAllowed(FlowEntry flowEntry) { - return (!inContainerMode) ? true : flowEntry.isInternal(); - } - - @Override - public Status modifyOrAddFlowEntry(FlowEntry newFlowEntry) { - /* - * Run a check on the original entries to decide whether to go with a - * add or modify method. A loose check means only check against the - * original flow entry requests and not against the installed flow - * entries which are the result of the original entry merged with the - * container flow(s) (if any). The modifyFlowEntry method in presence of - * conflicts with the Container flows (if any) would revert back to a - * delete + add pattern - */ - FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry); - - if (currentFlowEntry != null) { - return modifyFlowEntry(currentFlowEntry, newFlowEntry); - } else { - return installFlowEntry(newFlowEntry); - } - } - - @Override - public Status modifyOrAddFlowEntryAsync(FlowEntry newFlowEntry) { - /* - * Run a check on the original entries to decide whether to go with a - * add or modify method. A loose check means only check against the - * original flow entry requests and not against the installed flow - * entries which are the result of the original entry merged with the - * container flow(s) (if any). The modifyFlowEntry method in presence of - * conflicts with the Container flows (if any) would revert back to a - * delete + add pattern - */ - FlowEntry currentFlowEntry = originalSwView.get(newFlowEntry); - - if (currentFlowEntry != null) { - return modifyFlowEntryAsync(currentFlowEntry, newFlowEntry); - } else { - return installFlowEntryAsync(newFlowEntry); - } - } - - @Override - public Status uninstallFlowEntryGroup(String groupName) { - if (groupName == null || groupName.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid group name"); - } - if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) { - return new Status(StatusCode.BADREQUEST, "Internal static flows group cannot be deleted through this api"); - } - if (inContainerMode) { - String msg = "Controller in container mode: Group Uninstall Refused"; - String logMsg = msg + ": {}"; - log.warn(logMsg, groupName); - return new Status(StatusCode.NOTACCEPTABLE, msg); - } - int toBeRemoved = 0; - String error = ""; - if (groupFlows.containsKey(groupName)) { - List list = new ArrayList(groupFlows.get(groupName)); - toBeRemoved = list.size(); - for (FlowEntryInstall entry : list) { - // since this is the entry that was stored in groupFlows - // it is already validated and merged - // so can call removeEntryInternal directly - Status status = this.removeEntryInternal(entry, false); - if (status.isSuccess()) { - toBeRemoved -= 1; - } else { - error = status.getDescription(); - } - } - } - return (toBeRemoved == 0) ? new Status(StatusCode.SUCCESS) : new Status(StatusCode.INTERNALERROR, - "Not all the flows were removed: " + error); - } - - @Override - public Status uninstallFlowEntryGroupAsync(String groupName) { - if (groupName == null || groupName.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid group name"); - } - if (groupName.equals(FlowConfig.INTERNALSTATICFLOWGROUP)) { - return new Status(StatusCode.BADREQUEST, "Static flows group cannot be deleted through this api"); - } - if (inContainerMode) { - String msg = "Controller in container mode: Group Uninstall Refused"; - String logMsg = msg + ": {}"; - log.warn(logMsg, groupName); - return new Status(StatusCode.NOTACCEPTABLE, msg); - } - if (groupFlows.containsKey(groupName)) { - List list = new ArrayList(groupFlows.get(groupName)); - for (FlowEntryInstall entry : list) { - this.removeEntry(entry.getOriginal(), true); - } - } - return new Status(StatusCode.SUCCESS); - } - - @Override - public boolean checkFlowEntryConflict(FlowEntry flowEntry) { - return entryConflictsWithContainerFlows(flowEntry); - } - - /** - * Updates all installed flows because the container flow got updated This - * is obtained in two phases on per node basis: 1) Uninstall of all flows 2) - * Reinstall of all flows This is needed because a new container flows - * merged flow may conflict with an existing old container flows merged flow - * on the network node - */ - protected void updateFlowsContainerFlow() { - Set toReInstall = new HashSet(); - // First remove all installed entries - for (ConcurrentMap.Entry entry : installedSwView.entrySet()) { - FlowEntryInstall current = entry.getValue(); - // Store the original entry - toReInstall.add(current.getOriginal()); - // Remove the old couples. No validity checks to be run, use the - // internal remove - this.removeEntryInternal(current, false); - } - // Then reinstall the original entries - for (FlowEntry entry : toReInstall) { - // Reinstall the original flow entries, via the regular path: new - // cFlow merge + validations - this.installFlowEntry(entry); - } - } - - private void nonClusterObjectCreate() { - originalSwView = new ConcurrentHashMap(); - installedSwView = new ConcurrentHashMap(); - TSPolicies = new ConcurrentHashMap(); - staticFlowsOrdinal = new ConcurrentHashMap(); - portGroupConfigs = new ConcurrentHashMap(); - portGroupData = new ConcurrentHashMap>(); - staticFlows = new ConcurrentHashMap(); - inactiveFlows = new ConcurrentHashMap(); - } - - @Override - public void setTSPolicyData(String policyname, Object o, boolean add) { - - if (add) { - /* Check if this policy already exists */ - if (!(TSPolicies.containsKey(policyname))) { - TSPolicies.put(policyname, o); - } - } else { - TSPolicies.remove(policyname); - } - if (frmAware != null) { - synchronized (frmAware) { - for (IForwardingRulesManagerAware frma : frmAware) { - try { - frma.policyUpdate(policyname, add); - } catch (Exception e) { - log.warn("Exception on callback", e); - } - } - } - } - } - - @Override - public Map getTSPolicyData() { - return TSPolicies; - } - - @Override - public Object getTSPolicyData(String policyName) { - if (TSPolicies.containsKey(policyName)) { - return TSPolicies.get(policyName); - } else { - return null; - } - } - - @Override - public List getFlowEntriesForGroup(String policyName) { - List list = new ArrayList(); - if (policyName != null && !policyName.trim().isEmpty()) { - for (Map.Entry entry : this.originalSwView.entrySet()) { - if (policyName.equals(entry.getKey().getGroupName())) { - list.add(entry.getValue().clone()); - } - } - } - return list; - } - - @Override - public List getInstalledFlowEntriesForGroup(String policyName) { - List list = new ArrayList(); - if (policyName != null && !policyName.trim().isEmpty()) { - for (Map.Entry entry : this.installedSwView.entrySet()) { - if (policyName.equals(entry.getKey().getGroupName())) { - list.add(entry.getValue().getInstall().clone()); - } - } - } - return list; - } - - @Override - public void addOutputPort(Node node, String flowName, List portList) { - - for (FlowEntryInstall flow : this.nodeFlows.get(node)) { - if (flow.getFlowName().equals(flowName)) { - FlowEntry currentFlowEntry = flow.getOriginal(); - FlowEntry newFlowEntry = currentFlowEntry.clone(); - for (NodeConnector dstPort : portList) { - newFlowEntry.getFlow().addAction(new Output(dstPort)); - } - Status error = modifyEntry(currentFlowEntry, newFlowEntry, false); - if (error.isSuccess()) { - log.trace("Ports {} added to FlowEntry {}", portList, flowName); - } else { - log.warn("Failed to add ports {} to Flow entry {}. The failure is: {}", portList, - currentFlowEntry.toString(), error.getDescription()); - } - return; - } - } - log.warn("Failed to add ports to Flow {} on Node {}: Entry Not Found", flowName, node); - } - - @Override - public void removeOutputPort(Node node, String flowName, List portList) { - for (FlowEntryInstall index : this.nodeFlows.get(node)) { - FlowEntryInstall flow = this.installedSwView.get(index); - if (flow.getFlowName().equals(flowName)) { - FlowEntry currentFlowEntry = flow.getOriginal(); - FlowEntry newFlowEntry = currentFlowEntry.clone(); - for (NodeConnector dstPort : portList) { - Action action = new Output(dstPort); - newFlowEntry.getFlow().removeAction(action); - } - Status status = modifyEntry(currentFlowEntry, newFlowEntry, false); - if (status.isSuccess()) { - log.trace("Ports {} removed from FlowEntry {}", portList, flowName); - } else { - log.warn("Failed to remove ports {} from Flow entry {}. The failure is: {}", portList, - currentFlowEntry.toString(), status.getDescription()); - } - return; - } - } - log.warn("Failed to remove ports from Flow {} on Node {}: Entry Not Found", flowName, node); - } - - /* - * This function assumes the target flow has only one output port - */ - @Override - public void replaceOutputPort(Node node, String flowName, NodeConnector outPort) { - FlowEntry currentFlowEntry = null; - FlowEntry newFlowEntry = null; - - // Find the flow - for (FlowEntryInstall index : this.nodeFlows.get(node)) { - FlowEntryInstall flow = this.installedSwView.get(index); - if (flow.getFlowName().equals(flowName)) { - currentFlowEntry = flow.getOriginal(); - break; - } - } - if (currentFlowEntry == null) { - log.warn("Failed to replace output port for flow {} on node {}: Entry Not Found", flowName, node); - return; - } - - // Create a flow copy with the new output port - newFlowEntry = currentFlowEntry.clone(); - Action target = null; - for (Action action : newFlowEntry.getFlow().getActions()) { - if (action.getType() == ActionType.OUTPUT) { - target = action; - break; - } - } - newFlowEntry.getFlow().removeAction(target); - newFlowEntry.getFlow().addAction(new Output(outPort)); - - // Modify on network node - Status status = modifyEntry(currentFlowEntry, newFlowEntry, false); - - if (status.isSuccess()) { - log.trace("Output port replaced with {} for flow {} on node {}", outPort, flowName, node); - } else { - log.warn("Failed to replace output port for flow {} on node {}. The failure is: {}", flowName, node, - status.getDescription()); - } - return; - } - - @Override - public NodeConnector getOutputPort(Node node, String flowName) { - for (FlowEntryInstall index : this.nodeFlows.get(node)) { - FlowEntryInstall flow = this.installedSwView.get(index); - if (flow.getFlowName().equals(flowName)) { - for (Action action : flow.getOriginal().getFlow().getActions()) { - if (action.getType() == ActionType.OUTPUT) { - return ((Output) action).getPort(); - } - } - } - } - return null; - } - - private void cacheStartup() { - allocateCaches(); - retrieveCaches(); - } - - private void allocateCaches() { - if (this.clusterContainerService == null) { - log.warn("Un-initialized clusterContainerService, can't create cache"); - return; - } - - log.debug("Allocating caches for Container {}", container.getName()); - - try { - clusterContainerService.createCache(ORIGINAL_SW_VIEW_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterContainerService.createCache(INSTALLED_SW_VIEW_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterContainerService.createCache("frm.inactiveFlows", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterContainerService.createCache("frm.staticFlows", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterContainerService.createCache("frm.staticFlowsOrdinal", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterContainerService.createCache("frm.portGroupConfigs", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterContainerService.createCache("frm.portGroupData", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterContainerService.createCache("frm.TSPolicies", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterContainerService.createCache(WORK_STATUS_CACHE, - EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC)); - - clusterContainerService.createCache(WORK_ORDER_CACHE, - EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC)); - - } catch (CacheConfigException cce) { - log.error("CacheConfigException"); - } catch (CacheExistException cce) { - log.error("CacheExistException"); - } - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - ConcurrentMap map; - - if (this.clusterContainerService == null) { - log.warn("un-initialized clusterContainerService, can't retrieve cache"); - nonClusterObjectCreate(); - return; - } - - log.debug("Retrieving Caches for Container {}", container.getName()); - - map = clusterContainerService.getCache(ORIGINAL_SW_VIEW_CACHE); - if (map != null) { - originalSwView = (ConcurrentMap) map; - } else { - log.error("Retrieval of frm.originalSwView cache failed for Container {}", container.getName()); - } - - map = clusterContainerService.getCache(INSTALLED_SW_VIEW_CACHE); - if (map != null) { - installedSwView = (ConcurrentMap) map; - } else { - log.error("Retrieval of frm.installedSwView cache failed for Container {}", container.getName()); - } - - map = clusterContainerService.getCache("frm.inactiveFlows"); - if (map != null) { - inactiveFlows = (ConcurrentMap) map; - } else { - log.error("Retrieval of frm.inactiveFlows cache failed for Container {}", container.getName()); - } - - map = clusterContainerService.getCache("frm.staticFlows"); - if (map != null) { - staticFlows = (ConcurrentMap) map; - } else { - log.error("Retrieval of frm.staticFlows cache failed for Container {}", container.getName()); - } - - map = clusterContainerService.getCache("frm.staticFlowsOrdinal"); - if (map != null) { - staticFlowsOrdinal = (ConcurrentMap) map; - } else { - log.error("Retrieval of frm.staticFlowsOrdinal cache failed for Container {}", container.getName()); - } - - map = clusterContainerService.getCache("frm.portGroupConfigs"); - if (map != null) { - portGroupConfigs = (ConcurrentMap) map; - } else { - log.error("Retrieval of frm.portGroupConfigs cache failed for Container {}", container.getName()); - } - - map = clusterContainerService.getCache("frm.portGroupData"); - if (map != null) { - portGroupData = (ConcurrentMap>) map; - } else { - log.error("Retrieval of frm.portGroupData allocation failed for Container {}", container.getName()); - } - - map = clusterContainerService.getCache("frm.TSPolicies"); - if (map != null) { - TSPolicies = (ConcurrentMap) map; - } else { - log.error("Retrieval of frm.TSPolicies cache failed for Container {}", container.getName()); - } - - map = clusterContainerService.getCache(WORK_ORDER_CACHE); - if (map != null) { - workOrder = (ConcurrentMap) map; - } else { - log.error("Retrieval of " + WORK_ORDER_CACHE + " cache failed for Container {}", container.getName()); - } - - map = clusterContainerService.getCache(WORK_STATUS_CACHE); - if (map != null) { - workStatus = (ConcurrentMap) map; - } else { - log.error("Retrieval of " + WORK_STATUS_CACHE + " cache failed for Container {}", container.getName()); - } - } - - private boolean flowConfigExists(FlowConfig config) { - // Flow name has to be unique on per node id basis - for (ConcurrentMap.Entry entry : staticFlows.entrySet()) { - if (entry.getValue().isByNameAndNodeIdEqual(config)) { - return true; - } - } - return false; - } - - @Override - public Status addStaticFlow(FlowConfig config) { - return addStaticFlow(config, false); - } - - private Status addStaticFlow(FlowConfig config, boolean async) { - // Configuration object validation - Status status = config.validate(); - if (!status.isSuccess()) { - log.warn("Invalid Configuration for flow {}. The failure is {}", config, status.getDescription()); - String error = "Invalid Configuration (" + status.getDescription() + ")"; - config.setStatus(error); - return new Status(StatusCode.BADREQUEST, error); - } - return addStaticFlowInternal(config, async, false); - } - - - @Override - public Status addStaticFlowAsync(FlowConfig config) { - return addStaticFlow(config, true); - } - - /** - * Private method to add a static flow configuration which does not run any - * validation on the passed FlowConfig object. If restore is set to true, - * configuration is stored in configuration database regardless the - * installation on the network node was successful. This is useful at boot - * when static flows are present in startup configuration and are read - * before the switches connects. - * - * @param config - * The static flow configuration - * @param restore - * if true, the configuration is stored regardless the - * installation on the network node was successful - * @return The status of this request - */ - private Status addStaticFlowInternal(FlowConfig config, boolean async, boolean restore) { - boolean multipleFlowPush = false; - String error; - Status status; - config.setStatus(StatusCode.SUCCESS.toString()); - - // Presence check - if (flowConfigExists(config)) { - error = "Entry with this name on specified switch already exists"; - log.warn("Entry with this name on specified switch already exists: {}", config); - config.setStatus(error); - return new Status(StatusCode.CONFLICT, error); - } - - if ((config.getIngressPort() == null) && config.getPortGroup() != null) { - for (String portGroupName : portGroupConfigs.keySet()) { - if (portGroupName.equalsIgnoreCase(config.getPortGroup())) { - multipleFlowPush = true; - break; - } - } - if (!multipleFlowPush) { - log.warn("Invalid Configuration(Invalid PortGroup Name) for flow {}", config); - error = "Invalid Configuration (Invalid PortGroup Name)"; - config.setStatus(error); - return new Status(StatusCode.BADREQUEST, error); - } - } - - /* - * If requested program the entry in hardware first before updating the - * StaticFlow DB - */ - if (!multipleFlowPush) { - // Program hw - if (config.installInHw()) { - FlowEntry entry = config.getFlowEntry(); - status = async ? this.installFlowEntryAsync(entry) : this.installFlowEntry(entry); - if (!status.isSuccess()) { - config.setStatus(status.getDescription()); - if (!restore) { - return status; - } - } - } - } - - /* - * When the control reaches this point, either of the following - * conditions is true 1. This is a single entry configuration (non - * PortGroup) and the hardware installation is successful 2. This is a - * multiple entry configuration (PortGroup) and hardware installation is - * NOT done directly on this event. 3. The User prefers to retain the - * configuration in Controller and skip hardware installation. - * - * Hence it is safe to update the StaticFlow DB at this point. - * - * Note : For the case of PortGrouping, it is essential to have this DB - * populated before the PortGroupListeners can query for the DB - * triggered using portGroupChanged event... - */ - Integer ordinal = staticFlowsOrdinal.get(0); - staticFlowsOrdinal.put(0, ++ordinal); - staticFlows.put(ordinal, config); - - if (multipleFlowPush) { - PortGroupConfig pgconfig = portGroupConfigs.get(config.getPortGroup()); - Map existingData = portGroupData.get(pgconfig); - if (existingData != null) { - portGroupChanged(pgconfig, existingData, true); - } - } - return new Status(StatusCode.SUCCESS); - } - - private void addStaticFlowsToSwitch(Node node) { - for (ConcurrentMap.Entry entry : staticFlows.entrySet()) { - FlowConfig config = entry.getValue(); - if (config.isPortGroupEnabled()) { - continue; - } - if (config.getNode().equals(node)) { - if (config.installInHw() && !config.getStatus().equals(StatusCode.SUCCESS.toString())) { - Status status = this.installFlowEntryAsync(config.getFlowEntry()); - config.setStatus(status.getDescription()); - } - } - } - // Update cluster cache - refreshClusterStaticFlowsStatus(node); - } - - private void updateStaticFlowConfigsOnNodeDown(Node node) { - log.trace("Updating Static Flow configs on node down: {}", node); - - List toRemove = new ArrayList(); - for (Entry entry : staticFlows.entrySet()) { - - FlowConfig config = entry.getValue(); - - if (config.isPortGroupEnabled()) { - continue; - } - - if (config.installInHw() && config.getNode().equals(node)) { - if (config.isInternalFlow()) { - // Take note of this controller generated static flow - toRemove.add(entry.getKey()); - } else { - config.setStatus(NODE_DOWN); - } - } - } - // Remove controller generated static flows for this node - for (Integer index : toRemove) { - staticFlows.remove(index); - } - // Update cluster cache - refreshClusterStaticFlowsStatus(node); - - } - - private void updateStaticFlowConfigsOnContainerModeChange(UpdateType update) { - log.trace("Updating Static Flow configs on container mode change: {}", update); - - for (ConcurrentMap.Entry entry : staticFlows.entrySet()) { - FlowConfig config = entry.getValue(); - if (config.isPortGroupEnabled()) { - continue; - } - if (config.installInHw() && !config.isInternalFlow()) { - switch (update) { - case ADDED: - config.setStatus("Removed from node because in container mode"); - break; - case REMOVED: - config.setStatus(StatusCode.SUCCESS.toString()); - break; - default: - break; - } - } - } - // Update cluster cache - refreshClusterStaticFlowsStatus(null); - } - - @Override - public Status removeStaticFlow(FlowConfig config) { - return removeStaticFlow(config, false); - } - - @Override - public Status removeStaticFlowAsync(FlowConfig config) { - return removeStaticFlow(config, true); - } - - private Status removeStaticFlow(FlowConfig config, boolean async) { - /* - * No config.isInternal() check as NB does not take this path and GUI - * cannot issue a delete on an internal generated flow. We need this - * path to be accessible when switch mode is changed from proactive to - * reactive, so that we can remove the internal generated LLDP and ARP - * punt flows - */ - - // Look for the target configuration entry - Integer key = 0; - FlowConfig target = null; - for (ConcurrentMap.Entry entry : staticFlows.entrySet()) { - if (entry.getValue().isByNameAndNodeIdEqual(config)) { - key = entry.getKey(); - target = entry.getValue(); - break; - } - } - if (target == null) { - return new Status(StatusCode.NOTFOUND, "Entry Not Present"); - } - - // Program the network node - Status status = async ? this.uninstallFlowEntryAsync(config.getFlowEntry()) : this.uninstallFlowEntry(config - .getFlowEntry()); - - // Update configuration database if programming was successful - if (status.isSuccess()) { - staticFlows.remove(key); - } - - return status; - } - - @Override - public Status removeStaticFlow(String name, Node node) { - return removeStaticFlow(name, node, false); - } - - @Override - public Status removeStaticFlowAsync(String name, Node node) { - return removeStaticFlow(name, node, true); - } - - private Status removeStaticFlow(String name, Node node, boolean async) { - // Look for the target configuration entry - Integer key = 0; - FlowConfig target = null; - for (ConcurrentMap.Entry mapEntry : staticFlows.entrySet()) { - if (mapEntry.getValue().isByNameAndNodeIdEqual(name, node)) { - key = mapEntry.getKey(); - target = mapEntry.getValue(); - break; - } - } - if (target == null) { - return new Status(StatusCode.NOTFOUND, "Entry Not Present"); - } - - // Validity check for api3 entry point - if (target.isInternalFlow()) { - String msg = "Invalid operation: Controller generated flow cannot be deleted"; - String logMsg = msg + ": {}"; - log.warn(logMsg, name); - return new Status(StatusCode.NOTACCEPTABLE, msg); - } - - if (target.isPortGroupEnabled()) { - String msg = "Invalid operation: Port Group flows cannot be deleted through this API"; - String logMsg = msg + ": {}"; - log.warn(logMsg, name); - return new Status(StatusCode.NOTACCEPTABLE, msg); - } - - // Program the network node - Status status = this.removeEntry(target.getFlowEntry(), async); - - // Update configuration database if programming was successful - if (status.isSuccess()) { - staticFlows.remove(key); - } - - return status; - } - - @Override - public Status modifyStaticFlow(FlowConfig newFlowConfig) { - // Validity check for api3 entry point - if (newFlowConfig.isInternalFlow()) { - String msg = "Invalid operation: Controller generated flow cannot be modified"; - String logMsg = msg + ": {}"; - log.warn(logMsg, newFlowConfig); - return new Status(StatusCode.NOTACCEPTABLE, msg); - } - - // Validity Check - Status status = newFlowConfig.validate(); - if (!status.isSuccess()) { - String msg = "Invalid Configuration (" + status.getDescription() + ")"; - newFlowConfig.setStatus(msg); - log.warn("Invalid Configuration for flow {}. The failure is {}", newFlowConfig, status.getDescription()); - return new Status(StatusCode.BADREQUEST, msg); - } - - FlowConfig oldFlowConfig = null; - Integer index = null; - for (ConcurrentMap.Entry mapEntry : staticFlows.entrySet()) { - FlowConfig entry = mapEntry.getValue(); - if (entry.isByNameAndNodeIdEqual(newFlowConfig.getName(), newFlowConfig.getNode())) { - oldFlowConfig = entry; - index = mapEntry.getKey(); - break; - } - } - - if (oldFlowConfig == null) { - String msg = "Attempt to modify a non existing static flow"; - String logMsg = msg + ": {}"; - log.warn(logMsg, newFlowConfig); - return new Status(StatusCode.NOTFOUND, msg); - } - - // Do not attempt to reinstall the flow, warn user - if (newFlowConfig.equals(oldFlowConfig)) { - String msg = "No modification detected"; - log.trace("Static flow modification skipped. New flow and old flow are the same: {}", newFlowConfig); - return new Status(StatusCode.SUCCESS, msg); - } - - // If flow is installed, program the network node - status = new Status(StatusCode.SUCCESS, "Saved in config"); - if (oldFlowConfig.installInHw()) { - status = this.modifyFlowEntry(oldFlowConfig.getFlowEntry(), newFlowConfig.getFlowEntry()); - } - - // Update configuration database if programming was successful - if (status.isSuccess()) { - newFlowConfig.setStatus(status.getDescription()); - staticFlows.put(index, newFlowConfig); - } - - return status; - } - - @Override - public Status toggleStaticFlowStatus(String name, Node node) { - return toggleStaticFlowStatus(getStaticFlow(name, node)); - } - - @Override - public Status toggleStaticFlowStatus(FlowConfig config) { - if (config == null) { - String msg = "Invalid request: null flow config"; - log.warn(msg); - return new Status(StatusCode.BADREQUEST, msg); - } - // Validity check for api3 entry point - if (config.isInternalFlow()) { - String msg = "Invalid operation: Controller generated flow cannot be modified"; - String logMsg = msg + ": {}"; - log.warn(logMsg, config); - return new Status(StatusCode.NOTACCEPTABLE, msg); - } - - // Find the config entry - Integer key = 0; - FlowConfig target = null; - for (Map.Entry entry : staticFlows.entrySet()) { - FlowConfig conf = entry.getValue(); - if (conf.isByNameAndNodeIdEqual(config)) { - key = entry.getKey(); - target = conf; - break; - } - } - if (target != null) { - Status status = target.validate(); - if (!status.isSuccess()) { - log.warn(status.getDescription()); - return status; - } - status = (target.installInHw()) ? this.uninstallFlowEntry(target.getFlowEntry()) : this - .installFlowEntry(target.getFlowEntry()); - if (status.isSuccess()) { - // Update Configuration database - target.setStatus(StatusCode.SUCCESS.toString()); - target.toggleInstallation(); - staticFlows.put(key, target); - } - return status; - } - - return new Status(StatusCode.NOTFOUND, "Unable to locate the entry. Failed to toggle status"); - } - - /** - * Reinsert all static flows entries in the cache to force cache updates in - * the cluster. This is useful when only some parameters were changed in the - * entries, like the status. - * - * @param node - * The node for which the static flow configurations have to be - * refreshed. If null, all nodes static flows will be refreshed. - */ - private void refreshClusterStaticFlowsStatus(Node node) { - // Refresh cluster cache - for (ConcurrentMap.Entry entry : staticFlows.entrySet()) { - if (node == null || entry.getValue().getNode().equals(node)) { - staticFlows.put(entry.getKey(), entry.getValue()); - } - } - } - - /** - * Uninstall all the non-internal Flow Entries present in the software view. - * If requested, a copy of each original flow entry will be stored in the - * inactive list so that it can be re-applied when needed (This is typically - * the case when running in the default container and controller moved to - * container mode) NOTE WELL: The routine as long as does a bulk change will - * operate only on the entries for nodes locally attached so to avoid - * redundant operations initiated by multiple nodes - * - * @param preserveFlowEntries - * if true, a copy of each original entry is stored in the - * inactive list - */ - private void uninstallAllFlowEntries(boolean preserveFlowEntries) { - log.trace("Uninstalling all non-internal flows"); - - List toRemove = new ArrayList(); - - // Store entries / create target list - for (ConcurrentMap.Entry mapEntry : installedSwView.entrySet()) { - FlowEntryInstall flowEntries = mapEntry.getValue(); - // Skip internal generated static flows - if (!flowEntries.isInternal()) { - toRemove.add(flowEntries); - // Store the original entries if requested - if (preserveFlowEntries) { - inactiveFlows.put(flowEntries.getOriginal(), flowEntries.getOriginal()); - } - } - } - - // Now remove the entries - for (FlowEntryInstall flowEntryHw : toRemove) { - Node n = flowEntryHw.getNode(); - if (n != null && connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) { - Status status = this.removeEntryInternal(flowEntryHw, false); - if (!status.isSuccess()) { - log.trace("Failed to remove entry: {}. The failure is: {}", flowEntryHw, status.getDescription()); - } - } else { - log.debug("Not removing entry {} because not connected locally, the remote guy will do it's job", - flowEntryHw); - } - } - } - - /** - * Re-install all the Flow Entries present in the inactive list The inactive - * list will be empty at the end of this call This function is called on the - * default container instance of FRM only when the last container is deleted - */ - private void reinstallAllFlowEntries() { - log.trace("Reinstalling all inactive flows"); - - for (FlowEntry flowEntry : this.inactiveFlows.keySet()) { - this.addEntry(flowEntry, false); - } - - // Empty inactive list in any case - inactiveFlows.clear(); - } - - @Override - public List getStaticFlows() { - return new ArrayList(staticFlows.values()); - } - - @Override - public FlowConfig getStaticFlow(String name, Node node) { - ConcurrentMap.Entry entry = getStaticFlowEntry(name, node); - if(entry != null) { - return entry.getValue(); - } - return null; - } - - @Override - public List getStaticFlows(Node node) { - List list = new ArrayList(); - for (ConcurrentMap.Entry entry : staticFlows.entrySet()) { - if (entry.getValue().onNode(node)) { - list.add(entry.getValue()); - } - } - return list; - } - - @Override - public List getStaticFlowNamesForNode(Node node) { - List list = new ArrayList(); - for (ConcurrentMap.Entry entry : staticFlows.entrySet()) { - if (entry.getValue().onNode(node)) { - list.add(entry.getValue().getName()); - } - } - return list; - } - - @Override - public List getListNodeWithConfiguredFlows() { - Set set = new HashSet(); - for (ConcurrentMap.Entry entry : staticFlows.entrySet()) { - set.add(entry.getValue().getNode()); - } - return new ArrayList(set); - } - - private void loadFlowConfiguration() { - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, PORT_GROUP_FILE_NAME)) { - addPortGroupConfig(((PortGroupConfig) conf).getName(), ((PortGroupConfig) conf).getMatchString(), true); - } - - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, STATIC_FLOWS_FILE_NAME)) { - addStaticFlowInternal((FlowConfig) conf, false, true); - } - } - - @Override - public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException { - return ois.readObject(); - } - - @Override - public Status saveConfig() { - return saveConfigInternal(); - } - - private Status saveConfigInternal() { - List nonDynamicFlows = new ArrayList(); - - for (Integer ordinal : staticFlows.keySet()) { - FlowConfig config = staticFlows.get(ordinal); - // Do not save dynamic and controller generated static flows - if (config.isDynamic() || config.isInternalFlow()) { - continue; - } - nonDynamicFlows.add(config); - } - - configurationService.persistConfiguration(nonDynamicFlows, STATIC_FLOWS_FILE_NAME); - configurationService.persistConfiguration(new ArrayList(portGroupConfigs.values()), - PORT_GROUP_FILE_NAME); - - return new Status(StatusCode.SUCCESS); - } - - @Override - public void subnetNotify(Subnet sub, boolean add) { - } - - private boolean programInternalFlow(boolean proactive, FlowConfig fc) { - boolean retVal = true; // program flows unless determined otherwise - if(proactive) { - // if the flow already exists do not program - if(flowConfigExists(fc)) { - retVal = false; - } - } else { - // if the flow does not exist do not program - if(!flowConfigExists(fc)) { - retVal = false; - } - } - return retVal; - } - - /** - * (non-Javadoc) - * - * @see org.opendaylight.controller.switchmanager.ISwitchManagerAware#modeChangeNotify(org.opendaylight.controller.sal.core.Node, - * boolean) - * - * This method can be called from within the OSGi framework context, - * given the programming operation can take sometime, it not good - * pratice to have in it's context operations that can take time, - * hence moving off to a different thread for async processing. - */ - private ExecutorService executor; - @Override - public void modeChangeNotify(final Node node, final boolean proactive) { - Callable modeChangeCallable = new Callable() { - @Override - public Status call() throws Exception { - List defaultConfigs = new ArrayList(); - - List puntAction = new ArrayList(); - puntAction.add(ActionType.CONTROLLER.toString()); - - FlowConfig allowARP = new FlowConfig(); - allowARP.setInstallInHw(true); - allowARP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt ARP" + FlowConfig.INTERNALSTATICFLOWEND); - allowARP.setPriority("1"); - allowARP.setNode(node); - allowARP.setEtherType("0x" + Integer.toHexString(EtherTypes.ARP.intValue()) - .toUpperCase()); - allowARP.setActions(puntAction); - defaultConfigs.add(allowARP); - - FlowConfig allowLLDP = new FlowConfig(); - allowLLDP.setInstallInHw(true); - allowLLDP.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Punt LLDP" + FlowConfig.INTERNALSTATICFLOWEND); - allowLLDP.setPriority("1"); - allowLLDP.setNode(node); - allowLLDP.setEtherType("0x" + Integer.toHexString(EtherTypes.LLDP.intValue()) - .toUpperCase()); - allowLLDP.setActions(puntAction); - defaultConfigs.add(allowLLDP); - - List dropAction = new ArrayList(); - dropAction.add(ActionType.DROP.toString()); - - FlowConfig dropAllConfig = new FlowConfig(); - dropAllConfig.setInstallInHw(true); - dropAllConfig.setName(FlowConfig.INTERNALSTATICFLOWBEGIN + "Catch-All Drop" - + FlowConfig.INTERNALSTATICFLOWEND); - dropAllConfig.setPriority("0"); - dropAllConfig.setNode(node); - dropAllConfig.setActions(dropAction); - defaultConfigs.add(dropAllConfig); - - log.trace("Forwarding mode for node {} set to {}", node, (proactive ? "proactive" : "reactive")); - for (FlowConfig fc : defaultConfigs) { - // check if the frm really needs to act on the notification. - // this is to check against duplicate notifications - if(programInternalFlow(proactive, fc)) { - Status status = (proactive) ? addStaticFlowInternal(fc, false, false) : removeStaticFlow(fc); - if (status.isSuccess()) { - log.trace("{} Proactive Static flow: {}", (proactive ? "Installed" : "Removed"), fc.getName()); - } else { - log.warn("Failed to {} Proactive Static flow: {}", (proactive ? "install" : "remove"), - fc.getName()); - } - } else { - log.debug("Got redundant install request for internal flow: {} on node: {}. Request not sent to FRM.", fc.getName(), node); - } - } - return new Status(StatusCode.SUCCESS); - } - }; - - /* - * Execute the work outside the caller context, this could be an - * expensive operation and we don't want to block the caller for it. - */ - this.executor.submit(modeChangeCallable); - } - - /** - * Remove from the databases all the flows installed on the node - * - * @param node - */ - private void cleanDatabaseForNode(Node node) { - log.trace("Cleaning Flow database for Node {}", node); - if (nodeFlows.containsKey(node)) { - List toRemove = new ArrayList(nodeFlows.get(node)); - - for (FlowEntryInstall entry : toRemove) { - updateSwViews(entry, false); - } - } - } - - private boolean doesFlowContainNodeConnector(Flow flow, NodeConnector nc) { - if (nc == null) { - return false; - } - - Match match = flow.getMatch(); - if (match.isPresent(MatchType.IN_PORT)) { - NodeConnector matchPort = (NodeConnector) match.getField(MatchType.IN_PORT).getValue(); - if (matchPort.equals(nc)) { - return true; - } - } - List actionsList = flow.getActions(); - if (actionsList != null) { - for (Action action : actionsList) { - if (action instanceof Output) { - NodeConnector actionPort = ((Output) action).getPort(); - if (actionPort.equals(nc)) { - return true; - } - } - } - } - return false; - } - - @Override - public void notifyNode(Node node, UpdateType type, Map propMap) { - this.pendingEvents.offer(new NodeUpdateEvent(type, node)); - } - - @Override - public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map propMap) { - boolean updateStaticFlowCluster = false; - - switch (type) { - case ADDED: - break; - case CHANGED: - Config config = (propMap == null) ? null : (Config) propMap.get(Config.ConfigPropName); - if (config != null) { - switch (config.getValue()) { - case Config.ADMIN_DOWN: - log.trace("Port {} is administratively down: uninstalling interested flows", nodeConnector); - updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector); - break; - case Config.ADMIN_UP: - log.trace("Port {} is administratively up: installing interested flows", nodeConnector); - updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nodeConnector); - break; - case Config.ADMIN_UNDEF: - break; - default: - } - } - break; - case REMOVED: - // This is the case where a switch port is removed from the SDN agent space - log.trace("Port {} was removed from our control: uninstalling interested flows", nodeConnector); - updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nodeConnector); - break; - default: - - } - - if (updateStaticFlowCluster) { - refreshClusterStaticFlowsStatus(nodeConnector.getNode()); - } - } - - /* - * It goes through the static flows configuration, it identifies the ones - * which have the specified node connector as input or output port and - * install them on the network node if they are marked to be installed in - * hardware and their status shows they were not installed yet - */ - private boolean installFlowsOnNodeConnectorUp(NodeConnector nodeConnector) { - boolean updated = false; - List flowConfigForNode = getStaticFlows(nodeConnector.getNode()); - for (FlowConfig flowConfig : flowConfigForNode) { - if (doesFlowContainNodeConnector(flowConfig.getFlow(), nodeConnector)) { - if (flowConfig.installInHw() && !flowConfig.getStatus().equals(StatusCode.SUCCESS.toString())) { - Status status = this.installFlowEntryAsync(flowConfig.getFlowEntry()); - if (!status.isSuccess()) { - flowConfig.setStatus(status.getDescription()); - } else { - flowConfig.setStatus(StatusCode.SUCCESS.toString()); - } - updated = true; - } - } - } - return updated; - } - - /* - * Remove from the network node all the flows which have the specified node - * connector as input or output port. If any of the flow entry is a static - * flow, it updates the correspondent configuration. - */ - private boolean removeFlowsOnNodeConnectorDown(NodeConnector nodeConnector) { - boolean updated = false; - List nodeFlowEntries = nodeFlows.get(nodeConnector.getNode()); - if (nodeFlowEntries == null) { - return updated; - } - for (FlowEntryInstall fei : new ArrayList(nodeFlowEntries)) { - if (doesFlowContainNodeConnector(fei.getInstall().getFlow(), nodeConnector)) { - Status status = this.removeEntryInternal(fei, true); - if (!status.isSuccess()) { - continue; - } - /* - * If the flow entry is a static flow, then update its - * configuration - */ - if (fei.getGroupName().equals(FlowConfig.STATICFLOWGROUP)) { - FlowConfig flowConfig = getStaticFlow(fei.getFlowName(), fei.getNode()); - if (flowConfig != null) { - flowConfig.setStatus(PORT_REMOVED); - updated = true; - } - } - } - } - return updated; - } - - private FlowConfig getDerivedFlowConfig(FlowConfig original, String configName, Short port) { - FlowConfig derivedFlow = new FlowConfig(original); - derivedFlow.setDynamic(true); - derivedFlow.setPortGroup(null); - derivedFlow.setName(original.getName() + "_" + configName + "_" + port); - derivedFlow.setIngressPort(port + ""); - return derivedFlow; - } - - private void addPortGroupFlows(PortGroupConfig config, Node node, PortGroup data) { - for (FlowConfig staticFlow : staticFlows.values()) { - if (staticFlow.getPortGroup() == null) { - continue; - } - if ((staticFlow.getNode().equals(node)) && (staticFlow.getPortGroup().equals(config.getName()))) { - for (Short port : data.getPorts()) { - FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port); - addStaticFlowInternal(derivedFlow, false, false); - } - } - } - } - - private void removePortGroupFlows(PortGroupConfig config, Node node, PortGroup data) { - for (FlowConfig staticFlow : staticFlows.values()) { - if (staticFlow.getPortGroup() == null) { - continue; - } - if (staticFlow.getNode().equals(node) && staticFlow.getPortGroup().equals(config.getName())) { - for (Short port : data.getPorts()) { - FlowConfig derivedFlow = getDerivedFlowConfig(staticFlow, config.getName(), port); - removeStaticFlow(derivedFlow); - } - } - } - } - - @Override - public void portGroupChanged(PortGroupConfig config, Map data, boolean add) { - log.trace("PortGroup Changed for: {} Data: {}", config, portGroupData); - Map existingData = portGroupData.get(config); - if (existingData != null) { - for (Map.Entry entry : data.entrySet()) { - PortGroup existingPortGroup = existingData.get(entry.getKey()); - if (existingPortGroup == null) { - if (add) { - existingData.put(entry.getKey(), entry.getValue()); - addPortGroupFlows(config, entry.getKey(), entry.getValue()); - } - } else { - if (add) { - existingPortGroup.getPorts().addAll(entry.getValue().getPorts()); - addPortGroupFlows(config, entry.getKey(), entry.getValue()); - } else { - existingPortGroup.getPorts().removeAll(entry.getValue().getPorts()); - removePortGroupFlows(config, entry.getKey(), entry.getValue()); - } - } - } - } else { - if (add) { - portGroupData.put(config, data); - for (Node swid : data.keySet()) { - addPortGroupFlows(config, swid, data.get(swid)); - } - } - } - } - - @Override - public boolean addPortGroupConfig(String name, String regex, boolean restore) { - PortGroupConfig config = portGroupConfigs.get(name); - if (config != null) { - return false; - } - - if ((portGroupProvider == null) && !restore) { - return false; - } - if ((portGroupProvider != null) && (!portGroupProvider.isMatchCriteriaSupported(regex))) { - return false; - } - - config = new PortGroupConfig(name, regex); - portGroupConfigs.put(name, config); - if (portGroupProvider != null) { - portGroupProvider.createPortGroupConfig(config); - } - return true; - } - - @Override - public boolean delPortGroupConfig(String name) { - PortGroupConfig config = portGroupConfigs.get(name); - if (config == null) { - return false; - } - - if (portGroupProvider != null) { - portGroupProvider.deletePortGroupConfig(config); - } - portGroupConfigs.remove(name); - return true; - } - - @Override - public Map getPortGroupConfigs() { - return portGroupConfigs; - } - - public boolean isPortGroupSupported() { - if (portGroupProvider == null) { - return false; - } - return true; - } - - public void setIContainer(IContainer s) { - this.container = s; - } - - public void unsetIContainer(IContainer s) { - if (this.container == s) { - this.container = null; - } - } - - public void setConfigurationContainerService(IConfigurationContainerService service) { - log.trace("Got configuration service set request {}", service); - this.configurationService = service; - } - - public void unsetConfigurationContainerService(IConfigurationContainerService service) { - log.trace("Got configuration service UNset request"); - this.configurationService = null; - } - - @Override - public PortGroupProvider getPortGroupProvider() { - return portGroupProvider; - } - - public void unsetPortGroupProvider(PortGroupProvider portGroupProvider) { - this.portGroupProvider = null; - } - - public void setPortGroupProvider(PortGroupProvider portGroupProvider) { - this.portGroupProvider = portGroupProvider; - portGroupProvider.registerPortGroupChange(this); - for (PortGroupConfig config : portGroupConfigs.values()) { - portGroupProvider.createPortGroupConfig(config); - } - } - - public void setFrmAware(IForwardingRulesManagerAware obj) { - this.frmAware.add(obj); - } - - public void unsetFrmAware(IForwardingRulesManagerAware obj) { - this.frmAware.remove(obj); - } - - void setClusterContainerService(IClusterContainerServices s) { - log.debug("Cluster Service set"); - this.clusterContainerService = s; - } - - void unsetClusterContainerService(IClusterContainerServices s) { - if (this.clusterContainerService == s) { - log.debug("Cluster Service removed!"); - this.clusterContainerService = null; - } - } - - private String getContainerName() { - if (container == null) { - return GlobalConstants.DEFAULT.toString(); - } - return container.getName(); - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - - inContainerMode = false; - - if (portGroupProvider != null) { - portGroupProvider.registerPortGroupChange(this); - } - - nodeFlows = new ConcurrentHashMap>(); - groupFlows = new ConcurrentHashMap>(); - - cacheStartup(); - - /* - * If we are not the first cluster node to come up, do not initialize - * the static flow entries ordinal - */ - if (staticFlowsOrdinal.size() == 0) { - staticFlowsOrdinal.put(0, Integer.valueOf(0)); - } - - pendingEvents = new LinkedBlockingQueue(); - - // Initialize the event handler thread - frmEventHandler = new Thread(new Runnable() { - @Override - public void run() { - while (!stopping) { - try { - final FRMEvent event = pendingEvents.take(); - if (event == null) { - log.warn("Dequeued null event"); - continue; - } - log.trace("Dequeued {} event", event.getClass().getSimpleName()); - if (event instanceof NodeUpdateEvent) { - NodeUpdateEvent update = (NodeUpdateEvent) event; - Node node = update.getNode(); - switch (update.getUpdateType()) { - case ADDED: - addStaticFlowsToSwitch(node); - break; - case REMOVED: - cleanDatabaseForNode(node); - updateStaticFlowConfigsOnNodeDown(node); - break; - default: - } - } else if (event instanceof ErrorReportedEvent) { - ErrorReportedEvent errEvent = (ErrorReportedEvent) event; - processErrorEvent(errEvent); - } else if (event instanceof WorkOrderEvent) { - /* - * Take care of handling the remote Work request - */ - Runnable r = new Runnable() { - @Override - public void run() { - WorkOrderEvent work = (WorkOrderEvent) event; - FlowEntryDistributionOrder fe = work.getFe(); - if (fe != null) { - logsync.trace("Executing the workOrder {}", fe); - Status gotStatus = null; - FlowEntryInstall feiCurrent = fe.getEntry(); - FlowEntryInstall feiNew = workOrder.get(fe); - switch (fe.getUpType()) { - case ADDED: - gotStatus = addEntryInHw(feiCurrent, false); - break; - case CHANGED: - gotStatus = modifyEntryInHw(feiCurrent, feiNew, false); - break; - case REMOVED: - gotStatus = removeEntryInHw(feiCurrent, false); - break; - } - // Remove the Order - workOrder.remove(fe); - logsync.trace( - "The workOrder has been executed and now the status is being returned {}", fe); - // Place the status - workStatus.put(fe, gotStatus); - } else { - log.warn("Not expected null WorkOrder", work); - } - } - }; - if(executor != null) { - executor.execute(r); - } - } else if (event instanceof WorkStatusCleanup) { - /* - * Take care of handling the remote Work request - */ - WorkStatusCleanup work = (WorkStatusCleanup) event; - FlowEntryDistributionOrder fe = work.getFe(); - if (fe != null) { - logsync.trace("The workStatus {} is being removed", fe); - workStatus.remove(fe); - } else { - log.warn("Not expected null WorkStatus", work); - } - } else if (event instanceof ContainerFlowChangeEvent) { - /* - * Whether it is an addition or removal, we have to - * recompute the merged flows entries taking into - * account all the current container flows because - * flow merging is not an injective function - */ - updateFlowsContainerFlow(); - } else if (event instanceof UpdateIndexDBs) { - UpdateIndexDBs update = (UpdateIndexDBs)event; - updateIndexDatabase(update.getFei(), update.isAddition()); - } else { - log.warn("Dequeued unknown event {}", event.getClass().getSimpleName()); - } - } catch (InterruptedException e) { - // clear pending events - pendingEvents.clear(); - } - } - } - }, "FRM EventHandler Collector"); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - // Interrupt the thread - frmEventHandler.interrupt(); - // Clear the pendingEvents queue - pendingEvents.clear(); - frmAware.clear(); - workMonitor.clear(); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - /* - * If running in default container, need to know if controller is in - * container mode - */ - if (GlobalConstants.DEFAULT.toString().equals(this.getContainerName())) { - inContainerMode = containerManager.inContainerMode(); - } - - // Initialize graceful stop flag - stopping = false; - - // Allocate the executor service - this.executor = Executors.newFixedThreadPool(maxPoolSize); - - // Start event handler thread - frmEventHandler.start(); - - // replay the installedSwView data structure to populate - // node flows and group flows - for (FlowEntryInstall fei : installedSwView.values()) { - pendingEvents.offer(new UpdateIndexDBs(fei, true)); - } - - /* - * Read startup and build database if we are the coordinator - */ - loadFlowConfiguration(); - } - - /** - * Function called by the dependency manager before Container is Stopped and Destroyed. - */ - public void containerStop() { - uninstallAllFlowEntries(false); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - */ - void stop() { - stopping = true; - // Shutdown executor - this.executor.shutdownNow(); - // Now walk all the workMonitor and wake up the one sleeping because - // destruction is happening - for (FlowEntryDistributionOrder fe : workMonitor.keySet()) { - FlowEntryDistributionOrderFutureTask task = workMonitor.get(fe); - task.cancel(true); - } - } - - public void setFlowProgrammerService(IFlowProgrammerService service) { - this.programmer = service; - } - - public void unsetFlowProgrammerService(IFlowProgrammerService service) { - if (this.programmer == service) { - this.programmer = null; - } - } - - public void setSwitchManager(ISwitchManager switchManager) { - this.switchManager = switchManager; - } - - public void unsetSwitchManager(ISwitchManager switchManager) { - if (this.switchManager == switchManager) { - this.switchManager = null; - } - } - - @Override - public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) { - if (!container.getName().equals(containerName)) { - return; - } - } - - @Override - public void containerFlowUpdated(String containerName, ContainerFlow previous, ContainerFlow current, UpdateType t) { - if (!container.getName().equals(containerName)) { - return; - } - log.trace("Container {}: Updating installed flows because of container flow change: {} {}", - container.getName(), t, current); - ContainerFlowChangeEvent ev = new ContainerFlowChangeEvent(previous, current, t); - pendingEvents.offer(ev); - } - - @Override - public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) { - if (!container.getName().equals(containerName)) { - return; - } - - boolean updateStaticFlowCluster = false; - - switch (t) { - case REMOVED: - log.trace("Port {} was removed from container: uninstalling interested flows", nc); - updateStaticFlowCluster = removeFlowsOnNodeConnectorDown(nc); - break; - case ADDED: - log.trace("Port {} was added to container: reinstall interested flows", nc); - updateStaticFlowCluster = installFlowsOnNodeConnectorUp(nc); - - break; - case CHANGED: - break; - default: - } - - if (updateStaticFlowCluster) { - refreshClusterStaticFlowsStatus(nc.getNode()); - } - } - - @Override - public void containerModeUpdated(UpdateType update) { - // Only default container instance reacts on this event - if (!container.getName().equals(GlobalConstants.DEFAULT.toString())) { - return; - } - switch (update) { - case ADDED: - /* - * Controller is moving to container mode. We are in the default - * container context, we need to remove all our non-internal flows - * to prevent any container isolation breakage. We also need to - * preserve our flow so that they can be re-installed if we move - * back to non container mode (no containers). - */ - this.inContainerMode = true; - this.uninstallAllFlowEntries(true); - break; - case REMOVED: - this.inContainerMode = false; - this.reinstallAllFlowEntries(); - break; - default: - break; - } - - // Update our configuration DB - updateStaticFlowConfigsOnContainerModeChange(update); - } - - protected abstract class FRMEvent { - - } - - private class NodeUpdateEvent extends FRMEvent { - private final Node node; - private final UpdateType update; - - public NodeUpdateEvent(UpdateType update, Node node) { - this.update = update; - this.node = node; - } - - public UpdateType getUpdateType() { - return update; - } - - public Node getNode() { - return node; - } - } - - private class ErrorReportedEvent extends FRMEvent { - private final long rid; - private final Node node; - private final Object error; - - public ErrorReportedEvent(long rid, Node node, Object error) { - this.rid = rid; - this.node = node; - this.error = error; - } - - public long getRequestId() { - return rid; - } - - public Object getError() { - return error; - } - - public Node getNode() { - return node; - } - } - - private class WorkOrderEvent extends FRMEvent { - private FlowEntryDistributionOrder fe; - private FlowEntryInstall newEntry; - - /** - * @param fe - * @param newEntry - */ - WorkOrderEvent(FlowEntryDistributionOrder fe, FlowEntryInstall newEntry) { - this.fe = fe; - this.newEntry = newEntry; - } - - /** - * @return the fe - */ - public FlowEntryDistributionOrder getFe() { - return fe; - } - - /** - * @return the newEntry - */ - public FlowEntryInstall getNewEntry() { - return newEntry; - } - } - private class ContainerFlowChangeEvent extends FRMEvent { - private final ContainerFlow previous; - private final ContainerFlow current; - private final UpdateType type; - - public ContainerFlowChangeEvent(ContainerFlow previous, ContainerFlow current, UpdateType type) { - this.previous = previous; - this.current = current; - this.type = type; - } - - public ContainerFlow getPrevious() { - return this.previous; - } - - public ContainerFlow getCurrent() { - return this.current; - } - - public UpdateType getType() { - return this.type; - } - } - - - private class WorkStatusCleanup extends FRMEvent { - private FlowEntryDistributionOrder fe; - - /** - * @param fe - */ - WorkStatusCleanup(FlowEntryDistributionOrder fe) { - this.fe = fe; - } - - /** - * @return the fe - */ - public FlowEntryDistributionOrder getFe() { - return fe; - } - } - - private class UpdateIndexDBs extends FRMEvent { - private FlowEntryInstall fei; - private boolean add; - - /** - * - * @param fei the flow entry which was installed/removed on the netwrok node - * @param update - */ - UpdateIndexDBs(FlowEntryInstall fei, boolean add) { - this.fei = fei; - this.add = add; - } - - - /** - * @return the flowEntryInstall object which was added/removed - * to/from the installed software view cache - */ - public FlowEntryInstall getFei() { - return fei; - } - - /** - * - * @return whether this was an flow addition or removal - */ - public boolean isAddition() { - return add; - } - } - - @Override - public Status saveConfiguration() { - return saveConfig(); - } - - @Override - public void flowRemoved(Node node, Flow flow) { - log.trace("Received flow removed notification on {} for {}", node, flow); - - // For flow entry identification, only node, match and priority matter - FlowEntryInstall test = new FlowEntryInstall(new FlowEntry("", "", flow, node), null); - FlowEntryInstall installedEntry = this.installedSwView.get(test); - if (installedEntry == null) { - log.trace("Entry is not known to us"); - return; - } - - // Update Static flow status - Integer key = 0; - FlowConfig target = null; - for (Map.Entry entry : staticFlows.entrySet()) { - FlowConfig conf = entry.getValue(); - if (conf.isByNameAndNodeIdEqual(installedEntry.getFlowName(), node)) { - key = entry.getKey(); - target = conf; - break; - } - } - if (target != null) { - // Update Configuration database - if (target.getHardTimeout() != null || target.getIdleTimeout() != null) { - /* - * No need for checking if actual values: these strings were - * validated at configuration creation. Also, after a switch - * down scenario, no use to reinstall a timed flow. Mark it as - * "do not install". User can manually toggle it. - */ - target.toggleInstallation(); - } - target.setStatus(StatusCode.GONE.toString()); - staticFlows.put(key, target); - } - - // Update software views - this.updateSwViews(installedEntry, false); - } - - @Override - public void flowErrorReported(Node node, long rid, Object err) { - log.trace("Got error {} for message rid {} from node {}", new Object[] { err, rid, node }); - pendingEvents.offer(new ErrorReportedEvent(rid, node, err)); - } - - private void processErrorEvent(ErrorReportedEvent event) { - Node node = event.getNode(); - long rid = event.getRequestId(); - Object error = event.getError(); - String errorString = (error == null) ? "Not provided" : error.toString(); - /* - * If this was for a flow install, remove the corresponding entry from - * the software view. If it was a Looking for the rid going through the - * software database. TODO: A more efficient rid <-> FlowEntryInstall - * mapping will have to be added in future - */ - FlowEntryInstall target = null; - List flowEntryInstallList = nodeFlows.get(node); - // flowEntryInstallList could be null. - // so check for it. - if(flowEntryInstallList != null) { - for (FlowEntryInstall index : flowEntryInstallList) { - FlowEntryInstall entry = installedSwView.get(index); - if(entry != null) { - if (entry.getRequestId() == rid) { - target = entry; - break; - } - } - } - } - if (target != null) { - // This was a flow install, update database - this.updateSwViews(target, false); - // also update the config - if(FlowConfig.STATICFLOWGROUP.equals(target.getGroupName())) { - ConcurrentMap.Entry staticFlowEntry = getStaticFlowEntry(target.getFlowName(),target.getNode()); - // staticFlowEntry should never be null. - // the null check is just an extra defensive check. - if(staticFlowEntry != null) { - // Modify status and update cluster cache - log.debug("Updating static flow configuration on async error event"); - String status = String.format("Cannot be installed on node. reason: %s", errorString); - staticFlowEntry.getValue().setStatus(status); - refreshClusterStaticFlowsStatus(node); - } - } - } - - // Notify listeners - if (frmAware != null) { - synchronized (frmAware) { - for (IForwardingRulesManagerAware frma : frmAware) { - try { - frma.requestFailed(rid, errorString); - } catch (Exception e) { - log.warn("Failed to notify {}", frma); - } - } - } - } - } - - @Override - public Status solicitStatusResponse(Node node, boolean blocking) { - Status rv = new Status(StatusCode.INTERNALERROR); - - if (this.programmer != null) { - if (blocking) { - rv = programmer.syncSendBarrierMessage(node); - } else { - rv = programmer.asyncSendBarrierMessage(node); - } - } - - return rv; - } - - public void unsetIConnectionManager(IConnectionManager s) { - if (s == this.connectionManager) { - this.connectionManager = null; - } - } - - public void setIConnectionManager(IConnectionManager s) { - this.connectionManager = s; - } - - public void unsetIContainerManager(IContainerManager s) { - if (s == this.containerManager) { - this.containerManager = null; - } - } - - public void setIContainerManager(IContainerManager s) { - this.containerManager = s; - } - - @Override - public void entryCreated(Object key, String cacheName, boolean originLocal) { - /* - * Do nothing - */ - } - - @Override - public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) { - /* - * Streamline the updates for the per node and per group index databases - */ - if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) { - pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)new_value, true)); - } - - if (originLocal) { - /* - * Local updates are of no interest - */ - return; - } - if (cacheName.equals(WORK_ORDER_CACHE)) { - logsync.trace("Got a WorkOrderCacheUpdate for {}", key); - /* - * This is the case of one workOrder becoming available, so we need - * to dispatch the work to the appropriate handler - */ - FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key; - FlowEntryInstall fei = fe.getEntry(); - if (fei == null) { - return; - } - Node n = fei.getNode(); - if (connectionManager.getLocalityStatus(n) == ConnectionLocality.LOCAL) { - logsync.trace("workOrder for fe {} processed locally", fe); - // I'm the controller in charge for the request, queue it for - // processing - pendingEvents.offer(new WorkOrderEvent(fe, (FlowEntryInstall) new_value)); - } - } else if (cacheName.equals(WORK_STATUS_CACHE)) { - logsync.trace("Got a WorkStatusCacheUpdate for {}", key); - /* - * This is the case of one workOrder being completed and a status - * returned - */ - FlowEntryDistributionOrder fe = (FlowEntryDistributionOrder) key; - /* - * Check if the order was initiated by this controller in that case - * we need to actually look at the status returned - */ - if (fe.getRequestorController() - .equals(clusterContainerService.getMyAddress())) { - FlowEntryDistributionOrderFutureTask fet = workMonitor.remove(fe); - if (fet != null) { - logsync.trace("workStatus response is for us {}", fe); - // Signal we got the status - fet.gotStatus(fe, workStatus.get(fe)); - pendingEvents.offer(new WorkStatusCleanup(fe)); - } - } - } - } - - @Override - public void entryDeleted(Object key, String cacheName, boolean originLocal) { - /* - * Streamline the updates for the per node and per group index databases - */ - if (cacheName.equals(INSTALLED_SW_VIEW_CACHE)) { - pendingEvents.offer(new UpdateIndexDBs((FlowEntryInstall)key, false)); - } - } - - /** - * {@inheritDoc} - */ - @Override - public List getFlowEntriesForNode(Node node) { - List list = new ArrayList(); - if (node != null) { - for (Map.Entry entry : this.originalSwView.entrySet()) { - if (node.equals(entry.getKey().getNode())) { - list.add(entry.getValue().clone()); - } - } - } - return list; - } - - /** - * {@inheritDoc} - */ - @Override - public List getInstalledFlowEntriesForNode(Node node) { - List list = new ArrayList(); - if (node != null) { - List flowEntryInstallList = this.nodeFlows.get(node); - if(flowEntryInstallList != null) { - for(FlowEntryInstall fi: flowEntryInstallList) { - list.add(fi.getInstall().clone()); - } - } - } - return list; - } - -} diff --git a/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerCLI.java b/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerCLI.java deleted file mode 100644 index 320561b5de..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/implementation/src/main/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerCLI.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.forwardingrulesmanager.internal; - -import java.util.Dictionary; -import java.util.Hashtable; -import java.util.List; - -import org.apache.felix.service.command.Descriptor; -import org.opendaylight.controller.forwardingrulesmanager.FlowEntry; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.osgi.framework.ServiceRegistration; - -/** - * This class provides osgi cli commands for developers to debug - * ForwardingRulesManager functionality - */ -public class ForwardingRulesManagerCLI { - @SuppressWarnings("rawtypes") - private ServiceRegistration sr = null; - - public void init() { - } - - public void destroy() { - } - - public void start() { - final Dictionary props = new Hashtable(); - props.put("osgi.command.scope", "odpcontroller"); - props.put("osgi.command.function", new String[] { "showRequestedGroupFlows", "showInstalledGroupFlows", - "showRequestedNodeFlows", "showInstalledNodeFlows" }); - this.sr = ServiceHelper.registerGlobalServiceWReg(ForwardingRulesManagerCLI.class, this, props); - } - - public void stop() { - if (this.sr != null) { - this.sr.unregister(); - this.sr = null; - } - } - - @Descriptor("Displays all the flow entries in a given group") - public void showRequestedGroupFlows(@Descriptor("Container in which to query FRM") String container, - @Descriptor("Group name") String group, @Descriptor("True for verbose else false") Boolean verbose) { - IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( - IForwardingRulesManager.class, container, this); - if (frm == null) { - System.out.println("Cannot find the FRM instance on container: " + container); - return; - } - List groupFlows = frm.getFlowEntriesForGroup(group); - System.out.println("Group " + group); - for (FlowEntry flowEntry : groupFlows) { - if (!verbose) { - System.out.println(flowEntry.getNode() + " " + flowEntry.getFlowName()); - } else { - System.out.println(flowEntry.getNode() + " " + flowEntry.toString()); - } - } - } - - @Descriptor("Displays all the installed flow entries in a given group") - public void showInstalledGroupFlows(@Descriptor("Container in which to query FRM") String container, - @Descriptor("Group name") String group, @Descriptor("True for verbose else false") Boolean verbose) { - IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( - IForwardingRulesManager.class, container, this); - if (frm == null) { - System.out.println("Cannot find the FRM instance on container: " + container); - return; - } - List groupFlows = frm.getInstalledFlowEntriesForGroup(group); - System.out.println("Group " + group); - for (FlowEntry flowEntry : groupFlows) { - if (!verbose) { - System.out.println(flowEntry.getNode() + " " + flowEntry.getFlowName()); - } else { - System.out.println(flowEntry.getNode() + " " + flowEntry.toString()); - } - } - } - - @Descriptor("Displays all the flow entries for a network node") - public void showRequestedNodeFlows( - @Descriptor("Container in which to query FRM") String container, - @Descriptor("String representation of the Node, this need to be consumable from Node.fromString()") String nodeId, - @Descriptor("True for verbose else false") Boolean verbose) { - IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( - IForwardingRulesManager.class, container, this); - if (frm == null) { - System.out.println("Cannot find the FRM instance on container: " + container); - return; - } - Node node = Node.fromString(nodeId); - if (node == null) { - System.out.println("Please enter a valid node id"); - return; - } - List groupFlows = frm.getFlowEntriesForNode(node); - System.out.println("Node " + nodeId); - for (FlowEntry flowEntry : groupFlows) { - if (!verbose) { - System.out.println(flowEntry.getNode() + " " + flowEntry.getFlowName()); - } else { - System.out.println(flowEntry.getNode() + " " + flowEntry.toString()); - } - } - } - - @Descriptor("Displays all the flow entries installed in a network node") - public void showInstalledNodeFlows( - @Descriptor("Container in which to query FRM") String container, - @Descriptor("String representation of the Node, this need to be consumable from Node.fromString()") String nodeId, - @Descriptor("True for verbose else false") Boolean verbose) { - IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( - IForwardingRulesManager.class, container, this); - if (frm == null) { - System.out.println("Cannot find the FRM instance on container: " + container); - return; - } - Node node = Node.fromString(nodeId); - if (node == null) { - System.out.println("Please enter a valid node id"); - return; - } - List groupFlows = frm.getInstalledFlowEntriesForNode(node); - System.out.println("Node " + nodeId); - for (FlowEntry flowEntry : groupFlows) { - if (!verbose) { - System.out.println(flowEntry.getNode() + " " + flowEntry.getFlowName()); - } else { - System.out.println(flowEntry.getNode() + " " + flowEntry.toString()); - } - } - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/integrationtest/pom.xml b/opendaylight/adsal/forwardingrulesmanager/integrationtest/pom.xml deleted file mode 100644 index 361506ac27..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/integrationtest/pom.xml +++ /dev/null @@ -1,172 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.integrationtest - 0.7.0-SNAPSHOT - ../../commons/integrationtest - - - forwardingrulesmanager.integrationtest - 0.6.0-SNAPSHOT - - ../../implementation/target/jacoco-it.exec - - ../../implementation/target/jacoco.exec - - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - clustering.stub - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - configuration.implementation - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - connectionmanager.implementation - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.it.implementation - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - forwardingrulesmanager.implementation - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - hosttracker.implementation - - - org.opendaylight.controller - protocol_plugins.stub - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller - sal.connection.implementation - - - org.opendaylight.controller - sal.implementation - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - switchmanager.implementation - - - org.opendaylight.controller - topologymanager - - - org.slf4j - log4j-over-slf4j - - - - org.ops4j.pax.exam - pax-exam-container-native - test - - - org.ops4j.pax.exam - pax-exam-junit4 - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - test - - - org.ops4j.pax.url - pax-url-aether - test - - - - - - org.jacoco - jacoco-maven-plugin - - ../../implementation/target/jacoco-it.exec - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - true - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/forwardingrulesmanager/integrationtest/src/test/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerIT.java b/opendaylight/adsal/forwardingrulesmanager/integrationtest/src/test/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerIT.java deleted file mode 100644 index 6fd7eb2697..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/integrationtest/src/test/java/org/opendaylight/controller/forwardingrulesmanager/internal/ForwardingRulesManagerIT.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.forwardingrulesmanager.internal; - -import static org.junit.Assert.fail; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; -import static org.ops4j.pax.exam.CoreOptions.options; -import static org.ops4j.pax.exam.CoreOptions.systemPackages; -import static org.ops4j.pax.exam.CoreOptions.systemProperty; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - -import javax.inject.Inject; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.forwardingrulesmanager.FlowEntry; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.Drop; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.util.PathUtils; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(PaxExam.class) -public class ForwardingRulesManagerIT { - private Logger log = LoggerFactory.getLogger(ForwardingRulesManagerIT.class); - // get the OSGI bundle context - @Inject - private BundleContext bc; - - private IForwardingRulesManager manager = null; - - // Configure the OSGi container - @Configuration - public Option[] config() { - return options( - // - systemProperty("logback.configurationFile").value( - "file:" + PathUtils.getBaseDir() - + "/src/test/resources/logback.xml"), - // To start OSGi console for inspection remotely - systemProperty("osgi.console").value("2401"), - // Set the systemPackages (used by clustering) - systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"), - // List framework bundles - mavenBundle("equinoxSDK381", "org.eclipse.equinox.console").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.util").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.osgi.services").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell").versionAsInProject(), - // List logger bundles - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), - mavenBundle("org.slf4j", "log4j-over-slf4j") - .versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-core") - .versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-classic") - .versionAsInProject(), - // List all the bundles on which the test case depends - mavenBundle("org.opendaylight.controller", "sal") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.implementation") - .versionAsInProject(), - - mavenBundle("org.opendaylight.controller", - "protocol_plugins.stub").versionAsInProject(), - - mavenBundle("org.opendaylight.controller", "containermanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "containermanager.it.implementation").versionAsInProject(), - - mavenBundle("org.opendaylight.controller", - "forwardingrulesmanager").versionAsInProject(), - - mavenBundle("org.opendaylight.controller", - "forwardingrulesmanager.implementation") - .versionAsInProject(), - - mavenBundle("org.opendaylight.controller", - "clustering.services").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "clustering.stub") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "switchmanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "statisticsmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "switchmanager.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "configuration") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "configuration.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "hosttracker") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "hosttracker.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "connectionmanager.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "connectionmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "sal.connection").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "sal.connection.implementation").versionAsInProject(), - - // needed by hosttracker - mavenBundle("org.opendaylight.controller", "topologymanager") - .versionAsInProject(), - - mavenBundle("org.jboss.spec.javax.transaction", - "jboss-transaction-api_1.1_spec").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3") - .versionAsInProject(), - mavenBundle("org.apache.felix", - "org.apache.felix.dependencymanager") - .versionAsInProject(), junitBundles()); - } - - private String stateToString(int state) { - switch (state) { - case Bundle.ACTIVE: - return "ACTIVE"; - case Bundle.INSTALLED: - return "INSTALLED"; - case Bundle.RESOLVED: - return "RESOLVED"; - case Bundle.UNINSTALLED: - return "UNINSTALLED"; - default: - return "Not CONVERTED"; - } - } - - @Before - public void areWeReady() { - assertNotNull(bc); - boolean debugit = false; - Bundle b[] = bc.getBundles(); - for (Bundle element : b) { - int state = element.getState(); - if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) { - log.debug("Bundle:" + element.getSymbolicName() + " state:" - + stateToString(state)); - debugit = true; - } - } - if (debugit) { - log.debug("Do some debugging because some bundle is " - + "unresolved"); - } - - // Assert if true, if false we are good to go! - assertFalse(debugit); - - ServiceReference r = bc.getServiceReference(IForwardingRulesManager.class.getName()); - if (r != null) { - this.manager = (IForwardingRulesManager) bc.getService(r); - } - // If StatisticsManager is null, cannot run tests. - assertNotNull(this.manager); - - } - - @Test - public void testFlowEntries() { - Flow flow = new Flow(); - - Match match = new Match(); - try { - match.setField(MatchType.NW_DST, InetAddress.getByName("1.1.1.1")); - } catch (UnknownHostException e) { - } - flow.setMatch(match); - Action action = new Drop(); - - List actions = new ArrayList(); - actions.add(action); - flow.setActions(actions); - Node node; - try { - // Must use a node published by the stub protocol plugin else - // connection manager will not report it as a local node - node = new Node("STUB", 51966); - FlowEntry fe = new FlowEntry("g1", "f1", flow, node); - Status stat = manager.installFlowEntry(fe); - - Assert.assertTrue(stat.getCode() == StatusCode.SUCCESS); - } catch (ConstructionException e) { - // Got a failure while allocating the node - fail("Failed while allocating the node " + e.getMessage()); - } - } -} diff --git a/opendaylight/adsal/forwardingrulesmanager/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/forwardingrulesmanager/integrationtest/src/test/resources/logback.xml deleted file mode 100644 index 2d63ce5744..0000000000 --- a/opendaylight/adsal/forwardingrulesmanager/integrationtest/src/test/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/opendaylight/adsal/hosttracker/api/pom.xml b/opendaylight/adsal/hosttracker/api/pom.xml deleted file mode 100644 index 8e5a18df85..0000000000 --- a/opendaylight/adsal/hosttracker/api/pom.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - hosttracker - 0.7.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - sal - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.hosttracker, - org.opendaylight.controller.hosttracker.hostAware - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.packet.address, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.felix.dm, - org.osgi.service.component, - org.slf4j, - org.eclipse.osgi.framework.console, - org.osgi.framework - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/HostIdFactory.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/HostIdFactory.java deleted file mode 100644 index 4585306214..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/HostIdFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.hosttracker; - -import java.net.InetAddress; - -import org.opendaylight.controller.sal.packet.address.DataLinkAddress; - -/* - * Class used to generate a key based on the scheme choosen for hostsdb storage in hosttracker. - * @author Deepak Udapudi - */ -public class HostIdFactory { - public static final String DEFAULT_IP_KEY_SCHEME = "IP"; - public static final String IP_MAC_KEY_SCHEME = "IP+MAC"; - private static String scheme = null; - static { - scheme = System.getProperty("hosttracker.keyscheme"); - } - - public static String getScheme() { - return scheme; - } - - public static IHostId create(InetAddress ip, DataLinkAddress mac) { - IHostId ipHostId = new IPHostId(ip); - if (scheme != null) { - switch (scheme) { - - case DEFAULT_IP_KEY_SCHEME: - return ipHostId; - case IP_MAC_KEY_SCHEME: - IHostId ipMacHostId = new IPMacHostId(ip, mac); - return ipMacHostId; - default: - return ipHostId; - - } - } - return ipHostId; - } - -} diff --git a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostId.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostId.java deleted file mode 100644 index 03f409e737..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostId.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.hosttracker; - -import java.io.Serializable; - -/* - * Marker interface used by the key classes for their implementation - * @author Deepak Udapudi - */ - -public interface IHostId extends Serializable { - -} diff --git a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java deleted file mode 100644 index 5d11be4826..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.opendaylight.controller.hosttracker; - -import java.util.List; - -public interface IHostTrackerShell{ - - public List dumpPendingArpReqList(); - public List dumpFailedArpReqList(); -} \ No newline at end of file diff --git a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPHostId.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPHostId.java deleted file mode 100644 index a6314e0695..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPHostId.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.hosttracker; - -import java.io.Serializable; -import java.net.InetAddress; - -/* - * IP only key class implementation using the marker interface IHostId - * @author Deepak Udapudi - */ - -public class IPHostId implements IHostId, Serializable { - private static final long serialVersionUID = 1L; - private InetAddress ipAddress; - - public InetAddress getIpAddress() { - return ipAddress; - } - - public void setIpAddress(InetAddress ipAddress) { - this.ipAddress = ipAddress; - } - - public IPHostId(InetAddress ipAddress) { - super(); - this.ipAddress = ipAddress; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((ipAddress == null) ? 0 : ipAddress.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - IPHostId other = (IPHostId) obj; - if (ipAddress == null) { - if (other.ipAddress != null) { - return false; - } - } else if (!ipAddress.equals(other.ipAddress)) { - return false; - } - return true; - } - - public static IHostId fromIP(InetAddress addr) { - return new IPHostId(addr); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("IP=["); - if (this.ipAddress != null) { - builder.append(this.ipAddress.getHostAddress()); - } - builder.append("]"); - return (builder.toString()); - } -} diff --git a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPMacHostId.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPMacHostId.java deleted file mode 100644 index 19f3f585b1..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IPMacHostId.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.hosttracker; - -import java.io.Serializable; -import java.net.InetAddress; - -/* - * IP + Mac key class implementation using the marker interface IHostId - * @author Deepak Udapudi - */ - -import org.opendaylight.controller.sal.packet.address.DataLinkAddress; - -public class IPMacHostId implements IHostId, Serializable { - - private static final long serialVersionUID = 1L; - private InetAddress ipAddress; - private DataLinkAddress macAddr; - - public IPMacHostId(InetAddress ipAddress, DataLinkAddress macAddr) { - super(); - this.ipAddress = ipAddress; - this.macAddr = macAddr; - } - - public InetAddress getIpAddress() { - return ipAddress; - } - - public void setIpAddress(InetAddress ipAddress) { - this.ipAddress = ipAddress; - } - - public DataLinkAddress getMacAddr() { - return macAddr; - } - - public void setMacAddr(DataLinkAddress macAddr) { - this.macAddr = macAddr; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((ipAddress == null) ? 0 : ipAddress.hashCode()); - result = prime * result + ((macAddr == null) ? 0 : macAddr.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - IPMacHostId other = (IPMacHostId) obj; - if (ipAddress == null) { - if (other.ipAddress != null) { - return false; - } - } else if (!ipAddress.equals(other.ipAddress)) { - return false; - } - if (macAddr == null) { - if (other.macAddr != null) { - return false; - } - } else if (!macAddr.equals(other.macAddr)) { - return false; - } - return true; - } - - public static IHostId fromIPAndMac(InetAddress ip, DataLinkAddress mac) { - return new IPMacHostId(ip, mac); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("IP=["); - if (this.ipAddress != null) { - builder.append(this.ipAddress.getHostAddress()); - } - builder.append("]") - .append("MAC=["); - if (this.macAddr != null) { - builder.append(this.macAddr.toString()); - } - builder.append("]"); - return (builder.toString()); - } -} diff --git a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java deleted file mode 100644 index 51d68d87b4..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; - -/** - * This interface defines the method to notify detected Host on the network. The - * information includes Host's IP address, MAC address, switch ID, port, and - * VLAN. - * - */ - -public interface IfHostListener { - /** - * Learns new Hosts. Called by ArpHandler and implemented in - * HostTracker.java. If a Host is learned for the first time then adds it to - * the local database and informs other applications of coming up a new - * Host. For the hosts which it has already learned, it refreshes them. - * - * @param host - * Host info encapsulated in HostNodeConnector class - */ - public void hostListener(HostNodeConnector host); -} diff --git a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java deleted file mode 100644 index e70a6e1865..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker; - -import java.net.InetAddress; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Future; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.Status; - -/** - * This interface defines the methods to retrieve information about learned - * Hosts. Also provides methods to statically add/remove Hosts from the local - * database. - * - */ - -public interface IfIptoHost { - /** - * Applications call this interface methods to determine IP address to MAC - * binding and its connectivity to an OpenFlow switch in term of Node, Port, - * and VLAN. These bindings are learned dynamically as well as can be added - * statically through Northbound APIs. If a binding is unknown, then an ARP - * request is initiated immediately to discover the host. - * - * @param id - * IP address and Mac Address combination encapsulated in IHostId - * interface - * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * Class that contains the Host info such as its MAC address, Switch - * ID, port, VLAN. If Host is not found, returns NULL - */ - public HostNodeConnector hostFind(IHostId id); - - /** - * Applications call this interface methods to determine IP address to MAC - * binding and its connectivity to an OpenFlow switch in term of Node, Port, - * and VLAN. These bindings are learned dynamically as well as can be added - * statically through Northbound APIs. If a binding is unknown, then an ARP - * request is initiated immediately to discover the host. - * - * @param addr - * IP address of the host - * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * Class that contains the Host info such as its MAC address, Switch - * ID, port, VLAN. If Host is not found, returns NULL - */ - public HostNodeConnector hostFind(InetAddress addr); - - /** - * Checks the local Host Database to see if a Host has been learned for a - * given IP address and Mac combination using the HostId. - * - * @param id - * IP address and Mac Address combination encapsulated in IHostId - * interface - * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * Class that contains the Host info such as its MAC address, Switch - * ID, port, VLAN. If Host is not found, returns NULL - * - */ - public HostNodeConnector hostQuery(IHostId id); - - /** - * Checks the local Host Database to see if a Host has been learned for a - * given IP address and Mac combination using the HostId. - * - * @param addr - * IP address of the Host - * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * Class that contains the Host info such as its MAC address, Switch - * ID, port, VLAN. If Host is not found, returns NULL - * - */ - public HostNodeConnector hostQuery(InetAddress addr); - - /** - * Initiates an immediate discovery of the Host for a given Host id. This - * provides for the calling applications to block on the host discovery. - * - * @param id - * IP address and Mac Address combination encapsulated in IHostId - * interface - * @return Future - * {@link org.opendaylight.controller.hosttracker.HostTrackerCallable} - */ - public Future discoverHost(IHostId id); - - /** - * Initiates an immediate discovery of the Host for a given Host id. This - * provides for the calling applications to block on the host discovery. - * - * @param addr - * IP address of the host - * @return Future - * {@link org.opendaylight.controller.hosttracker.HostTrackerCallable} - */ - public Future discoverHost(InetAddress addr); - - /** - * Returns the Network Hierarchy for a given Host. This API is typically - * used by applications like Hadoop for Rack Awareness functionality. - * - * @param id - * IP address and Mac Address combination encapsulated in IHostId - * interface - * @return List of String ArrayList containing the Hierarchies. - */ - public List> getHostNetworkHierarchy(IHostId id); - - /** - * Returns the Network Hierarchy for a given Host. This API is typically - * used by applications like Hadoop for Rack Awareness functionality. - * - * @param addr - * IP address of the host - * @return List of String ArrayList containing the Hierarchies. - */ - public List> getHostNetworkHierarchy(InetAddress addr); - - /** - * Returns all the the Hosts either learned dynamically or added statically - * via Northbound APIs. - * - * @return Set of - * {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * . Class that contains the Host info such as its MAC address, - * Switch ID, port, VLAN. - */ - public Set getAllHosts(); - - /** - * Returns all the "Active Hosts" learned "Statically" via Northbound APIs. - * These Hosts are categorized as "Active" because the Switch and Port they - * are connected to, are in up state. - * - * @return Set of - * {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * . Class that contains the Host info such as MAC address, Switch - * ID, port, VLAN. If Host is not found, returns NULL - */ - public Set getActiveStaticHosts(); - - /** - * Returns all the "Inactive Hosts" learned "Statically" via Northbound - * APIs. These Hosts are categorized as "Inactive" because either the Switch - * or the Port they are connected to, is in down state. - * - * @return Set of HostNodeConnector - * {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * . HostNodeConnector is Class that contains the Host info such as - * its MAC address, OpenFlowNode ID, port, VLAN. - */ - public Set getInactiveStaticHosts(); - - /** - * Hosts can be learned dynamically or added statically. This method allows - * the addition of a Host to the local database statically. - * - * @param networkAddress - * IP Address of the Host - * @param dataLayerAddress - * MAC Address of the Host - * @param nc - * NodeConnector to which the host is attached - * @param vlan - * VLAN the host belongs to (null or empty for no vlan) - * @return The status object as described in {@code Status} indicating the - * result of this action. - */ - public Status addStaticHost(String networkAddress, String dataLayerAddress, NodeConnector nc, String vlan); - - /** - * Allows the deletion of statically learned Host - * - * @param networkAddress - * @return The status object as described in {@code Status} indicating the - * result of this action. - */ - public Status removeStaticHost(String networkAddress); - - /** - * Allows the deletion of statically learned Host - * - * @param networkAddress - * @param macAddress - * @return The status object as described in {@code Status} indicating the - * result of this action. - */ - public Status removeStaticHostUsingIPAndMac(String networkAddress, String macAddress); -} diff --git a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java deleted file mode 100644 index ef900e475e..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; - -/** - * This Interface defines the methods for client applications of Host Tracker to - * get notifications when a new host is learned or existing host is removed from - * the network. - * - */ -public interface IfNewHostNotify { - /** - * Notifies the HostTracker Clients that a new Host has been learned - * - * @param host - * Host Info encapsulated in HostNodeConnector class - */ - public void notifyHTClient(HostNodeConnector host); - - /** - * Notifies the HostTracker Clients that a Host which was learned in the - * past has been removed either due to switch/port down event or due to ARP - * Aging - * - * @param host - * Host Info encapsulated in HostNodeConnector class - */ - public void notifyHTClientHostRemoved(HostNodeConnector host); -} diff --git a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java deleted file mode 100644 index f3f86a56e2..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.hostAware; - -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.util.Arrays; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Host; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.packet.address.EthernetAddress; - -@XmlRootElement(name = "host") -@XmlAccessorType(XmlAccessType.NONE) -public class HostNodeConnector extends Host { - private static final long serialVersionUID = 1L; - @XmlElement - private NodeConnector nodeConnector; - @XmlElement - private short vlan; - @XmlElement - private boolean staticHost; - private short arpSendCountDown; - - /** - * Private constructor used for JAXB mapping - */ - @SuppressWarnings("unused") - private HostNodeConnector() { - } - - public HostNodeConnector(InetAddress ip) throws ConstructionException { - this(ip, null); - } - - public HostNodeConnector(InetAddress ip, NodeConnector nc) - throws ConstructionException { - this(new EthernetAddress(new byte[] { (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }), ip, nc, - (short) 0); - } - - public HostNodeConnector(byte[] mac, InetAddress ip, NodeConnector nc, - short vlan) throws ConstructionException { - this(new EthernetAddress(mac.clone()), ip, nc, vlan); - } - - public HostNodeConnector(EthernetAddress eaddr, InetAddress naddr, - NodeConnector nc, short vlan) throws ConstructionException { - super(eaddr, naddr); - this.nodeConnector = nc; - this.vlan = vlan; - } - - /** - * @return the NodeConnector - */ - public NodeConnector getnodeConnector() { - return this.nodeConnector; - } - - /** - * @return the Node - */ - public Node getnodeconnectorNode() { - return this.nodeConnector.getNode(); - } - - /** - * @return the DataLayerAddress - */ - public byte[] getDataLayerAddressBytes() { - byte[] macaddr = null; - if (getDataLayerAddress() instanceof EthernetAddress) { - EthernetAddress e = (EthernetAddress) getDataLayerAddress(); - macaddr = e.getValue(); - } - return macaddr; - } - - /** - * @return the vlan - */ - public short getVlan() { - return this.vlan; - } - - public boolean isStaticHost() { - return this.staticHost; - } - - public HostNodeConnector setStaticHost(boolean statically_learned) { - this.staticHost = statically_learned; - return this; - } - - public HostNodeConnector initArpSendCountDown() { - this.arpSendCountDown = 24; - return this; - } - - public short getArpSendCountDown() { - return (this.arpSendCountDown); - } - - public HostNodeConnector setArpSendCountDown(short cntdown) { - this.arpSendCountDown = cntdown; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result - + ((nodeConnector == null) ? 0 : nodeConnector.hashCode()); - result = prime * result + (staticHost ? 1231 : 1237); - result = prime * result + vlan; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - HostNodeConnector other = (HostNodeConnector) obj; - if (nodeConnector == null) { - if (other.nodeConnector != null) { - return false; - } - } else if (!nodeConnector.equals(other.nodeConnector)) { - return false; - } - if (staticHost != other.staticHost) { - return false; - } - if (vlan != other.vlan) { - return false; - } - return true; - } - - public boolean equalsByIP(InetAddress networkAddress) { - return (this.getNetworkAddress().equals(networkAddress)); - } - - public boolean isRewriteEnabled() { - byte[] emptyArray = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00 }; - byte[] macaddr = null; - if (getDataLayerAddress() instanceof EthernetAddress) { - EthernetAddress e = (EthernetAddress) getDataLayerAddress(); - macaddr = e.getValue(); - } - if (macaddr == null) { - return false; - } - return !Arrays.equals(emptyArray, macaddr); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("HostNodeConnector ["); - if (nodeConnector != null) { - builder.append("nodeConnector=") - .append(nodeConnector) - .append(", "); - } - builder.append("vlan=") - .append(vlan) - .append(", staticHost=") - .append(staticHost) - .append(", arpSendCountDown=") - .append(arpSendCountDown) - .append("]"); - return builder.toString(); - } - - public boolean isV4Host() { - return (getNetworkAddress() instanceof Inet4Address); - } - - public boolean isV6Host() { - return (getNetworkAddress() instanceof Inet6Address); - } - - public String toJson() { - return "{\"host\":\"" + super.toString() + "\", " + "\"vlan\":\"" - + String.valueOf(vlan) + "\",\"NodeConnector\":\"" - + nodeConnector.toString() + "\"," + "\"static\":\"" - + String.valueOf(isStaticHost()) + "\"}"; - } - -} diff --git a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java b/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java deleted file mode 100644 index abe75180cf..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.hostAware; - -import java.net.InetAddress; - -/** - * This Interface defines the methods to trigger the discovery of a Host and to - * probe if a learned Host is still in the network. - * - * - * - */ -public interface IHostFinder { - /** - * This method initiates the discovery of a host based on its IP address. - * This is triggered by query of an application to the HostTracker. The - * requested IP address doesn't exist in the local database at this point. - * - * @param networkAddress - * IP Address encapsulated in InetAddress class - * - */ - public void find(InetAddress networkAddress); - - /** - * This method is called by HostTracker to see if a learned Host is still in - * the network. Used mostly for ARP Aging. - * - * @param host - * The Host that needs to be probed - */ - public void probe(HostNodeConnector host); -} diff --git a/opendaylight/adsal/hosttracker/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java b/opendaylight/adsal/hosttracker/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java deleted file mode 100644 index 96cf308983..0000000000 --- a/opendaylight/adsal/hosttracker/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.hostAware; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.packet.address.EthernetAddress; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -public class HostNodeConnectorTest { - - @Test - public void testHostNodeConnector() throws UnknownHostException { - HostNodeConnector hostnodeconnector_1, hostnodeconnector_2, hostnodeconnector_3; - InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8"); - InetAddress hostIP_2 = InetAddress - .getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress hostIP_3 = InetAddress.getByName("192.168.0.28"); - byte[] hostMAC_2 = new byte[] { (byte) 0x11, (byte) 0x22, (byte) 0x33, - (byte) 0x22, (byte) 0x22, (byte) 0x22 }; - byte[] hostMAC_3 = new byte[] { (byte) 0x11, (byte) 0x22, (byte) 0x33, - (byte) 0x33, (byte) 0x33, (byte) 0x33 }; - - Node node = NodeCreator.createOFNode(1L); - NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node); - NodeConnector nc2 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node); - - try { - hostnodeconnector_1 = new HostNodeConnector(hostIP_1); - Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1)); - Assert.assertTrue(hostnodeconnector_1.isV4Host()); - Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1)); - } catch (ConstructionException e) { - Assert.assertTrue(false); - } - - try { - hostnodeconnector_2 = new HostNodeConnector(hostMAC_2, hostIP_2, - nc1, (short) 2); - Assert.assertTrue(hostnodeconnector_2.isV6Host()); - Assert.assertTrue(hostnodeconnector_2.getnodeConnector() - .equals(nc1)); - Assert.assertTrue(hostnodeconnector_2.getnodeconnectorNode() - .equals(node)); - Assert.assertTrue(node.equals(hostnodeconnector_2 - .getnodeconnectorNode())); - } catch (ConstructionException e) { - Assert.assertTrue(false); - } - - try { - hostnodeconnector_3 = new HostNodeConnector(new EthernetAddress( - hostMAC_3), hostIP_3, nc2, (short) 3); - byte[] hostMAC_3_rb = hostnodeconnector_3 - .getDataLayerAddressBytes(); - HostNodeConnector hostnodeconnector_3rb = new HostNodeConnector( - new EthernetAddress(hostMAC_3_rb), hostIP_3, nc2, (short) 3); - Assert.assertTrue(hostnodeconnector_3.equals(hostnodeconnector_3rb)); - - Assert.assertTrue(hostnodeconnector_3.getVlan() == (short) 3); - - hostnodeconnector_3.setStaticHost(true); - Assert.assertTrue(hostnodeconnector_3.isStaticHost()); - - Assert.assertTrue(hostnodeconnector_3.isRewriteEnabled()); - - hostnodeconnector_3.initArpSendCountDown().setArpSendCountDown( - (short) 10); - Assert.assertTrue(hostnodeconnector_3.getArpSendCountDown() == (short) 10); - - } catch (ConstructionException e) { - Assert.assertTrue(false); - } - - } - -} diff --git a/opendaylight/adsal/hosttracker/implementation/pom.xml b/opendaylight/adsal/hosttracker/implementation/pom.xml deleted file mode 100644 index 50bb26783a..0000000000 --- a/opendaylight/adsal/hosttracker/implementation/pom.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - hosttracker.implementation - 0.7.0-SNAPSHOT - bundle - - - - reuseReports - target/jacoco.exec - target/jacoco-it.exec - - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - topologymanager - - - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.topology, - org.opendaylight.controller.hosttracker, - org.opendaylight.controller.topologymanager, - org.opendaylight.controller.sal.packet.address, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.hosttracker.hostAware, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.felix.dm, - org.apache.commons.lang3.builder, - org.osgi.service.component, - org.slf4j, - org.eclipse.osgi.framework.console, - org.osgi.framework - org.opendaylight.controller.hosttracker.internal.Activator - - - ${project.basedir}/META-INF - - - - org.jacoco - jacoco-maven-plugin - - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - report - - test - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java b/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java deleted file mode 100644 index 7e527712b1..0000000000 --- a/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.internal; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.hosttracker.IHostTrackerShell; -import org.opendaylight.controller.hosttracker.IfHostListener; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.IfNewHostNotify; -import org.opendaylight.controller.hosttracker.hostAware.IHostFinder; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.ISwitchManagerAware; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.opendaylight.controller.topologymanager.ITopologyManagerAware; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the list of - * known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { HostTracker.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies is - * required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - * @param containerName - * The containerName being configured, this allow also optional - * per-container different behavior if needed, usually should not - * be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(HostTracker.class)) { - Dictionary props = new Hashtable(); - Set propSet = new HashSet(); - propSet.add(HostTracker.ACTIVE_HOST_CACHE); - props.put("cachenames", propSet); - - // export the service - c.setInterface( - new String[] { ISwitchManagerAware.class.getName(), - IInventoryListener.class.getName(), - IfIptoHost.class.getName(), - IfHostListener.class.getName(), - IHostTrackerShell.class.getName(), - ITopologyManagerAware.class.getName(), - ICacheUpdateAware.class.getName() }, props); - - c.add(createContainerServiceDependency(containerName) - .setService(ISwitchManager.class) - .setCallbacks("setSwitchManager", "unsetSwitchManager") - .setRequired(true)); - c.add(createContainerServiceDependency(containerName) - .setService(IClusterContainerServices.class) - .setCallbacks("setClusterContainerService", - "unsetClusterContainerService").setRequired(true)); - c.add(createContainerServiceDependency(containerName) - .setService(IHostFinder.class) - .setCallbacks("setArpHandler", "unsetArpHandler") - .setRequired(false)); - c.add(createContainerServiceDependency(containerName) - .setService(ITopologyManager.class) - .setCallbacks("setTopologyManager", "unsetTopologyManager") - .setRequired(false)); - c.add(createContainerServiceDependency(containerName) - .setService(IfNewHostNotify.class) - .setCallbacks("setnewHostNotify", "unsetnewHostNotify") - .setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java b/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java deleted file mode 100644 index f728b35bbf..0000000000 --- a/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java +++ /dev/null @@ -1,1642 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Dictionary; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import org.apache.felix.dm.Component; -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.hosttracker.HostIdFactory; -import org.opendaylight.controller.hosttracker.IHostId; -import org.opendaylight.controller.hosttracker.IHostTrackerShell; -import org.opendaylight.controller.hosttracker.IPHostId; -import org.opendaylight.controller.hosttracker.IPMacHostId; -import org.opendaylight.controller.hosttracker.IfHostListener; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.IfNewHostNotify; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.hosttracker.hostAware.IHostFinder; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Host; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.Tier; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.packet.address.DataLinkAddress; -import org.opendaylight.controller.sal.packet.address.EthernetAddress; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.ISwitchManagerAware; -import org.opendaylight.controller.switchmanager.Subnet; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.opendaylight.controller.topologymanager.ITopologyManagerAware; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @file HostTracker.java This class tracks the location of IP Hosts as to which - * Switch, Port, VLAN, they are connected to, as well as their MAC - * address. This is done dynamically as well as statically. The dynamic - * mechanism consists of listening to ARP messages as well sending ARP - * requests. Static mechanism consists of Northbound APIs to add or remove - * the hosts from the local database. ARP aging is also implemented to age - * out dynamically learned hosts. Interface methods are provided for other - * applications to 1. Query the local database for a single host 2. Get a - * list of all hosts 3. Get notification if a host is learned/added or - * removed the database - */ - -/*** - * - * HostTracker db key scheme implementation support. Support has been added for - * IP only or IP + MAC scheme as of now. User can use either of the schemes - * based on the configuration done in config.ini file. By default IP only key - * scheme is choosen. The attribute to be set in config.ini is - * hosttracker.keyscheme. It could have a value of 0 or 1 as of now. 0 is for IP - * only scheme. 1 is for IP + MAC scheme. - * - * - */ - -public class HostTracker implements IfIptoHost, IfHostListener, IHostTrackerShell, ISwitchManagerAware, IInventoryListener, - ITopologyManagerAware, ICacheUpdateAware, CommandProvider { - static final String ACTIVE_HOST_CACHE = "hosttracker.ActiveHosts"; - static final String INACTIVE_HOST_CACHE = "hosttracker.InactiveHosts"; - private static final Logger logger = LoggerFactory.getLogger(HostTracker.class); - protected final Set hostFinders = new CopyOnWriteArraySet(); - protected ConcurrentMap hostsDB; - /* - * Following is a list of hosts which have been requested by NB APIs to be - * added, but either the switch or the port is not sup, so they will be - * added here until both come up - */ - private ConcurrentMap inactiveStaticHosts; - private final Set newHostNotify = Collections.synchronizedSet(new HashSet()); - - private ITopologyManager topologyManager; - protected IClusterContainerServices clusterContainerService = null; - protected ISwitchManager switchManager = null; - private Timer timer; - private Timer arpRefreshTimer; - private String containerName = null; - private ExecutorService executor; - protected boolean stopping; - private static boolean hostRefresh = true; - private static int hostRetryCount = 5; - private String keyScheme = null; - - private static class ARPPending { - protected IHostId hostId; - protected short sent_count; - protected HostTrackerCallable hostTrackerCallable; - - public IHostId getHostId() { - return hostId; - } - - public short getSent_count() { - return sent_count; - } - - public HostTrackerCallable getHostTrackerCallable() { - return hostTrackerCallable; - } - - public void setHostId(IHostId id) { - this.hostId = id; - } - - public void setSent_count(short count) { - this.sent_count = count; - } - - public void setHostTrackerCallable(HostTrackerCallable callable) { - hostTrackerCallable = callable; - } - } - - // This list contains the hosts for which ARP requests are being sent - // periodically - ConcurrentMap ARPPendingList; - /* - * This list below contains the hosts which were initially in ARPPendingList - * above, but ARP response didn't come from there hosts after multiple - * attempts over 8 seconds. The assumption is that the response didn't come - * back due to one of the following possibilities: 1. The L3 interface - * wasn't created for this host in the controller. This would cause - * arphandler not to know where to send the ARP 2. The host facing port is - * down 3. The IP host doesn't exist or is not responding to ARP requests - * - * Conditions 1 and 2 above can be recovered if ARP is sent when the - * relevant L3 interface is added or the port facing host comes up. Whenever - * L3 interface is added or host facing port comes up, ARP will be sent to - * hosts in this list. - * - * We can't recover from condition 3 above - */ - ConcurrentMap failedARPReqList; - - public HostTracker() { - } - - private void startUp() { - nonClusterObjectCreate(); - allocateCache(); - retrieveCache(); - stopping = false; - - timer = new Timer(); - timer.schedule(new OutStandingARPHandler(), 4000, 4000); - executor = Executors.newFixedThreadPool(2); - /* ARP Refresh Timer to go off every 5 seconds to implement ARP aging */ - arpRefreshTimer = new Timer(); - arpRefreshTimer.schedule(new ARPRefreshHandler(), 5000, 5000); - keyScheme = HostIdFactory.getScheme(); - logger.debug("startUp: Caches created, timers started"); - } - - private void allocateCache() { - if (this.clusterContainerService == null) { - logger.error("un-initialized clusterContainerService, can't create cache"); - return; - } - logger.debug("Creating Cache for HostTracker"); - try { - this.clusterContainerService.createCache(ACTIVE_HOST_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - this.clusterContainerService.createCache(INACTIVE_HOST_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheConfigException cce) { - logger.error("Cache couldn't be created for HostTracker - check cache mode"); - } catch (CacheExistException cce) { - logger.error("Cache for HostTracker already exists, destroy and recreate"); - } - logger.debug("Cache successfully created for HostTracker"); - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCache() { - if (this.clusterContainerService == null) { - logger.error("un-initialized clusterContainerService, can't retrieve cache"); - return; - } - logger.debug("Retrieving cache for HostTrackerAH"); - hostsDB = (ConcurrentMap) this.clusterContainerService.getCache(ACTIVE_HOST_CACHE); - if (hostsDB == null) { - logger.error("Cache couldn't be retrieved for HostTracker"); - } - logger.debug("Cache was successfully retrieved for HostTracker"); - logger.debug("Retrieving cache for HostTrackerIH"); - inactiveStaticHosts = (ConcurrentMap) this.clusterContainerService - .getCache(INACTIVE_HOST_CACHE); - if (inactiveStaticHosts == null) { - logger.error("Cache couldn't be retrieved for HostTrackerIH"); - } - logger.debug("Cache was successfully retrieved for HostTrackerIH"); - } - - public void nonClusterObjectCreate() { - hostsDB = new ConcurrentHashMap(); - inactiveStaticHosts = new ConcurrentHashMap(); - ARPPendingList = new ConcurrentHashMap(); - failedARPReqList = new ConcurrentHashMap(); - } - - public void shutDown() { - } - - public void setnewHostNotify(IfNewHostNotify obj) { - this.newHostNotify.add(obj); - } - - public void unsetnewHostNotify(IfNewHostNotify obj) { - this.newHostNotify.remove(obj); - } - - public void setArpHandler(IHostFinder hostFinder) { - this.hostFinders.add(hostFinder); - } - - public void unsetArpHandler(IHostFinder hostFinder) { - logger.debug("Arp Handler Service removed!"); - this.hostFinders.remove(hostFinder); - } - - public void setTopologyManager(ITopologyManager s) { - this.topologyManager = s; - } - - public void unsetTopologyManager(ITopologyManager s) { - if (this.topologyManager == s) { - logger.debug("Topology Manager Service removed!"); - this.topologyManager = null; - } - } - - private boolean hostExists(HostNodeConnector host) { - IHostId id = HostIdFactory.create(host.getNetworkAddress(), host.getDataLayerAddress()); - HostNodeConnector lhost = hostsDB.get(id); - return host.equals(lhost); - } - - private HostNodeConnector getHostFromOnActiveDB(IHostId id) { - return hostsDB.get(id); - } - - private Entry getHostFromInactiveDB(IHostId id) { - for (Entry entry : inactiveStaticHosts.entrySet()) { - HostNodeConnector hnc = entry.getValue(); - IHostId cmpId = HostIdFactory.create(hnc.getNetworkAddress(), hnc.getDataLayerAddress()); - if (cmpId.equals(id)) { - logger.debug("getHostFromInactiveDB(): Inactive Host found for ID:{} ", decodeIPFromId(id)); - return entry; - } - } - logger.debug("getHostFromInactiveDB() Inactive Host Not found for ID: {}", decodeIPFromId(id)); - return null; - } - - private void removeHostFromInactiveDB(IHostId id) { - NodeConnector nodeConnector = null; - for (Entry entry : inactiveStaticHosts.entrySet()) { - HostNodeConnector hnc = entry.getValue(); - IHostId cmpId = HostIdFactory.create(hnc.getNetworkAddress(), hnc.getDataLayerAddress()); - if (cmpId.equals(id)) { - nodeConnector = entry.getKey(); - break; - } - } - if (nodeConnector != null) { - inactiveStaticHosts.remove(nodeConnector); - logger.debug("removeHostFromInactiveDB(): Host Removed for IP: {}", decodeIPFromId(id)); - return; - } - logger.debug("removeHostFromInactiveDB(): Host Not found for IP: {}", decodeIPFromId(id)); - } - - protected boolean hostMoved(HostNodeConnector host) { - IHostId id = HostIdFactory.create(host.getNetworkAddress(), host.getDataLayerAddress()); - if (hostQuery(id) != null) { - return true; - } - return false; - } - - @Override - public HostNodeConnector hostQuery(IHostId id) { - return hostsDB.get(id); - } - - @Override - public Future discoverHost(IHostId id) { - if (executor == null) { - logger.debug("discoverHost: Null executor"); - return null; - } - Callable worker = new HostTrackerCallable(this, id); - Future submit = executor.submit(worker); - return submit; - } - - @Override - public HostNodeConnector hostFind(IHostId id) { - /* - * Sometimes at boot with containers configured in the startup we hit - * this path (from TIF) when hostFinder has not been set yet Caller - * already handles the null return - */ - - if (hostFinders.isEmpty()) { - logger.debug("No available host finders, exiting hostFind()"); - return null; - } - - HostNodeConnector host = hostQuery(id); - if (host != null) { - logger.debug("hostFind(): Host found for IP: {}", id); - return host; - } - - /* Add this host to ARPPending List for any potential retries */ - - addToARPPendingList(id); - logger.debug("hostFind(): Host Not Found for IP: {}, Inititated Host Discovery ...", id); - - /* host is not found, initiate a discovery */ - for (IHostFinder hf : hostFinders) { - InetAddress addr = decodeIPFromId(id); - hf.find(addr); - } - return null; - } - - @Override - public Set getAllHosts() { - Set allHosts = new HashSet(hostsDB.values()); - return allHosts; - } - - @Override - public Set getActiveStaticHosts() { - Set list = new HashSet(); - for (Entry entry : hostsDB.entrySet()) { - HostNodeConnector host = entry.getValue(); - if (host.isStaticHost()) { - list.add(host); - } - } - return list; - } - - @Override - public Set getInactiveStaticHosts() { - Set list = new HashSet(inactiveStaticHosts.values()); - return list; - } - - private void addToARPPendingList(IHostId id) { - ARPPending arphost = new ARPPending(); - - arphost.setHostId(id); - arphost.setSent_count((short) 1); - ARPPendingList.put(id, arphost); - logger.debug("Host Added to ARPPending List, IP: {}", decodeIPFromId(id)); - - } - - public void setCallableOnPendingARP(IHostId id, HostTrackerCallable callable) { - ARPPending arphost; - for (Entry entry : ARPPendingList.entrySet()) { - arphost = entry.getValue(); - if (arphost.getHostId().equals(id)) { - arphost.setHostTrackerCallable(callable); - } - } - } - - private void processPendingARPReqs(IHostId id) { - ARPPending arphost; - - if ((arphost = ARPPendingList.remove(id)) != null) { - // Remove the arphost from ARPPendingList as it has been learned now - logger.debug("Host Removed from ARPPending List, IP: {}", id); - HostTrackerCallable htCallable = arphost.getHostTrackerCallable(); - if (htCallable != null) { - htCallable.wakeup(); - } - return; - } - - /* - * It could have been a host from the FailedARPReqList - */ - - if (failedARPReqList.containsKey(id)) { - failedARPReqList.remove(id); - logger.debug("Host Removed from FailedARPReqList List, IP: {}", decodeIPFromId(id)); - } - } - - // Learn a new Host - private void learnNewHost(HostNodeConnector host) { - IHostId id = HostIdFactory.create(host.getNetworkAddress(), host.getDataLayerAddress()); - host.initArpSendCountDown(); - HostNodeConnector rHost = hostsDB.putIfAbsent(id, host); - if (rHost != null) { - // Another host is already learned for this IP address, replace it - replaceHost(id, rHost, host); - } else { - logger.debug("New Host Learned: MAC: {} IP: {}", HexEncode.bytesToHexString(host - .getDataLayerAddressBytes()), host.getNetworkAddress().getHostAddress()); - } - } - - private void replaceHost(IHostId id, HostNodeConnector removedHost, HostNodeConnector newHost) { - // Ignore ARP messages from internal nodes - NodeConnector newHostNc = newHost.getnodeConnector(); - boolean newHostIsInternal = topologyManager.isInternal(newHostNc); - if (newHostIsInternal) { - return; - } - - newHost.initArpSendCountDown(); - - if (hostsDB.replace(id, removedHost, newHost)) { - logger.debug("Host move occurred: Old Host IP:{}, New Host IP: {}", removedHost.getNetworkAddress() - .getHostAddress(), newHost.getNetworkAddress().getHostAddress()); - logger.debug("Old Host MAC: {}, New Host MAC: {}", - HexEncode.bytesToHexString(removedHost.getDataLayerAddressBytes()), - HexEncode.bytesToHexString(newHost.getDataLayerAddressBytes())); - // Display the Old and New HostNodeConnectors also - logger.debug("Old {}, New {}", removedHost, newHost); - } else { - /* - * Host replacement has failed, do the recovery - */ - hostsDB.put(id, newHost); - logger.error("Host replacement failed. Overwrite the host. Replaced Host: {}, New Host: {}", removedHost, - newHost); - } - notifyHostLearnedOrRemoved(removedHost, false); - notifyHostLearnedOrRemoved(newHost, true); - if (!newHost.isStaticHost()) { - processPendingARPReqs(id); - } - } - - // Remove known Host - private void removeKnownHost(IHostId key) { - HostNodeConnector host = hostsDB.get(key); - if (host != null) { - logger.debug("Removing Host: IP:{}", host.getNetworkAddress().getHostAddress()); - hostsDB.remove(key); - } else { - logger.error("removeKnownHost(): Host for IP address {} not found in hostsDB", decodeIPFromId(key)); - } - } - - private class NotifyHostThread extends Thread { - - private final HostNodeConnector host; - - public NotifyHostThread(HostNodeConnector h) { - this.host = h; - } - - @Override - public void run() { - HostNodeConnector removedHost = null; - InetAddress networkAddr = host.getNetworkAddress(); - IHostId id = HostIdFactory.create(networkAddr, host.getDataLayerAddress()); - /* Check for Host Move case */ - if (hostMoved(host)) { - /* - * Host has been moved from one location (switch,port, MAC, or - * VLAN) to another. Replace the existing host and its previous - * location parameters with new information, and notify the - * applications listening to host move. - */ - - removedHost = hostsDB.get(id); - if (removedHost != null) { - replaceHost(id, removedHost, host); - return; - } else { - logger.error("Host to be removed not found in hostsDB"); - } - } - - // It is a new host - learnNewHost(host); - - /* check if there is an outstanding request for this host */ - processPendingARPReqs(id); - notifyHostLearnedOrRemoved(host, true); - } - } - - @Override - public void hostListener(HostNodeConnector host) { - logger.debug("Received for Host: IP {}, MAC {}, {}", host.getNetworkAddress().getHostAddress(), - HexEncode.bytesToHexString(host.getDataLayerAddressBytes()), host); - if (hostExists(host)) { - IHostId id = HostIdFactory.create(host.getNetworkAddress(), host.getDataLayerAddress()); - HostNodeConnector existinghost = hostsDB.get(id); - existinghost.initArpSendCountDown(); - // Update the host - - hostsDB.put(id, existinghost); - logger.debug("hostListener returned without adding the host"); - return; - } - new NotifyHostThread(host).start(); - } - - // Notify whoever is interested that a new host was learned (dynamically or - // statically) - private void notifyHostLearnedOrRemoved(HostNodeConnector host, boolean add) { - // Update listeners if any - if (newHostNotify != null) { - logger.debug("Notifying Applications for Host {} Being {}", host.getNetworkAddress().getHostAddress(), - add ? "Added" : "Deleted"); - synchronized (this.newHostNotify) { - for (IfNewHostNotify ta : newHostNotify) { - try { - if (add) { - ta.notifyHTClient(host); - } else { - ta.notifyHTClientHostRemoved(host); - } - } catch (Exception e) { - logger.error("Exception on new host notification", e); - } - } - } - } else { - logger.error("notifyHostLearnedOrRemoved(): New host notify is null"); - } - - // Topology update is for some reason outside of listeners registry - // logic - Node node = host.getnodeconnectorNode(); - Host h = null; - NodeConnector p = host.getnodeConnector(); - try { - DataLinkAddress dla = new EthernetAddress(host.getDataLayerAddressBytes()); - h = new Host(dla, host.getNetworkAddress()); - } catch (ConstructionException ce) { - p = null; - h = null; - } - - if (topologyManager != null && p != null && h != null) { - logger.debug("Notifying Topology Manager for Host {} Being {}", h.getNetworkAddress().getHostAddress(), - add ? "Added" : "Deleted"); - if (add == true) { - Tier tier = new Tier(1); - switchManager.setNodeProp(node, tier); - topologyManager.updateHostLink(p, h, UpdateType.ADDED, null); - } else { - // No need to reset the tiering if no other hosts are currently - // connected - // If this switch was discovered to be an access switch, it - // still is even if the host is down - Tier tier = new Tier(0); - switchManager.setNodeProp(node, tier); - topologyManager.updateHostLink(p, h, UpdateType.REMOVED, null); - } - } - } - - /** - * When a new Host is learnt by the hosttracker module, it places the - * directly connected Node in Tier-1 & using this function, updates the Tier - * value for all other Nodes in the network hierarchy. - * - * This is a recursive function and it takes care of updating the Tier value - * for all the connected and eligible Nodes. - * - * @param n - * Node that represents one of the Vertex in the Topology Graph. - * @param currentTier - * The Tier on which n belongs - */ - @SuppressWarnings("unused") - private void updateSwitchTiers(Node n, int currentTier) { - Map> ndlinks = topologyManager.getNodeEdges(); - if (ndlinks == null) { - logger.debug("updateSwitchTiers(): ndlinks null for Node: {}, Tier:{}", n, currentTier); - return; - } - Set links = ndlinks.get(n); - if (links == null) { - logger.debug("updateSwitchTiers(): links null for ndlinks:{}", ndlinks); - return; - } - ArrayList needsVisiting = new ArrayList(); - for (Edge lt : links) { - if (!lt.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) { - // We don't want to work on Node that are not openflow - // for now - continue; - } - Node dstNode = lt.getHeadNodeConnector().getNode(); - if (switchNeedsTieringUpdate(dstNode, currentTier + 1)) { - Tier t = new Tier(currentTier + 1); - switchManager.setNodeProp(dstNode, t); - needsVisiting.add(dstNode); - } - } - - /* - * Due to the nature of the problem, having a separate loop for nodes - * that needs visiting provides a decent walk optimization. - */ - for (Node node : needsVisiting) { - updateSwitchTiers(node, currentTier + 1); - } - } - - /** - * Internal convenience routine to check the eligibility of a Switch for a - * Tier update. Any Node with Tier=0 or a Tier value that is greater than - * the new Tier Value is eligible for the update. - * - * @param n - * Node for which the Tier update eligibility is checked - * @param tier - * new Tier Value - * @return true if the Node is eligible for Tier Update - * false otherwise - */ - - private boolean switchNeedsTieringUpdate(Node n, int tier) { - if (n == null) { - logger.error("switchNeedsTieringUpdate(): Null node for tier: {}", tier); - return false; - } - /* - * Node could have gone down - */ - if (!switchManager.getNodes().contains(n)) { - return false; - } - // This is the case where Tier was never set for this node - Tier t = (Tier) switchManager.getNodeProp(n, Tier.TierPropName); - if (t == null) { - return true; - } - if (t.getValue() == 0) { - return true; - } else if (t.getValue() > tier) { - return true; - } - return false; - } - - /** - * Internal convenience routine to clear all the Tier values to 0. This - * cleanup is performed during cases such as Topology Change where the - * existing Tier values might become incorrect - */ - @SuppressWarnings("unused") - private void clearTiers() { - Set nodes = null; - if (switchManager == null) { - logger.error("clearTiers(): Null switchManager"); - return; - } - nodes = switchManager.getNodes(); - - for (Node n : nodes) { - Tier t = new Tier(0); - switchManager.setNodeProp(n, t); - } - } - - /** - * Internal convenience routine to print the hierarchies of switches. - */ - @SuppressWarnings("unused") - private void logHierarchies(ArrayList> hierarchies) { - String hierarchyString = null; - int num = 1; - for (ArrayList hierarchy : hierarchies) { - StringBuffer buf = new StringBuffer(); - buf.append("Hierarchy#").append(num).append(" : "); - for (String switchName : hierarchy) { - buf.append(switchName).append("/"); - } - logger.debug("{} -> {}", getContainerName(), buf); - num++; - } - } - - /** - * getHostNetworkHierarchy is the Back-end routine for the North-Bound API - * that returns the Network Hierarchy for a given Host. This API is - * typically used by applications like Hadoop for Rack Awareness - * functionality. - * - * @param hostAddress - * IP-Address of the host/node. - * @return Network Hierarchies represented by an Array of Array (of - * Switch-Ids as String). - */ - @Override - public List> getHostNetworkHierarchy(IHostId id) { - HostNodeConnector host = hostQuery(id); - if (host == null) { - return null; - } - - List> hierarchies = new ArrayList>(); - ArrayList currHierarchy = new ArrayList(); - hierarchies.add(currHierarchy); - - Node node = host.getnodeconnectorNode(); - updateCurrentHierarchy(node, currHierarchy, hierarchies); - return hierarchies; - } - - /** - * dpidToHostNameHack is a hack function for Cisco Live Hadoop Demo. Mininet - * is used as the network for Hadoop Demos & in order to give a meaningful - * rack-awareness switch names, the DPID is organized in ASCII Characters - * and retrieved as string. - * - * @param dpid - * Switch DataPath Id - * @return Ascii String represented by the DPID. - */ - private String dpidToHostNameHack(long dpid) { - String hex = Long.toHexString(dpid); - - StringBuffer sb = new StringBuffer(); - int result = 0; - for (int i = 0; i < hex.length(); i++) { - result = (int) ((dpid >> (i * 8)) & 0xff); - if (result == 0) { - continue; - } - if (result < 0x30) { - result += 0x40; - } - sb.append(String.format("%c", result)); - } - return sb.reverse().toString(); - } - - /** - * A convenient recursive routine to obtain the Hierarchy of Switches. - * - * @param node - * Current Node in the Recursive routine. - * @param currHierarchy - * Array of Nodes that make this hierarchy on which the Current - * Switch belong - * @param fullHierarchy - * Array of multiple Hierarchies that represent a given host. - */ - @SuppressWarnings("unchecked") - private void updateCurrentHierarchy(Node node, ArrayList currHierarchy, List> fullHierarchy) { - currHierarchy.add(dpidToHostNameHack((Long) node.getID())); - // Shallow copy as required - ArrayList currHierarchyClone = (ArrayList) currHierarchy.clone(); - - Map> ndlinks = topologyManager.getNodeEdges(); - if (ndlinks == null) { - logger.debug("updateCurrentHierarchy(): topologyManager returned null ndlinks for node: {}", node); - return; - } - Node n = NodeCreator.createOFNode((Long) node.getID()); - Set links = ndlinks.get(n); - if (links == null) { - logger.debug("updateCurrentHierarchy(): Null links for ndlinks"); - return; - } - for (Edge lt : links) { - if (!lt.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) { - // We don't want to work on Node that are not openflow - // for now - continue; - } - Node dstNode = lt.getHeadNodeConnector().getNode(); - - Tier nodeTier = (Tier) switchManager.getNodeProp(node, Tier.TierPropName); - /* - * If the host is directly attached to the src node, then the node - * should have been assigned the "Access" tier in - * notifyHostLearnedOrRemoved. If not, it would be assigned - * "Unknown" tier. Thus the tier of host attached node cannot be - * null. If the src node here, is the next node in the hierarchy of - * the nodes, then its tier cannot be null - */ - - Tier dstNodeTier = (Tier) switchManager.getNodeProp(dstNode, Tier.TierPropName); - /* - * Skip if the tier of the destination node is null - */ - if (dstNodeTier == null) { - continue; - } - if (dstNodeTier.getValue() > nodeTier.getValue()) { - ArrayList buildHierarchy = currHierarchy; - if (currHierarchy.size() > currHierarchyClone.size()) { - // Shallow copy as required - buildHierarchy = (ArrayList) currHierarchyClone.clone(); - fullHierarchy.add(buildHierarchy); - } - updateCurrentHierarchy(dstNode, buildHierarchy, fullHierarchy); - } - } - } - - private void debugEdgeUpdate(Edge e, UpdateType type, Set props) { - Long srcNid = null; - Short srcPort = null; - Long dstNid = null; - Short dstPort = null; - boolean added = false; - String srcType = null; - String dstType = null; - - if (e == null || type == null) { - logger.error("Edge or Update type are null!"); - return; - } else { - srcType = e.getTailNodeConnector().getType(); - dstType = e.getHeadNodeConnector().getType(); - - if (srcType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) { - logger.debug("Skip updates for {}", e); - return; - } - - if (!srcType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) { - logger.debug("For now we cannot handle updates for non-openflow nodes"); - return; - } - - if (dstType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) { - logger.debug("Skip updates for {}", e); - return; - } - - if (!dstType.equals(NodeConnector.NodeConnectorIDType.OPENFLOW)) { - logger.debug("For now we cannot handle updates for non-openflow nodes"); - return; - } - - // At this point we know we got an openflow update, so - // lets fill everything accordingly. - srcNid = (Long) e.getTailNodeConnector().getNode().getID(); - srcPort = (Short) e.getTailNodeConnector().getID(); - dstNid = (Long) e.getHeadNodeConnector().getNode().getID(); - dstPort = (Short) e.getHeadNodeConnector().getID(); - - // Now lets update the added flag - switch (type) { - case ADDED: - case CHANGED: - added = true; - break; - case REMOVED: - added = false; - } - } - - logger.debug("HostTracker Topology linkUpdate handling src:{}[port {}] dst:{}[port {}] added: {}", - new Object[] { srcNid, srcPort, dstNid, dstPort, added }); - } - - @Override - public void edgeUpdate(List topoedgeupdateList) { - if (logger.isDebugEnabled()) { - for (TopoEdgeUpdate topoEdgeUpdate : topoedgeupdateList) { - Edge e = topoEdgeUpdate.getEdge(); - Set p = topoEdgeUpdate.getProperty(); - UpdateType type = topoEdgeUpdate.getUpdateType(); - - debugEdgeUpdate(e, type, p); - } - } - } - - @Override - public void subnetNotify(Subnet sub, boolean add) { - logger.debug("Received subnet notification: {} add={}", sub, add); - if (add) { - for (Entry entry : failedARPReqList.entrySet()) { - ARPPending arphost; - arphost = entry.getValue(); - if (hostFinders.isEmpty()) { - logger.debug("ARPHandler Services are not available on subnet addition"); - continue; - } - logger.debug("Sending the ARP from FailedARPReqList fors IP: {}", decodeIPFromId(arphost.getHostId())); - for (IHostFinder hf : hostFinders) { - hf.find(decodeIPFromId(arphost.getHostId())); - } - } - } - } - - /* - * This thread runs every 4 seconds - */ - - class OutStandingARPHandler extends TimerTask { - @Override - public void run() { - if (stopping) { - return; - } - ARPPending arphost; - try { - for (Entry entry : ARPPendingList.entrySet()) { - arphost = entry.getValue(); - - if (hostsDB.containsKey(arphost.getHostId())) { - // this host is already learned, shouldn't be in - // ARPPendingList - // Remove it and continue - logger.warn("Learned Host {} found in ARPPendingList", decodeIPFromId(arphost.getHostId())); - ARPPendingList.remove(entry.getKey()); - continue; - } - if (arphost.getSent_count() < hostRetryCount) { - /* - * No reply has been received of first ARP Req, send the - * next one. Before sending the ARP, check if ARPHandler - * is available or not - */ - if (hostFinders.isEmpty()) { - logger.warn("ARPHandler Services are not available for Outstanding ARPs"); - continue; - } - for (IHostFinder hf : hostFinders) { - hf.find(decodeIPFromId(arphost.getHostId())); - } - arphost.sent_count++; - logger.debug("ARP Sent from ARPPending List, IP: {}", decodeIPFromId(arphost.getHostId())); - } else if (arphost.getSent_count() >= hostRetryCount) { - /* - * ARP requests have been sent without receiving a - * reply, remove this from the pending list - */ - ARPPendingList.remove(entry.getKey()); - logger.debug( - "ARP reply not received after multiple attempts, removing from Pending List IP: {}", - decodeIPFromId(arphost.getHostId())); - /* - * Add this host to a different list which will be - * processed on link up events - */ - logger.debug("Adding the host to FailedARPReqList IP: {}", decodeIPFromId(arphost.getHostId())); - failedARPReqList.put(entry.getKey(), arphost); - - } else { - logger.error("Inavlid arp_sent count for entry: {}", entry); - } - } - } catch (IllegalStateException e) { - logger.debug("IllegalStateException Received by OutStandingARPHandler from: {}", e.getMessage()); - } - } - } - - private class ARPRefreshHandler extends TimerTask { - @Override - public void run() { - if ((clusterContainerService != null) && !clusterContainerService.amICoordinator()) { - return; - } - if (stopping) { - return; - } - if (!hostRefresh) { - /* - * The host probe procedure is turned off - */ - return; - } - if (hostsDB == null) { - /* hostsDB is not allocated yet */ - logger.error("ARPRefreshHandler(): hostsDB is not allocated yet:"); - return; - } - try { - for (Entry entry : hostsDB.entrySet()) { - HostNodeConnector host = entry.getValue(); - if (host.isStaticHost()) { - /* this host was learned via API3, don't age it out */ - continue; - } - - short arp_cntdown = host.getArpSendCountDown(); - arp_cntdown--; - if (arp_cntdown > hostRetryCount) { - host.setArpSendCountDown(arp_cntdown); - } else if (arp_cntdown <= 0) { - /* - * No ARP Reply received in last 2 minutes, remove this - * host and inform applications - */ - removeKnownHost(entry.getKey()); - notifyHostLearnedOrRemoved(host, false); - } else if (arp_cntdown <= hostRetryCount) { - /* - * Use the services of arphandler to check if host is - * still there - */ - if (logger.isTraceEnabled()) { - logger.trace( - "ARP Probing ({}) for {}({})", - new Object[] { arp_cntdown, host.getNetworkAddress().getHostAddress(), - HexEncode.bytesToHexString(host.getDataLayerAddressBytes()) }); - } - host.setArpSendCountDown(arp_cntdown); - if (hostFinders.isEmpty()) { - /* - * If hostfinder is not available, then can't send - * the probe. However, continue the age out the - * hosts since we don't know if the host is indeed - * out there or not. - */ - logger.trace("ARPHandler is not avaialable, can't send the probe"); - continue; - } - for (IHostFinder hf : hostFinders) { - hf.probe(host); - } - } - } - } catch (IllegalStateException e) { - logger.debug("IllegalStateException Received by ARPRefreshHandler from: {}", e.getMessage()); - } - } - } - - /** - * Inform the controller IP to MAC binding of a host and its connectivity to - * an openflow switch in terms of Node, port, and VLAN. - * - * @param networkAddr - * IP address of the host - * @param dataLayer - * Address MAC address of the host - * @param nc - * NodeConnector to which host is connected - * @param port - * Port of the switch to which host is connected - * @param vlan - * Vlan of which this host is member of - * - * @return Status The status object as described in {@code Status} - * indicating the result of this action. - */ - - protected Status addStaticHostReq(InetAddress networkAddr, byte[] dataLayerAddress, NodeConnector nc, short vlan) { - if (dataLayerAddress.length != NetUtils.MACAddrLengthInBytes) { - return new Status(StatusCode.BADREQUEST, "Invalid MAC address"); - } - - if (nc == null) { - return new Status(StatusCode.BADREQUEST, "Invalid NodeConnector"); - } - HostNodeConnector host = null; - try { - host = new HostNodeConnector(dataLayerAddress, networkAddr, nc, vlan); - IHostId id = HostIdFactory.create(networkAddr, new EthernetAddress(dataLayerAddress)); - if (hostExists(host)) { - // This host is already learned either via ARP or through a - // northbound request - HostNodeConnector transHost = hostsDB.get(networkAddr); - transHost.setStaticHost(true); - return new Status(StatusCode.SUCCESS); - } - - if (hostsDB.get(id) != null) { - // There is already a host with this IP address (but behind - // a different (switch, port, vlan) tuple. Return an error - return new Status(StatusCode.CONFLICT, "Host with this IP already exists."); - } - host.setStaticHost(true); - /* - * Check if the nc is an ISL port - */ - if (topologyManager != null) { - if (topologyManager.isInternal(nc)) { - return new Status(StatusCode.BADREQUEST, "Cannot add host on ISL port"); - } - } - /* - * Before adding host, Check if the switch and the port have already - * come up - */ - if (switchManager.isNodeConnectorEnabled(nc)) { - learnNewHost(host); - processPendingARPReqs(id); - notifyHostLearnedOrRemoved(host, true); - } else { - inactiveStaticHosts.put(nc, host); - logger.debug("Switch or switchport is not up, adding host {} to inactive list", - networkAddr.getHostName()); - } - return new Status(StatusCode.SUCCESS); - } catch (ConstructionException e) { - logger.error("", e); - return new Status(StatusCode.INTERNALERROR, "Host could not be created"); - } - - } - - /** - * Update the controller IP to MAC binding of a host and its connectivity to - * an openflow switch in terms of switch id, switch port, and VLAN. - * - * @param networkAddr - * IP address of the host - * @param dataLayer - * Address MAC address of the host - * @param nc - * NodeConnector to which host is connected - * @param port - * Port of the switch to which host is connected - * @param vlan - * Vlan of which this host is member of - * - * @return Status The status object as described in {@code Status} - * indicating the result of this action. - */ - public Status updateHostReq(InetAddress networkAddr, byte[] dataLayerAddress, NodeConnector nc, short vlan) { - HostNodeConnector tobeUpdatedHost; - HostNodeConnector host = null; - - if (dataLayerAddress.length != NetUtils.MACAddrLengthInBytes) { - return new Status(StatusCode.BADREQUEST, "Invalid MAC address"); - } - - if (nc == null) { - return new Status(StatusCode.BADREQUEST, "Invalid NodeConnector"); - } - - try { - host = new HostNodeConnector(dataLayerAddress, networkAddr, nc, vlan); - if (hostExists(host)) { - return new Status(StatusCode.BADREQUEST, "Host already exists"); - } - - IHostId id = HostIdFactory.create(networkAddr, new EthernetAddress(dataLayerAddress)); - - if ((tobeUpdatedHost = hostsDB.get(networkAddr)) != null) { - if (hostsDB.replace(id, tobeUpdatedHost, host)) { - logger.debug("Host replaced from hostsDB. Old host: {} New Host: {}", tobeUpdatedHost, host); - notifyHostLearnedOrRemoved(tobeUpdatedHost, false); - notifyHostLearnedOrRemoved(host, true); - return new Status(StatusCode.SUCCESS); - } else { - logger.error("Static host replacement failed from hostsDB, Replaced Host: {}, New Host: {}", - tobeUpdatedHost, host); - return new Status(StatusCode.INTERNALERROR, - "Host Replacement Failed due to presence of another host with same IP"); - } - } - - // Check if the host exists in inactive hosts database - if ((tobeUpdatedHost = inactiveStaticHosts.get(nc)) != null) { - if (inactiveStaticHosts.replace(nc, tobeUpdatedHost, host)) { - logger.debug("Host replaced from inactive hostsDB. Old host: {} New Host: {}", tobeUpdatedHost, - host); - return new Status(StatusCode.SUCCESS); - } else { - logger.error("Static host replacement failed, Replaced Host: {}, New Host: {}", tobeUpdatedHost, - host); - return new Status(StatusCode.INTERNALERROR, - "Host Replacement Failed due to presence of another host with same IP"); - } - } - - // Host doesn't exist - return new Status(StatusCode.BADREQUEST, "Host doesn't exists, can't update"); - } catch (ConstructionException e) { - logger.error("", e); - return new Status(StatusCode.INTERNALERROR, "host object creation failure"); - } - } - - /** - * Remove from the controller IP to MAC binding of a host and its - * connectivity to an openflow switch - * - * @param networkAddr - * IP address of the host - * - * @return boolean true if the host was removed successfully, false - * otherwise - */ - - public Status removeStaticHostReq(InetAddress networkAddress, DataLinkAddress mac) { - // Check if host is in active hosts database - IHostId id = HostIdFactory.create(networkAddress, mac); - HostNodeConnector host = getHostFromOnActiveDB(id); - if (host != null) { - // Validation check - if (!host.isStaticHost()) { - return new Status(StatusCode.FORBIDDEN, "Host " + networkAddress.getHostName() + " is not static"); - } - // Remove and notify - notifyHostLearnedOrRemoved(host, false); - removeKnownHost(id); - return new Status(StatusCode.SUCCESS, null); - } - - // Check if host is in inactive hosts database - Entry entry = getHostFromInactiveDB(id); - if (entry != null) { - host = entry.getValue(); - // Validation check - if (!host.isStaticHost()) { - return new Status(StatusCode.FORBIDDEN, "Host " + networkAddress.getHostName() + " is not static"); - } - this.removeHostFromInactiveDB(id); - return new Status(StatusCode.SUCCESS, null); - } - - // Host is neither in active nor inactive hosts database - return new Status(StatusCode.NOTFOUND, "Host does not exist"); - } - - @Override - public void modeChangeNotify(Node node, boolean proactive) { - logger.debug("Set Switch {} Mode to {}", node.getID(), proactive); - } - - @Override - public void notifyNode(Node node, UpdateType type, Map propMap) { - if (node == null) { - return; - } - - switch (type) { - case REMOVED: - logger.debug("Received removed node {}", node); - for (Entry entry : hostsDB.entrySet()) { - HostNodeConnector host = entry.getValue(); - if (host.getnodeconnectorNode().equals(node)) { - logger.debug("Node: {} is down, remove from Hosts_DB", node); - removeKnownHost(entry.getKey()); - notifyHostLearnedOrRemoved(host, false); - } - } - break; - default: - break; - } - } - - @Override - public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map propMap) { - if (nodeConnector == null) { - return; - } - - boolean up = false; - switch (type) { - case ADDED: - up = true; - break; - case REMOVED: - break; - case CHANGED: - State state = (State) propMap.get(State.StatePropName); - if ((state != null) && (state.getValue() == State.EDGE_UP)) { - up = true; - } - break; - default: - return; - } - - if (up) { - handleNodeConnectorStatusUp(nodeConnector); - } else { - handleNodeConnectorStatusDown(nodeConnector); - } - } - - @Override - public Status addStaticHost(String networkAddress, String dataLayerAddress, NodeConnector nc, String vlan) { - try { - InetAddress ip = InetAddress.getByName(networkAddress); - short vl = 0; - if (vlan != null && !vlan.isEmpty()) { - vl = Short.decode(vlan); - if (vl < 1 || vl > 4095) { - return new Status(StatusCode.BADREQUEST, "Host vlan out of range [1 - 4095]"); - } - } - - return addStaticHostReq(ip, HexEncode.bytesFromHexString(dataLayerAddress), nc, vl); - - } catch (UnknownHostException e) { - logger.debug("Invalid host IP specified when adding static host", e); - return new Status(StatusCode.BADREQUEST, "Invalid Host IP Address"); - } catch (NumberFormatException nfe) { - logger.debug("Invalid host vlan or MAC specified when adding static host", nfe); - return new Status(StatusCode.BADREQUEST, "Invalid Host vLan/MAC"); - } - } - - @Override - public Status removeStaticHost(String networkAddress) { - try { - if ((keyScheme != null) && (!keyScheme.equals(HostIdFactory.DEFAULT_IP_KEY_SCHEME))) { - return new Status(StatusCode.NOTALLOWED, "Host DB Key scheme used is not IP only scheme."); - } - InetAddress address = InetAddress.getByName(networkAddress); - return removeStaticHostReq(address, null); - } catch (UnknownHostException e) { - logger.debug("Invalid IP Address when trying to remove host", e); - return new Status(StatusCode.BADREQUEST, "Invalid IP Address when trying to remove host"); - } - } - - @Override - public Status removeStaticHostUsingIPAndMac(String networkAddress, String macAddress) { - try { - if ((keyScheme != null) && (keyScheme.equals(HostIdFactory.DEFAULT_IP_KEY_SCHEME))) { - return new Status(StatusCode.NOTALLOWED, "Host DB Key scheme used is not IP only scheme."); - } - InetAddress address = InetAddress.getByName(networkAddress); - DataLinkAddress mac = new EthernetAddress(HexEncode.bytesFromHexString(macAddress)); - return removeStaticHostReq(address, mac); - } catch (UnknownHostException e) { - logger.debug("Invalid IP Address when trying to remove host", e); - return new Status(StatusCode.BADREQUEST, "Invalid IP Address when trying to remove host"); - } catch (ConstructionException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return new Status(StatusCode.BADREQUEST, "Invalid Input parameters have been passed."); - } - } - - private InetAddress decodeIPFromId(IHostId id) { - if ((keyScheme != null) && (keyScheme.equals(HostIdFactory.DEFAULT_IP_KEY_SCHEME))) { - IPHostId ipId = (IPHostId) id; - return (ipId.getIpAddress()); - } else if ((keyScheme != null) && (keyScheme.equals(HostIdFactory.IP_MAC_KEY_SCHEME))) { - IPMacHostId ipMacId = (IPMacHostId) id; - return (ipMacId.getIpAddress()); - } - return null; - } - - private DataLinkAddress decodeMacFromId(IHostId id) { - if ((keyScheme != null) && (!keyScheme.equals(HostIdFactory.DEFAULT_IP_KEY_SCHEME))) { - IPMacHostId ipMacId = (IPMacHostId) id; - return (ipMacId.getMacAddr()); - } - - return null; - } - - private void handleNodeConnectorStatusUp(NodeConnector nodeConnector) { - ARPPending arphost; - HostNodeConnector host = null; - - logger.trace("handleNodeConnectorStatusUp {}", nodeConnector); - - for (Entry entry : failedARPReqList.entrySet()) { - arphost = entry.getValue(); - logger.trace("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostId()); - if (hostFinders.isEmpty()) { - logger.warn("ARPHandler is not available at interface up"); - logger.warn("Since this event is missed, host(s) connected to interface {} may not be discovered", - nodeConnector); - continue; - } - - // Send a broadcast ARP only on the interface which just came up. - // Use hostFinder's "probe" method - try { - byte[] dataLayerAddress = NetUtils.getBroadcastMACAddr(); - host = new HostNodeConnector(dataLayerAddress, decodeIPFromId(arphost.getHostId()), nodeConnector, - (short) 0); - for (IHostFinder hf : hostFinders) { - hf.probe(host); - } - } catch (ConstructionException e) { - logger.debug("HostNodeConnector couldn't be created for Host: {}, NodeConnector: {}", - arphost.getHostId(), nodeConnector); - logger.error("", e); - } - } - - host = inactiveStaticHosts.get(nodeConnector); - if (host != null) { - inactiveStaticHosts.remove(nodeConnector); - learnNewHost(host); - IHostId id = HostIdFactory.create(host.getNetworkAddress(), host.getDataLayerAddress()); - processPendingARPReqs(id); - notifyHostLearnedOrRemoved(host, true); - } - } - - private void handleNodeConnectorStatusDown(NodeConnector nodeConnector) { - logger.trace("handleNodeConnectorStatusDown {}", nodeConnector); - - for (Entry entry : hostsDB.entrySet()) { - HostNodeConnector host = entry.getValue(); - if (host.getnodeConnector().equals(nodeConnector)) { - logger.debug(" NodeConnector: {} is down, remove from Hosts_DB", nodeConnector); - removeKnownHost(entry.getKey()); - notifyHostLearnedOrRemoved(host, false); - } - } - } - - void setClusterContainerService(IClusterContainerServices s) { - logger.debug("Cluster Service set"); - this.clusterContainerService = s; - } - - void unsetClusterContainerService(IClusterContainerServices s) { - if (this.clusterContainerService == s) { - logger.debug("Cluster Service removed!"); - this.clusterContainerService = null; - } - } - - void setSwitchManager(ISwitchManager s) { - logger.debug("SwitchManager set"); - this.switchManager = s; - } - - void unsetSwitchManager(ISwitchManager s) { - if (this.switchManager == s) { - logger.debug("SwitchManager removed!"); - this.switchManager = null; - } - } - - public String getContainerName() { - if (containerName == null) { - return GlobalConstants.DEFAULT.toString(); - } - return containerName; - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init(Component c) { - Dictionary props = c.getServiceProperties(); - if (props != null) { - this.containerName = (String) props.get("containerName"); - logger.debug("Running containerName: {}", this.containerName); - } else { - // In the Global instance case the containerName is empty - this.containerName = ""; - } - startUp(); - - logger.debug("key Scheme in hosttracker is {}", keyScheme); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - registerWithOSGIConsole(); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - } - - void stopping() { - stopping = true; - arpRefreshTimer.cancel(); - timer.cancel(); - executor.shutdownNow(); - } - - @Override - public void edgeOverUtilized(Edge edge) { - - } - - @Override - public void edgeUtilBackToNormal(Edge edge) { - - } - - @Override - public void entryCreated(IHostId key, String cacheName, boolean originLocal) { - if (originLocal) { - return; - } - processPendingARPReqs(key); - } - - @Override - public void entryUpdated(IHostId key, HostNodeConnector new_value, String cacheName, boolean originLocal) { - } - - @Override - public void entryDeleted(IHostId key, String cacheName, boolean originLocal) { - } - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, null); - } - - @Override - public String getHelp() { - return null; - } - - public void _dumpPendingARPReqList(CommandInterpreter ci) { - ARPPending arphost; - for (Entry entry : ARPPendingList.entrySet()) { - arphost = entry.getValue(); - ci.println(arphost.getHostId().toString()); - } - } - - public void _dumpFailedARPReqList(CommandInterpreter ci) { - ARPPending arphost; - for (Entry entry : failedARPReqList.entrySet()) { - arphost = entry.getValue(); - ci.println(arphost.getHostId().toString()); - } - } - - @Override - public HostNodeConnector hostFind(InetAddress addr) { - IHostId id = HostIdFactory.create(addr, null); - return (hostFind(id)); - } - - @Override - public HostNodeConnector hostQuery(InetAddress addr) { - IHostId id = HostIdFactory.create(addr, null); - return (hostQuery(id)); - } - - @Override - public Future discoverHost(InetAddress addr) { - IHostId id = HostIdFactory.create(addr, null); - return discoverHost(id); - } - - @Override - public List> getHostNetworkHierarchy(InetAddress addr) { - IHostId id = HostIdFactory.create(addr, null); - return getHostNetworkHierarchy(id); - } - - @Override - public List dumpPendingArpReqList() { - ARPPending arphost; - List arpReq = new ArrayList(); - for (Entry entry : ARPPendingList.entrySet()) { - arpReq.add(entry.getValue().getHostId().toString()); - } - return arpReq; - } - - @Override - public List dumpFailedArpReqList() { - ARPPending arphost; - List arpReq = new ArrayList(); - for (Entry entry : failedARPReqList.entrySet()) { - arpReq.add(entry.getValue().getHostId().toString()); - } - return arpReq; - } -} diff --git a/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTrackerCallable.java b/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTrackerCallable.java deleted file mode 100644 index 59b4a08464..0000000000 --- a/opendaylight/adsal/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTrackerCallable.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/* - * Provides a mechanism for applications to do an inline Host Discovery as opposed - * to a delayed discovery - */ -package org.opendaylight.controller.hosttracker.internal; - -/** - * This Class provides methods to discover Host through a blocking call - * mechanism. Applications can make use of these methods if they don't - * find a host in HostTracker's database and want to discover the host - * in the same thread without being called by a callback function. - */ -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; - -import org.opendaylight.controller.hosttracker.IHostId; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; - -/** - * - * - */ -public class HostTrackerCallable implements Callable { - - //host id which could be ip or a combination of ip + mac based on the scheme chosen. - IHostId trackedHost; - HostTracker hostTracker; - protected CountDownLatch latch; - - public HostTrackerCallable(HostTracker tracker, IHostId inet) { - trackedHost = inet; - hostTracker = tracker; - latch = new CountDownLatch(1); - } - - @Override - public HostNodeConnector call() throws Exception { - HostNodeConnector h = hostTracker.hostFind(trackedHost); - if (h != null) { - return h; - } - hostTracker.setCallableOnPendingARP(trackedHost, this); - Thread.sleep(2000); // wait 2sec to see if the host responds - return hostTracker.hostQuery(trackedHost); - } - - public void wakeup() { - this.latch.countDown(); - } -} diff --git a/opendaylight/adsal/hosttracker/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerTest.java b/opendaylight/adsal/hosttracker/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerTest.java deleted file mode 100644 index 984d5d3000..0000000000 --- a/opendaylight/adsal/hosttracker/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.hosttracker.IHostId; -import org.opendaylight.controller.hosttracker.IPHostId; - -public class HostTrackerTest { - - @Test - public void testHostTrackerCallable() throws UnknownHostException { - - HostTracker hostTracker = null; - hostTracker = new HostTracker(); - - InetAddress hostIP = InetAddress.getByName("192.168.0.8"); - IHostId id = IPHostId.fromIP(hostIP); - - HostTrackerCallable htCallable = new HostTrackerCallable(hostTracker, - id); - Assert.assertTrue(htCallable.trackedHost.equals(id)); - Assert.assertTrue(htCallable.hostTracker.equals(hostTracker)); - - long count = htCallable.latch.getCount(); - htCallable.wakeup(); - Assert.assertTrue(htCallable.latch.getCount() == (count - 1)); - } - - @Test - public void testHostTracker() throws UnknownHostException { - HostTracker hostTracker = null; - hostTracker = new HostTracker(); - - InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8"); - IHostId id1 = IPHostId.fromIP(hostIP_1); - InetAddress hostIP_2 = InetAddress.getByName("192.168.0.18"); - IHostId id2 = IPHostId.fromIP(hostIP_2); - hostTracker.discoverHost(id1); - hostTracker.discoverHost(id2); - hostTracker.nonClusterObjectCreate(); - } - -} diff --git a/opendaylight/adsal/hosttracker/integrationtest/pom.xml b/opendaylight/adsal/hosttracker/integrationtest/pom.xml deleted file mode 100644 index a6a39e8fe7..0000000000 --- a/opendaylight/adsal/hosttracker/integrationtest/pom.xml +++ /dev/null @@ -1,165 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.integrationtest - 0.7.0-SNAPSHOT - ../../commons/integrationtest - - - hosttracker.integrationtest - 0.7.0-SNAPSHOT - - ../../implementaiton/target/jacoco-it.exec - - ../../implementation/target/jacoco.exec - - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - junit - junit - - - org.opendaylight.controller - arphandler - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - clustering.stub - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - configuration.implementation - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - connectionmanager.implementation - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.it.implementation - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - hosttracker.implementation - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller - sal.connection.implementation - - - org.opendaylight.controller - sal.implementation - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - switchmanager.implementation - - - org.opendaylight.controller - topologymanager - - - org.slf4j - log4j-over-slf4j - - - - org.ops4j.pax.exam - pax-exam-container-native - test - - - org.ops4j.pax.exam - pax-exam-junit4 - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - test - - - org.ops4j.pax.url - pax-url-aether - test - - - - - - - org.jacoco - jacoco-maven-plugin - - ../../implementation/target/jacoco-it.exec - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - true - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/hosttracker/integrationtest/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerIT.java b/opendaylight/adsal/hosttracker/integrationtest/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerIT.java deleted file mode 100644 index a454eb97e1..0000000000 --- a/opendaylight/adsal/hosttracker/integrationtest/src/test/java/org/opendaylight/controller/hosttracker/internal/HostTrackerIT.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.internal; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; -import static org.ops4j.pax.exam.CoreOptions.options; -import static org.ops4j.pax.exam.CoreOptions.systemPackages; -import static org.ops4j.pax.exam.CoreOptions.systemProperty; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Iterator; - -import javax.inject.Inject; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.hosttracker.IHostId; -import org.opendaylight.controller.hosttracker.IPHostId; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.util.PathUtils; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -//import org.opendaylight.controller.hosttracker.*; - -@RunWith(PaxExam.class) -public class HostTrackerIT { - private Logger log = LoggerFactory.getLogger(HostTrackerIT.class); - // get the OSGI bundle context - @Inject - private BundleContext bc; - - private IfIptoHost hosttracker = null; - private IInventoryListener invtoryListener = null; - - // Configure the OSGi container - @Configuration - public Option[] config() { - return options( - - // - systemProperty("logback.configurationFile").value( - "file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"), - // To start OSGi console for inspection remotely - systemProperty("osgi.console").value("2401"), - // Set the systemPackages (used by clustering) - systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"), - // List framework bundles - mavenBundle("equinoxSDK381", "org.eclipse.equinox.console").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.util").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.osgi.services").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell").versionAsInProject(), - // List logger bundles - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), - mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(), - - // List all the bundles on which the test case depends - mavenBundle("org.opendaylight.controller", "sal").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.connection").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.connection.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "connectionmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "connectionmanager.implementation").versionAsInProject(), - - // needed by statisticsmanager - mavenBundle("org.opendaylight.controller", "containermanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "containermanager.it.implementation").versionAsInProject(), - - mavenBundle("org.opendaylight.controller", "clustering.services").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "clustering.stub").versionAsInProject(), - - // needed by forwardingrulesmanager - mavenBundle("org.opendaylight.controller", "switchmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "forwardingrulesmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "statisticsmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "switchmanager.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "configuration").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "configuration.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "hosttracker").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "hosttracker.implementation").versionAsInProject(), - - // needed by hosttracker - mavenBundle("org.opendaylight.controller", "topologymanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "arphandler").versionAsInProject(), - - mavenBundle("org.jboss.spec.javax.transaction", "jboss-transaction-api_1.1_spec").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(), - mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager").versionAsInProject(), - junitBundles()); - } - - private String stateToString(int state) { - switch (state) { - case Bundle.ACTIVE: - return "ACTIVE"; - case Bundle.INSTALLED: - return "INSTALLED"; - case Bundle.RESOLVED: - return "RESOLVED"; - case Bundle.UNINSTALLED: - return "UNINSTALLED"; - default: - return "Not CONVERTED"; - } - } - - @Before - public void areWeReady() { - assertNotNull(bc); - boolean debugit = false; - Bundle b[] = bc.getBundles(); - for (int i = 0; i < b.length; i++) { - int state = b[i].getState(); - if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) { - log.debug("Bundle:" + b[i].getSymbolicName() + " state:" + stateToString(state)); - debugit = true; - } - } - if (debugit) { - log.debug("Do some debugging because some bundle is " + "unresolved"); - } - - // Assert if true, if false we are good to go! - assertFalse(debugit); - - // Now lets create a hosttracker for testing purpose - ServiceReference s = bc.getServiceReference(IfIptoHost.class.getName()); - if (s != null) { - this.hosttracker = (IfIptoHost) bc.getService(s); - this.invtoryListener = (IInventoryListener) this.hosttracker; - } - - // If StatisticsManager is null, cannot run tests. - assertNotNull(this.hosttracker); - } - - @Test - public void testStaticHost() throws UnknownHostException { - String ip; - - assertNotNull(this.hosttracker); - - // create one node and two node connectors - Node node1 = NodeCreator.createOFNode(1L); - NodeConnector nc1_1 = NodeConnectorCreator.createOFNodeConnector((short) 1, node1); - NodeConnector nc1_2 = NodeConnectorCreator.createOFNodeConnector((short) 2, node1); - - // test addStaticHost(), store into inactive host DB - Status st = this.hosttracker.addStaticHost("192.168.0.8", "11:22:33:44:55:66", nc1_1, null); - Assert.assertTrue(st.isSuccess()); - st = this.hosttracker.addStaticHost("192.168.0.13", "11:22:33:44:55:77", nc1_2, ""); - Assert.assertTrue(st.isSuccess()); - - // check inactive DB - Iterator hnci = this.hosttracker.getInactiveStaticHosts().iterator(); - while (hnci.hasNext()) { - ip = hnci.next().getNetworkAddressAsString(); - Assert.assertTrue(ip.equals("192.168.0.8") || ip.equals("192.168.0.13")); - } - - // check active host DB - hnci = this.hosttracker.getActiveStaticHosts().iterator(); - Assert.assertFalse(hnci.hasNext()); - - // test removeStaticHost() - st = this.hosttracker.removeStaticHost("192.168.0.8"); - Assert.assertTrue(st.isSuccess()); - - hnci = this.hosttracker.getInactiveStaticHosts().iterator(); - while (hnci.hasNext()) { - ip = hnci.next().getNetworkAddressAsString(); - Assert.assertTrue(ip.equals("192.168.0.13")); - } - } - - @Test - public void testNotifyNodeConnector() throws UnknownHostException { - String ip; - - assertNotNull(this.invtoryListener); - - // create one node and two node connectors - Node node1 = NodeCreator.createOFNode(1L); - NodeConnector nc1_1 = NodeConnectorCreator.createOFNodeConnector((short) 1, node1); - NodeConnector nc1_2 = NodeConnectorCreator.createOFNodeConnector((short) 2, node1); - - // test addStaticHost(), put into inactive host DB if not verifiable - Status st = this.hosttracker.addStaticHost("192.168.0.8", "11:22:33:44:55:66", nc1_1, null); - Assert.assertTrue(st.isSuccess()); - st = this.hosttracker.addStaticHost("192.168.0.13", "11:22:33:44:55:77", nc1_2, "0"); - Assert.assertFalse(st.isSuccess()); - - this.invtoryListener.notifyNodeConnector(nc1_1, UpdateType.ADDED, null); - - // check all host list - Iterator hnci = this.hosttracker.getAllHosts().iterator(); - while (hnci.hasNext()) { - ip = hnci.next().getNetworkAddressAsString(); - Assert.assertTrue(ip.equals("192.168.0.8")); - } - - // check active host DB - hnci = this.hosttracker.getActiveStaticHosts().iterator(); - while (hnci.hasNext()) { - ip = hnci.next().getNetworkAddressAsString(); - Assert.assertTrue(ip.equals("192.168.0.8")); - } - - // check inactive host DB - hnci = this.hosttracker.getInactiveStaticHosts().iterator(); - while (hnci.hasNext()) { - ip = hnci.next().getNetworkAddressAsString(); - Assert.assertTrue(ip.equals("192.168.0.13")); - } - } - - @Test - public void testHostFind() throws UnknownHostException { - - assertNotNull(this.invtoryListener); - - // create one node and two node connectors - Node node1 = NodeCreator.createOFNode(1L); - NodeConnector nc1_1 = NodeConnectorCreator.createOFNodeConnector((short) 1, node1); - NodeConnector nc1_2 = NodeConnectorCreator.createOFNodeConnector((short) 2, node1); - - // test addStaticHost(), put into inactive host DB if not verifiable - Status st = this.hosttracker.addStaticHost("192.168.0.8", "11:22:33:44:55:66", nc1_1, null); - st = this.hosttracker.addStaticHost("192.168.0.13", "11:22:33:44:55:77", nc1_2, ""); - - IHostId id1 = IPHostId.fromIP(InetAddress.getByName("192.168.0.8")); - HostNodeConnector hnc_1 = this.hosttracker.hostFind(id1); - assertNull(hnc_1); - - this.invtoryListener.notifyNodeConnector(nc1_1, UpdateType.ADDED, null); - - IHostId id2 = IPHostId.fromIP(InetAddress.getByName("192.168.0.8")); - hnc_1 = this.hosttracker.hostFind(id2); - - assertNotNull(hnc_1); - - } - -} diff --git a/opendaylight/adsal/hosttracker/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/hosttracker/integrationtest/src/test/resources/logback.xml deleted file mode 100644 index 5fa21fecfc..0000000000 --- a/opendaylight/adsal/hosttracker/integrationtest/src/test/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/opendaylight/adsal/hosttracker/shell/pom.xml b/opendaylight/adsal/hosttracker/shell/pom.xml deleted file mode 100644 index 2d5039cc10..0000000000 --- a/opendaylight/adsal/hosttracker/shell/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - hosttracker.shell - ${hosttracker.shell.version} - bundle - - - junit - junit - - - org.apache.karaf.shell - org.apache.karaf.shell.console - ${karaf.version} - - - org.mockito - mockito-all - - - org.opendaylight.controller - hosttracker.implementation - ${hosttracker.implementation.version} - - - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - - - org.apache.felix.service.command, - org.apache.karaf.shell.commands, - org.apache.karaf.shell.console, - * - - - - - - - diff --git a/opendaylight/adsal/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java b/opendaylight/adsal/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java deleted file mode 100644 index cb57b44aba..0000000000 --- a/opendaylight/adsal/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.opendaylight.controller.hosttracker.shell; -/** -* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. -* -* This program and the accompanying materials are made available under the -* terms of the Eclipse Public License v1.0 which accompanies this distribution, -* and is available at http://www.eclipse.org/legal/epl-v10.html -*/ - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.hosttracker.IHostTrackerShell; - -@Command(scope = "hosttracker", name = "dumpFailedARPReqList", description="Display the dump failed ARPReqList") -public class DumpFailedARPReqList extends OsgiCommandSupport{ - - private IHostTrackerShell hostTracker; - - @Override - protected Object doExecute() throws Exception { - System.out.print(hostTracker.dumpFailedArpReqList()); - return null; - } - - public void setHostTracker(IHostTrackerShell hostTracker){ - this.hostTracker = hostTracker; - } -} diff --git a/opendaylight/adsal/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java b/opendaylight/adsal/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java deleted file mode 100644 index fafc48fde7..0000000000 --- a/opendaylight/adsal/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.opendaylight.controller.hosttracker.shell; -/** -* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. -* -* This program and the accompanying materials are made available under the -* terms of the Eclipse Public License v1.0 which accompanies this distribution, -* and is available at http://www.eclipse.org/legal/epl-v10.html -*/ - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.hosttracker.IHostTrackerShell; - -@Command(scope = "hosttracker", name = "dumpPendingARPReqList", description="Display the dump pending ARPReqList") -public class DumpPendingARPReqList extends OsgiCommandSupport{ - - private IHostTrackerShell hostTracker; - - @Override - protected Object doExecute() throws Exception { - System.out.print(hostTracker.dumpPendingArpReqList()); - return null; - } - - public void setHostTracker(IHostTrackerShell hostTracker){ - this.hostTracker = hostTracker; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/opendaylight/adsal/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml deleted file mode 100644 index ba79b5d8c5..0000000000 --- a/opendaylight/adsal/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java b/opendaylight/adsal/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java deleted file mode 100644 index a0a5a2e610..0000000000 --- a/opendaylight/adsal/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.opendaylight.controller.hosttracker.shell; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import org.opendaylight.controller.hosttracker.IHostTrackerShell; - -public class HostTrackerShellTest { - - private final long COMMAND_TIMEOUT = 1000; - private IHostTrackerShell hostTracker; - - @Test - public void testDumpPendingARPReqList() throws Exception { - DumpPendingARPReqList dumpPendTest = new DumpPendingARPReqList(); - hostTracker = mock(IHostTrackerShell.class); - List failedList = new ArrayList(Arrays.asList("a", "b", "c")); - when(hostTracker.dumpPendingArpReqList()).thenReturn(failedList); - dumpPendTest.setHostTracker(hostTracker); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - dumpPendTest.doExecute(); - //Assert.assertTrue(true); - Assert.assertEquals("[a, b, c]", baos.toString()); - } - - @Test - public void testDumpFailedARPReqList() throws Exception { - DumpFailedARPReqList dumpFailTest = new DumpFailedARPReqList(); - hostTracker = mock(IHostTrackerShell.class); - List failedList = new ArrayList(Arrays.asList("a", "b", "c")); - when(hostTracker.dumpFailedArpReqList()).thenReturn(failedList); - dumpFailTest.setHostTracker(hostTracker); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos)); - dumpFailTest.doExecute(); - //Assert.assertTrue(true); - Assert.assertEquals("[a, b, c]", baos.toString()); - } -} diff --git a/opendaylight/adsal/hosttracker_new/api/pom.xml b/opendaylight/adsal/hosttracker_new/api/pom.xml deleted file mode 100644 index 8bb1612300..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - hosttracker_new - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - topologymanager - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.hosttracker, - org.opendaylight.controller.hosttracker.hostAware - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.topologymanager, - org.opendaylight.controller.sal.packet.address, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.clustering.services, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.felix.dm, - org.apache.commons.lang3.builder, - org.osgi.service.component, - org.slf4j, - org.eclipse.osgi.framework.console, - org.osgi.framework - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/Entity.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/Entity.java deleted file mode 100644 index f10c116755..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/Entity.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Copyright (c) 2011,2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker; - -import java.net.InetAddress; -import java.util.Date; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.NetUtils; - -/** - * An entity on the network is a visible trace of a device that corresponds to a - * packet received from a particular interface on the edge of a network, with a - * particular VLAN tag, and a particular MAC address, along with any other - * packet characteristics we might want to consider as helpful for - * disambiguating devices. - * - * Entities are the most basic element of devices; devices consist of one or - * more entities. Entities are immutable once created, except for the last seen - * timestamp. - * - * @author readams - * - */ -public class Entity implements Comparable { - /** - * Timeout for computing {@link Entity#activeSince}. - * - * @see {@link Entity#activeSince} - */ - protected static int ACTIVITY_TIMEOUT = 30000; - - /** - * The MAC address associated with this entity - */ - protected long macAddress; - - /** - * The IP address associated with this entity, or null if no IP learned from - * the network observation associated with this entity - */ - protected Integer ipv4Address; - - /** - * The VLAN tag on this entity, or null if untagged - */ - protected Short vlan; - - /** - * The attachment point for this entity - */ - NodeConnector port; - - /** - * The last time we observed this entity on the network - */ - protected Date lastSeenTimestamp; - - /** - * The time between {@link Entity#activeSince} and - * {@link Entity#lastSeenTimestamp} is a period of activity for this entity - * where it was observed repeatedly. If, when the entity is observed, the is - * longer ago than the activity timeout, {@link Entity#lastSeenTimestamp} - * and {@link Entity#activeSince} will be set to the current time. - */ - protected Date activeSince; - - private int hashCode = 0; - - // ************ - // Constructors - // ************ - - /** - * Create a new entity - * - * @param macAddress - * @param vlan - * @param ipv4Address - * @param switchDPID - * @param switchPort - * @param lastSeenTimestamp - */ - public Entity(long macAddress, Short vlan, Integer ipv4Address, - NodeConnector port, Date lastSeenTimestamp) { - this.macAddress = macAddress; - this.ipv4Address = ipv4Address; - this.vlan = vlan; - this.port = port; - this.lastSeenTimestamp = lastSeenTimestamp; - this.activeSince = lastSeenTimestamp; - } - - // *************** - // Getters/Setters - // *************** - - // @JsonSerialize(using=MACSerializer.class) - public long getMacAddress() { - return macAddress; - } - - // @JsonSerialize(using=IPv4Serializer.class) - public Integer getIpv4Address() { - return ipv4Address; - } - - public Short getVlan() { - return vlan; - } - - public NodeConnector getPort() { - return port; - } - - // @JsonIgnore - public boolean hasSwitchPort() { - return port != null; - } - - public Date getLastSeenTimestamp() { - return lastSeenTimestamp; - } - - /** - * Set the last seen timestamp and also update {@link Entity#activeSince} if - * appropriate - * - * @param lastSeenTimestamp - * the new last seen timestamp - * @see {@link Entity#activeSince} - */ - public void setLastSeenTimestamp(Date lastSeenTimestamp) { - if (activeSince == null - || (activeSince.getTime() + ACTIVITY_TIMEOUT) < lastSeenTimestamp - .getTime()) { - this.activeSince = lastSeenTimestamp; - } - this.lastSeenTimestamp = lastSeenTimestamp; - } - - public Date getActiveSince() { - return activeSince; - } - - public void setActiveSince(Date activeSince) { - this.activeSince = activeSince; - } - - @Override - public int hashCode() { - if (hashCode != 0) { - return hashCode; - } - final int prime = 31; - hashCode = 1; - hashCode = prime * hashCode - + ((ipv4Address == null) ? 0 : ipv4Address.hashCode()); - hashCode = prime * hashCode + (int) (macAddress ^ (macAddress >>> 32)); - hashCode = prime * hashCode + ((port == null) ? 0 : port.hashCode()); - hashCode = prime * hashCode + ((vlan == null) ? 0 : vlan.hashCode()); - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Entity other = (Entity) obj; - if (ipv4Address == null) { - if (other.ipv4Address != null) { - return false; - } - } else if (!ipv4Address.equals(other.ipv4Address)) { - return false; - } - if (macAddress != other.macAddress) { - return false; - } - if (port == null) { - if (other.port != null) { - return false; - } - } else if (!port.equals(other.port)) { - return false; - } - if (vlan == null) { - if (other.vlan != null) { - return false; - } - } else if (!vlan.equals(other.vlan)) { - return false; - } - return true; - } - - public HostNodeConnector toHostNodeConnector() { - try { - NodeConnector n = this.getPort(); - InetAddress ip = InetAddress.getByAddress(NetUtils.intToByteArray4(this.getIpv4Address())); - byte[] macAddr = NetUtils.longToByteArray6(this.getMacAddress()); - HostNodeConnector nc = new HostNodeConnector(macAddr, ip, n, - (short) 0); - return nc; - } catch (Exception e) { - return null; - } - } - - @Override - public String toString() { - return "Entity [macAddress=" + macAddress + ", ipv4Address=" - + ipv4Address + ", vlan=" + vlan + ", port=" + port + "]"; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public int compareTo(Entity o) { - int r; - if (port == null) { - r = o.port == null ? 0 : -1; - } - else if (o.port == null) { - r = 1; - } - else { - // XXX - the node id is only defined as an object rather - // than something useful. We're just going to have to - // blindly cast to Comparable and hope it works. - Comparable switchId = (Comparable) port.getNode().getID(); - Comparable oswitchId = (Comparable) o.port.getNode().getID(); - r = switchId.compareTo(oswitchId); - if (r != 0) { - return r; - } - - Comparable portId = (Comparable) port.getID(); - Comparable oportId = (Comparable) o.port.getID(); - r = portId.compareTo(oportId); - } - return r; - } - -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDevice.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDevice.java deleted file mode 100644 index 8c9367e25a..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDevice.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2011,2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker; - -import java.util.Date; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; - -/** - * Represents an independent device on the network. A device consists of a set - * of entities, and all the information known about a given device comes only - * from merging all associated entities for that device. - * - * @author readams - */ -public interface IDevice { - /** - * Get the primary key for this device. - * - * @return the primary key - */ - public Long getDeviceKey(); - - /** - * Get the MAC address of the device as a Long value. - * - * @return the MAC address for the device - */ - public long getMACAddress(); - - /** - * Get the MAC address of the device as a String value. - * - * @return the MAC address for the device - */ - public String getMACAddressString(); - - /** - * Get all unique VLAN IDs for the device. If the device has untagged - * entities, then the value -1 will be returned. - * - * @return an array containing all unique VLAN IDs for the device. - */ - public Short[] getVlanId(); - - /** - * Get all unique IPv4 addresses associated with the device. - * - * @return an array containing the unique IPv4 addresses for the device. - */ - public Integer[] getIPv4Addresses(); - - /** - * Get all unique attachment points associated with the device. This will - * not include any blocked attachment points. - * - * @return an array containing all unique attachment points for the device - */ - public SwitchPort[] getAttachmentPoints(); - - /** - * Get all old attachment points associated with the device. this is used in - * host movement scenario. - * - * @return an array containing all unique old attachment points for the - * device - */ - public SwitchPort[] getOldAP(); - - /** - * Get all unique attachment points associated with the device. - * - * @param includeError - * whether to include blocked attachment points. Blocked - * attachment points should not be used for forwarding, but could - * be useful to show to a user - * @return an array containing all unique attachment points for the device - */ - public SwitchPort[] getAttachmentPoints(boolean includeError); - - /** - * Returns all unique VLAN IDs for the device that were observed on the - * given switch port - * - * @param swp - * the switch port to query - * @return an array containing the unique VLAN IDs - */ - public Short[] getSwitchPortVlanIds(SwitchPort swp); - - /** - * Get the most recent timestamp for this device - * - * @return the last seen timestamp - */ - public Date getLastSeen(); - - /** - * Get the entity class for the device. - * - * @return the entity class - * @see IEntityClassifierService - */ - public IEntityClass getEntityClass(); - - public boolean isStaticHost(); - - public void setStaticHost(boolean isStatic); - - public HostNodeConnector toHostNodeConnector(); - -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceListener.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceListener.java deleted file mode 100644 index 586191531b..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceListener.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2011 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker; - -import org.opendaylight.controller.sal.utils.IListener; - -/** - * Implementors of this interface can receive updates from DeviceManager about - * the state of devices under its control. - * - * @author David Erickson (daviderickson@cs.stanford.edu) - */ -public interface IDeviceListener extends IListener { - /** - * Called when a new Device is found - * - * @param device - * the device that changed - */ - public void deviceAdded(IDevice device); - - /** - * Called when a Device is removed, this typically occurs when the port the - * Device is attached to goes down, or the switch it is attached to is - * removed. - * - * @param device - * the device that changed - */ - public void deviceRemoved(IDevice device); - - /** - * Called when a Device has moved to a new location on the network. Note - * that either the switch or the port or both has changed. - * - * @param device - * the device that changed - */ - public void deviceMoved(IDevice device); - - /** - * Called when a network address has been added or remove from a device - * - * @param device - * the device that changed - */ - public void deviceIPV4AddrChanged(IDevice device); - - /** - * Called when a VLAN tag for the device has been added or removed - * - * @param device - * the device that changed - */ - public void deviceVlanChanged(IDevice device); -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceService.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceService.java deleted file mode 100755 index 53b23f2831..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IDeviceService.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (c) 2011,2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker; - -import java.util.Collection; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.Set; - -import org.opendaylight.controller.sal.core.NodeConnector; - -/** - * Device manager allows interacting with devices on the network. Note that - * under normal circumstances, {@link Device} objects should be retrieved from - * the {@link FloodlightContext} rather than from {@link IDeviceManager}. - */ -public interface IDeviceService { - - /** - * Fields used in devices for indexes and querying - * - * @see IDeviceService#addIndex - */ - enum DeviceField { - MAC, IPV4, VLAN, SWITCHPORT - } - - /** - * Get the device with the given device key. - * - * @param deviceKey - * the key to search for - * @return the device associated with the key, or null if no such device - * @see IDevice#getDeviceKey() - */ - public IDevice getDevice(Long deviceKey); - - /** - * Search for a device exactly matching the provided device fields. This is - * the same lookup process that is used for packet_in processing and device - * learning. Thus, findDevice() can be used to match flow entries from - * switches to devices. Only the key fields as defined by the - * {@link IEntityClassifierService} will be important in this search. All - * key fields MUST be supplied. - * - * {@link queryDevices()} might be more appropriate! - * - * @param macAddress - * The MAC address - * @param vlan - * the VLAN. Null means no VLAN and is valid even if VLAN is a - * key field. - * @param ipv4Address - * the ipv4 address - * @param port - * the node connector - * @return an {@link IDevice} or null if no device is found. - * @see IDeviceManager#setEntityClassifier(IEntityClassifierService) - * @throws IllegalArgumentException - * if not all key fields of the current - * {@link IEntityClassifierService} are specified. - */ - public IDevice findDevice(long macAddress, Short vlan, Integer ipv4Address, - NodeConnector port) throws IllegalArgumentException; - - /** - * Get a destination device using entity fields that corresponds with the - * given source device. The source device is important since there could be - * ambiguity in the destination device without the attachment point - * information. Search for a device in a given entity class. This is the - * same as the lookup process for destination devices. - * - * Only the key fields as defined by the reference entity class will be - * important in this search. All key fields MUST be supplied. - * - * @param entityClass - * The entity class in which to perform the lookup. - * @param macAddress - * The MAC address for the destination - * @param vlan - * the VLAN if available - * @param ipv4Address - * The IP address if available. - * @return an {@link IDevice} or null if no device is found. - * @see IDeviceService#findDevice(long, Short, Integer, Long, Integer) - * @throws IllegalArgumentException - * if not all key fields of the source's {@link IEntityClass} - * are specified. - */ - public IDevice findClassDevice(IEntityClass entityClass, long macAddress, - Short vlan, Integer ipv4Address) throws IllegalArgumentException; - - /** - * Get an unmodifiable collection view over all devices currently known. - * - * @return the collection of all devices - */ - public Collection getAllDevices(); - - /** - * Create an index over a set of fields. This allows efficient lookup of - * devices when querying using the indexed set of specified fields. The - * index must be registered before any device learning takes place, or it - * may be incomplete. It's OK if this is called multiple times with the same - * fields; only one index will be created for each unique set of fields. - * - * @param perClass - * set to true if the index should be maintained for each entity - * class separately. - * @param keyFields - * the set of fields on which to index - */ - public void addIndex(boolean perClass, EnumSet keyFields); - - /** - * Find devices that match the provided query. Any fields that are null will - * not be included in the query. If there is an index for the query, then it - * will be performed efficiently using the index. Otherwise, there will be a - * full scan of the device list. - * - * @param macAddress - * The MAC address - * @param vlan - * the VLAN - * @param ipv4Address - * the ipv4 address - * @param port - * the switch port - * @return an iterator over a set of devices matching the query - * @see IDeviceService#queryClassDevices(IEntityClass, Long, Short, Integer, - * Long, Integer) - */ - public Iterator queryDevices(Long macAddress, - Short vlan, Integer ipv4Address, NodeConnector port); - - /** - * Find devices that match the provided query. Only the index for the - * specified class will be searched. Any fields that are null will not be - * included in the query. If there is an index for the query, then it will - * be performed efficiently using the index. Otherwise, there will be a full - * scan of the device list. - * - * @param entityClass - * The entity class in which to perform the query - * @param macAddress - * The MAC address - * @param vlan - * the VLAN - * @param ipv4Address - * the ipv4 address - * @param port - * the switch port - * @return an iterator over a set of devices matching the query - * @see IDeviceService#queryClassDevices(Long, Short, Integer, Long, - * Integer) - */ - public Iterator queryClassDevices( - IEntityClass entityClass, Long macAddress, Short vlan, - Integer ipv4Address, NodeConnector port); - - /** - * Adds a listener to listen for IDeviceManagerServices notifications - * - * @param listener - * The listener that wants the notifications - * @param type - * The type of the listener - */ - public void addListener(IDeviceListener listener); - - /** - * Specify points in the network where attachment points are not to be - * learned. - * - * @param sw - * @param port - */ - public void addSuppressAPs(NodeConnector port); - - public void removeSuppressAPs(NodeConnector port); - - public Set getSuppressAPs(); - -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClass.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClass.java deleted file mode 100644 index 5d57e4dc8a..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClass.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2011,2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker; - -import java.util.EnumSet; - -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; - -/** - * Entities within an entity class are grouped into {@link Device} objects based - * on the {@link IEntityClass}, and the key fields specified by the entity - * class. A set of entities are considered to be the same device if and only if - * they belong to the same entity class and they match on all key fields for - * that entity class. A field is effectively wildcarded by not including it in - * the list of key fields returned by {@link IEntityClassifierService} and/or - * {@link IEntityClass}. - * - * Note that if you're not using static objects, you'll need to override - * {@link Object#equals(Object)} and {@link Object#hashCode()}. - * - * @author readams - * - */ -public interface IEntityClass { - /** - * Return the set of key fields for this entity class. Entities belonging to - * this class that differ in fields not included in this collection will be - * considered the same device. The key fields for an entity class must not - * change unless associated with a flush of that entity class. - * - * @return a set containing the fields that should not be wildcarded. May be - * null to indicate that all fields are key fields. - */ - EnumSet getKeyFields(); - - /** - * Returns a user-friendly, unique name for this EntityClass - * - * @return the name of the entity class - */ - String getName(); -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassListener.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassListener.java deleted file mode 100644 index be5f2585a6..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassListener.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2011 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker; - -import java.util.Set; - -/** - * Implementors of this interface can receive updates from the Entity Classifier - * about the changes to entity Classes. - * - * @author Ananth Suryanarayana (Ananth.Suryanarayana@bigswitch.com) - */ -public interface IEntityClassListener { - - /** - * Process entity classes change event. - * - * @param entityClassNames - * Set of entity classes changed - */ - public void entityClassChanged(Set entityClassNames); -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassifierService.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassifierService.java deleted file mode 100644 index f6071e1072..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IEntityClassifierService.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2011,2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker; - -import java.util.Collection; -import java.util.EnumSet; - -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; - -/** - * A component that wishes to participate in entity classification needs to - * implement the IEntityClassifier interface, and register with the Device - * Manager as an entity classifier. An entity is classified by the classifier - * into an {@link IEntityClass} - * - * @author readams - */ -public interface IEntityClassifierService { - /** - * Classify the given entity into an IEntityClass. It is important that the - * key fields returned by {@link IEntityClassifierService#getKeyFields()} be - * sufficient for classifying entities. That is, if two entities are - * identical except for a field that is not a key field, they must be - * assigned the same class. Furthermore, entity classification must be - * transitive: For all entities x, y, z, if x and y belong to a class c, and - * y and z belong class c, then x and z must belong to class c. - * - * @param entity - * the entity to classify - * @return the IEntityClass resulting from the classification. - * @see IEntityClassifierService#getKeyFields() - */ - IEntityClass classifyEntity(Entity entity); - - /** - * Return the most general list of fields that should be used as key fields. - * If devices differ in any fields not listed here, they can never be - * considered a different device by any {@link IEntityClass} returned by - * {@link IEntityClassifierService#classifyEntity}. The key fields for an - * entity classifier must not change unless associated with a flush of all - * entity state. The list of key fields must be the union of all key fields - * that could be returned by {@link IEntityClass#getKeyFields()}. - * - * @return a set containing the fields that should not be wildcarded. May be - * null to indicate that all fields are key fields. - * @see {@link IEntityClass#getKeyFields()} - * @see {@link IEntityClassifierService#classifyEntity} - */ - EnumSet getKeyFields(); - - /** - * Reclassify the given entity into a class. When reclassifying entities, it - * can be helpful to take into account the current classification either as - * an optimization or to allow flushing any cached state tied to the key for - * that device. The entity will be assigned to a new device with a new - * object if the entity class returned is different from the entity class - * for curDevice. - * - *

- * Note that you must take steps to ensure you always return classes in some - * consistent ordering. - * - * @param curDevice - * the device currently associated with the entity - * @param entity - * the entity to reclassify - * @return the IEntityClass resulting from the classification - */ - IEntityClass reclassifyEntity(IDevice curDevice, Entity entity); - - /** - * Once reclassification is complete for a device, this method will be - * called. If any entities within the device changed their classification, - * it will split into one or more new devices for each of the entities. If - * two devices are merged because of a reclassification, then this will be - * called on each of the devices, with the same device in the newDevices - * collection. - * - * @param oldDevice - * the original device object - * @param newDevices - * all the new devices derived from the entities of the old - * device. If null, the old device was unchanged. - */ - void deviceUpdate(IDevice oldDevice, - Collection newDevices); - - /** - * Adds a listener to listen for IEntityClassifierServices notifications - * - * @param listener - * The listener that wants the notifications - */ - public void addListener(IEntityClassListener listener); -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java deleted file mode 100644 index 51d68d87b4..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfHostListener.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; - -/** - * This interface defines the method to notify detected Host on the network. The - * information includes Host's IP address, MAC address, switch ID, port, and - * VLAN. - * - */ - -public interface IfHostListener { - /** - * Learns new Hosts. Called by ArpHandler and implemented in - * HostTracker.java. If a Host is learned for the first time then adds it to - * the local database and informs other applications of coming up a new - * Host. For the hosts which it has already learned, it refreshes them. - * - * @param host - * Host info encapsulated in HostNodeConnector class - */ - public void hostListener(HostNodeConnector host); -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java deleted file mode 100644 index 995ee57515..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfIptoHost.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker; - -import java.net.InetAddress; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Future; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.Status; - -/** - * This interface defines the methods to retrieve information about learned - * Hosts. Also provides methods to statically add/remove Hosts from the local - * database. - * - */ - -public interface IfIptoHost { - /** - * Applications call this interface methods to determine IP address to MAC - * binding and its connectivity to an OpenFlow switch in term of Node, Port, - * and VLAN. These bindings are learned dynamically as well as can be added - * statically through Northbound APIs. If a binding is unknown, then an ARP - * request is initiated immediately to discover the host. - * - * @param networkAddress - * IP Address of the Host encapsulated in class InetAddress - * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * Class that contains the Host info such as its MAC address, Switch - * ID, port, VLAN. If Host is not found, returns NULL - */ - public HostNodeConnector hostFind(InetAddress networkAddress); - - /** - * Checks the local Host Database to see if a Host has been learned for a - * given IP address. - * - * @param networkAddress - * IP Address of the Host encapsulated in class InetAddress - * @return {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * Class that contains the Host info such as its MAC address, Switch - * ID, port, VLAN. If Host is not found, returns NULL - * - */ - public HostNodeConnector hostQuery(InetAddress networkAddress); - - /** - * Initiates an immediate discovery of the Host for a given IP address. This - * provides for the calling applications to block on the host discovery. - * - * @param networkAddress - * IP address encapsulated in InetAddress class - * @return Future - * {@link org.opendaylight.controller.hosttracker.HostTrackerCallable} - */ - public Future discoverHost(InetAddress networkAddress); - - /** - * Returns the Network Hierarchy for a given Host. This API is typically - * used by applications like Hadoop for Rack Awareness functionality. - * - * @param IP - * address of the Host encapsulated in InetAddress class - * @return List of String ArrayList containing the Hierarchies. - */ - public List> getHostNetworkHierarchy(InetAddress hostAddress); - - /** - * Returns all the the Hosts either learned dynamically or added statically - * via Northbound APIs. - * - * @return Set of - * {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * . Class that contains the Host info such as its MAC address, - * Switch ID, port, VLAN. - */ - public Set getAllHosts(); - - /** - * Returns all the "Active Hosts" learned "Statically" via Northbound APIs. - * These Hosts are categorized as "Active" because the Switch and Port they - * are connected to, are in up state. - * - * @return Set of - * {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * . Class that contains the Host info such as MAC address, Switch - * ID, port, VLAN. If Host is not found, returns NULL - */ - public Set getActiveStaticHosts(); - - /** - * Returns all the "Inactive Hosts" learned "Statically" via Northbound - * APIs. These Hosts are categorized as "Inactive" because either the Switch - * or the Port they are connected to, is in down state. - * - * @return Set of HostNodeConnector - * {@link org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector} - * . HostNodeConnector is Class that contains the Host info such as - * its MAC address, OpenFlowNode ID, port, VLAN. - */ - public Set getInactiveStaticHosts(); - - /** - * Hosts can be learned dynamically or added statically. This method allows - * the addition of a Host to the local database statically. - * - * @param networkAddress - * IP Address of the Host - * @param dataLayerAddress - * MAC Address of the Host - * @param nc - * NodeConnector to which the host is attached - * @param vlan - * VLAN the host belongs to - * @return The status object as described in {@code Status} indicating the - * result of this action. - */ - public Status addStaticHost(String networkAddress, String dataLayerAddress, - NodeConnector nc, String vlan); - - /** - * Allows the deletion of statically learned Host - * - * @param networkAddress - * @return The status object as described in {@code Status} indicating the - * result of this action. - */ - public Status removeStaticHost(String networkAddress); -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java deleted file mode 100644 index ef900e475e..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/IfNewHostNotify.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; - -/** - * This Interface defines the methods for client applications of Host Tracker to - * get notifications when a new host is learned or existing host is removed from - * the network. - * - */ -public interface IfNewHostNotify { - /** - * Notifies the HostTracker Clients that a new Host has been learned - * - * @param host - * Host Info encapsulated in HostNodeConnector class - */ - public void notifyHTClient(HostNodeConnector host); - - /** - * Notifies the HostTracker Clients that a Host which was learned in the - * past has been removed either due to switch/port down event or due to ARP - * Aging - * - * @param host - * Host Info encapsulated in HostNodeConnector class - */ - public void notifyHTClientHostRemoved(HostNodeConnector host); -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/SwitchPort.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/SwitchPort.java deleted file mode 100644 index 892e1d6c79..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/SwitchPort.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker; - -import org.opendaylight.controller.sal.core.NodeConnector; - -/** - * A simple switch DPID/port pair This class is immutable - * - * @author readams - * - */ -public class SwitchPort { - public enum ErrorStatus { - DUPLICATE_DEVICE("duplicate-device"); - - private String value; - - ErrorStatus(String v) { - value = v; - } - - @Override - public String toString() { - return value; - } - - public static ErrorStatus fromString(String str) { - for (ErrorStatus m : ErrorStatus.values()) { - if (m.value.equals(str)) { - return m; - } - } - return null; - } - } - - private final NodeConnector port; - private final ErrorStatus errorStatus; - - /** - * Simple constructor - * - * @param switchDPID - * the dpid - * @param port - * the port - * @param errorStatus - * any error status for the switch port - */ - public SwitchPort(NodeConnector port, ErrorStatus errorStatus) { - super(); - this.port = port; - this.errorStatus = errorStatus; - } - - /** - * Simple constructor - * - * @param switchDPID - * the dpid - * @param port - * the port - */ - public SwitchPort(NodeConnector port) { - super(); - this.port = port; - this.errorStatus = null; - } - - // *************** - // Getters/Setters - // *************** - - public NodeConnector getPort() { - return port; - } - - public ErrorStatus getErrorStatus() { - return errorStatus; - } - - // ****** - // Object - // ****** - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((errorStatus == null) ? 0 : errorStatus.hashCode()); - result = prime * result + ((port == null) ? 0 : port.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SwitchPort other = (SwitchPort) obj; - if (errorStatus != other.errorStatus) { - return false; - } - if (port == null) { - if (other.port != null) { - return false; - } - } else if (!port.equals(other.port)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "SwitchPort [port=" + port + ", errorStatus=" + errorStatus - + "]"; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java deleted file mode 100644 index 86376be5c5..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnector.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.hostAware; - -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.util.Arrays; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.apache.commons.lang3.builder.ReflectionToStringBuilder; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Host; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.packet.address.EthernetAddress; - -@XmlRootElement(name = "host") -@XmlAccessorType(XmlAccessType.NONE) -public class HostNodeConnector extends Host { - private static final long serialVersionUID = 1L; - @XmlElement - private NodeConnector nodeConnector; - @XmlElement - private short vlan; - @XmlElement - private boolean staticHost; - private transient short arpSendCountDown; - - /** - * Private constructor used for JAXB mapping - */ - @SuppressWarnings("unused") - private HostNodeConnector() { - } - - public HostNodeConnector(InetAddress ip) throws ConstructionException { - this(ip, null); - } - - public HostNodeConnector(InetAddress ip, NodeConnector nc) - throws ConstructionException { - this(new EthernetAddress(new byte[] { (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 }), ip, nc, - (short) 0); - } - - public HostNodeConnector(byte[] mac, InetAddress ip, NodeConnector nc, - short vlan) throws ConstructionException { - this(new EthernetAddress(mac.clone()), ip, nc, vlan); - } - - public HostNodeConnector(EthernetAddress eaddr, InetAddress naddr, - NodeConnector nc, short vlan) throws ConstructionException { - super(eaddr, naddr); - this.nodeConnector = nc; - this.vlan = vlan; - } - - /** - * @return the NodeConnector - */ - public NodeConnector getnodeConnector() { - return this.nodeConnector; - } - - /** - * @return the Node - */ - public Node getnodeconnectorNode() { - return this.nodeConnector.getNode(); - } - - /** - * @return the NodeId - */ - public Long getnodeconnectornodeId() { - return (Long) this.nodeConnector.getNode().getID(); - } - - /** - * @return the port - */ - public Short getnodeconnectorportId() { - return (Short) this.nodeConnector.getID(); - } - - /** - * @return the DataLayerAddress - */ - public byte[] getDataLayerAddressBytes() { - byte[] macaddr = null; - if (getDataLayerAddress() instanceof EthernetAddress) { - EthernetAddress e = (EthernetAddress) getDataLayerAddress(); - macaddr = e.getValue(); - } - return macaddr; - } - - /** - * @return the vlan - */ - public short getVlan() { - return this.vlan; - } - - public boolean isStaticHost() { - return this.staticHost; - } - - public HostNodeConnector setStaticHost(boolean statically_learned) { - this.staticHost = statically_learned; - return this; - } - - public HostNodeConnector initArpSendCountDown() { - this.arpSendCountDown = 24; - return this; - } - - public short getArpSendCountDown() { - return (this.arpSendCountDown); - } - - public HostNodeConnector setArpSendCountDown(short cntdown) { - this.arpSendCountDown = cntdown; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result - + ((nodeConnector == null) ? 0 : nodeConnector.hashCode()); - result = prime * result + (staticHost ? 1231 : 1237); - result = prime * result + vlan; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - HostNodeConnector other = (HostNodeConnector) obj; - if (nodeConnector == null) { - if (other.nodeConnector != null) { - return false; - } - } else if (!nodeConnector.equals(other.nodeConnector)) { - return false; - } - if (staticHost != other.staticHost) { - return false; - } - if (vlan != other.vlan) { - return false; - } - return true; - } - - public boolean equalsByIP(InetAddress networkAddress) { - return (this.getNetworkAddress().equals(networkAddress)); - } - - public boolean isRewriteEnabled() { - byte[] emptyArray = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00 }; - byte[] macaddr = null; - if (getDataLayerAddress() instanceof EthernetAddress) { - EthernetAddress e = (EthernetAddress) getDataLayerAddress(); - macaddr = e.getValue(); - } - if (macaddr == null) { - return false; - } - return !Arrays.equals(emptyArray, macaddr); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "HostNodeConnector[" + ReflectionToStringBuilder.toString(this) - + "]"; - } - - public boolean isV4Host() { - return (getNetworkAddress() instanceof Inet4Address); - } - - public boolean isV6Host() { - return (getNetworkAddress() instanceof Inet6Address); - } - - public String toJson() { - return "{\"host\":\"" + super.toString() + "\", " + "\"vlan\":\"" - + String.valueOf(vlan) + "\",\"NodeConnector\":\"" - + nodeConnector.toString() + "\"," + "\"static\":\"" - + String.valueOf(isStaticHost()) + "\"}"; - } - -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java b/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java deleted file mode 100644 index abe75180cf..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/main/java/org/opendaylight/controller/hosttracker/hostAware/IHostFinder.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.hostAware; - -import java.net.InetAddress; - -/** - * This Interface defines the methods to trigger the discovery of a Host and to - * probe if a learned Host is still in the network. - * - * - * - */ -public interface IHostFinder { - /** - * This method initiates the discovery of a host based on its IP address. - * This is triggered by query of an application to the HostTracker. The - * requested IP address doesn't exist in the local database at this point. - * - * @param networkAddress - * IP Address encapsulated in InetAddress class - * - */ - public void find(InetAddress networkAddress); - - /** - * This method is called by HostTracker to see if a learned Host is still in - * the network. Used mostly for ARP Aging. - * - * @param host - * The Host that needs to be probed - */ - public void probe(HostNodeConnector host); -} diff --git a/opendaylight/adsal/hosttracker_new/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java b/opendaylight/adsal/hosttracker_new/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java deleted file mode 100644 index 4248c6dfd0..0000000000 --- a/opendaylight/adsal/hosttracker_new/api/src/test/java/org/opendaylight/controller/hosttracker/hostAware/HostNodeConnectorTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.hostAware; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.packet.address.EthernetAddress; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -public class HostNodeConnectorTest { - - @Test - public void testHostNodeConnector() throws UnknownHostException { - HostNodeConnector hostnodeconnector_1, hostnodeconnector_2, hostnodeconnector_3; - InetAddress hostIP_1 = InetAddress.getByName("192.168.0.8"); - InetAddress hostIP_2 = InetAddress - .getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress hostIP_3 = InetAddress.getByName("192.168.0.28"); - byte[] hostMAC_2 = new byte[] { (byte) 0x11, (byte) 0x22, (byte) 0x33, - (byte) 0x22, (byte) 0x22, (byte) 0x22 }; - byte[] hostMAC_3 = new byte[] { (byte) 0x11, (byte) 0x22, (byte) 0x33, - (byte) 0x33, (byte) 0x33, (byte) 0x33 }; - - Node node = NodeCreator.createOFNode(1L); - NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node); - NodeConnector nc2 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node); - - try { - hostnodeconnector_1 = new HostNodeConnector(hostIP_1); - Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1)); - Assert.assertTrue(hostnodeconnector_1.isV4Host()); - Assert.assertTrue(hostnodeconnector_1.equalsByIP(hostIP_1)); - } catch (ConstructionException e) { - Assert.assertTrue(false); - } - - try { - hostnodeconnector_2 = new HostNodeConnector(hostMAC_2, hostIP_2, - nc1, (short) 2); - Assert.assertTrue(hostnodeconnector_2.isV6Host()); - Assert.assertTrue(hostnodeconnector_2.getnodeConnector() - .equals(nc1)); - Assert.assertTrue(hostnodeconnector_2.getnodeconnectorNode() - .equals(node)); - Assert.assertTrue(node.getID().equals( - hostnodeconnector_2.getnodeconnectornodeId())); - Assert.assertTrue(hostnodeconnector_2.getnodeconnectorportId() - .equals((short) 2)); - } catch (ConstructionException e) { - Assert.assertTrue(false); - } - - try { - hostnodeconnector_3 = new HostNodeConnector(new EthernetAddress( - hostMAC_3), hostIP_3, nc2, (short) 3); - byte[] hostMAC_3_rb = hostnodeconnector_3 - .getDataLayerAddressBytes(); - HostNodeConnector hostnodeconnector_3rb = new HostNodeConnector( - new EthernetAddress(hostMAC_3_rb), hostIP_3, nc2, (short) 3); - Assert.assertTrue(hostnodeconnector_3.equals(hostnodeconnector_3rb)); - - Assert.assertTrue(hostnodeconnector_3.getVlan() == (short) 3); - - hostnodeconnector_3.setStaticHost(true); - Assert.assertTrue(hostnodeconnector_3.isStaticHost()); - - Assert.assertTrue(hostnodeconnector_3.isRewriteEnabled()); - - hostnodeconnector_3.initArpSendCountDown().setArpSendCountDown( - (short) 10); - Assert.assertTrue(hostnodeconnector_3.getArpSendCountDown() == (short) 10); - - } catch (ConstructionException e) { - Assert.assertTrue(false); - } - - } - -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/pom.xml b/opendaylight/adsal/hosttracker_new/implementation/pom.xml deleted file mode 100644 index 1b03fc4902..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/pom.xml +++ /dev/null @@ -1,125 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - hosttracker_new.implementation - 0.6.0-SNAPSHOT - bundle - - - - reuseReports - target/jacoco-it.exec - target/jacoco.exec - - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - commons.logback_settings - - - org.opendaylight.controller - hosttracker_new - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - topologymanager - - - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.topology, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.hosttracker, - org.opendaylight.controller.topologymanager, - org.opendaylight.controller.sal.packet.address, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.hosttracker.hostAware, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.felix.dm, - org.apache.commons.lang3.builder, - org.osgi.service.component, - org.slf4j, - org.eclipse.osgi.framework.console, - org.osgi.framework - org.opendaylight.controller.hosttracker.internal.Activator - - - ${project.basedir}/META-INF - - - - org.jacoco - jacoco-maven-plugin - - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - report - - test - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java deleted file mode 100644 index ad3f7eef1a..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.internal; - -import java.util.Dictionary; -import java.util.Hashtable; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.hosttracker.IDeviceService; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.IfNewHostNotify; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.opendaylight.controller.topologymanager.ITopologyManagerAware; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the list of - * known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { DeviceManagerImpl.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies is - * required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - * @param containerName - * The containerName being configured, this allow also optional - * per-container different behavior if needed, usually should not - * be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(DeviceManagerImpl.class)) { - // export the service - // XXX - TODO merge with existing APIs - Dictionary props = new Hashtable(); - props.put("salListenerName", "devicemanager"); - - c.setInterface( - new String[] { IDeviceService.class.getName(), - IfIptoHost.class.getName(), - IListenDataPacket.class.getName(), - ITopologyManagerAware.class.getName() }, props); - - c.add(createContainerServiceDependency(containerName) - .setService(ISwitchManager.class) - .setCallbacks("setSwitchManager", "unsetSwitchManager") - .setRequired(false)); - - c.add(createContainerServiceDependency(containerName) - .setService(IDataPacketService.class) - .setCallbacks("setDataPacketService", - "unsetDataPacketService").setRequired(true)); - - c.add(createContainerServiceDependency(containerName) - .setService(IfNewHostNotify.class) - .setCallbacks("setNewHostNotify", - "unsetNewHostNotify").setRequired(false)); - - c.add(createContainerServiceDependency(containerName) - .setService(ITopologyManager.class) - .setCallbacks("setTopologyManager", "unsetTopologyManager") - .setRequired(false)); - } - } - - /** - * Method which tells how many Global implementations are supported by the - * bundle. This way we can tune the number of components created. This - * components will be created ONLY at the time of bundle startup and will be - * destroyed only at time of bundle destruction, this is the major - * difference with the implementation retrieved via getImplementations where - * all of them are assumed to be in a container ! - * - * - * @return The list of implementations the bundle will support, in Global - * version - */ - @Override - protected Object[] getGlobalImplementations() { - return null; - } - - /** - * Configure the dependency for a given instance Global - * - * @param c - * Component assigned for this instance, this will be what will - * be used for configuration - * @param imp - * implementation to be configured - * @param containerName - * container on which the configuration happens - */ - @Override - protected void configureGlobalInstance(Component c, Object imp) { - - } - -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/AttachmentPoint.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/AttachmentPoint.java deleted file mode 100644 index ba2c64aff0..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/AttachmentPoint.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2011,2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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. - */ - -/** - * @author Srini - */ - -package org.opendaylight.controller.hosttracker.internal; - -import org.opendaylight.controller.sal.core.NodeConnector; - -public class AttachmentPoint { - NodeConnector port; - long activeSince; - long lastSeen; - - // Timeout for moving attachment points from OF/broadcast - // domain to another. - public static final long INACTIVITY_INTERVAL = 30000; // 30 seconds - public static final long EXTERNAL_TO_EXTERNAL_TIMEOUT = 5000; // 5 seconds - public static final long OPENFLOW_TO_EXTERNAL_TIMEOUT = 30000; // 30 seconds - public static final long CONSISTENT_TIMEOUT = 30000; // 30 seconds - - public AttachmentPoint(NodeConnector port, long activeSince, long lastSeen) { - this.port = port; - this.activeSince = activeSince; - this.lastSeen = lastSeen; - } - - public AttachmentPoint(NodeConnector port, long lastSeen) { - this.port = port; - this.lastSeen = lastSeen; - this.activeSince = lastSeen; - } - - public AttachmentPoint(AttachmentPoint ap) { - this.port = ap.port; - this.activeSince = ap.activeSince; - this.lastSeen = ap.lastSeen; - } - - public NodeConnector getPort() { - return port; - } - - public void setPort(NodeConnector port) { - this.port = port; - } - - public long getActiveSince() { - return activeSince; - } - - public void setActiveSince(long activeSince) { - this.activeSince = activeSince; - } - - public long getLastSeen() { - return lastSeen; - } - - public void setLastSeen(long lastSeen) { - if (this.lastSeen + INACTIVITY_INTERVAL < lastSeen) - this.activeSince = lastSeen; - if (this.lastSeen < lastSeen) - this.lastSeen = lastSeen; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((port == null) ? 0 : port.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - AttachmentPoint other = (AttachmentPoint) obj; - if (port == null) { - if (other.port != null) - return false; - } else if (!port.equals(other.port)) - return false; - return true; - } - - @Override - public String toString() { - return "AttachmentPoint [port=" + port + ", activeSince=" + activeSince - + ", lastSeen=" + lastSeen + "]"; - } -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DefaultEntityClassifier.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DefaultEntityClassifier.java deleted file mode 100644 index 39c322fdef..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DefaultEntityClassifier.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2011,2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker.internal; - -import java.util.Collection; -import java.util.EnumSet; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDevice; -import org.opendaylight.controller.hosttracker.IDeviceService; -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; -import org.opendaylight.controller.hosttracker.IEntityClass; -import org.opendaylight.controller.hosttracker.IEntityClassListener; -import org.opendaylight.controller.hosttracker.IEntityClassifierService; - -/** - * This is a default entity classifier that simply classifies all entities into - * a fixed entity class, with key fields of MAC and VLAN. - * - * @author readams - */ -public class DefaultEntityClassifier implements IEntityClassifierService { - /** - * A default fixed entity class - */ - protected static class DefaultEntityClass implements IEntityClass { - String name; - - public DefaultEntityClass(String name) { - this.name = name; - } - - @Override - public EnumSet getKeyFields() { - return keyFields; - } - - @Override - public String getName() { - return name; - } - } - - protected static EnumSet keyFields; - static { - keyFields = EnumSet.of(DeviceField.MAC, DeviceField.VLAN); - } - protected static DefaultEntityClass entityClass = new DefaultEntityClass( - "DefaultEntityClass"); - - @Override - public IEntityClass classifyEntity(Entity entity) { - return entityClass; - } - - @Override - public IEntityClass reclassifyEntity(IDevice curDevice, Entity entity) { - return entityClass; - } - - @Override - public void deviceUpdate(IDevice oldDevice, - Collection newDevices) { - // no-op - } - - @Override - public EnumSet getKeyFields() { - return keyFields; - } - - @Override - public void addListener(IEntityClassListener listener) { - // no-op - - } -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Device.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Device.java deleted file mode 100755 index 8fcb988b6c..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Device.java +++ /dev/null @@ -1,828 +0,0 @@ -/* - * Copyright (c) 2011,2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker.internal; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TreeSet; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDevice; -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; -import org.opendaylight.controller.hosttracker.IEntityClass; -import org.opendaylight.controller.hosttracker.SwitchPort; -import org.opendaylight.controller.hosttracker.SwitchPort.ErrorStatus; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Concrete implementation of {@link IDevice} - * - * @author readams - */ -public class Device implements IDevice { - protected static Logger log = LoggerFactory.getLogger(Device.class); - public static final short VLAN_UNTAGGED = (short) 0xffff; - - private final Long deviceKey; - protected final DeviceManagerImpl deviceManager; - - protected final Entity[] entities; - private final IEntityClass entityClass; - - protected final String macAddressString; - // the vlan Ids from the entities of this device - protected final Short[] vlanIds; - protected volatile String dhcpClientName; - - private boolean staticHost; - - /** - * These are the old attachment points for the device that were valid no - * more than INACTIVITY_TIME ago. - */ - protected volatile List oldAPs; - /** - * The current attachment points for the device. - */ - protected volatile List attachmentPoints; - - // ************ - // Constructors - // ************ - - /** - * Create a device from an entities - * - * @param deviceManager - * the device manager for this device - * @param deviceKey - * the unique identifier for this device object - * @param entity - * the initial entity for the device - * @param entityClass - * the entity classes associated with the entity - */ - public Device(DeviceManagerImpl deviceManager, Long deviceKey, - Entity entity, IEntityClass entityClass) { - this.deviceManager = deviceManager; - this.deviceKey = deviceKey; - this.entities = new Entity[] { entity }; - this.macAddressString = HexEncode.longToHexString(entity - .getMacAddress()); - this.entityClass = entityClass; - Arrays.sort(this.entities); - - this.dhcpClientName = null; - this.oldAPs = null; - this.attachmentPoints = null; - - if (entity.getPort() != null) { - NodeConnector port = entity.getPort(); - - if (deviceManager.isValidAttachmentPoint(port)) { - AttachmentPoint ap; - ap = new AttachmentPoint(port, entity.getLastSeenTimestamp() - .getTime()); - - this.attachmentPoints = new ArrayList(); - this.attachmentPoints.add(ap); - } - } - vlanIds = computeVlandIds(); - } - - /** - * Create a device from a set of entities - * - * @param deviceManager - * the device manager for this device - * @param deviceKey - * the unique identifier for this device object - * @param entities - * the initial entities for the device - * @param entityClass - * the entity class associated with the entities - */ - public Device(DeviceManagerImpl deviceManager, Long deviceKey, - String dhcpClientName, Collection oldAPs, - Collection attachmentPoints, - Collection entities, IEntityClass entityClass) { - this.deviceManager = deviceManager; - this.deviceKey = deviceKey; - this.dhcpClientName = dhcpClientName; - this.entities = entities.toArray(new Entity[entities.size()]); - this.oldAPs = null; - this.attachmentPoints = null; - if (oldAPs != null) { - this.oldAPs = new ArrayList(oldAPs); - } - if (attachmentPoints != null) { - this.attachmentPoints = new ArrayList( - attachmentPoints); - } - this.macAddressString = HexEncode.longToHexString(this.entities[0] - .getMacAddress()); - this.entityClass = entityClass; - Arrays.sort(this.entities); - vlanIds = computeVlandIds(); - } - - /** - * Construct a new device consisting of the entities from the old device - * plus an additional entity. The caller needs to ensure that the additional - * entity is not already present in the array - * - * @param device - * the old device object - * @param newEntity - * the entity to add. newEntity must be have the same entity - * class as device - * @param insertionpoint - * if positive indicates the index in the entities array were the new - * entity should be inserted. If negative we will compute the correct - * insertion point - */ - public Device(Device device, Entity newEntity, int insertionpoint) { - this.deviceManager = device.deviceManager; - this.deviceKey = device.deviceKey; - this.dhcpClientName = device.dhcpClientName; - - this.entities = new Entity[device.entities.length + 1]; - if (insertionpoint < 0) { - insertionpoint = -(Arrays.binarySearch(device.entities, newEntity) + 1); - } - if (insertionpoint > 0) { - // insertion point is not the beginning: - // copy up to insertion point - System.arraycopy(device.entities, 0, this.entities, 0, - insertionpoint); - } - if (insertionpoint < device.entities.length) { - // insertion point is not the end - // copy from insertion point - System.arraycopy(device.entities, insertionpoint, this.entities, - insertionpoint + 1, device.entities.length - insertionpoint); - } - this.entities[insertionpoint] = newEntity; - /* - * this.entities = Arrays.copyOf(device.entities, - * device.entities.length + 1); this.entities[this.entities.length - 1] - * = newEntity; Arrays.sort(this.entities); - */ - this.oldAPs = null; - if (device.oldAPs != null) { - this.oldAPs = new ArrayList(device.oldAPs); - } - this.attachmentPoints = null; - if (device.attachmentPoints != null) { - this.attachmentPoints = new ArrayList( - device.attachmentPoints); - } - - this.macAddressString = HexEncode.longToHexString(this.entities[0] - .getMacAddress()); - - this.entityClass = device.entityClass; - vlanIds = computeVlandIds(); - } - - private Short[] computeVlandIds() { - if (entities.length == 1) { - if (entities[0].getVlan() != null) { - return new Short[] { entities[0].getVlan() }; - } else { - return new Short[] { Short.valueOf((short) -1) }; - } - } - - TreeSet vals = new TreeSet(); - for (Entity e : entities) { - if (e.getVlan() == null) { - vals.add((short) -1); - } else { - vals.add(e.getVlan()); - } - } - return vals.toArray(new Short[vals.size()]); - } - - /** - * Given a list of attachment points (apList), the procedure would return a - * map of attachment points for each L2 domain. L2 domain id is the key. - * - * @param apList - * @return - */ - private Map getAPMap(List apList) { - - if (apList == null) - return null; - // ITopologyService topology = deviceManager.topology; - - // Get the old attachment points and sort them. - List oldAP = new ArrayList(); - if (apList != null) - oldAP.addAll(apList); - - // Remove invalid attachment points before sorting. - List tempAP = new ArrayList(); - for (AttachmentPoint ap : oldAP) { - if (deviceManager.isValidAttachmentPoint(ap.getPort())) { - tempAP.add(ap); - } - } - oldAP = tempAP; - - Collections.sort(oldAP, deviceManager.apComparator); - - // Map of attachment point by L2 domain Id. - Map apMap = new HashMap(); - - for (int i = 0; i < oldAP.size(); ++i) { - AttachmentPoint ap = oldAP.get(i); - // if this is not a valid attachment point, continue - if (!deviceManager.isValidAttachmentPoint(ap.getPort())) - continue; - - // long id = topology.getL2DomainId(ap.getSw()); - // XXX - Missing functionality - long id = 0; - - apMap.put(id, ap); - } - - if (apMap.isEmpty()) - return null; - return apMap; - } - - /** - * Remove all attachment points that are older than INACTIVITY_INTERVAL from - * the list. - * - * @param apList - * @return - */ - private boolean removeExpiredAttachmentPoints(List apList) { - - List expiredAPs = new ArrayList(); - - if (apList == null) - return false; - - for (AttachmentPoint ap : apList) { - if (ap.getLastSeen() + AttachmentPoint.INACTIVITY_INTERVAL < System.currentTimeMillis()) { - expiredAPs.add(ap); - } - } - if (expiredAPs.size() > 0) { - apList.removeAll(expiredAPs); - return true; - } else { - return false; - } - } - - /** - * Get a list of duplicate attachment points, given a list of old attachment - * points and one attachment point per L2 domain. Given a true attachment - * point in the L2 domain, say trueAP, another attachment point in the same - * L2 domain, say ap, is duplicate if: 1. ap is inconsistent with trueAP, - * and 2. active time of ap is after that of trueAP; and 3. last seen time - * of ap is within the last INACTIVITY_INTERVAL - * - * @param oldAPList - * @param apMap - * @return - */ - List getDuplicateAttachmentPoints( - List oldAPList, Map apMap) { - List dupAPs = new ArrayList(); - long timeThreshold = System.currentTimeMillis() - - AttachmentPoint.INACTIVITY_INTERVAL; - - if (oldAPList == null || apMap == null) - return dupAPs; - - for (AttachmentPoint ap : oldAPList) { - long id = 0; - AttachmentPoint trueAP = apMap.get(id); - - if (trueAP == null) - continue; - boolean c = true; - boolean active = (ap.getActiveSince() > trueAP.getActiveSince()); - boolean last = ap.getLastSeen() > timeThreshold; - if (!c && active && last) { - dupAPs.add(ap); - } - } - - return dupAPs; - } - - /** - * Update the known attachment points. This method is called whenever - * topology changes. The method returns true if there's any change to the - * list of attachment points -- which indicates a possible device move. - * - * @return - */ - protected boolean updateAttachmentPoint() { - boolean moved = false; - this.oldAPs = attachmentPoints; - if (attachmentPoints == null || attachmentPoints.isEmpty()) - return false; - - List apList = new ArrayList(); - if (attachmentPoints != null) - apList.addAll(attachmentPoints); - Map newMap = getAPMap(apList); - if (newMap == null || newMap.size() != apList.size()) { - moved = true; - } - - // Prepare the new attachment point list. - if (moved) { - log.info("updateAttachmentPoint: ap {} newmap {} ", - attachmentPoints, newMap); - List newAPList = new ArrayList(); - if (newMap != null) - newAPList.addAll(newMap.values()); - this.attachmentPoints = newAPList; - } - - // Set the oldAPs to null. - return moved; - } - - /** - * Update the list of attachment points given that a new packet-in was seen - * from (sw, port) at time (lastSeen). The return value is true if there was - * any change to the list of attachment points for the device -- which - * indicates a device move. - * - * @param port - * @param lastSeen - * @return - */ - protected boolean updateAttachmentPoint(NodeConnector port, long lastSeen) { - // ITopologyService topology = deviceManager.topology; - List oldAPList; - List apList; - boolean oldAPFlag = false; - - if (!deviceManager.isValidAttachmentPoint(port)) - return false; - AttachmentPoint newAP = new AttachmentPoint(port, lastSeen); - // Copy the oldAP and ap list. - apList = new ArrayList(); - if (attachmentPoints != null) - apList.addAll(attachmentPoints); - oldAPList = new ArrayList(); - if (oldAPs != null) - oldAPList.addAll(oldAPs); - - // if the sw, port is in old AP, remove it from there - // and update the lastSeen in that object. - if (oldAPList.contains(newAP)) { - int index = oldAPList.indexOf(newAP); - newAP = oldAPList.remove(index); - newAP.setLastSeen(lastSeen); - this.oldAPs = oldAPList; - oldAPFlag = true; - } - - // newAP now contains the new attachment point. - - // Get the APMap is null or empty. - Map apMap = getAPMap(apList); - if (apMap == null || apMap.isEmpty()) { - apList.add(newAP); - attachmentPoints = apList; - // there are no old attachment points - since the device exists, - // this - // may be because the host really moved (so the old AP port went - // down); - // or it may be because the switch restarted (so old APs were - // nullified). - // For now we will treat both cases as host moved. - return true; - } - - // XXX - Missing functionality - long id = 0; - AttachmentPoint oldAP = apMap.get(id); - - if (oldAP == null) // No attachment on this L2 domain. - { - apList = new ArrayList(); - apList.addAll(apMap.values()); - apList.add(newAP); - this.attachmentPoints = apList; - return true; // new AP found on an L2 island. - } - - // There is already a known attachment point on the same L2 island. - // we need to compare oldAP and newAP. - if (oldAP.equals(newAP)) { - // nothing to do here. just the last seen has to be changed. - if (newAP.lastSeen > oldAP.lastSeen) { - oldAP.setLastSeen(newAP.lastSeen); - } - this.attachmentPoints = new ArrayList( - apMap.values()); - return false; // nothing to do here. - } - - int x = deviceManager.apComparator.compare(oldAP, newAP); - if (x < 0) { - // newAP replaces oldAP. - apMap.put(id, newAP); - this.attachmentPoints = new ArrayList( - apMap.values()); - - oldAPList = new ArrayList(); - if (oldAPs != null) - oldAPList.addAll(oldAPs); - oldAPList.add(oldAP); - this.oldAPs = oldAPList; - return true; - } else if (oldAPFlag) { - // retain oldAP as is. Put the newAP in oldAPs for flagging - // possible duplicates. - oldAPList = new ArrayList(); - if (oldAPs != null) - oldAPList.addAll(oldAPs); - // Add to oldAPList only if it was picked up from the oldAPList - oldAPList.add(newAP); - this.oldAPs = oldAPList; - return true; - } - return false; - } - - /** - * Delete (sw,port) from the list of list of attachment points and oldAPs. - * - * @param port - * @return - */ - public boolean deleteAttachmentPoint(NodeConnector port) { - AttachmentPoint ap = new AttachmentPoint(port, 0); - - if (this.oldAPs != null) { - ArrayList apList = new ArrayList(); - apList.addAll(this.oldAPs); - int index = apList.indexOf(ap); - if (index > 0) { - apList.remove(index); - this.oldAPs = apList; - } - } - - if (this.attachmentPoints != null) { - ArrayList apList = new ArrayList(); - apList.addAll(this.attachmentPoints); - int index = apList.indexOf(ap); - if (index > 0) { - apList.remove(index); - this.attachmentPoints = apList; - return true; - } - } - return false; - } - - // ******* - // IDevice - // ******* - - @Override - public SwitchPort[] getOldAP() { - List sp = new ArrayList(); - SwitchPort[] returnSwitchPorts = new SwitchPort[] {}; - if (oldAPs == null) - return returnSwitchPorts; - if (oldAPs.isEmpty()) - return returnSwitchPorts; - - // copy ap list. - List oldAPList; - oldAPList = new ArrayList(); - - if (oldAPs != null) - oldAPList.addAll(oldAPs); - removeExpiredAttachmentPoints(oldAPList); - - if (oldAPList != null) { - for (AttachmentPoint ap : oldAPList) { - SwitchPort swport = new SwitchPort(ap.getPort()); - sp.add(swport); - } - } - return sp.toArray(new SwitchPort[sp.size()]); - } - - @Override - public SwitchPort[] getAttachmentPoints() { - return getAttachmentPoints(false); - } - - @Override - public SwitchPort[] getAttachmentPoints(boolean includeError) { - List sp = new ArrayList(); - SwitchPort[] returnSwitchPorts = new SwitchPort[] {}; - if (attachmentPoints == null) - return returnSwitchPorts; - if (attachmentPoints.isEmpty()) - return returnSwitchPorts; - - // copy ap list. - List apList = attachmentPoints; - - if (apList != null) { - for (AttachmentPoint ap : apList) { - SwitchPort swport = new SwitchPort(ap.getPort()); - sp.add(swport); - } - } - - if (!includeError) - return sp.toArray(new SwitchPort[sp.size()]); - - List oldAPList; - oldAPList = new ArrayList(); - - if (oldAPs != null) - oldAPList.addAll(oldAPs); - - if (removeExpiredAttachmentPoints(oldAPList)) - this.oldAPs = oldAPList; - - List dupList; - // get AP map. - Map apMap = getAPMap(apList); - dupList = this.getDuplicateAttachmentPoints(oldAPList, apMap); - if (dupList != null) { - for (AttachmentPoint ap : dupList) { - SwitchPort swport = new SwitchPort(ap.getPort(), - ErrorStatus.DUPLICATE_DEVICE); - sp.add(swport); - } - } - return sp.toArray(new SwitchPort[sp.size()]); - } - - @Override - public Long getDeviceKey() { - return deviceKey; - } - - @Override - public long getMACAddress() { - // we assume only one MAC per device for now. - return entities[0].getMacAddress(); - } - - @Override - public String getMACAddressString() { - return macAddressString; - } - - @Override - public Short[] getVlanId() { - return Arrays.copyOf(vlanIds, vlanIds.length); - } - - static final EnumSet ipv4Fields = EnumSet.of(DeviceField.IPV4); - - @Override - public Integer[] getIPv4Addresses() { - // XXX - TODO we can cache this result. Let's find out if this - // is really a performance bottleneck first though. - - TreeSet vals = new TreeSet(); - for (Entity e : entities) { - if (e.getIpv4Address() == null) - continue; - - // We have an IP address only if among the devices within the class - // we have the most recent entity with that IP. - boolean validIP = true; - Iterator devices = deviceManager.queryClassByEntity( - entityClass, ipv4Fields, e); - while (devices.hasNext()) { - Device d = devices.next(); - if (deviceKey.equals(d.getDeviceKey())) - continue; - for (Entity se : d.entities) { - if (se.getIpv4Address() != null - && se.getIpv4Address().equals(e.getIpv4Address()) - && se.getLastSeenTimestamp() != null - && 0 < se.getLastSeenTimestamp().compareTo( - e.getLastSeenTimestamp())) { - validIP = false; - break; - } - } - if (!validIP) - break; - } - - if (validIP) - vals.add(e.getIpv4Address()); - } - - return vals.toArray(new Integer[vals.size()]); - } - - @Override - public Short[] getSwitchPortVlanIds(SwitchPort swp) { - TreeSet vals = new TreeSet(); - for (Entity e : entities) { - if (e.getPort().equals(swp.getPort())) { - if (e.getVlan() == null) { - vals.add(VLAN_UNTAGGED); - } - else { - vals.add(e.getVlan()); - } - } - } - return vals.toArray(new Short[vals.size()]); - } - - @Override - public Date getLastSeen() { - Date d = null; - for (int i = 0; i < entities.length; i++) { - if (d == null - || entities[i].getLastSeenTimestamp().compareTo(d) > 0) - d = entities[i].getLastSeenTimestamp(); - } - return d; - } - - // *************** - // Getters/Setters - // *************** - - @Override - public IEntityClass getEntityClass() { - return entityClass; - } - - public Entity[] getEntities() { - return entities; - } - - public String getDHCPClientName() { - return dhcpClientName; - } - - // *************** - // Utility Methods - // *************** - - /** - * Check whether the device contains the specified entity - * - * @param entity - * the entity to search for - * @return the index of the entity, or <0 if not found - */ - protected int entityIndex(Entity entity) { - return Arrays.binarySearch(entities, entity); - } - - // ****** - // Object - // ****** - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(entities); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Device other = (Device) obj; - if (!deviceKey.equals(other.deviceKey)) - return false; - if (!Arrays.equals(entities, other.entities)) - return false; - return true; - } - - public HostNodeConnector toHostNodeConnector() { - Integer[] ipv4s = this.getIPv4Addresses(); - try { - Entity e = this.entities[this.entities.length-1]; - NodeConnector n = null; - if(e!=null) - n = e.getPort(); - InetAddress ip = InetAddress.getByName(ipv4s[ipv4s.length - 1] - .toString()); - byte[] macAddr = macLongToByte(this.getMACAddress()); - HostNodeConnector nc = new HostNodeConnector(macAddr, ip, n, - (short) 0); - nc.setStaticHost(this.isStaticHost()); - return nc; - } catch (Exception e) { - return null; - } - } - - private byte[] macLongToByte(long mac) { - byte[] macAddr = new byte[6]; - for (int i = 0; i < 6; i++) { - macAddr[5 - i] = (byte) (mac >> (8 * i)); - } - return macAddr; - } - - public boolean isStaticHost(){ - return this.staticHost; - } - - public void setStaticHost(boolean isStatic){ - this.staticHost = isStatic; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Device [deviceKey="); - builder.append(deviceKey); - builder.append(", entityClass="); - builder.append(entityClass.getName()); - builder.append(", MAC="); - builder.append(macAddressString); - builder.append(", IPs=["); - boolean isFirst = true; - for (Integer ip : getIPv4Addresses()) { - if (!isFirst) - builder.append(", "); - isFirst = false; - builder.append(ip); - } - builder.append("], APs="); - builder.append(Arrays.toString(getAttachmentPoints(true))); - builder.append("]"); - return builder.toString(); - } -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndex.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndex.java deleted file mode 100644 index 5f068063e7..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndex.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker.internal; - -import java.util.Collection; -import java.util.EnumSet; -import java.util.Iterator; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; - -/** - * An index that maps key fields of an entity to device keys - */ -public abstract class DeviceIndex { - /** - * The key fields for this index - */ - protected EnumSet keyFields; - - /** - * Construct a new device index using the provided key fields - * - * @param keyFields - * the key fields to use - */ - public DeviceIndex(EnumSet keyFields) { - super(); - this.keyFields = keyFields; - } - - /** - * Find all device keys in the index that match the given entity on all the - * key fields for this index - * - * @param e - * the entity to search for - * @return an iterator over device keys - */ - public abstract Iterator queryByEntity(Entity entity); - - /** - * Get all device keys in the index. If certain devices exist multiple - * times, then these devices may be returned multiple times - * - * @return an iterator over device keys - */ - public abstract Iterator getAll(); - - /** - * Attempt to update an index with the entities in the provided - * {@link Device}. If the update fails because of a concurrent update, will - * return false. - * - * @param device - * the device to update - * @param deviceKey - * the device key for the device - * @return true if the update succeeded, false otherwise. - */ - public abstract boolean updateIndex(Device device, Long deviceKey); - - /** - * Add a mapping from the given entity to the given device key. This update - * will not fail because of a concurrent update - * - * @param device - * the device to update - * @param deviceKey - * the device key for the device - */ - public abstract void updateIndex(Entity entity, Long deviceKey); - - /** - * Remove the entry for the given entity - * - * @param entity - * the entity to remove - */ - public abstract void removeEntity(Entity entity); - - /** - * Remove the given device key from the index for the given entity - * - * @param entity - * the entity to search for - * @param deviceKey - * the key to remove - */ - public abstract void removeEntity(Entity entity, Long deviceKey); - - /** - * Remove the give device from the index only if this the collection of - * others does not contain an entity that is identical on all the key fields - * for this index. - * - * @param entity - * the entity to search for - * @param deviceKey - * the key to remove - * @param others - * the others against which to check - */ - public void removeEntityIfNeeded(Entity entity, Long deviceKey, - Collection others) { - IndexedEntity ie = new IndexedEntity(keyFields, entity); - for (Entity o : others) { - IndexedEntity oio = new IndexedEntity(keyFields, o); - if (oio.equals(ie)) - return; - } - - Iterator keyiter = this.queryByEntity(entity); - while (keyiter.hasNext()) { - Long key = keyiter.next(); - if (key.equals(deviceKey)) { - removeEntity(entity, deviceKey); - break; - } - } - } - -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndexInterator.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndexInterator.java deleted file mode 100644 index 469bd61066..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIndexInterator.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker.internal; - -import java.util.Iterator; - -/** - * An iterator for handling device index queries - */ -public class DeviceIndexInterator implements Iterator { - private DeviceManagerImpl deviceManager; - private Iterator subIterator; - - /** - * Construct a new device index iterator referring to a device manager - * instance and an iterator over device keys - * - * @param deviceManager - * the device manager - * @param subIterator - * an iterator over device keys - */ - public DeviceIndexInterator(DeviceManagerImpl deviceManager, - Iterator subIterator) { - super(); - this.deviceManager = deviceManager; - this.subIterator = subIterator; - } - - @Override - public boolean hasNext() { - return subIterator.hasNext(); - } - - @Override - public Device next() { - Long next = subIterator.next(); - return deviceManager.deviceMap.get(next); - } - - @Override - public void remove() { - subIterator.remove(); - } - -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIterator.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIterator.java deleted file mode 100644 index 68f175c52e..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceIterator.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker.internal; - -import java.util.Arrays; -import java.util.Iterator; - -import org.opendaylight.controller.hosttracker.IEntityClass; -import org.opendaylight.controller.hosttracker.SwitchPort; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.FilterIterator; - -/** - * An iterator for handling device queries - */ -public class DeviceIterator extends FilterIterator { - private IEntityClass[] entityClasses; - - private Long macAddress; - private Short vlan; - private Integer ipv4Address; - private NodeConnector port; - - /** - * Construct a new device iterator over the key fields - * - * @param subIterator - * an iterator over the full data structure to scan - * @param entityClasses - * the entity classes to search for - * @param macAddress - * The MAC address - * @param vlan - * the VLAN - * @param ipv4Address - * the ipv4 address - * @param switchDPID - * the switch DPID - * @param switchPort - * the switch port - */ - public DeviceIterator(Iterator subIterator, - IEntityClass[] entityClasses, Long macAddress, Short vlan, - Integer ipv4Address, NodeConnector port) { - super(subIterator); - this.entityClasses = entityClasses; - this.subIterator = subIterator; - this.macAddress = macAddress; - this.vlan = vlan; - this.ipv4Address = ipv4Address; - this.port = port; - } - - @Override - protected boolean matches(Device value) { - boolean match; - if (entityClasses != null) { - IEntityClass clazz = value.getEntityClass(); - if (clazz == null) - return false; - - match = false; - for (IEntityClass entityClass : entityClasses) { - if (clazz.equals(entityClass)) { - match = true; - break; - } - } - if (!match) - return false; - } - if (macAddress != null) { - if (macAddress.longValue() != value.getMACAddress()) - return false; - } - if (vlan != null) { - Short[] vlans = value.getVlanId(); - if (Arrays.binarySearch(vlans, vlan) < 0) - return false; - } - if (ipv4Address != null) { - Integer[] ipv4Addresses = value.getIPv4Addresses(); - if (Arrays.binarySearch(ipv4Addresses, ipv4Address) < 0) - return false; - } - if (port != null) { - SwitchPort[] sps = value.getAttachmentPoints(); - if (sps == null) - return false; - - match = false; - for (SwitchPort sp : sps) { - if (sp.getPort().equals(sp.getPort())) { - match = true; - break; - } - } - if (!match) - return false; - } - return true; - } -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImpl.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImpl.java deleted file mode 100755 index ee75ac06e3..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImpl.java +++ /dev/null @@ -1,2114 +0,0 @@ -/* - * Copyright (c) 2011,2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker.internal; - -import static org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl.DeviceUpdate.Change.ADD; -import static org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl.DeviceUpdate.Change.CHANGE; -import static org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl.DeviceUpdate.Change.DELETE; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDevice; -import org.opendaylight.controller.hosttracker.IDeviceListener; -import org.opendaylight.controller.hosttracker.IDeviceService; -import org.opendaylight.controller.hosttracker.IEntityClass; -import org.opendaylight.controller.hosttracker.IEntityClassListener; -import org.opendaylight.controller.hosttracker.IEntityClassifierService; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.IfNewHostNotify; -import org.opendaylight.controller.hosttracker.SwitchPort; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Host; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.Tier; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.packet.ARP; -import org.opendaylight.controller.sal.packet.Ethernet; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.sal.packet.Packet; -import org.opendaylight.controller.sal.packet.PacketResult; -import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.packet.address.DataLinkAddress; -import org.opendaylight.controller.sal.packet.address.EthernetAddress; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.ListenerDispatcher; -import org.opendaylight.controller.sal.utils.MultiIterator; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.SingletonTask; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.opendaylight.controller.topologymanager.ITopologyManagerAware; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * DeviceManager creates Devices based upon MAC addresses seen in the network. - * It tracks any network addresses mapped to the Device, and its location within - * the network. - * - * @author readams - */ -public class DeviceManagerImpl implements IDeviceService, IEntityClassListener, - IListenDataPacket, ITopologyManagerAware, IfIptoHost, - IInventoryListener { - protected static Logger logger = LoggerFactory - .getLogger(DeviceManagerImpl.class); - - public static final String MODULE_NAME = "devicemanager"; - - private ITopologyManager topology; - private ISwitchManager switchManager = null; - private IDataPacketService dataPacketService = null; - - public static final String CNT_INCOMING = MODULE_NAME + "-incoming"; - public static final String CNT_RECONCILE_REQUEST = MODULE_NAME - + "-reconcileRequest"; - public static final String CNT_RECONCILE_NO_SOURCE = MODULE_NAME - + "-reconcileNoSourceDevice"; - public static final String CNT_RECONCILE_NO_DEST = MODULE_NAME - + "-reconcileNoDestDevice"; - public static final String CNT_BROADCAST_SOURCE = MODULE_NAME - + "-broadcastSource"; - public static final String CNT_NO_SOURCE = MODULE_NAME + "-noSourceDevice"; - public static final String CNT_NO_DEST = MODULE_NAME + "-noDestDevice"; - public static final String CNT_DHCP_CLIENT_NAME_SNOOPED = MODULE_NAME - + "-dhcpClientNameSnooped"; - public static final String CNT_DEVICE_ON_INTERAL_PORT_NOT_LEARNED = MODULE_NAME - + "-deviceOnInternalPortNotLearned"; - public static final String CNT_PACKET_NOT_ALLOWED = MODULE_NAME - + "-packetNotAllowed"; - public static final String CNT_NEW_DEVICE = MODULE_NAME + "-newDevice"; - public static final String CNT_PACKET_ON_INTERNAL_PORT_FOR_KNOWN_DEVICE = MODULE_NAME - + "-packetOnInternalPortForKnownDevice"; - public static final String CNT_NEW_ENTITY = MODULE_NAME + "-newEntity"; - public static final String CNT_DEVICE_CHANGED = MODULE_NAME - + "-deviceChanged"; - public static final String CNT_DEVICE_MOVED = MODULE_NAME + "-deviceMoved"; - public static final String CNT_CLEANUP_ENTITIES_RUNS = MODULE_NAME - + "-cleanupEntitiesRuns"; - public static final String CNT_ENTITY_REMOVED_TIMEOUT = MODULE_NAME - + "-entityRemovedTimeout"; - public static final String CNT_DEVICE_DELETED = MODULE_NAME - + "-deviceDeleted"; - public static final String CNT_DEVICE_RECLASSIFY_DELETE = MODULE_NAME - + "-deviceReclassifyDelete"; - public static final String CNT_DEVICE_STORED = MODULE_NAME - + "-deviceStored"; - public static final String CNT_DEVICE_STORE_THROTTLED = MODULE_NAME - + "-deviceStoreThrottled"; - public static final String CNT_DEVICE_REMOVED_FROM_STORE = MODULE_NAME - + "-deviceRemovedFromStore"; - public static final String CNT_SYNC_EXCEPTION = MODULE_NAME - + "-syncException"; - public static final String CNT_DEVICES_FROM_STORE = MODULE_NAME - + "-devicesFromStore"; - public static final String CNT_CONSOLIDATE_STORE_RUNS = MODULE_NAME - + "-consolidateStoreRuns"; - public static final String CNT_CONSOLIDATE_STORE_DEVICES_REMOVED = MODULE_NAME - + "-consolidateStoreDevicesRemoved"; - - static final String DEVICE_SYNC_STORE_NAME = DeviceManagerImpl.class - .getCanonicalName() + ".stateStore"; - - - /** - * Time in milliseconds before entities will expire - */ - protected static final int ENTITY_TIMEOUT = 60 * 60 * 1000; - - /** - * Time in seconds between cleaning up old entities/devices - */ - protected static final int ENTITY_CLEANUP_INTERVAL = 60 * 60; - - /** - * This is the master device map that maps device IDs to {@link Device} - * objects. - */ - protected ConcurrentHashMap deviceMap; - - protected ConcurrentHashMap inactiveStaticDevices; - /** - * Counter used to generate device keys - */ - protected long deviceKeyCounter = 0; - - /** - * Lock for incrementing the device key counter - */ - protected Object deviceKeyLock = new Object(); - - /** - * This is the primary entity index that contains all entities - */ - protected DeviceUniqueIndex primaryIndex; - - /** - * This stores secondary indices over the fields in the devices - */ - protected Map, DeviceIndex> secondaryIndexMap; - - /** - * This map contains state for each of the {@ref IEntityClass} that exist - */ - protected ConcurrentHashMap classStateMap; - - /** - * This is the list of indices we want on a per-class basis - */ - protected Set> perClassIndices; - - /** - * The entity classifier currently in use - */ - protected IEntityClassifierService entityClassifier; - - /** - * Used to cache state about specific entity classes - */ - protected class ClassState { - - /** - * The class index - */ - protected DeviceUniqueIndex classIndex; - - /** - * This stores secondary indices over the fields in the device for the - * class - */ - protected Map, DeviceIndex> secondaryIndexMap; - - /** - * Allocate a new {@link ClassState} object for the class - * - * @param clazz - * the class to use for the state - */ - public ClassState(IEntityClass clazz) { - EnumSet keyFields = clazz.getKeyFields(); - EnumSet primaryKeyFields = entityClassifier - .getKeyFields(); - boolean keyFieldsMatchPrimary = primaryKeyFields.equals(keyFields); - - if (!keyFieldsMatchPrimary) - classIndex = new DeviceUniqueIndex(keyFields); - - secondaryIndexMap = new HashMap, DeviceIndex>(); - for (EnumSet fields : perClassIndices) { - secondaryIndexMap.put(fields, new DeviceMultiIndex(fields)); - } - } - } - - /** - * Device manager event listeners reclassifyDeviceListeners are notified - * first before reconcileDeviceListeners. This is to make sure devices are - * correctly reclassified before reconciliation. - */ - protected ListenerDispatcher deviceListeners; - - /** - * Using the IfNewHostNotify to notify listeners of host changes. - */ - private Set newHostNotify = Collections - .synchronizedSet(new HashSet()); - - /** - * A device update event to be dispatched - */ - protected static class DeviceUpdate { - public enum Change { - ADD, DELETE, CHANGE; - } - - /** - * The affected device - */ - protected Device device; - - /** - * The change that was made - */ - protected Change change; - - /** - * If not added, then this is the list of fields changed - */ - protected EnumSet fieldsChanged; - - public DeviceUpdate(Device device, Change change, - EnumSet fieldsChanged) { - super(); - this.device = device; - this.change = change; - this.fieldsChanged = fieldsChanged; - } - - @Override - public String toString() { - String devIdStr = device.getEntityClass().getName() + "::" - + device.getMACAddressString(); - return "DeviceUpdate [device=" + devIdStr + ", change=" + change - + ", fieldsChanged=" + fieldsChanged + "]"; - } - - } - - /** - * AttachmentPointComparator - * - * Compares two attachment points and returns the latest one. It is assumed - * that the two attachment points are in the same L2 domain. - * - * @author srini - */ - protected class AttachmentPointComparator implements - Comparator { - public AttachmentPointComparator() { - super(); - } - - @Override - public int compare(AttachmentPoint oldAP, AttachmentPoint newAP) { - // First compare based on L2 domain ID; - - // XXX - missing functionality -- need topology - // long oldDomain = topology.getL2DomainId(oldSw); - // boolean oldBD = topology.isBroadcastDomainPort(oldSw, oldPort); - long oldDomain = 0; - boolean oldBD = false; - - // XXX - missing functionality -- need topology - // long newDomain = topology.getL2DomainId(newSw); - // boolean newBD = topology.isBroadcastDomainPort(newSw, newPort); - long newDomain = 0; - boolean newBD = false; - - if (oldDomain < newDomain) { - return -1; - } else if (oldDomain > newDomain) { - return 1; - } - // Give preference to OFPP_LOCAL always - if (!oldAP.getPort().getType().equals(NodeConnectorIDType.SWSTACK) - && newAP.getPort().getType() - .equals(NodeConnectorIDType.SWSTACK)) { - return -1; - } else if (oldAP.getPort().getType() - .equals(NodeConnectorIDType.SWSTACK) - && !newAP.getPort().getType() - .equals(NodeConnectorIDType.SWSTACK)) { - return 1; - } - - // We expect that the last seen of the new AP is higher than - // old AP, if it is not, just reverse and send the negative - // of the result. - if (oldAP.getActiveSince() > newAP.getActiveSince()) - return -compare(newAP, oldAP); - - long activeOffset = 0; - - if (!newBD && oldBD) { - return -1; - } - if (newBD && oldBD) { - activeOffset = AttachmentPoint.EXTERNAL_TO_EXTERNAL_TIMEOUT; - } else if (newBD && !oldBD) { - activeOffset = AttachmentPoint.OPENFLOW_TO_EXTERNAL_TIMEOUT; - } - - - if ((newAP.getActiveSince() > oldAP.getLastSeen() + activeOffset) - || (newAP.getLastSeen() > oldAP.getLastSeen() - + AttachmentPoint.INACTIVITY_INTERVAL)) { - return -1; - } - return 1; - } - } - - /** - * Comparator for sorting by cluster ID - */ - public AttachmentPointComparator apComparator; - - /** - * Switch ports where attachment points shouldn't be learned - */ - private Set suppressAPs; - - /** - * Periodic task to clean up expired entities - */ - public SingletonTask entityCleanupTask; - - // ******************** - // Dependency injection - // ******************** - - void setNewHostNotify(IfNewHostNotify obj) { - this.newHostNotify.add(obj); - } - - void unsetNewHostNotify(IfNewHostNotify obj) { - this.newHostNotify.remove(obj); - } - - void setDataPacketService(IDataPacketService s) { - this.dataPacketService = s; - } - - void unsetDataPacketService(IDataPacketService s) { - if (this.dataPacketService == s) { - this.dataPacketService = null; - } - } - - public void setTopologyManager(ITopologyManager s) { - this.topology = s; - } - - public void unsetTopologyManager(ITopologyManager s) { - if (this.topology == s) { - logger.debug("Topology Manager Service removed!"); - this.topology = null; - } - } - - private volatile boolean stopped = true; - private ScheduledExecutorService ses; - - public void stop() { - stopped = true; - if (ses != null) - ses.shutdownNow(); - } - - public void start() { - this.perClassIndices = new HashSet>(); - - // XXX - TODO need to make it possible to register a non-default - // classifier - entityClassifier = new DefaultEntityClassifier(); - this.deviceListeners = new ListenerDispatcher(); - this.suppressAPs = Collections - .newSetFromMap(new ConcurrentHashMap()); - primaryIndex = new DeviceUniqueIndex(entityClassifier.getKeyFields()); - secondaryIndexMap = new HashMap, DeviceIndex>(); - - deviceMap = new ConcurrentHashMap(); - inactiveStaticDevices = new ConcurrentHashMap(); - classStateMap = new ConcurrentHashMap(); - apComparator = new AttachmentPointComparator(); - - addIndex(true, EnumSet.of(DeviceField.IPV4)); - - stopped = false; - // XXX - Should use a common threadpool but this doesn't currently exist - ses = Executors.newScheduledThreadPool(1); - Runnable ecr = new Runnable() { - @Override - public void run() { - cleanupEntities(); - if (!stopped) - entityCleanupTask.reschedule(ENTITY_CLEANUP_INTERVAL, - TimeUnit.SECONDS); - } - }; - entityCleanupTask = new SingletonTask(ses, ecr); - entityCleanupTask.reschedule(ENTITY_CLEANUP_INTERVAL, TimeUnit.SECONDS); - - registerDeviceManagerDebugCounters(); - } - - /** - * Periodic task to consolidate entries in the store. I.e., delete entries - * in the store that are not known to DeviceManager - */ - // XXX - Missing functionality - // private SingletonTask storeConsolidateTask; - - // ********************* - // IDeviceManagerService - // ********************* - - void setSwitchManager(ISwitchManager s) { - logger.debug("SwitchManager set"); - this.switchManager = s; - } - - void unsetSwitchManager(ISwitchManager s) { - if (this.switchManager == s) { - logger.debug("SwitchManager removed!"); - this.switchManager = null; - } - } - - @Override - public IDevice getDevice(Long deviceKey) { - return deviceMap.get(deviceKey); - } - - @Override - public IDevice findDevice(long macAddress, Short vlan, Integer ipv4Address, - NodeConnector port) throws IllegalArgumentException { - if (vlan != null && vlan.shortValue() <= 0) - vlan = null; - if (ipv4Address != null && ipv4Address == 0) - ipv4Address = null; - Entity e = new Entity(macAddress, vlan, ipv4Address, port, null); - if (!allKeyFieldsPresent(e, entityClassifier.getKeyFields())) { - throw new IllegalArgumentException("Not all key fields specified." - + " Required fields: " + entityClassifier.getKeyFields()); - } - return findDeviceByEntity(e); - } - - @Override - public IDevice findClassDevice(IEntityClass entityClass, long macAddress, - Short vlan, Integer ipv4Address) throws IllegalArgumentException { - if (vlan != null && vlan.shortValue() <= 0) - vlan = null; - if (ipv4Address != null && ipv4Address == 0) - ipv4Address = null; - Entity e = new Entity(macAddress, vlan, ipv4Address, null, null); - if (entityClass == null - || !allKeyFieldsPresent(e, entityClass.getKeyFields())) { - throw new IllegalArgumentException("Not all key fields and/or " - + " no source device specified. Required fields: " - + entityClassifier.getKeyFields()); - } - return findDestByEntity(entityClass, e); - } - - @Override - public Collection getAllDevices() { - return Collections.unmodifiableCollection(deviceMap.values()); - } - - @Override - public void addIndex(boolean perClass, EnumSet keyFields) { - if (perClass) { - perClassIndices.add(keyFields); - } else { - secondaryIndexMap.put(keyFields, new DeviceMultiIndex(keyFields)); - } - } - - @Override - public Iterator queryDevices(Long macAddress, - Short vlan, Integer ipv4Address, NodeConnector port) { - DeviceIndex index = null; - if (secondaryIndexMap.size() > 0) { - EnumSet keys = getEntityKeys(macAddress, vlan, - ipv4Address, port); - index = secondaryIndexMap.get(keys); - } - - Iterator deviceIterator = null; - if (index == null) { - // Do a full table scan - deviceIterator = deviceMap.values().iterator(); - } else { - // index lookup - Entity entity = new Entity((macAddress == null ? 0 : macAddress), - vlan, ipv4Address, port, null); - deviceIterator = new DeviceIndexInterator(this, - index.queryByEntity(entity)); - } - - DeviceIterator di = new DeviceIterator(deviceIterator, null, - macAddress, vlan, ipv4Address, port); - return di; - } - - @Override - public Iterator queryClassDevices( - IEntityClass entityClass, Long macAddress, Short vlan, - Integer ipv4Address, NodeConnector port) { - ArrayList> iterators = new ArrayList>(); - ClassState classState = getClassState(entityClass); - - DeviceIndex index = null; - if (classState.secondaryIndexMap.size() > 0) { - EnumSet keys = getEntityKeys(macAddress, vlan, - ipv4Address, port); - index = classState.secondaryIndexMap.get(keys); - } - - Iterator iter; - if (index == null) { - index = classState.classIndex; - if (index == null) { - // scan all devices - return new DeviceIterator(deviceMap.values().iterator(), - new IEntityClass[] { entityClass }, macAddress, vlan, - ipv4Address, port); - } else { - // scan the entire class - iter = new DeviceIndexInterator(this, index.getAll()); - } - } else { - // index lookup - Entity entity = new Entity((macAddress == null ? 0 : macAddress), - vlan, ipv4Address, port, null); - iter = new DeviceIndexInterator(this, index.queryByEntity(entity)); - } - iterators.add(iter); - - return new MultiIterator(iterators.iterator()); - } - - protected Iterator getDeviceIteratorForQuery(Long macAddress, - Short vlan, Integer ipv4Address, NodeConnector port) { - DeviceIndex index = null; - if (secondaryIndexMap.size() > 0) { - EnumSet keys = getEntityKeys(macAddress, vlan, - ipv4Address, port); - index = secondaryIndexMap.get(keys); - } - - Iterator deviceIterator = null; - if (index == null) { - // Do a full table scan - deviceIterator = deviceMap.values().iterator(); - } else { - // index lookup - Entity entity = new Entity((macAddress == null ? 0 : macAddress), - vlan, ipv4Address, port, null); - deviceIterator = new DeviceIndexInterator(this, - index.queryByEntity(entity)); - } - - DeviceIterator di = new DeviceIterator(deviceIterator, null, - macAddress, vlan, ipv4Address, port); - return di; - } - - @Override - public void addListener(IDeviceListener listener) { - deviceListeners.addListener("device", listener); - logListeners(); - } - - @Override - public void addSuppressAPs(NodeConnector port) { - suppressAPs.add(new SwitchPort(port)); - } - - @Override - public void removeSuppressAPs(NodeConnector port) { - suppressAPs.remove(new SwitchPort(port)); - } - - @Override - public Set getSuppressAPs() { - return Collections.unmodifiableSet(suppressAPs); - } - - private void logListeners() { - List listeners = deviceListeners.getOrderedListeners(); - if (listeners != null) { - StringBuffer sb = new StringBuffer(); - sb.append("DeviceListeners: "); - for (IDeviceListener l : listeners) { - sb.append(l.getName()); - sb.append(","); - } - logger.debug(sb.toString()); - } - } - - - // ***************** - // IListenDataPacket - // ***************** - - @Override - public PacketResult receiveDataPacket(RawPacket inPkt) { - // XXX - Can this really pass in null? Why would you ever want that? - if (inPkt == null) { - return PacketResult.IGNORED; - } - - Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt); - Ethernet eth; - if (formattedPak instanceof Ethernet) { - eth = (Ethernet) formattedPak; - } else { - return PacketResult.IGNORED; - } - - // Extract source entity information - NodeConnector inPort = inPkt.getIncomingNodeConnector(); - Entity srcEntity = getSourceEntityFromPacket(eth, inPort); - if (srcEntity == null) { - return PacketResult.CONSUME; - } - - // Learn from ARP packet for special VRRP settings. - // In VRRP settings, the source MAC address and sender MAC - // addresses can be different. In such cases, we need to learn - // the IP to MAC mapping of the VRRP IP address. The source - // entity will not have that information. Hence, a separate call - // to learn devices in such cases. - learnDeviceFromArpResponseData(eth, inPort); - - // Learn/lookup device information - Device srcDevice = learnDeviceByEntity(srcEntity); - if (srcDevice == null) { - return PacketResult.CONSUME; - } - logger.trace("Saw packet from device {}", srcDevice); - - return PacketResult.KEEP_PROCESSING; - } - - // **************** - // Internal methods - // **************** - - - /** - * Check whether the given attachment point is valid given the current - * topology - * - * @param switchDPID - * the DPID - * @param switchPort - * the port - * @return true if it's a valid attachment point - */ - public boolean isValidAttachmentPoint(NodeConnector port) { - // XXX - missing functionality -- need topology module - // if (topology.isAttachmentPointPort(port) == false) - // return false; - if (topology.isInternal(port)) - return false; - if (!switchManager.isNodeConnectorEnabled(port)) - return false; - if (suppressAPs.contains(new SwitchPort(port))) - return false; - - return true; - } - - /** - * Get sender IP address from packet if the packet is either an ARP packet. - * - * @param eth - * @param dlAddr - * @return - */ - private int getSrcNwAddr(Ethernet eth, long dlAddr) { - if (eth.getPayload() instanceof ARP) { - ARP arp = (ARP) eth.getPayload(); - if ((arp.getProtocolType() == ARP.PROTO_TYPE_IP) - && (toLong(arp.getSenderHardwareAddress()) == dlAddr)) { - return toIPv4Address(arp.getSenderProtocolAddress()); - } - } - return 0; - } - - /** - * Parse an entity from an {@link Ethernet} packet. - * - * @param eth - * the packet to parse - * @param sw - * the switch on which the packet arrived - * @param pi - * the original packetin - * @return the entity from the packet - */ - protected Entity getSourceEntityFromPacket(Ethernet eth, NodeConnector port) { - byte[] dlAddrArr = eth.getSourceMACAddress(); - long dlAddr = toLong(dlAddrArr); - - // Ignore broadcast/multicast source - if ((dlAddrArr[0] & 0x1) != 0) - return null; - - // XXX missing functionality - // short vlan = 0; - int nwSrc = getSrcNwAddr(eth, dlAddr); - return new Entity(dlAddr, null, ((nwSrc != 0) ? nwSrc : null), port, - new Date()); - } - - /** - * Learn device from ARP data in scenarios where the Ethernet source MAC is - * different from the sender hardware address in ARP data. - */ - protected void learnDeviceFromArpResponseData(Ethernet eth, - NodeConnector port) { - - if (!(eth.getPayload() instanceof ARP)) - return; - ARP arp = (ARP) eth.getPayload(); - - byte[] dlAddrArr = eth.getSourceMACAddress(); - long dlAddr = toLong(dlAddrArr); - - byte[] senderHardwareAddr = arp.getSenderHardwareAddress(); - long senderAddr = toLong(senderHardwareAddr); - - if (dlAddr == senderAddr) - return; - - // Ignore broadcast/multicast source - if ((senderHardwareAddr[0] & 0x1) != 0) - return; - - // short vlan = eth.getVlanID(); - int nwSrc = toIPv4Address(arp.getSenderProtocolAddress()); - - Entity e = new Entity(senderAddr, null, ((nwSrc != 0) ? nwSrc : null), - port, new Date()); - - learnDeviceByEntity(e); - } - - /** - * Look up a {@link Device} based on the provided {@link Entity}. We first - * check the primary index. If we do not find an entry there we classify the - * device into its IEntityClass and query the classIndex. This implies that - * all key field of the current IEntityClassifier must be present in the - * entity for the lookup to succeed! - * - * @param entity - * the entity to search for - * @return The {@link Device} object if found - */ - protected Device findDeviceByEntity(Entity entity) { - // Look up the fully-qualified entity to see if it already - // exists in the primary entity index. - Long deviceKey = primaryIndex.findByEntity(entity); - IEntityClass entityClass = null; - - if (deviceKey == null) { - // If the entity does not exist in the primary entity index, - // use the entity classifier for find the classes for the - // entity. Look up the entity in the returned class' - // class entity index. - entityClass = entityClassifier.classifyEntity(entity); - if (entityClass == null) { - return null; - } - ClassState classState = getClassState(entityClass); - - if (classState.classIndex != null) { - deviceKey = classState.classIndex.findByEntity(entity); - } - } - if (deviceKey == null) - return null; - return deviceMap.get(deviceKey); - } - - /** - * Get a destination device using entity fields that corresponds with the - * given source device. The source device is important since there could be - * ambiguity in the destination device without the attachment point - * information. - * - * @param reference - * the source device's entity class. The returned destination - * will be in the same entity class as the source. - * @param dstEntity - * the entity to look up - * @return an {@link Device} or null if no device is found. - */ - protected Device findDestByEntity(IEntityClass reference, Entity dstEntity) { - - // Look up the fully-qualified entity to see if it - // exists in the primary entity index - Long deviceKey = primaryIndex.findByEntity(dstEntity); - - if (deviceKey == null) { - // This could happen because: - // 1) no destination known, or a broadcast destination - // 2) if we have attachment point key fields since - // attachment point information isn't available for - // destination devices. - // For the second case, we'll need to match up the - // destination device with the class of the source - // device. - ClassState classState = getClassState(reference); - if (classState.classIndex == null) { - return null; - } - deviceKey = classState.classIndex.findByEntity(dstEntity); - } - if (deviceKey == null) - return null; - return deviceMap.get(deviceKey); - } - - /** - * Look up a {@link Device} within a particular entity class based on the - * provided {@link Entity}. - * - * @param clazz - * the entity class to search for the entity - * @param entity - * the entity to search for - * @return The {@link Device} object if found private Device - * findDeviceInClassByEntity(IEntityClass clazz, Entity entity) { // - * XXX - TODO throw new UnsupportedOperationException(); } - */ - - /** - * Look up a {@link Device} based on the provided {@link Entity}. Also - * learns based on the new entity, and will update existing devices as - * required. - * - * @param entity - * the {@link Entity} - * @return The {@link Device} object if found - */ - protected Device learnDeviceByEntity(Entity entity) { - logger.info("Primary index {}", primaryIndex); - ArrayList deleteQueue = null; - LinkedList deviceUpdates = null; - Device oldDevice = null; - Device device = null; - - // we may need to restart the learning process if we detect - // concurrent modification. Note that we ensure that at least - // one thread should always succeed so we don't get into infinite - // starvation loops - while (true) { - deviceUpdates = null; - - // Look up the fully-qualified entity to see if it already - // exists in the primary entity index. - Long deviceKey = primaryIndex.findByEntity(entity); - IEntityClass entityClass = null; - - if (deviceKey == null) { - // If the entity does not exist in the primary entity index, - // use the entity classifier for find the classes for the - // entity. Look up the entity in the returned class' - // class entity index. - entityClass = entityClassifier.classifyEntity(entity); - if (entityClass == null) { - // could not classify entity. No device - device = null; - break; - } - ClassState classState = getClassState(entityClass); - - if (classState.classIndex != null) { - deviceKey = classState.classIndex.findByEntity(entity); - } - } - if (deviceKey != null) { - // If the primary or secondary index contains the entity - // use resulting device key to look up the device in the - // device map, and use the referenced Device below. - device = deviceMap.get(deviceKey); - if (device == null) { - // This can happen due to concurrent modification - if (logger.isDebugEnabled()) { - logger.debug("No device for deviceKey {} while " - + "while processing entity {}", deviceKey, - entity); - } - // if so, then try again till we don't even get the device - // key - // and so we recreate the device - continue; - } - } else { - // If the secondary index does not contain the entity, - // create a new Device object containing the entity, and - // generate a new device ID if the the entity is on an - // attachment point port. Otherwise ignore. - if (entity.hasSwitchPort() - && !isValidAttachmentPoint(entity.getPort())) { - // debugCounters.updateCounter(CNT_DEVICE_ON_INTERAL_PORT_NOT_LEARNED); - if (logger.isDebugEnabled()) { - logger.debug("Not learning new device on internal" - + " link: {}", entity); - } - device = null; - break; - } - // Before we create the new device also check if - // the entity is allowed (e.g., for spoofing protection) - if (!isEntityAllowed(entity, entityClass)) { - // debugCounters.updateCounter(CNT_PACKET_NOT_ALLOWED); - if (logger.isDebugEnabled()) { - logger.debug("PacketIn is not allowed {} {}", - entityClass.getName(), entity); - } - device = null; - break; - } - synchronized (deviceKeyLock) { - deviceKey = Long.valueOf(deviceKeyCounter++); - } - device = allocateDevice(deviceKey, entity, entityClass); - - // Add the new device to the primary map with a simple put - deviceMap.put(deviceKey, device); - - // update indices - if (!updateIndices(device, deviceKey)) { - if (deleteQueue == null) - deleteQueue = new ArrayList(); - deleteQueue.add(deviceKey); - continue; - } - - updateSecondaryIndices(entity, entityClass, deviceKey); - - // We need to count and log here. If we log earlier we could - // hit a concurrent modification and restart the dev creation - // and potentially count the device twice. - // debugCounters.updateCounter(CNT_NEW_DEVICE); - if (logger.isDebugEnabled()) { - logger.debug( - "New device created: {} deviceKey={}, entity={}", - new Object[] { device, deviceKey, entity }); - } - // generate new device update - deviceUpdates = updateUpdates(deviceUpdates, new DeviceUpdate( - device, ADD, null)); - - break; - } - // if it gets here, we have a pre-existing Device for this Entity - if (!isEntityAllowed(entity, device.getEntityClass())) { - // debugCounters.updateCounter(CNT_PACKET_NOT_ALLOWED); - if (logger.isDebugEnabled()) { - logger.info("PacketIn is not allowed {} {}", device - .getEntityClass().getName(), entity); - } - return null; - } - // If this is not an attachment point port we don't learn the new - // entity - // and don't update indexes. But we do allow the device to continue - // up - // the chain. - if (entity.hasSwitchPort() - && !isValidAttachmentPoint(entity.getPort())) { - // debugCounters.updateCounter(CNT_PACKET_ON_INTERNAL_PORT_FOR_KNOWN_DEVICE); - break; - } - int entityindex = -1; - if ((entityindex = device.entityIndex(entity)) >= 0) { - // Entity already exists - // update timestamp on the found entity - Date lastSeen = entity.getLastSeenTimestamp(); - if (lastSeen == null) { - lastSeen = new Date(); - entity.setLastSeenTimestamp(lastSeen); - } - device.entities[entityindex].setLastSeenTimestamp(lastSeen); - // we break the loop after checking for changes to the AP - } else { - // New entity for this device - // compute the insertion point for the entity. - // see Arrays.binarySearch() - entityindex = -(entityindex + 1); - Device newDevice = allocateDevice(device, entity, entityindex); - - // generate updates - EnumSet changedFields = findChangedFields(device, - entity); - - // update the device map with a replace call - boolean res = deviceMap.replace(deviceKey, device, newDevice); - // If replace returns false, restart the process from the - // beginning (this implies another thread concurrently - // modified this Device). - if (!res) - continue; - oldDevice = device; - device = newDevice; - // update indices - if (!updateIndices(device, deviceKey)) { - continue; - } - updateSecondaryIndices(entity, device.getEntityClass(), - deviceKey); - - // We need to count here after all the possible "continue" - // statements in this branch - // debugCounters.updateCounter(CNT_NEW_ENTITY); - if (changedFields.size() > 0) { - // debugCounters.updateCounter(CNT_DEVICE_CHANGED); - deviceUpdates = updateUpdates(deviceUpdates, - new DeviceUpdate(newDevice, CHANGE, changedFields)); - } - // we break the loop after checking for changed AP - } - // Update attachment point (will only be hit if the device - // already existed and no concurrent modification) - if (entity.hasSwitchPort()) { - boolean moved = device.updateAttachmentPoint(entity.getPort(), - entity.getLastSeenTimestamp().getTime()); - // TODO: use update mechanism instead of sending the - // notification directly - if (moved) { - // we count device moved events in - // sendDeviceMovedNotification() - sendDeviceMovedNotification(device, oldDevice); - if (logger.isTraceEnabled()) { - logger.trace("Device moved: attachment points {}," - + "entities {}", device.attachmentPoints, - device.entities); - } - } else { - if (logger.isTraceEnabled()) { - logger.trace("Device attachment point updated: " - + "attachment points {}," + "entities {}", - device.attachmentPoints, device.entities); - } - } - } - break; - } - - if (deleteQueue != null) { - for (Long l : deleteQueue) { - Device dev = deviceMap.get(l); - this.deleteDevice(dev); - } - } - - processUpdates(deviceUpdates); - // deviceSyncManager.storeDeviceThrottled(device); - - return device; - } - - protected boolean isEntityAllowed(Entity entity, IEntityClass entityClass) { - return true; - } - - protected EnumSet findChangedFields(Device device, - Entity newEntity) { - EnumSet changedFields = EnumSet.of(DeviceField.IPV4, - DeviceField.VLAN, DeviceField.SWITCHPORT); - - if (newEntity.getIpv4Address() == null) - changedFields.remove(DeviceField.IPV4); - if (newEntity.getVlan() == null) - changedFields.remove(DeviceField.VLAN); - if (newEntity.getPort() == null) - changedFields.remove(DeviceField.SWITCHPORT); - - if (changedFields.size() == 0) - return changedFields; - - for (Entity entity : device.getEntities()) { - if (newEntity.getIpv4Address() == null - || (entity.getIpv4Address() != null && entity - .getIpv4Address() - .equals(newEntity.getIpv4Address()))) - changedFields.remove(DeviceField.IPV4); - if (newEntity.getVlan() == null - || (entity.getVlan() != null && entity.getVlan().equals( - newEntity.getVlan()))) - changedFields.remove(DeviceField.VLAN); - if (newEntity.getPort() == null - || (entity.getPort() != null && entity.getPort().equals( - newEntity.getPort()))) - changedFields.remove(DeviceField.SWITCHPORT); - } - - return changedFields; - } - - /** - * Send update notifications to listeners - * - * @param updates - * the updates to process. - */ - protected void processUpdates(Queue updates) { - if (updates == null) - return; - DeviceUpdate update = null; - while (null != (update = updates.poll())) { - if (logger.isTraceEnabled()) { - logger.trace("Dispatching device update: {}", update); - } - // if (update.change == DeviceUpdate.Change.DELETE) - // deviceSyncManager.removeDevice(update.device); - // else - // deviceSyncManager.storeDevice(update.device); - List listeners = deviceListeners - .getOrderedListeners(); - notifyListeners(listeners, update); - } - } - - protected void notifyListeners(List listeners, - DeviceUpdate update) { - // Topology update is for some reason outside of listeners registry - // logic - Entity[] ents = update.device.getEntities(); - Entity e = ents[ents.length - 1]; - - NodeConnector p = e.getPort(); - Node node = p.getNode(); - Host h = null; - try { - - byte[] mac = NetUtils.longToByteArray6(e.getMacAddress()); - DataLinkAddress dla = new EthernetAddress( - mac); - e.getIpv4Address(); - InetAddress.getAllByName(e.getIpv4Address().toString()); - h = new org.opendaylight.controller.sal.core.Host(dla, - InetAddress.getByName(e.getIpv4Address().toString())); - } catch (ConstructionException ce) { - p = null; - h = null; - } catch (UnknownHostException ue) { - p = null; - h = null; - } - - if (topology != null && p != null && h != null) { - if (update.change.equals(DeviceUpdate.Change.ADD)) { - Tier tier = new Tier(1); - switchManager.setNodeProp(node, tier); - topology.updateHostLink(p, h, UpdateType.ADDED, null); - } else { - // No need to reset the tiering if no other hosts are currently - // connected - // If this switch was discovered to be an access switch, it - // still is even if the host is down - Tier tier = new Tier(0); - switchManager.setNodeProp(node, tier); - topology.updateHostLink(p, h, UpdateType.REMOVED, null); - } - } - - if (listeners == null && newHostNotify.isEmpty()) { - return; - } - /** - * TODO: IfNewHostNotify is needed for current controller API. Adding - * logic so that existing apps (like SimpleForwardingManager) work. - * IDeviceListener adds additional methods and uses IListener's callback - * ordering. The two interfaces need to be merged. - */ - - for (IfNewHostNotify notify : newHostNotify) { - switch (update.change) { - case ADD: - notify.notifyHTClient(update.device.toHostNodeConnector()); - break; - case DELETE: - notify.notifyHTClientHostRemoved(update.device - .toHostNodeConnector()); - break; - case CHANGE: - } - } - - /** - * TODO: Remove this section as IDeviceListener functionality gets - * merged with IfNewHostNotify - */ - for (IDeviceListener listener : listeners) { - switch (update.change) { - case ADD: - listener.deviceAdded(update.device); - break; - case DELETE: - listener.deviceRemoved(update.device); - break; - case CHANGE: - for (DeviceField field : update.fieldsChanged) { - switch (field) { - case IPV4: - listener.deviceIPV4AddrChanged(update.device); - break; - case SWITCHPORT: - // listener.deviceMoved(update.device); - break; - case VLAN: - listener.deviceVlanChanged(update.device); - break; - default: - logger.debug("Unknown device field changed {}", - update.fieldsChanged.toString()); - break; - } - } - break; - } - } - } - - /** - * Check if the entity e has all the keyFields set. Returns false if not - * - * @param e - * entity to check - * @param keyFields - * the key fields to check e against - * @return - */ - protected boolean allKeyFieldsPresent(Entity e, - EnumSet keyFields) { - for (DeviceField f : keyFields) { - switch (f) { - case MAC: - // MAC address is always present - break; - case IPV4: - if (e.getIpv4Address() == null) - return false; - break; - case SWITCHPORT: - if (e.getPort() == null) - return false; - break; - case VLAN: - // FIXME: vlan==null is ambiguous: it can mean: not present - // or untagged - // if (e.vlan == null) return false; - break; - default: - // we should never get here. unless somebody extended - // DeviceFields - throw new IllegalStateException(); - } - } - return true; - } - - private LinkedList updateUpdates( - LinkedList list, DeviceUpdate update) { - if (update == null) - return list; - if (list == null) - list = new LinkedList(); - list.add(update); - - return list; - } - - /** - * Get the secondary index for a class. Will return null if the secondary - * index was created concurrently in another thread. - * - * @param clazz - * the class for the index - * @return - */ - private ClassState getClassState(IEntityClass clazz) { - ClassState classState = classStateMap.get(clazz.getName()); - if (classState != null) - return classState; - - classState = new ClassState(clazz); - ClassState r = classStateMap.putIfAbsent(clazz.getName(), classState); - if (r != null) { - // concurrent add - return r; - } - return classState; - } - - /** - * Update both the primary and class indices for the provided device. If the - * update fails because of an concurrent update, will return false. - * - * @param device - * the device to update - * @param deviceKey - * the device key for the device - * @return true if the update succeeded, false otherwise. - */ - private boolean updateIndices(Device device, Long deviceKey) { - if (!primaryIndex.updateIndex(device, deviceKey)) { - return false; - } - IEntityClass entityClass = device.getEntityClass(); - ClassState classState = getClassState(entityClass); - - if (classState.classIndex != null) { - if (!classState.classIndex.updateIndex(device, deviceKey)) - return false; - } - return true; - } - - /** - * Update the secondary indices for the given entity and associated entity - * classes - * - * @param entity - * the entity to update - * @param entityClass - * the entity class for the entity - * @param deviceKey - * the device key to set up - */ - private void updateSecondaryIndices(Entity entity, - IEntityClass entityClass, Long deviceKey) { - for (DeviceIndex index : secondaryIndexMap.values()) { - index.updateIndex(entity, deviceKey); - } - ClassState state = getClassState(entityClass); - for (DeviceIndex index : state.secondaryIndexMap.values()) { - index.updateIndex(entity, deviceKey); - } - } - - /** - * Clean up expired entities/devices - */ - protected void cleanupEntities() { - // debugCounters.updateCounter(CNT_CLEANUP_ENTITIES_RUNS); - - Calendar c = Calendar.getInstance(); - c.add(Calendar.MILLISECOND, -ENTITY_TIMEOUT); - Date cutoff = c.getTime(); - - ArrayList toRemove = new ArrayList(); - ArrayList toKeep = new ArrayList(); - - Iterator diter = deviceMap.values().iterator(); - LinkedList deviceUpdates = new LinkedList(); - - while (diter.hasNext()) { - Device d = diter.next(); - - while (true) { - deviceUpdates.clear(); - toRemove.clear(); - toKeep.clear(); - for (Entity e : d.getEntities()) { - if (e.getLastSeenTimestamp() != null - && 0 > e.getLastSeenTimestamp().compareTo(cutoff)) { - // individual entity needs to be removed - toRemove.add(e); - } else { - toKeep.add(e); - } - } - if (toRemove.size() == 0) { - break; - } - - // debugCounters.updateCounter(CNT_ENTITY_REMOVED_TIMEOUT); - for (Entity e : toRemove) { - removeEntity(e, d.getEntityClass(), d.getDeviceKey(), - toKeep); - } - - if (toKeep.size() > 0) { - Device newDevice = allocateDevice(d.getDeviceKey(), - d.getDHCPClientName(), d.oldAPs, - d.attachmentPoints, toKeep, d.getEntityClass()); - - EnumSet changedFields = EnumSet - .noneOf(DeviceField.class); - for (Entity e : toRemove) { - changedFields.addAll(findChangedFields(newDevice, e)); - } - DeviceUpdate update = null; - if (changedFields.size() > 0) { - update = new DeviceUpdate(d, CHANGE, changedFields); - } - - if (!deviceMap.replace(newDevice.getDeviceKey(), d, - newDevice)) { - // concurrent modification; try again - // need to use device that is the map now for the next - // iteration - d = deviceMap.get(d.getDeviceKey()); - if (null != d) - continue; - } - if (update != null) { - // need to count after all possibly continue stmts in - // this branch - // debugCounters.updateCounter(CNT_DEVICE_CHANGED); - deviceUpdates.add(update); - } - } else { - DeviceUpdate update = new DeviceUpdate(d, DELETE, null); - if (!deviceMap.remove(d.getDeviceKey(), d)) { - // concurrent modification; try again - // need to use device that is the map now for the next - // iteration - d = deviceMap.get(d.getDeviceKey()); - if (null != d) - continue; - // debugCounters.updateCounter(CNT_DEVICE_DELETED); - } - deviceUpdates.add(update); - } - processUpdates(deviceUpdates); - break; - } - } - } - - protected void removeEntity(Entity removed, IEntityClass entityClass, - Long deviceKey, Collection others) { - // Don't count in this method. This method CAN BE called to clean-up - // after concurrent device adds/updates and thus counting here - // is misleading - for (DeviceIndex index : secondaryIndexMap.values()) { - index.removeEntityIfNeeded(removed, deviceKey, others); - } - ClassState classState = getClassState(entityClass); - for (DeviceIndex index : classState.secondaryIndexMap.values()) { - index.removeEntityIfNeeded(removed, deviceKey, others); - } - - primaryIndex.removeEntityIfNeeded(removed, deviceKey, others); - - if (classState.classIndex != null) { - classState.classIndex.removeEntityIfNeeded(removed, deviceKey, - others); - } - } - - /** - * method to delete a given device, remove all entities first and then - * finally delete the device itself. - * - * @param device - */ - protected void deleteDevice(Device device) { - // Don't count in this method. This method CAN BE called to clean-up - // after concurrent device adds/updates and thus counting here - // is misleading - ArrayList emptyToKeep = new ArrayList(); - for (Entity entity : device.getEntities()) { - this.removeEntity(entity, device.getEntityClass(), - device.getDeviceKey(), emptyToKeep); - } - if (!deviceMap.remove(device.getDeviceKey(), device)) { - if (logger.isDebugEnabled()) - logger.debug("device map does not have this device -" - + device.toString()); - } - } - - private EnumSet getEntityKeys(Long macAddress, Short vlan, - Integer ipv4Address, NodeConnector port) { - // FIXME: vlan==null is a valid search. Need to handle this - // case correctly. Note that the code will still work correctly. - // But we might do a full device search instead of using an index. - EnumSet keys = EnumSet.noneOf(DeviceField.class); - if (macAddress != null) - keys.add(DeviceField.MAC); - if (vlan != null) - keys.add(DeviceField.VLAN); - if (ipv4Address != null) - keys.add(DeviceField.IPV4); - if (port != null) - keys.add(DeviceField.SWITCHPORT); - return keys; - } - - protected Iterator queryClassByEntity(IEntityClass clazz, - EnumSet keyFields, Entity entity) { - ClassState classState = getClassState(clazz); - DeviceIndex index = classState.secondaryIndexMap.get(keyFields); - if (index == null) - return Collections. emptySet().iterator(); - return new DeviceIndexInterator(this, index.queryByEntity(entity)); - } - - protected Device allocateDevice(Long deviceKey, Entity entity, - IEntityClass entityClass) { - return new Device(this, deviceKey, entity, entityClass); - } - - // TODO: FIX THIS. - protected Device allocateDevice(Long deviceKey, String dhcpClientName, - List aps, List trueAPs, - Collection entities, IEntityClass entityClass) { - return new Device(this, deviceKey, dhcpClientName, aps, trueAPs, - entities, entityClass); - } - - protected Device allocateDevice(Device device, Entity entity, - int insertionpoint) { - return new Device(device, entity, insertionpoint); - } - - // not used - protected Device allocateDevice(Device device, Set entities) { - List newPossibleAPs = new ArrayList(); - List newAPs = new ArrayList(); - for (Entity entity : entities) { - if (entity.getPort() != null) { - AttachmentPoint aP = new AttachmentPoint(entity.getPort(), 0); - newPossibleAPs.add(aP); - } - } - if (device.attachmentPoints != null) { - for (AttachmentPoint oldAP : device.attachmentPoints) { - if (newPossibleAPs.contains(oldAP)) { - newAPs.add(oldAP); - } - } - } - if (newAPs.isEmpty()) - newAPs = null; - Device d = new Device(this, device.getDeviceKey(), - device.getDHCPClientName(), newAPs, null, entities, - device.getEntityClass()); - d.updateAttachmentPoint(); - return d; - } - - // ********************* - // ITopologyManagerAware - // ********************* - - @Override - public void edgeUpdate(List topoedgeupdateList) { - Iterator diter = deviceMap.values().iterator(); - - while (diter.hasNext()) { - Device d = diter.next(); - if (d.updateAttachmentPoint()) { - if (logger.isDebugEnabled()) { - logger.debug("Attachment point changed for device: {}", d); - } - sendDeviceMovedNotification(d); - } - } - } - - @Override - public void edgeOverUtilized(Edge edge) { - // nothing to do - } - - @Override - public void edgeUtilBackToNormal(Edge edge) { - // nothing to do - } - - // ********************* - // IEntityClassListener - // ********************* - - @Override - public void entityClassChanged(Set entityClassNames) { - /* - * iterate through the devices, reclassify the devices that belong to - * these entity class names - */ - Iterator diter = deviceMap.values().iterator(); - while (diter.hasNext()) { - Device d = diter.next(); - if (d.getEntityClass() == null - || entityClassNames.contains(d.getEntityClass().getName())) - reclassifyDevice(d); - } - } - - // ************* - // Local methods - // ************* - /** - * Send update notifications to listeners - * - * @param updates - * the updates to process. - */ - protected void sendDeviceMovedNotification(Device d) { - // debugCounters.updateCounter(CNT_DEVICE_MOVED); - // deviceSyncManager.storeDevice(d); - List listeners = deviceListeners.getOrderedListeners(); - if (listeners != null) { - for (IDeviceListener listener : listeners) { - listener.deviceMoved(d); - } - } - } - - /** - * Send update notifications to listeners. IfNewHostNotify listeners need to - * remove old device and add new device. - * - * @param device - * @param oldDevice - */ - protected void sendDeviceMovedNotification(Device device, Device oldDevice) { - for (IfNewHostNotify notify : newHostNotify) { - notify.notifyHTClientHostRemoved(oldDevice.toHostNodeConnector()); - notify.notifyHTClient(device.toHostNodeConnector()); - } - sendDeviceMovedNotification(device); - } - - /** - * this method will reclassify and reconcile a device - possibilities are - - * create new device(s), remove entities from this device. If the device - * entity class did not change then it returns false else true. - * - * @param device - */ - protected boolean reclassifyDevice(Device device) { - // first classify all entities of this device - if (device == null) { - logger.debug("In reclassify for null device"); - return false; - } - boolean needToReclassify = false; - for (Entity entity : device.entities) { - IEntityClass entityClass = this.entityClassifier - .classifyEntity(entity); - if (entityClass == null || device.getEntityClass() == null) { - needToReclassify = true; - break; - } - if (!entityClass.getName() - .equals(device.getEntityClass().getName())) { - needToReclassify = true; - break; - } - } - if (needToReclassify == false) { - return false; - } - - // debugCounters.updateCounter(CNT_DEVICE_RECLASSIFY_DELETE); - LinkedList deviceUpdates = new LinkedList(); - // delete this device and then re-learn all the entities - this.deleteDevice(device); - deviceUpdates.add(new DeviceUpdate(device, DeviceUpdate.Change.DELETE, - null)); - if (!deviceUpdates.isEmpty()) - processUpdates(deviceUpdates); - for (Entity entity : device.entities) { - this.learnDeviceByEntity(entity); - } - return true; - } - - - private long toLong(byte[] address) { - long mac = 0; - for (int i = 0; i < 6; i++) { - long t = (address[i] & 0xffL) << ((5 - i) * 8); - mac |= t; - } - return mac; - } - - /** - * Accepts an IPv4 address in a byte array and returns the corresponding - * 32-bit integer value. - * - * @param ipAddress - * @return - */ - private static int toIPv4Address(byte[] ipAddress) { - int ip = 0; - for (int i = 0; i < 4; i++) { - int t = (ipAddress[i] & 0xff) << ((3 - i) * 8); - ip |= t; - } - return ip; - } - - private void registerDeviceManagerDebugCounters() { - /* - * XXX Missing functionality if (debugCounters == null) { - * logger.error("Debug Counter Service not found."); debugCounters = new - * NullDebugCounter(); return; } - * debugCounters.registerCounter(CNT_INCOMING, - * "All incoming packets seen by this module", - * CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_RECONCILE_REQUEST, - * "Number of flows that have been received for reconciliation by " + - * "this module", CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_RECONCILE_NO_SOURCE, - * "Number of flow reconcile events that failed because no source " + - * "device could be identified", CounterType.WARN); // is this really a - * warning debugCounters.registerCounter(CNT_RECONCILE_NO_DEST, - * "Number of flow reconcile events that failed because no " + - * "destination device could be identified", CounterType.WARN); // is - * this really a warning - * debugCounters.registerCounter(CNT_BROADCAST_SOURCE, - * "Number of packetIns that were discarded because the source " + - * "MAC was broadcast or multicast", CounterType.WARN); - * debugCounters.registerCounter(CNT_NO_SOURCE, - * "Number of packetIns that were discarded because the " + - * "could not identify a source device. This can happen if a " + - * "packet is not allowed, appears on an illegal port, does not " + - * "have a valid address space, etc.", CounterType.WARN); - * debugCounters.registerCounter(CNT_NO_DEST, - * "Number of packetIns that did not have an associated " + - * "destination device. E.g., because the destination MAC is " + - * "broadcast/multicast or is not yet known to the controller.", - * CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_DHCP_CLIENT_NAME_SNOOPED, - * "Number of times a DHCP client name was snooped from a " + - * "packetIn.", CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_DEVICE_ON_INTERAL_PORT_NOT_LEARNED, - * "Number of times packetIn was received on an internal port and" + - * "no source device is known for the source MAC. The packetIn is " + - * "discarded.", CounterType.WARN); - * debugCounters.registerCounter(CNT_PACKET_NOT_ALLOWED, - * "Number of times a packetIn was not allowed due to spoofing " + - * "protection configuration.", CounterType.WARN); // is this really a - * warning? debugCounters.registerCounter(CNT_NEW_DEVICE, - * "Number of times a new device was learned", - * CounterType.ALWAYS_COUNT); debugCounters.registerCounter( - * CNT_PACKET_ON_INTERNAL_PORT_FOR_KNOWN_DEVICE, - * "Number of times a packetIn was received on an internal port " + - * "for a known device.", CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_NEW_ENTITY, - * "Number of times a new entity was learned for an existing device", - * CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_DEVICE_CHANGED, - * "Number of times device properties have changed", - * CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_DEVICE_MOVED, - * "Number of times devices have moved", CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_CLEANUP_ENTITIES_RUNS, - * "Number of times the entity cleanup task has been run", - * CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_ENTITY_REMOVED_TIMEOUT, - * "Number of times entities have been removed due to timeout " + - * "(entity has been inactive for " + ENTITY_TIMEOUT/1000 + "s)", - * CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_DEVICE_DELETED, - * "Number of devices that have been removed due to inactivity", - * CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_DEVICE_RECLASSIFY_DELETE, - * "Number of devices that required reclassification and have been " + - * "temporarily delete for reclassification", CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_DEVICE_STORED, - * "Number of device entries written or updated to the sync store", - * CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_DEVICE_STORE_THROTTLED, - * "Number of times a device update to the sync store was " + - * "requested but not performed because the same device entities " + - * "have recently been updated already", CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_DEVICE_REMOVED_FROM_STORE, - * "Number of devices that were removed from the sync store " + - * "because the local controller removed the device due to " + - * "inactivity", CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_SYNC_EXCEPTION, - * "Number of times an operation on the sync store resulted in " + - * "sync exception", CounterType.WARN); // it this an error? - * debugCounters.registerCounter(CNT_DEVICES_FROM_STORE, - * "Number of devices that were read from the sync store after " + - * "the local controller transitioned from SLAVE to MASTER", - * CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_CONSOLIDATE_STORE_RUNS, - * "Number of times the task to consolidate entries in the " + - * "store witch live known devices has been run", - * CounterType.ALWAYS_COUNT); - * debugCounters.registerCounter(CNT_CONSOLIDATE_STORE_DEVICES_REMOVED, - * "Number of times a device has been removed from the sync " + - * "store because no corresponding live device is known. " + - * "This indicates a remote controller still writing device " + - * "entries despite the local controller being MASTER or an " + - * "incosistent store update from the local controller.", - * CounterType.WARN); - * debugCounters.registerCounter(CNT_TRANSITION_TO_MASTER, - * "Number of times this controller has transitioned from SLAVE " + - * "to MASTER role. Will be 0 or 1.", CounterType.ALWAYS_COUNT); - */ - } - - @Override - public HostNodeConnector hostFind(InetAddress networkAddress) { - // TODO Auto-generated method stub - return null; - } - - @Override - public HostNodeConnector hostQuery(InetAddress networkAddress) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future discoverHost(InetAddress networkAddress) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List> getHostNetworkHierarchy(InetAddress hostAddress) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Set getAllHosts() { - Collection devices = Collections - .unmodifiableCollection(deviceMap.values()); - Iterator i = devices.iterator(); - Set nc = new HashSet(); - while (i.hasNext()) { - Device device = i.next(); - nc.add(device.toHostNodeConnector()); - } - return nc; - } - - @Override - public Set getActiveStaticHosts() { - Collection devices = Collections - .unmodifiableCollection(deviceMap.values()); - Iterator i = devices.iterator(); - Set nc = new HashSet(); - while (i.hasNext()) { - Device device = i.next(); - if (device.isStaticHost()) - nc.add(device.toHostNodeConnector()); - } - return nc; - } - - @Override - public Set getInactiveStaticHosts() { - Collection devices = Collections - .unmodifiableCollection(inactiveStaticDevices.values()); - Iterator i = devices.iterator(); - Set nc = new HashSet(); - while (i.hasNext()) { - Entity ent = i.next(); - nc.add(ent.toHostNodeConnector()); - - } - return nc; - } - - @Override - public Status addStaticHost(String networkAddress, String dataLayerAddress, - NodeConnector nc, String vlan) { - Long mac = HexEncode.stringToLong(dataLayerAddress); - try { - InetAddress addr = InetAddress.getByName(networkAddress); - int ip = toIPv4Address(addr.getAddress()); - Entity e = new Entity(mac, Short.valueOf(vlan), ip, nc, new Date()); - - if (switchManager.isNodeConnectorEnabled(e.getPort())) { - Device d = this.learnDeviceByEntity(e); - d.setStaticHost(true); - } else { - logger.debug( - "Switch or switchport is not up, adding host {} to inactive list", - addr.getHostName()); - inactiveStaticDevices.put(e.getPort(), e); - } - return new Status(StatusCode.SUCCESS); - } catch (UnknownHostException e) { - return new Status(StatusCode.INTERNALERROR); - } - } - - @Override - public Status removeStaticHost(String networkAddress) { - Integer addr; - try { - addr = toIPv4Address(InetAddress.getByName(networkAddress) - .getAddress()); - } catch (UnknownHostException e) { - return new Status(StatusCode.NOTFOUND, "Host does not exist"); - } - Iterator di = this.getDeviceIteratorForQuery(null, null, addr, - null); - List listeners = deviceListeners.getOrderedListeners(); - while (di.hasNext()) { - Device d = di.next(); - if (d.isStaticHost()) { - deleteDevice(d); - for (IfNewHostNotify notify : newHostNotify) { - notify.notifyHTClientHostRemoved(d.toHostNodeConnector()); - } - for (IDeviceListener listener : listeners) { - listener.deviceRemoved(d); - } - } - } - //go through inactive entites. - Set inactive = this.getInactiveStaticHosts(); - for(HostNodeConnector nc : inactive){ - Integer ip =toIPv4Address(nc.getNetworkAddress().getAddress()); - if(ip.equals(addr)){ - this.inactiveStaticDevices.remove(nc.getnodeConnector()); - } - } - - - return new Status(StatusCode.SUCCESS); - } - - @Override - public void notifyNode(Node node, UpdateType type, - Map propMap) { - if (node == null) - return; - List listeners = deviceListeners.getOrderedListeners(); - switch (type) { - case REMOVED: - logger.debug("Received removed node {}", node); - for (Entry d : deviceMap.entrySet()) { - Device device = d.getValue(); - HostNodeConnector host = device.toHostNodeConnector(); - if (host.getnodeconnectorNode().equals(node)) { - logger.debug("Node: {} is down, remove from Hosts_DB", node); - deleteDevice(device); - for (IfNewHostNotify notify : newHostNotify) { - notify.notifyHTClientHostRemoved(host); - } - for (IDeviceListener listener : listeners) { - listener.deviceRemoved(device); - } - } - } - break; - default: - break; - } - } - - @Override - public void notifyNodeConnector(NodeConnector nodeConnector, - UpdateType type, Map propMap) { - if (nodeConnector == null) - return; - List listeners = deviceListeners.getOrderedListeners(); - boolean up = false; - switch (type) { - case ADDED: - up = true; - break; - case REMOVED: - break; - case CHANGED: - State state = (State) propMap.get(State.StatePropName); - if ((state != null) && (state.getValue() == State.EDGE_UP)) { - up = true; - } - break; - default: - return; - } - - if (up) { - logger.debug("handleNodeConnectorStatusUp {}", nodeConnector); - - Entity ent = inactiveStaticDevices.get(nodeConnector); - Device device = this.learnDeviceByEntity(ent); - if(device!=null){ - HostNodeConnector host = device.toHostNodeConnector(); - if (host != null) { - inactiveStaticDevices.remove(nodeConnector); - for (IfNewHostNotify notify : newHostNotify) { - notify.notifyHTClient(host); - } - for (IDeviceListener listener : listeners) { - listener.deviceAdded(device); - } - } else { - logger.debug("handleNodeConnectorStatusDown {}", nodeConnector); - } - } - }else{ - // remove all devices on the node that went down. - for (Entry entry : deviceMap.entrySet()) { - Device device = entry.getValue(); - HostNodeConnector host = device.toHostNodeConnector(); - if (host.getnodeConnector().equals(nodeConnector)) { - deleteDevice(device); - for (IfNewHostNotify notify : newHostNotify) { - notify.notifyHTClientHostRemoved(host); - } - for (IDeviceListener listener : listeners) { - listener.deviceRemoved(device); - } - } - } - - } - } - -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceMultiIndex.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceMultiIndex.java deleted file mode 100644 index 85cb094874..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceMultiIndex.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker.internal; - -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; -import org.opendaylight.controller.sal.utils.IterableIterator; - -/** - * An index that maps key fields of an entity to device keys, with multiple - * device keys allowed per entity - */ -public class DeviceMultiIndex extends DeviceIndex { - /** - * The index - */ - private ConcurrentHashMap> index; - - /** - * @param keyFields - */ - public DeviceMultiIndex(EnumSet keyFields) { - super(keyFields); - index = new ConcurrentHashMap>(); - } - - // *********** - // DeviceIndex - // *********** - - @Override - public Iterator queryByEntity(Entity entity) { - IndexedEntity ie = new IndexedEntity(keyFields, entity); - Collection devices = index.get(ie); - if (devices != null) - return devices.iterator(); - - return Collections. emptySet().iterator(); - } - - @Override - public Iterator getAll() { - Iterator> iter = index.values().iterator(); - return new IterableIterator(iter); - } - - @Override - public boolean updateIndex(Device device, Long deviceKey) { - for (Entity e : device.entities) { - updateIndex(e, deviceKey); - } - return true; - } - - @Override - public void updateIndex(Entity entity, Long deviceKey) { - Collection devices = null; - - IndexedEntity ie = new IndexedEntity(keyFields, entity); - if (!ie.hasNonNullKeys()) - return; - - devices = index.get(ie); - if (devices == null) { - Map chm = new ConcurrentHashMap(); - devices = Collections.newSetFromMap(chm); - Collection r = index.putIfAbsent(ie, devices); - if (r != null) - devices = r; - } - - devices.add(deviceKey); - } - - @Override - public void removeEntity(Entity entity) { - IndexedEntity ie = new IndexedEntity(keyFields, entity); - index.remove(ie); - } - - @Override - public void removeEntity(Entity entity, Long deviceKey) { - IndexedEntity ie = new IndexedEntity(keyFields, entity); - Collection devices = index.get(ie); - if (devices != null) - devices.remove(deviceKey); - } -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndex.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndex.java deleted file mode 100644 index 6ca0556292..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndex.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker.internal; - -import java.util.Collections; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.concurrent.ConcurrentHashMap; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDeviceService; - -/** - * An index that maps key fields of an entity uniquely to a device key - */ -public class DeviceUniqueIndex extends DeviceIndex { - /** - * The index - */ - private final ConcurrentHashMap index; - - /** - * Construct a new device index using the provided key fields - * - * @param keyFields - * the key fields to use - */ - public DeviceUniqueIndex(EnumSet keyFields) { - super(keyFields); - index = new ConcurrentHashMap(); - } - - // *********** - // DeviceIndex - // *********** - - @Override - public Iterator queryByEntity(Entity entity) { - final Long deviceKey = findByEntity(entity); - if (deviceKey != null) - return Collections. singleton(deviceKey).iterator(); - - return Collections. emptySet().iterator(); - } - - @Override - public Iterator getAll() { - return index.values().iterator(); - } - - @Override - public boolean updateIndex(Device device, Long deviceKey) { - for (Entity e : device.entities) { - IndexedEntity ie = new IndexedEntity(keyFields, e); - if (!ie.hasNonNullKeys()) - continue; - - Long ret = index.putIfAbsent(ie, deviceKey); - if (ret != null && !ret.equals(deviceKey)) { - // If the return value is non-null, then fail the insert - // (this implies that a device using this entity has - // already been created in another thread). - return false; - } - } - return true; - } - - @Override - public void updateIndex(Entity entity, Long deviceKey) { - IndexedEntity ie = new IndexedEntity(keyFields, entity); - if (!ie.hasNonNullKeys()) - return; - index.put(ie, deviceKey); - } - - @Override - public void removeEntity(Entity entity) { - IndexedEntity ie = new IndexedEntity(keyFields, entity); - index.remove(ie); - } - - @Override - public void removeEntity(Entity entity, Long deviceKey) { - IndexedEntity ie = new IndexedEntity(keyFields, entity); - index.remove(ie, deviceKey); - } - - // ************** - // Public Methods - // ************** - - /** - * Look up a {@link Device} based on the provided {@link Entity}. - * - * @param entity - * the entity to search for - * @return The key for the {@link Device} object if found - */ - public Long findByEntity(Entity entity) { - IndexedEntity ie = new IndexedEntity(keyFields, entity); - Long deviceKey = index.get(ie); - if (deviceKey == null) - return null; - return deviceKey; - } - -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/IndexedEntity.java b/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/IndexedEntity.java deleted file mode 100644 index fa9fad881c..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/IndexedEntity.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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.opendaylight.controller.hosttracker.internal; - -import java.util.EnumSet; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDeviceService; -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This is a thin wrapper around {@link Entity} that allows overriding the - * behavior of {@link Object#hashCode()} and {@link Object#equals(Object)} so - * that the keying behavior in a hash map can be changed dynamically - * - * @author readams - */ -public class IndexedEntity { - protected EnumSet keyFields; - protected Entity entity; - private int hashCode = 0; - protected static Logger logger = LoggerFactory - .getLogger(IndexedEntity.class); - - /** - * Create a new {@link IndexedEntity} for the given {@link Entity} using the - * provided key fields. - * - * @param keyFields - * The key fields that will be used for computing - * {@link IndexedEntity#hashCode()} and - * {@link IndexedEntity#equals(Object)} - * @param entity - * the entity to wrap - */ - public IndexedEntity(EnumSet keyFields, Entity entity) { - super(); - this.keyFields = keyFields; - this.entity = entity; - } - - /** - * Check whether this entity has non-null values in any of its key fields - * - * @return true if any key fields have a non-null value - */ - public boolean hasNonNullKeys() { - for (DeviceField f : keyFields) { - switch (f) { - case MAC: - return true; - case IPV4: - if (entity.getIpv4Address() != null) - return true; - break; - case SWITCHPORT: - if (entity.getPort() != null) - return true; - break; - case VLAN: - if (entity.getVlan() != null) - return true; - break; - } - } - return false; - } - - @Override - public int hashCode() { - - if (hashCode != 0) { - return hashCode; - } - - final int prime = 31; - hashCode = 1; - for (DeviceField f : keyFields) { - switch (f) { - case MAC: - hashCode = prime - * hashCode - + (int) (entity.getMacAddress() ^ (entity - .getMacAddress() >>> 32)); - break; - case IPV4: - hashCode = prime - * hashCode - + ((entity.getIpv4Address() == null) ? 0 : entity - .getIpv4Address().hashCode()); - break; - case SWITCHPORT: - hashCode = prime - * hashCode - + ((entity.getPort() == null) ? 0 : entity.getPort() - .hashCode()); - break; - case VLAN: - hashCode = prime - * hashCode - + ((entity.getVlan() == null) ? 0 : entity.getVlan() - .hashCode()); - break; - } - } - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - IndexedEntity other = (IndexedEntity) obj; - - if (!keyFields.equals(other.keyFields)) - return false; - - for (IDeviceService.DeviceField f : keyFields) { - switch (f) { - case MAC: - if (entity.getMacAddress() != other.entity.getMacAddress()) - return false; - break; - case IPV4: - if (entity.getIpv4Address() == null) { - if (other.entity.getIpv4Address() != null) - return false; - } else if (!entity.getIpv4Address().equals( - other.entity.getIpv4Address())) - return false; - break; - case SWITCHPORT: - if (entity.getPort() == null) { - if (other.entity.getPort() != null) - return false; - } else if (!entity.getPort().equals(other.entity.getPort())) - return false; - break; - case VLAN: - if (entity.getVlan() == null) { - if (other.entity.getVlan() != null) - return false; - } else if (!entity.getVlan().equals(other.entity.getVlan())) - return false; - break; - } - } - - return true; - } - -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImplTest.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImplTest.java deleted file mode 100644 index 3bed3a513a..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceManagerImplTest.java +++ /dev/null @@ -1,2644 +0,0 @@ -package org.opendaylight.controller.hosttracker.internal; - -///* -// * Copyright (c) 2011,2013 Big Switch Networks, Inc. -// * -// * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html -// * -// * 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. -// * -// * This file incorporates work covered by the following copyright and -// * permission notice: -// * -// * Originally created by David Erickson, Stanford University -// * -// * Licensed 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.opendaylight.controller.hosttracker.internal; -// -//import static org.easymock.EasyMock.anyLong; -//import static org.easymock.EasyMock.anyObject; -//import static org.easymock.EasyMock.anyShort; -//import static org.easymock.EasyMock.createMock; -//import static org.easymock.EasyMock.createNiceMock; -//import static org.easymock.EasyMock.eq; -//import static org.easymock.EasyMock.expect; -//import static org.easymock.EasyMock.expectLastCall; -//import static org.easymock.EasyMock.isA; -//import static org.easymock.EasyMock.or; -//import static org.easymock.EasyMock.replay; -//import static org.easymock.EasyMock.reset; -//import static org.easymock.EasyMock.verify; -//import static org.junit.Assert.*; -// -//import java.util.ArrayList; -//import java.util.Arrays; -//import java.util.Calendar; -//import java.util.Collection; -//import java.util.Collections; -//import java.util.Date; -//import java.util.EnumSet; -//import java.util.HashMap; -//import java.util.HashSet; -//import java.util.Iterator; -//import java.util.List; -//import java.util.Map; -//import java.util.Map.Entry; -//import java.util.Set; -//import java.util.concurrent.ConcurrentHashMap; -// -//import org.junit.Before; -//import org.junit.Test; -// -//import org.slf4j.Logger; -//import org.slf4j.LoggerFactory; -// -//public class DeviceManagerImplTest { -// -// protected static Logger logger = -// LoggerFactory.getLogger(DeviceManagerImplTest.class); -// -// protected OFPacketIn packetIn_1, packetIn_2, packetIn_3; -// protected IPacket testARPReplyPacket_1, testARPReplyPacket_2, -// testARPReplyPacket_3; -// protected IPacket testARPReqPacket_1, testARPReqPacket_2; -// protected byte[] testARPReplyPacket_1_Srld, testARPReplyPacket_2_Srld; -// private MockSyncService syncService; -// private IStoreClient storeClient; -// -// DeviceManagerImpl deviceManager; -// MemoryStorageSource storageSource; -// FlowReconcileManager flowReconcileMgr; -// -// private IOFSwitch makeSwitchMock(long id) { -// IOFSwitch mockSwitch = createMock(IOFSwitch.class); -// ImmutablePort port = ImmutablePort.create("p1", (short)1); -// expect(mockSwitch.getId()).andReturn(id).anyTimes(); -// expect(mockSwitch.getStringId()) -// .andReturn(HexString.toHexString(id, 6)).anyTimes(); -// expect(mockSwitch.getPort(anyShort())) -// .andReturn(port).anyTimes(); -// return mockSwitch; -// } -// -// /* -// * return an EasyMock ITopologyService that's setup so that it will -// * answer all questions a device or device manager will ask -// * (isAttachmentPointPort, etc.) in a way so that every port is a -// * non-BD, attachment point port. -// * The returned mock is still in record mode -// */ -// private ITopologyService makeMockTopologyAllPortsAp() { -// ITopologyService mockTopology = createMock(ITopologyService.class); -// mockTopology.isAttachmentPointPort(anyLong(), anyShort()); -// expectLastCall().andReturn(true).anyTimes(); -// mockTopology.getL2DomainId(anyLong()); -// expectLastCall().andReturn(1L).anyTimes(); -// mockTopology.isBroadcastDomainPort(anyLong(), anyShort()); -// expectLastCall().andReturn(false).anyTimes(); -// mockTopology.isConsistent(anyLong(), anyShort(), anyLong(), anyShort()); -// expectLastCall().andReturn(false).anyTimes(); -// mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(), -// anyLong(), anyShort()); -// expectLastCall().andReturn(false).anyTimes(); -// return mockTopology; -// } -// -// @Override -// @Before -// public void setUp() throws Exception { -// doSetUp(Role.MASTER); -// } -// -// public void doSetUp(Role initialRole) throws Exception { -// super.setUp(); -// -// this.syncService = new MockSyncService(); -// -// FloodlightModuleContext fmc = new FloodlightModuleContext(); -// RestApiServer restApi = new RestApiServer(); -// MockThreadPoolService tp = new MockThreadPoolService(); -// ITopologyService topology = createMock(ITopologyService.class); -// fmc.addService(IThreadPoolService.class, tp); -// mockFloodlightProvider = getMockFloodlightProvider(); -// mockFloodlightProvider.setRole(initialRole, ""); -// -// deviceManager = new DeviceManagerImpl(); -// flowReconcileMgr = new FlowReconcileManager(); -// DefaultEntityClassifier entityClassifier = new DefaultEntityClassifier(); -// fmc.addService(IDeviceService.class, deviceManager); -// storageSource = new MemoryStorageSource(); -// fmc.addService(IStorageSourceService.class, storageSource); -// fmc.addService(IFloodlightProviderService.class, mockFloodlightProvider); -// fmc.addService(IRestApiService.class, restApi); -// fmc.addService(IFlowReconcileService.class, flowReconcileMgr); -// fmc.addService(IEntityClassifierService.class, entityClassifier); -// fmc.addService(ITopologyService.class, topology); -// fmc.addService(ISyncService.class, syncService); -// tp.init(fmc); -// restApi.init(fmc); -// storageSource.init(fmc); -// deviceManager.init(fmc); -// flowReconcileMgr.init(fmc); -// entityClassifier.init(fmc); -// syncService.init(fmc); -// storageSource.startUp(fmc); -// deviceManager.startUp(fmc); -// flowReconcileMgr.startUp(fmc); -// tp.startUp(fmc); -// entityClassifier.startUp(fmc); -// syncService.startUp(fmc); -// -// this.storeClient = -// this.syncService.getStoreClient(DeviceManagerImpl.DEVICE_SYNC_STORE_NAME, -// String.class, DeviceSyncRepresentation.class); -// -// reset(topology); -// topology.addListener(deviceManager); -// expectLastCall().anyTimes(); -// replay(topology); -// -// IOFSwitch mockSwitch1 = makeSwitchMock(1L); -// IOFSwitch mockSwitch10 = makeSwitchMock(10L); -// IOFSwitch mockSwitch5 = makeSwitchMock(5L); -// IOFSwitch mockSwitch50 = makeSwitchMock(50L); -// Map switches = new HashMap(); -// switches.put(1L, mockSwitch1); -// switches.put(10L, mockSwitch10); -// switches.put(5L, mockSwitch5); -// switches.put(50L, mockSwitch50); -// mockFloodlightProvider.setSwitches(switches); -// -// replay(mockSwitch1, mockSwitch5, mockSwitch10, mockSwitch50); -// -// // Build our test packet -// this.testARPReplyPacket_1 = new Ethernet() -// .setSourceMACAddress("00:44:33:22:11:01") -// .setDestinationMACAddress("00:11:22:33:44:55") -// .setEtherType(Ethernet.TYPE_ARP) -// .setVlanID((short)5) -// .setPayload( -// new ARP() -// .setHardwareType(ARP.HW_TYPE_ETHERNET) -// .setProtocolType(ARP.PROTO_TYPE_IP) -// .setHardwareAddressLength((byte) 6) -// .setProtocolAddressLength((byte) 4) -// .setOpCode(ARP.OP_REPLY) -// .setSenderHardwareAddress(Ethernet.toMACAddress("00:44:33:22:11:01")) -// .setSenderProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.1")) -// .setTargetHardwareAddress(Ethernet.toMACAddress("00:11:22:33:44:55")) -// .setTargetProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.2"))); -// this.testARPReplyPacket_1_Srld = testARPReplyPacket_1.serialize(); -// -// // Another test packet with a different source IP -// this.testARPReplyPacket_2 = new Ethernet() -// .setSourceMACAddress("00:99:88:77:66:55") -// .setDestinationMACAddress("00:11:22:33:44:55") -// .setEtherType(Ethernet.TYPE_ARP) -// .setVlanID((short)5) -// .setPayload( -// new ARP() -// .setHardwareType(ARP.HW_TYPE_ETHERNET) -// .setProtocolType(ARP.PROTO_TYPE_IP) -// .setHardwareAddressLength((byte) 6) -// .setProtocolAddressLength((byte) 4) -// .setOpCode(ARP.OP_REPLY) -// .setSenderHardwareAddress(Ethernet.toMACAddress("00:44:33:22:11:01")) -// .setSenderProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.1")) -// .setTargetHardwareAddress(Ethernet.toMACAddress("00:11:22:33:44:55")) -// .setTargetProtocolAddress(IPv4.toIPv4AddressBytes("192.168.1.2"))); -// this.testARPReplyPacket_2_Srld = testARPReplyPacket_2.serialize(); -// -// // Build the PacketIn -// this.packetIn_1 = ((OFPacketIn) mockFloodlightProvider. -// getOFMessageFactory().getMessage(OFType.PACKET_IN)) -// .setBufferId(-1) -// .setInPort((short) 1) -// .setPacketData(this.testARPReplyPacket_1_Srld) -// .setReason(OFPacketInReason.NO_MATCH) -// .setTotalLength((short) this.testARPReplyPacket_1_Srld.length); -// -// // Build the PacketIn -// this.packetIn_2 = ((OFPacketIn) mockFloodlightProvider. -// getOFMessageFactory().getMessage(OFType.PACKET_IN)) -// .setBufferId(-1) -// .setInPort((short) 1) -// .setPacketData(this.testARPReplyPacket_2_Srld) -// .setReason(OFPacketInReason.NO_MATCH) -// .setTotalLength((short) this.testARPReplyPacket_2_Srld.length); -// } -// -// -// -// -// -// @Test -// public void testLastSeen() throws Exception { -// Calendar c = Calendar.getInstance(); -// Date d1 = c.getTime(); -// Entity entity1 = new Entity(1L, null, null, null, null, d1); -// c.add(Calendar.SECOND, 1); -// Entity entity2 = new Entity(1L, null, 1, null, null, c.getTime()); -// -// IDevice d = deviceManager.learnDeviceByEntity(entity2); -// assertEquals(c.getTime(), d.getLastSeen()); -// d = deviceManager.learnDeviceByEntity(entity1); -// assertEquals(c.getTime(), d.getLastSeen()); -// -// deviceManager.startUp(null); -// d = deviceManager.learnDeviceByEntity(entity1); -// assertEquals(d1, d.getLastSeen()); -// d = deviceManager.learnDeviceByEntity(entity2); -// assertEquals(c.getTime(), d.getLastSeen()); -// } -// -// @Test -// public void testEntityLearning() throws Exception { -// IDeviceListener mockListener = -// createMock(IDeviceListener.class); -// expect(mockListener.getName()).andReturn("mockListener").atLeastOnce(); -// expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// -// replay(mockListener); -// deviceManager.addListener(mockListener); -// verify(mockListener); -// reset(mockListener); -// deviceManager.entityClassifier= new MockEntityClassifier(); -// deviceManager.startUp(null); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// expect(mockTopology.getL2DomainId(anyLong())). -// andReturn(1L).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(anyLong(), anyShort())). -// andReturn(false).anyTimes(); -// -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())).andReturn(true).anyTimes(); -// expect(mockTopology.isConsistent(10L, (short)1, 10L, (short)1)). -// andReturn(true).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)1, 1L, (short)1)). -// andReturn(true).anyTimes(); -// expect(mockTopology.isConsistent(50L, (short)3, 50L, (short)3)). -// andReturn(true).anyTimes(); -// -// Date topologyUpdateTime = new Date(); -// expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime). -// anyTimes(); -// -// deviceManager.topology = mockTopology; -// -// Entity entity1 = new Entity(1L, null, null, 1L, 1, new Date()); -// Entity entity2 = new Entity(1L, null, null, 10L, 1, new Date()); -// Entity entity3 = new Entity(1L, null, 1, 10L, 1, new Date()); -// Entity entity4 = new Entity(1L, null, 1, 1L, 1, new Date()); -// Entity entity5 = new Entity(2L, (short)4, 1, 5L, 2, new Date()); -// Entity entity6 = new Entity(2L, (short)4, 1, 50L, 3, new Date()); -// Entity entity7 = new Entity(2L, (short)4, 2, 50L, 3, new Date()); -// -// mockListener.deviceAdded(isA(IDevice.class)); -// replay(mockListener, mockTopology); -// -// Device d1 = deviceManager.learnDeviceByEntity(entity1); -// assertSame(d1, deviceManager.learnDeviceByEntity(entity1)); -// assertSame(d1, deviceManager.findDeviceByEntity(entity1)); -// assertEquals(DefaultEntityClassifier.entityClass , -// d1.getEntityClass()); -// assertArrayEquals(new Short[] { -1 }, d1.getVlanId()); -// assertArrayEquals(new Integer[] { }, d1.getIPv4Addresses()); -// -// assertEquals(1, deviceManager.getAllDevices().size()); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceAdded(isA(IDevice.class)); -// replay(mockListener); -// -// Device d2 = deviceManager.learnDeviceByEntity(entity2); -// assertFalse(d1.equals(d2)); -// assertNotSame(d1, d2); -// assertNotSame(d1.getDeviceKey(), d2.getDeviceKey()); -// assertEquals(MockEntityClassifier.testEC, d2.getEntityClass()); -// assertArrayEquals(new Short[] { -1 }, d2.getVlanId()); -// assertArrayEquals(new Integer[] { }, d2.getIPv4Addresses()); -// -// assertEquals(2, deviceManager.getAllDevices().size()); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceIPV4AddrChanged(isA(IDevice.class)); -// replay(mockListener); -// -// Device d3 = deviceManager.learnDeviceByEntity(entity3); -// assertNotSame(d2, d3); -// assertEquals(d2.getDeviceKey(), d3.getDeviceKey()); -// assertEquals(MockEntityClassifier.testEC, d3.getEntityClass()); -// assertArrayEquals(new Integer[] { 1 }, -// d3.getIPv4Addresses()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(10L, 1) }, -// d3.getAttachmentPoints()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(10L, 1) }, -// d3.getAttachmentPoints(true)); -// assertArrayEquals(new Short[] { -1 }, -// d3.getVlanId()); -// -// assertEquals(2, deviceManager.getAllDevices().size()); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceIPV4AddrChanged(isA(IDevice.class)); -// replay(mockListener); -// -// Device d4 = deviceManager.learnDeviceByEntity(entity4); -// assertNotSame(d1, d4); -// assertEquals(d1.getDeviceKey(), d4.getDeviceKey()); -// assertEquals(DefaultEntityClassifier.entityClass, d4.getEntityClass()); -// assertArrayEquals(new Integer[] { 1 }, -// d4.getIPv4Addresses()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, -// d4.getAttachmentPoints()); -// assertArrayEquals(new Short[] { -1 }, -// d4.getVlanId()); -// -// assertEquals(2, deviceManager.getAllDevices().size()); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceAdded((isA(IDevice.class))); -// replay(mockListener); -// -// Device d5 = deviceManager.learnDeviceByEntity(entity5); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 2) }, -// d5.getAttachmentPoints()); -// assertArrayEquals(new Short[] { (short) 4 }, -// d5.getVlanId()); -// assertEquals(2L, d5.getMACAddress()); -// assertEquals("00:00:00:00:00:02", d5.getMACAddressString()); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceAdded(isA(IDevice.class)); -// replay(mockListener); -// -// Device d6 = deviceManager.learnDeviceByEntity(entity6); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(50L, 3) }, -// d6.getAttachmentPoints()); -// assertArrayEquals(new Short[] { (short) 4 }, -// d6.getVlanId()); -// -// assertEquals(4, deviceManager.getAllDevices().size()); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceIPV4AddrChanged(isA(IDevice.class)); -// replay(mockListener); -// -// Device d7 = deviceManager.learnDeviceByEntity(entity7); -// assertNotSame(d6, d7); -// assertEquals(d6.getDeviceKey(), d7.getDeviceKey()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(50L, 3) }, -// d7.getAttachmentPoints()); -// assertArrayEquals(new Short[] { (short) 4 }, -// d7.getVlanId()); -// -// assertEquals(4, deviceManager.getAllDevices().size()); -// verify(mockListener); -// -// -// reset(mockListener); -// replay(mockListener); -// -// reset(deviceManager.topology); -// deviceManager.topology.addListener(deviceManager); -// expectLastCall().times(1); -// replay(deviceManager.topology); -// -// deviceManager.entityClassifier = new MockEntityClassifierMac(); -// deviceManager.startUp(null); -// Entity entityNoClass = new Entity(5L, (short)1, 5, -1L, 1, new Date()); -// assertEquals(null, deviceManager.learnDeviceByEntity(entityNoClass)); -// -// verify(mockListener); -// } -// -// -// private void doTestEntityOrdering(boolean computeInsertionPoint) throws Exception { -// Entity e = new Entity(10L, null, null, null, null, null); -// IEntityClass ec = createNiceMock(IEntityClass.class); -// Device d = new Device(deviceManager, 1L, e, ec); -// -// int expectedLength = 1; -// Long[] macs = new Long[] { 5L, // new first element -// 15L, // new last element -// 7L, // insert in middle -// 12L, // insert in middle -// 6L, // insert at idx 1 -// 14L, // insert at idx length-2 -// 1L, -// 20L -// }; -// -// for (Long mac: macs) { -// e = new Entity(mac, null, null, null, null, null); -// int insertionPoint; -// if (computeInsertionPoint) { -// insertionPoint = -(Arrays.binarySearch(d.entities, e)+1); -// } else { -// insertionPoint = -1; -// } -// d = deviceManager.allocateDevice(d, e, insertionPoint); -// expectedLength++; -// assertEquals(expectedLength, d.entities.length); -// for (int i = 0; i < d.entities.length-1; i++) -// assertEquals(-1, d.entities[i].compareTo(d.entities[i+1])); -// } -// } -// -// @Test -// public void testEntityOrderingExternal() throws Exception { -// doTestEntityOrdering(true); -// } -// -// @Test -// public void testEntityOrderingInternal() throws Exception { -// doTestEntityOrdering(false); -// } -// -// @Test -// public void testAttachmentPointLearning() throws Exception { -// IDeviceListener mockListener = -// createMock(IDeviceListener.class); -// expect(mockListener.getName()).andReturn("mockListener").atLeastOnce(); -// expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// -// replay(mockListener); -// deviceManager.addListener(mockListener); -// verify(mockListener); -// reset(mockListener); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// expect(mockTopology.getL2DomainId(1L)). -// andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(5L)). -// andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(10L)). -// andReturn(10L).anyTimes(); -// expect(mockTopology.getL2DomainId(50L)). -// andReturn(10L).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(anyLong(), anyShort())). -// andReturn(false).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(), -// anyLong(), anyShort())).andReturn(false).anyTimes(); -// -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())).andReturn(true).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)1, 5L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(5L, (short)1, 10L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(10L, (short)1, 50L, (short)1)). -// andReturn(false).anyTimes(); -// -// Date topologyUpdateTime = new Date(); -// expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime). -// anyTimes(); -// -// replay(mockTopology); -// -// deviceManager.topology = mockTopology; -// -// Calendar c = Calendar.getInstance(); -// Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime()); -// Entity entity0 = new Entity(1L, null, null, null, null, c.getTime()); -// c.add(Calendar.SECOND, 1); -// Entity entity2 = new Entity(1L, null, null, 5L, 1, c.getTime()); -// c.add(Calendar.SECOND, 1); -// Entity entity3 = new Entity(1L, null, null, 10L, 1, c.getTime()); -// c.add(Calendar.SECOND, 1); -// Entity entity4 = new Entity(1L, null, null, 50L, 1, c.getTime()); -// -// IDevice d; -// SwitchPort[] aps; -// Integer[] ips; -// -// mockListener.deviceAdded(isA(IDevice.class)); -// replay(mockListener); -// -// deviceManager.learnDeviceByEntity(entity1); -// d = deviceManager.learnDeviceByEntity(entity0); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps); -// ips = d.getIPv4Addresses(); -// assertArrayEquals(new Integer[] { 1 }, ips); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceMoved((isA(IDevice.class))); -// replay(mockListener); -// -// d = deviceManager.learnDeviceByEntity(entity2); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// -// assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1) }, aps); -// ips = d.getIPv4Addresses(); -// assertArrayEquals(new Integer[] { 1 }, ips); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceMoved((isA(IDevice.class))); -// replay(mockListener); -// -// d = deviceManager.learnDeviceByEntity(entity3); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] {new SwitchPort(5L, 1), new SwitchPort(10L, 1)}, aps); -// ips = d.getIPv4Addresses(); -// assertArrayEquals(new Integer[] { 1 }, ips); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceMoved((isA(IDevice.class))); -// replay(mockListener); -// -// d = deviceManager.learnDeviceByEntity(entity4); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1), -// new SwitchPort(50L, 1) }, aps); -// ips = d.getIPv4Addresses(); -// assertArrayEquals(new Integer[] { 1 }, ips); -// verify(mockListener); -// } -// -// private void verifyEntityArray(Entity[] expected, Device d) { -// Arrays.sort(expected); -// assertArrayEquals(expected, d.entities); -// } -// -// @Test -// public void testNoLearningOnInternalPorts() throws Exception { -// IDeviceListener mockListener = -// createMock(IDeviceListener.class); -// -// expect(mockListener.getName()).andReturn("mockListener").anyTimes(); -// expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// -// replay(mockListener); -// deviceManager.addListener(mockListener); -// verify(mockListener); -// reset(mockListener); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// expect(mockTopology.getL2DomainId(1L)). -// andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(2L)). -// andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(3L)). -// andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(4L)). -// andReturn(1L).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(anyLong(), anyShort())) -// .andReturn(false).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(), -// anyLong(), anyShort())) -// .andReturn(false).anyTimes(); -// -// expect(mockTopology.isAttachmentPointPort(or(eq(1L), eq(3L)), anyShort())) -// .andReturn(true).anyTimes(); -// // Switches 2 and 4 have only internal ports -// expect(mockTopology.isAttachmentPointPort(or(eq(2L), eq(4L)), anyShort())) -// .andReturn(false).anyTimes(); -// -// expect(mockTopology.isConsistent(1L, (short)1, 3L, (short)1)) -// .andReturn(false).once(); -// -// Date topologyUpdateTime = new Date(); -// expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime). -// anyTimes(); -// -// replay(mockTopology); -// -// deviceManager.topology = mockTopology; -// -// Calendar c = Calendar.getInstance(); -// Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime()); -// c.add(Calendar.SECOND, 1); -// Entity entity2 = new Entity(1L, null, 2, 2L, 1, c.getTime()); -// c.add(Calendar.SECOND, 1); -// Entity entity3 = new Entity(1L, null, 3, 3L, 1, c.getTime()); -// c.add(Calendar.SECOND, 1); -// Entity entity4 = new Entity(1L, null, 4, 4L, 1, c.getTime()); -// -// IDevice d; -// SwitchPort[] aps; -// Integer[] ips; -// -// mockListener.deviceAdded(isA(IDevice.class)); -// expectLastCall().once(); -// replay(mockListener); -// -// // cannot learn device internal ports -// d = deviceManager.learnDeviceByEntity(entity2); -// assertNull(d); -// d = deviceManager.learnDeviceByEntity(entity4); -// assertNull(d); -// -// d = deviceManager.learnDeviceByEntity(entity1); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps); -// verifyEntityArray(new Entity[] { entity1 } , (Device)d); -// ips = d.getIPv4Addresses(); -// assertArrayEquals(new Integer[] { 1 }, ips); -// verify(mockListener); -// -// reset(mockListener); -// replay(mockListener); -// -// // don't learn -// d = deviceManager.learnDeviceByEntity(entity2); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps); -// verifyEntityArray(new Entity[] { entity1 } , (Device)d); -// ips = d.getIPv4Addresses(); -// assertArrayEquals(new Integer[] { 1 }, ips); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceMoved(isA(IDevice.class)); -// mockListener.deviceIPV4AddrChanged(isA(IDevice.class)); -// replay(mockListener); -// -// // learn -// d = deviceManager.learnDeviceByEntity(entity3); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(3L, 1) }, aps); -// verifyEntityArray(new Entity[] { entity1, entity3 } , (Device)d); -// ips = d.getIPv4Addresses(); -// Arrays.sort(ips); -// assertArrayEquals(new Integer[] { 1, 3 }, ips); -// verify(mockListener); -// -// reset(mockListener); -// replay(mockListener); -// -// // don't learn -// d = deviceManager.learnDeviceByEntity(entity4); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(3L, 1) }, aps); -// verifyEntityArray(new Entity[] { entity1, entity3 } , (Device)d); -// ips = d.getIPv4Addresses(); -// Arrays.sort(ips); -// assertArrayEquals(new Integer[] { 1, 3 }, ips); -// verify(mockListener); -// } -// -// @Test -// public void testAttachmentPointSuppression() throws Exception { -// IDeviceListener mockListener = -// createMock(IDeviceListener.class); -// -// expect(mockListener.getName()).andReturn("mockListener").anyTimes(); -// expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// -// replay(mockListener); -// deviceManager.addListener(mockListener); -// verify(mockListener); -// reset(mockListener); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// expect(mockTopology.getL2DomainId(1L)). -// andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(5L)). -// andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(10L)). -// andReturn(10L).anyTimes(); -// expect(mockTopology.getL2DomainId(50L)). -// andReturn(10L).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(anyLong(), anyShort())) -// .andReturn(false).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(), -// anyLong(), anyShort())) -// .andReturn(false).anyTimes(); -// -// expect(mockTopology.isAttachmentPointPort(anyLong(), anyShort())) -// .andReturn(true).anyTimes(); -// expect(mockTopology.isConsistent(5L, (short)1, 50L, (short)1)) -// .andReturn(false).anyTimes(); -// -// Date topologyUpdateTime = new Date(); -// expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime). -// anyTimes(); -// -// replay(mockTopology); -// -// deviceManager.topology = mockTopology; -// // suppress (1L, 1) and (10L, 1) -// deviceManager.addSuppressAPs(1L, (short)1); -// deviceManager.addSuppressAPs(10L, (short)1); -// -// Calendar c = Calendar.getInstance(); -// Entity entity0 = new Entity(1L, null, null, null, null, c.getTime()); -// // No attachment point should be learnt on 1L, 1 -// Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime()); -// c.add(Calendar.SECOND, 1); -// Entity entity2 = new Entity(1L, null, 1, 5L, 1, c.getTime()); -// c.add(Calendar.SECOND, 1); -// Entity entity3 = new Entity(1L, null, null, 10L, 1, c.getTime()); -// c.add(Calendar.SECOND, 1); -// Entity entity4 = new Entity(1L, null, null, 50L, 1, c.getTime()); -// -// IDevice d; -// SwitchPort[] aps; -// Integer[] ips; -// -// mockListener.deviceAdded(isA(IDevice.class)); -// mockListener.deviceIPV4AddrChanged((isA(IDevice.class))); -// replay(mockListener); -// -// // TODO: we currently do learn entities on suppressed APs -// // // cannot learn device on suppressed AP -// // d = deviceManager.learnDeviceByEntity(entity1); -// // assertNull(d); -// -// deviceManager.learnDeviceByEntity(entity0); -// d = deviceManager.learnDeviceByEntity(entity1); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertEquals(aps.length, 0); -// verifyEntityArray(new Entity[] { entity0, entity1} , (Device)d); -// ips = d.getIPv4Addresses(); -// assertArrayEquals(new Integer[] { 1 }, ips); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceMoved((isA(IDevice.class))); -// //mockListener.deviceIPV4AddrChanged((isA(IDevice.class))); -// replay(mockListener); -// d = deviceManager.learnDeviceByEntity(entity2); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1) }, aps); -// verifyEntityArray(new Entity[] { entity0, entity1, entity2 } , (Device)d); -// ips = d.getIPv4Addresses(); -// assertArrayEquals(new Integer[] { 1 }, ips); -// verify(mockListener); -// -// reset(mockListener); -// replay(mockListener); -// -// d = deviceManager.learnDeviceByEntity(entity3); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1) }, aps); -// verifyEntityArray(new Entity[] { entity0, entity1, entity2, entity3 } , (Device)d); -// ips = d.getIPv4Addresses(); -// assertArrayEquals(new Integer[] { 1 }, ips); -// verify(mockListener); -// -// reset(mockListener); -// mockListener.deviceMoved((isA(IDevice.class))); -// replay(mockListener); -// -// d = deviceManager.learnDeviceByEntity(entity4); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(5L, 1), -// new SwitchPort(50L, 1) }, aps); -// verifyEntityArray(new Entity[] { entity0, entity1, entity2, entity3, entity4} , (Device)d); -// ips = d.getIPv4Addresses(); -// assertArrayEquals(new Integer[] { 1 }, ips); -// verify(mockListener); -// } -// -// @Test -// public void testBDAttachmentPointLearning() throws Exception { -// ITopologyService mockTopology = createMock(ITopologyService.class); -// expect(mockTopology.getL2DomainId(anyLong())). -// andReturn(1L).anyTimes(); -// expect(mockTopology.isAttachmentPointPort(anyLong(), anyShort())). -// andReturn(true).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(1L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(1L, (short)2)). -// andReturn(true).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(1L, (short)1, -// 1L, (short)2)).andReturn(true).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(1L, (short)2, -// 1L, (short)1)).andReturn(true).anyTimes(); -// expect(mockTopology.isConsistent(anyLong(), anyShort(), anyLong(), anyShort())).andReturn(false).anyTimes(); -// -// Date topologyUpdateTime = new Date(); -// expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime). -// anyTimes(); -// -// replay(mockTopology); -// -// deviceManager.topology = mockTopology; -// -// Calendar c = Calendar.getInstance(); -// Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime()); -// c.add(Calendar.MILLISECOND, -// (int)AttachmentPoint.OPENFLOW_TO_EXTERNAL_TIMEOUT/ 2); -// Entity entity2 = new Entity(1L, null, null, 1L, 2, c.getTime()); -// c.add(Calendar.MILLISECOND, -// (int)AttachmentPoint.OPENFLOW_TO_EXTERNAL_TIMEOUT / 2 + 1); -// Entity entity3 = new Entity(1L, null, null, 1L, 2, c.getTime()); -// -// IDevice d; -// SwitchPort[] aps; -// -// d = deviceManager.learnDeviceByEntity(entity1); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps); -// -// // this timestamp is too soon; don't switch -// d = deviceManager.learnDeviceByEntity(entity2); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps); -// -// // it should switch when we learn with a timestamp after the -// // timeout -// d = deviceManager.learnDeviceByEntity(entity3); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 2) }, aps); -// } -// -// /** -// * This test verifies that the learning behavior on OFPP_LOCAL ports. -// * Once a host is learned on OFPP_LOCAL, it is allowed to move only from -// * one OFPP_LOCAL to another OFPP_LOCAL port. -// * @throws Exception -// */ -// @Test -// public void testLOCALAttachmentPointLearning() throws Exception { -// ITopologyService mockTopology = createMock(ITopologyService.class); -// expect(mockTopology.getL2DomainId(anyLong())). -// andReturn(1L).anyTimes(); -// expect(mockTopology.isAttachmentPointPort(anyLong(), anyShort())). -// andReturn(true).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(1L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(1L, OFPort.OFPP_LOCAL.getValue())). -// andReturn(false).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(1L, (short)2)). -// andReturn(true).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(1L, (short)1, -// 1L, OFPort.OFPP_LOCAL.getValue())).andReturn(true).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(1L, OFPort.OFPP_LOCAL.getValue(), -// 1L, (short)2)).andReturn(true).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(1L, (short)2, -// 1L, OFPort.OFPP_LOCAL.getValue())).andReturn(true).anyTimes(); -// expect(mockTopology.isConsistent(anyLong(), anyShort(), anyLong(), anyShort())).andReturn(false).anyTimes(); -// -// Date topologyUpdateTime = new Date(); -// expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime). -// anyTimes(); -// -// replay(mockTopology); -// -// deviceManager.topology = mockTopology; -// -// Calendar c = Calendar.getInstance(); -// Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime()); -// c.add(Calendar.MILLISECOND, -// (int)AttachmentPoint.OPENFLOW_TO_EXTERNAL_TIMEOUT/ 2); -// Entity entity2 = new Entity(1L, null, null, 1L, (int)OFPort.OFPP_LOCAL.getValue(), c.getTime()); -// c.add(Calendar.MILLISECOND, -// (int)AttachmentPoint.OPENFLOW_TO_EXTERNAL_TIMEOUT + 1); -// Entity entity3 = new Entity(1L, null, null, 1L, 2, c.getTime()); -// -// IDevice d; -// SwitchPort[] aps; -// -// d = deviceManager.learnDeviceByEntity(entity1); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, aps); -// -// // Ensure that the attachment point changes to OFPP_LOCAL -// d = deviceManager.learnDeviceByEntity(entity2); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, OFPort.OFPP_LOCAL.getValue()) }, aps); -// -// // Even though the new attachment point is consistent with old -// // and the time has elapsed, OFPP_LOCAL attachment point should -// // be maintained. -// d = deviceManager.learnDeviceByEntity(entity3); -// assertEquals(1, deviceManager.getAllDevices().size()); -// aps = d.getAttachmentPoints(); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, OFPort.OFPP_LOCAL.getValue()) }, aps); -// } -// -// @Test -// public void testPacketInBasic(byte[] deviceMac, OFPacketIn packetIn) { -// // Mock up our expected behavior -// ITopologyService mockTopology = createMock(ITopologyService.class); -// deviceManager.topology = mockTopology; -// expect(mockTopology.isAttachmentPointPort(EasyMock.anyLong(), -// EasyMock.anyShort())). -// andReturn(true).anyTimes(); -// expect(mockTopology.isConsistent(EasyMock.anyLong(), -// EasyMock.anyShort(), -// EasyMock.anyLong(), -// EasyMock.anyShort())).andReturn(false). -// anyTimes(); -// expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes(); -// replay(mockTopology); -// -// Date currentDate = new Date(); -// -// // build our expected Device -// Integer ipaddr = IPv4.toIPv4Address("192.168.1.1"); -// Device device = -// new Device(deviceManager, -// new Long(deviceManager.deviceKeyCounter), -// new Entity(Ethernet.toLong(deviceMac), -// (short)5, -// ipaddr, -// 1L, -// 1, -// currentDate), -// DefaultEntityClassifier.entityClass); -// -// // Get the listener and trigger the packet in -// IOFSwitch switch1 = mockFloodlightProvider.getSwitch(1L); -// mockFloodlightProvider.dispatchMessage(switch1, packetIn); -// -// // Verify the replay matched our expectations -// // verify(mockTopology); -// -// // Verify the device -// Device rdevice = (Device) -// deviceManager.findDevice(Ethernet.toLong(deviceMac), -// (short)5, null, null, null); -// -// assertEquals(device, rdevice); -// assertEquals(new Short((short)5), rdevice.getVlanId()[0]); -// -// Device result = null; -// Iterator dstiter = -// deviceManager.queryClassDevices(device.getEntityClass(), -// null, null, ipaddr, -// null, null); -// if (dstiter.hasNext()) { -// result = (Device)dstiter.next(); -// } -// -// assertEquals(device, result); -// -// device = -// new Device(device, -// new Entity(Ethernet.toLong(deviceMac), -// (short)5, -// ipaddr, -// 5L, -// 2, -// currentDate), -// -1); -// -// reset(mockTopology); -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())). -// andReturn(true). -// anyTimes(); -// expect(mockTopology.isConsistent(EasyMock.anyLong(), -// EasyMock.anyShort(), -// EasyMock.anyLong(), -// EasyMock.anyShort())).andReturn(false). -// anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(EasyMock.anyLong(), -// EasyMock.anyShort())) -// .andReturn(false) -// .anyTimes(); -// expect(mockTopology.getL2DomainId(1L)).andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(5L)).andReturn(1L).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(1L, (short)1, 5L, (short)2)). -// andReturn(false).anyTimes(); -// -// // Start recording the replay on the mocks -// replay(mockTopology); -// // Get the listener and trigger the packet in -// IOFSwitch switch5 = mockFloodlightProvider.getSwitch(5L); -// mockFloodlightProvider. -// dispatchMessage(switch5, this.packetIn_1.setInPort((short)2)); -// -// // Verify the replay matched our expectations -// verify(mockTopology); -// -// // Verify the device -// rdevice = (Device) -// deviceManager.findDevice(Ethernet.toLong(deviceMac), -// (short)5, null, null, null); -// assertEquals(device, rdevice); -// } -// -// @Test -// public void testPacketIn() throws Exception { -// byte[] deviceMac1 = -// ((Ethernet)this.testARPReplyPacket_1).getSourceMACAddress(); -// testPacketInBasic(deviceMac1, packetIn_1); -// } -// -// /** -// * This test ensures the device manager learns the source device -// * corresponding to the senderHardwareAddress and senderProtocolAddress -// * in an ARP response whenever the senderHardwareAddress is different -// * from the source MAC address of the Ethernet frame. -// * -// * This test is the same as testPacketIn method, except for the -// * packet-in that's used. -// * @throws Exception -// */ -// @Test -// public void testDeviceLearningFromArpResponseData() throws Exception { -// ARP arp = (ARP)((Ethernet)this.testARPReplyPacket_2).getPayload(); -// byte[] deviceMac2 = arp.getSenderHardwareAddress(); -// -// testPacketInBasic(deviceMac2, packetIn_2); -// } -// -// /** -// * Note: Entity expiration does not result in device moved notification. -// * @throws Exception -// */ -// public void doTestEntityExpiration() throws Exception { -// IDeviceListener mockListener = -// createMock(IDeviceListener.class); -// expect(mockListener.getName()).andReturn("mockListener").anyTimes(); -// expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())). -// andReturn(true).anyTimes(); -// -// expect(mockTopology.isBroadcastDomainPort(1L, (short)1)).andReturn(false).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(5L, (short)1)).andReturn(false).anyTimes(); -// expect(mockTopology.getL2DomainId(1L)).andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(5L)).andReturn(5L).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)1, 5L, (short)1)). -// andReturn(false).anyTimes(); -// -// Date topologyUpdateTime = new Date(); -// expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime). -// anyTimes(); -// -// replay(mockTopology); -// deviceManager.topology = mockTopology; -// -// Calendar c = Calendar.getInstance(); -// Entity entity1 = new Entity(1L, null, 2, 1L, 1, c.getTime()); -// c.add(Calendar.MILLISECOND, -DeviceManagerImpl.ENTITY_TIMEOUT-1); -// Entity entity2 = new Entity(1L, null, 1, 5L, 1, c.getTime()); -// -// deviceManager.learnDeviceByEntity(entity1); -// IDevice d = deviceManager.learnDeviceByEntity(entity2); -// assertArrayEquals(new Integer[] { 1, 2 }, d.getIPv4Addresses()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1), -// new SwitchPort(5L, 1)}, -// d.getAttachmentPoints()); -// Iterator diter = -// deviceManager.queryClassDevices(d.getEntityClass(), -// null, null, 1, null, null); -// assertTrue(diter.hasNext()); -// assertEquals(d.getDeviceKey(), diter.next().getDeviceKey()); -// diter = deviceManager.queryClassDevices(d.getEntityClass(), -// null, null, 2, null, null); -// assertTrue(diter.hasNext()); -// assertEquals(d.getDeviceKey(), diter.next().getDeviceKey()); -// -// replay(mockListener); -// deviceManager.addListener(mockListener); -// verify(mockListener); -// reset(mockListener); -// -// mockListener.deviceIPV4AddrChanged(isA(IDevice.class)); -// replay(mockListener); -// deviceManager.entityCleanupTask.reschedule(0, null); -// -// d = deviceManager.getDevice(d.getDeviceKey()); -// assertArrayEquals(new Integer[] { 2 }, d.getIPv4Addresses()); -// -// // Attachment points are not removed, previous ones are still valid. -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1), -// new SwitchPort(5L, 1) }, -// d.getAttachmentPoints()); -// diter = deviceManager.queryClassDevices(d.getEntityClass(), -// null, null, 2, null, null); -// assertTrue(diter.hasNext()); -// assertEquals(d.getDeviceKey(), diter.next().getDeviceKey()); -// diter = deviceManager.queryClassDevices(d.getEntityClass(), -// null, null, 1, null, null); -// assertFalse(diter.hasNext()); -// -// d = deviceManager.findDevice(1L, null, null, null, null); -// assertArrayEquals(new Integer[] { 2 }, d.getIPv4Addresses()); -// -// // Attachment points are not removed, previous ones are still valid. -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1), -// new SwitchPort(5L, 1) }, -// d.getAttachmentPoints()); -// -// verify(mockListener); -// } -// -// public void doTestDeviceExpiration() throws Exception { -// IDeviceListener mockListener = -// createMock(IDeviceListener.class); -// expect(mockListener.getName()).andReturn("mockListener").anyTimes(); -// expect(mockListener.isCallbackOrderingPostreq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// expect(mockListener.isCallbackOrderingPrereq((String)anyObject(), (String)anyObject())) -// .andReturn(false).atLeastOnce(); -// -// Calendar c = Calendar.getInstance(); -// c.add(Calendar.MILLISECOND, -DeviceManagerImpl.ENTITY_TIMEOUT-1); -// Entity entity1 = new Entity(1L, null, 1, 1L, 1, c.getTime()); -// Entity entity2 = new Entity(1L, null, 2, 5L, 1, c.getTime()); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// deviceManager.topology = mockTopology; -// -// expect(mockTopology.isAttachmentPointPort(EasyMock.anyLong(), -// EasyMock.anyShort())). -// andReturn(true). -// anyTimes(); -// expect(mockTopology.getL2DomainId(1L)).andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(5L)).andReturn(1L).anyTimes(); -// expect(mockTopology.isConsistent(EasyMock.anyLong(), -// EasyMock.anyShort(), -// EasyMock.anyLong(), -// EasyMock.anyShort())).andReturn(false). -// anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(EasyMock.anyLong(), -// EasyMock.anyShort())). -// andReturn(false).anyTimes(); -// replay(mockTopology); -// -// IDevice d = deviceManager.learnDeviceByEntity(entity2); -// d = deviceManager.learnDeviceByEntity(entity1); -// assertArrayEquals(new Integer[] { 1, 2 }, d.getIPv4Addresses()); -// -// replay(mockListener); -// deviceManager.addListener(mockListener); -// verify(mockListener); -// reset(mockListener); -// -// mockListener.deviceRemoved(isA(IDevice.class)); -// replay(mockListener); -// deviceManager.entityCleanupTask.reschedule(0, null); -// -// IDevice r = deviceManager.getDevice(d.getDeviceKey()); -// assertNull(r); -// Iterator diter = -// deviceManager.queryClassDevices(d.getEntityClass(), -// null, null, 1, null, null); -// assertFalse(diter.hasNext()); -// -// r = deviceManager.findDevice(1L, null, null, null, null); -// assertNull(r); -// -// verify(mockListener); -// } -// -// /* -// * A ConcurrentHashMap for devices (deviceMap) that can be used to test -// * code that specially handles concurrent modification situations. In -// * particular, we overwrite values() and will replace / remove all the -// * elements returned by values. -// * -// * The remove flag in the constructor specifies if devices returned by -// * values() should be removed or replaced. -// */ -// protected static class ConcurrentlyModifiedDeviceMap -// extends ConcurrentHashMap { -// private static final long serialVersionUID = 7784938535441180562L; -// protected boolean remove; -// public ConcurrentlyModifiedDeviceMap(boolean remove) { -// super(); -// this.remove = remove; -// } -// -// @Override -// public Collection values() { -// // Get the values from the real map and copy them since -// // the collection returned by values can reflect changed -// Collection devs = new ArrayList(super.values()); -// for (Device d: devs) { -// if (remove) { -// // We remove the device from the underlying map -// super.remove(d.getDeviceKey()); -// } else { -// super.remove(d.getDeviceKey()); -// // We add a different Device instance with the same -// // key to the map. We'll do some hackery so the device -// // is different enough to compare differently in equals -// // but otherwise looks the same. -// // It's ugly but it works. -// // clone entities -// Device newDevice = d; -// for (Entity e: d.getEntities()) { -// Entity newEntity = new Entity (e.macAddress, -// e.vlan, -// e.ipv4Address, -// e.switchDPID, -// e.switchPort, -// e.lastSeenTimestamp); -// if (e.vlan == null) -// newEntity.vlan = (short)1; -// else -// newEntity.vlan = (short)((e.vlan + 1 % 4095)+1); -// newDevice = new Device(newDevice, newEntity, -1); -// } -// assertEquals(false, newDevice.equals(d)); -// super.put(newDevice.getDeviceKey(), newDevice); -// } -// } -// return devs; -// } -// } -// -// @Test -// public void testEntityExpiration() throws Exception { -// doTestEntityExpiration(); -// } -// -// @Test -// public void testDeviceExpiration() throws Exception { -// doTestDeviceExpiration(); -// } -// -// /* Test correct entity cleanup behavior when a concurrent modification -// * occurs. -// */ -// @Test -// public void testEntityExpirationConcurrentModification() throws Exception { -// deviceManager.deviceMap = new ConcurrentlyModifiedDeviceMap(false); -// doTestEntityExpiration(); -// } -// -// /* Test correct entity cleanup behavior when a concurrent remove -// * occurs. -// */ -// @Test -// public void testDeviceExpirationConcurrentRemove() throws Exception { -// deviceManager.deviceMap = new ConcurrentlyModifiedDeviceMap(true); -// doTestDeviceExpiration(); -// } -// -// /* Test correct entity cleanup behavior when a concurrent modification -// * occurs. -// */ -// @Test -// public void testDeviceExpirationConcurrentModification() throws Exception { -// deviceManager.deviceMap = new ConcurrentlyModifiedDeviceMap(false); -// doTestDeviceExpiration(); -// } -// -// -// @Test -// public void testAttachmentPointFlapping() throws Exception { -// Calendar c = Calendar.getInstance(); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())).andReturn(true).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(anyLong(), -// anyShort())). -// andReturn(false).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(), -// anyLong(), anyShort())).andReturn(false).anyTimes(); -// expect(mockTopology.getL2DomainId(anyLong())). -// andReturn(1L).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)1, 1L, (short)1)). -// andReturn(true).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)1, 5L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)1, 10L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(5L, (short)1, 10L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(10L, (short)1, 1L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(5L, (short)1, 1L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(10L, (short)1, 5L, (short)1)). -// andReturn(false).anyTimes(); -// -// Date topologyUpdateTime = new Date(); -// expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime). -// anyTimes(); -// -// -// replay(mockTopology); -// deviceManager.topology = mockTopology; -// -// Entity entity1 = new Entity(1L, null, null, 1L, 1, c.getTime()); -// Entity entity1a = new Entity(1L, null, 1, 1L, 1, c.getTime()); -// Entity entity2 = new Entity(1L, null, null, 5L, 1, c.getTime()); -// Entity entity3 = new Entity(1L, null, null, 10L, 1, c.getTime()); -// entity1.setLastSeenTimestamp(c.getTime()); -// c.add(Calendar.MILLISECOND, Entity.ACTIVITY_TIMEOUT/2); -// entity1a.setLastSeenTimestamp(c.getTime()); -// c.add(Calendar.MILLISECOND, 1); -// entity2.setLastSeenTimestamp(c.getTime()); -// c.add(Calendar.MILLISECOND, 1); -// entity3.setLastSeenTimestamp(c.getTime()); -// -// -// -// IDevice d; -// d = deviceManager.learnDeviceByEntity(entity1); -// d = deviceManager.learnDeviceByEntity(entity1a); -// d = deviceManager.learnDeviceByEntity(entity2); -// d = deviceManager.learnDeviceByEntity(entity3); -// -// // all entities are active, so entity3 should win -// assertArrayEquals(new SwitchPort[] { new SwitchPort(10L, 1) }, -// d.getAttachmentPoints()); -// -// assertArrayEquals(new SwitchPort[] { new SwitchPort(10L, 1),}, -// d.getAttachmentPoints(true)); -// -// c.add(Calendar.MILLISECOND, Entity.ACTIVITY_TIMEOUT/4); -// entity1.setLastSeenTimestamp(c.getTime()); -// d = deviceManager.learnDeviceByEntity(entity1); -// -// // all are still active; entity3 should still win -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, -// d.getAttachmentPoints()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1), -// new SwitchPort(5L, 1, -// ErrorStatus.DUPLICATE_DEVICE), -// new SwitchPort(10L, 1, -// ErrorStatus.DUPLICATE_DEVICE) }, -// d.getAttachmentPoints(true)); -// -// c.add(Calendar.MILLISECOND, Entity.ACTIVITY_TIMEOUT+2000); -// entity1.setLastSeenTimestamp(c.getTime()); -// d = deviceManager.learnDeviceByEntity(entity1); -// -// assertEquals(entity1.getActiveSince(), entity1.getLastSeenTimestamp()); -// // entity1 should now be the only active entity -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, -// d.getAttachmentPoints()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1) }, -// d.getAttachmentPoints(true)); -// } -// -// -// @Test -// public void testAttachmentPointFlappingTwoCluster() throws Exception { -// Calendar c = Calendar.getInstance(); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())).andReturn(true).anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(anyLong(), -// anyShort())). -// andReturn(false).anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(anyLong(), anyShort(), -// anyLong(), anyShort())).andReturn(false).anyTimes(); -// expect(mockTopology.getL2DomainId(1L)). -// andReturn(1L).anyTimes(); -// expect(mockTopology.getL2DomainId(5L)). -// andReturn(5L).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)1, 1L, (short)2)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)2, 5L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(5L, (short)1, 5L, (short)2)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)2, 1L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)1, 5L, (short)1)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(1L, (short)1, 5L, (short)2)). -// andReturn(false).anyTimes(); -// expect(mockTopology.isConsistent(5L, (short)2, 5L, (short)1)). -// andReturn(false).anyTimes(); -// -// Date topologyUpdateTime = new Date(); -// expect(mockTopology.getLastUpdateTime()).andReturn(topologyUpdateTime). -// anyTimes(); -// -// replay(mockTopology); -// deviceManager.topology = mockTopology; -// -// Entity entity1 = new Entity(1L, null, null, 1L, 1, c.getTime()); -// Entity entity2 = new Entity(1L, null, null, 1L, 2, c.getTime()); -// Entity entity3 = new Entity(1L, null, null, 5L, 1, c.getTime()); -// Entity entity4 = new Entity(1L, null, null, 5L, 2, c.getTime()); -// entity1.setLastSeenTimestamp(c.getTime()); -// c.add(Calendar.MILLISECOND, Entity.ACTIVITY_TIMEOUT/2); -// c.add(Calendar.MILLISECOND, 1); -// entity2.setLastSeenTimestamp(c.getTime()); -// c.add(Calendar.MILLISECOND, 1); -// entity3.setLastSeenTimestamp(c.getTime()); -// c.add(Calendar.MILLISECOND, 1); -// entity4.setLastSeenTimestamp(c.getTime()); -// -// deviceManager.learnDeviceByEntity(entity1); -// deviceManager.learnDeviceByEntity(entity2); -// deviceManager.learnDeviceByEntity(entity3); -// IDevice d = deviceManager.learnDeviceByEntity(entity4); -// -// // all entities are active, so entities 2,4 should win -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 2), -// new SwitchPort(5L, 2) }, -// d.getAttachmentPoints()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 2), -// new SwitchPort(5L, 2)}, -// d.getAttachmentPoints(true)); -// -// c.add(Calendar.MILLISECOND, 1); -// entity1.setLastSeenTimestamp(c.getTime()); -// d = deviceManager.learnDeviceByEntity(entity1); -// -// // all entities are active, so entities 2,4 should win -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1), -// new SwitchPort(5L, 2) }, -// d.getAttachmentPoints()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1), -// new SwitchPort(5L, 2), -// new SwitchPort(1L, 2, ErrorStatus.DUPLICATE_DEVICE)}, -// d.getAttachmentPoints(true)); -// -// c.add(Calendar.MILLISECOND, Entity.ACTIVITY_TIMEOUT+1); -// entity1.setLastSeenTimestamp(c.getTime()); -// d = deviceManager.learnDeviceByEntity(entity1); -// -// // entities 3,4 are still in conflict, but 1 should be resolved -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1), -// new SwitchPort(5L, 2) }, -// d.getAttachmentPoints()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1), -// new SwitchPort(5L, 2)}, -// d.getAttachmentPoints(true)); -// -// entity3.setLastSeenTimestamp(c.getTime()); -// d = deviceManager.learnDeviceByEntity(entity3); -// -// // no conflicts, 1 and 3 will win -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1), -// new SwitchPort(5L, 1) }, -// d.getAttachmentPoints()); -// assertArrayEquals(new SwitchPort[] { new SwitchPort(1L, 1), -// new SwitchPort(5L, 1) }, -// d.getAttachmentPoints(true)); -// -// } -// -// protected void doTestDeviceQuery() throws Exception { -// Entity entity1 = new Entity(1L, (short)1, 1, 1L, 1, new Date()); -// Entity entity2 = new Entity(2L, (short)2, 2, 1L, 2, new Date()); -// Entity entity3 = new Entity(3L, (short)3, 3, 5L, 1, new Date()); -// Entity entity4 = new Entity(4L, (short)4, 3, 5L, 2, new Date()); -// Entity entity5 = new Entity(1L, (short)4, 3, 5L, 2, new Date()); -// -// Device d1 = deviceManager.learnDeviceByEntity(entity1); -// deviceManager.learnDeviceByEntity(entity2); -// Device d3 = deviceManager.learnDeviceByEntity(entity3); -// Device d4 = deviceManager.learnDeviceByEntity(entity4); -// -// IDevice d; -// -// Iterator iter = -// deviceManager.queryDevices(null, (short)1, 1, null, null); -// int count = 0; -// while (iter.hasNext()) { -// count += 1; -// d = iter.next(); -// assertEquals(d1.getDeviceKey(), d.getDeviceKey()); -// } -// assertEquals(1, count); -// -// iter = deviceManager.queryDevices(null, (short)3, 3, null, null); -// count = 0; -// while (iter.hasNext()) { -// count += 1; -// d = iter.next(); -// assertEquals(d3.getDeviceKey(), d.getDeviceKey()); -// } -// assertEquals(1, count); -// -// iter = deviceManager.queryDevices(null, (short)1, 3, null, null); -// count = 0; -// while (iter.hasNext()) { -// count += 1; -// iter.next(); -// } -// assertEquals(0, count); -// -// Device d5 = deviceManager.learnDeviceByEntity(entity5); -// iter = deviceManager.queryDevices(null, (short)4, 3, null, null); -// count = 0; -// Set deviceKeysFromIterator = new HashSet(); -// while (iter.hasNext()) { -// count += 1; -// d = iter.next(); -// deviceKeysFromIterator.add(d.getDeviceKey()); -// } -// Set expectedDeviceKeys = new HashSet(); -// expectedDeviceKeys.add(d4.getDeviceKey()); -// expectedDeviceKeys.add(d5.getDeviceKey()); -// assertEquals(expectedDeviceKeys, deviceKeysFromIterator); -// assertEquals(2, count); -// -// -// iter = deviceManager.queryDevices(1L, null, null, null, null); -// count = 0; -// deviceKeysFromIterator = new HashSet(); -// while (iter.hasNext()) { -// count += 1; -// d = iter.next(); -// deviceKeysFromIterator.add(d.getDeviceKey()); -// } -// expectedDeviceKeys = new HashSet(); -// expectedDeviceKeys.add(d1.getDeviceKey()); -// expectedDeviceKeys.add(d5.getDeviceKey()); -// assertEquals(expectedDeviceKeys, deviceKeysFromIterator); -// assertEquals(2, count); -// } -// -// @Test -// public void testDeviceIndex() throws Exception { -// EnumSet indexFields = -// EnumSet.noneOf(IDeviceService.DeviceField.class); -// indexFields.add(IDeviceService.DeviceField.IPV4); -// indexFields.add(IDeviceService.DeviceField.VLAN); -// deviceManager.addIndex(false, indexFields); -// -// indexFields = EnumSet.noneOf(IDeviceService.DeviceField.class); -// deviceManager.addIndex(false, indexFields); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// deviceManager.topology = mockTopology; -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())). -// andReturn(true).anyTimes(); -// expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes(); -// replay(mockTopology); -// doTestDeviceQuery(); -// } -// -// @Test -// public void testDeviceQuery() throws Exception { -// ITopologyService mockTopology = createMock(ITopologyService.class); -// deviceManager.topology = mockTopology; -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())). -// andReturn(true).anyTimes(); -// expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes(); -// replay(mockTopology); -// -// doTestDeviceQuery(); -// } -// -// protected void doTestDeviceClassQuery() throws Exception { -// Entity entity1 = new Entity(1L, (short)1, 1, 1L, 1, new Date()); -// Entity entity2 = new Entity(2L, (short)2, 2, 1L, 2, new Date()); -// Entity entity3 = new Entity(3L, (short)3, 3, 5L, 1, new Date()); -// Entity entity4 = new Entity(4L, (short)4, 3, 5L, 2, new Date()); -// Entity entity5 = new Entity(1L, (short)4, 3, 5L, 2, new Date()); -// -// IDevice d1 = deviceManager.learnDeviceByEntity(entity1); -// IDevice d2 = deviceManager.learnDeviceByEntity(entity2); -// IDevice d3 = deviceManager.learnDeviceByEntity(entity3); -// IDevice d4 = deviceManager.learnDeviceByEntity(entity4); -// assertEquals(d1.getEntityClass(), d2.getEntityClass()); -// assertEquals(d1.getEntityClass(), d3.getEntityClass()); -// assertEquals(d1.getEntityClass(), d4.getEntityClass()); -// -// IDevice d; -// -// Iterator iter = -// deviceManager.queryClassDevices(d1.getEntityClass(), null, -// (short)1, 1, null, null); -// int count = 0; -// while (iter.hasNext()) { -// count += 1; -// d = iter.next(); -// assertEquals(d1.getDeviceKey(), d.getDeviceKey()); -// } -// assertEquals(1, count); -// -// iter = deviceManager.queryClassDevices(d1.getEntityClass(), null, -// (short)3, 3, null, null); -// count = 0; -// while (iter.hasNext()) { -// count += 1; -// d = iter.next(); -// assertEquals(d3.getDeviceKey(), d.getDeviceKey()); -// -// } -// assertEquals(1, count); -// -// iter = deviceManager.queryClassDevices(d1.getEntityClass(), null, -// (short)1, 3, null, null); -// count = 0; -// while (iter.hasNext()) { -// count += 1; -// iter.next(); -// } -// assertEquals(0, count); -// -// IDevice d5 = deviceManager.learnDeviceByEntity(entity5); -// assertEquals(d1.getEntityClass(), d5.getEntityClass()); -// iter = deviceManager.queryClassDevices(d1.getEntityClass(), null, -// (short)4, 3, null, null); -// count = 0; -// Set deviceKeysFromIterator = new HashSet(); -// while (iter.hasNext()) { -// count += 1; -// d = iter.next(); -// deviceKeysFromIterator.add(d.getDeviceKey()); -// } -// Set expectedDeviceKeys = new HashSet(); -// expectedDeviceKeys.add(d4.getDeviceKey()); -// expectedDeviceKeys.add(d5.getDeviceKey()); -// assertEquals(expectedDeviceKeys, deviceKeysFromIterator); -// assertEquals(2, count); -// } -// -// @Test -// public void testDeviceClassIndex() throws Exception { -// EnumSet indexFields = -// EnumSet.noneOf(IDeviceService.DeviceField.class); -// indexFields.add(IDeviceService.DeviceField.IPV4); -// indexFields.add(IDeviceService.DeviceField.VLAN); -// deviceManager.addIndex(true, indexFields); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// deviceManager.topology = mockTopology; -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())). -// andReturn(true).anyTimes(); -// expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes(); -// replay(mockTopology); -// -// doTestDeviceClassQuery(); -// } -// -// @Test -// public void testDeviceClassQuery() throws Exception { -// ITopologyService mockTopology = createMock(ITopologyService.class); -// deviceManager.topology = mockTopology; -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())). -// andReturn(true).anyTimes(); -// expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes(); -// replay(mockTopology); -// -// doTestDeviceClassQuery(); -// } -// -// @Test -// public void testFindDevice() throws FloodlightModuleException { -// boolean exceptionCaught; -// deviceManager.entityClassifier= new MockEntityClassifierMac(); -// deviceManager.startUp(null); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// deviceManager.topology = mockTopology; -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())). -// andReturn(true).anyTimes(); -// expect(mockTopology.getL2DomainId(EasyMock.anyLong())).andReturn(1L).anyTimes(); -// replay(mockTopology); -// -// Entity entity1 = new Entity(1L, (short)1, 1, 1L, 1, new Date()); -// Entity entity2 = new Entity(2L, (short)2, 2, 1L, 2, new Date()); -// Entity entity2b = new Entity(22L, (short)2, 2, 1L, 2, new Date()); -// -// Entity entity3 = new Entity(3L, (short)1, 3, 2L, 1, new Date()); -// Entity entity4 = new Entity(4L, (short)2, 4, 2L, 2, new Date()); -// -// Entity entity5 = new Entity(5L, (short)1, 5, 3L, 1, new Date()); -// -// -// IDevice d1 = deviceManager.learnDeviceByEntity(entity1); -// IDevice d2 = deviceManager.learnDeviceByEntity(entity2); -// IDevice d3 = deviceManager.learnDeviceByEntity(entity3); -// IDevice d4 = deviceManager.learnDeviceByEntity(entity4); -// IDevice d5 = deviceManager.learnDeviceByEntity(entity5); -// -// // Make sure the entity classifier worked as expected -// assertEquals(MockEntityClassifierMac.testECMac1, d1.getEntityClass()); -// assertEquals(MockEntityClassifierMac.testECMac1, d2.getEntityClass()); -// assertEquals(MockEntityClassifierMac.testECMac2, d3.getEntityClass()); -// assertEquals(MockEntityClassifierMac.testECMac2, d4.getEntityClass()); -// assertEquals(DefaultEntityClassifier.entityClass, -// d5.getEntityClass()); -// -// // Look up the device using findDevice() which uses only the primary -// // index -// assertEquals(d1, deviceManager.findDevice(entity1.getMacAddress(), -// entity1.getVlan(), -// entity1.getIpv4Address(), -// entity1.getSwitchDPID(), -// entity1.getSwitchPort())); -// // port changed. Device will be found through class index -// assertEquals(d1, deviceManager.findDevice(entity1.getMacAddress(), -// entity1.getVlan(), -// entity1.getIpv4Address(), -// entity1.getSwitchDPID(), -// entity1.getSwitchPort()+1)); -// // VLAN changed. No device matches -// assertEquals(null, deviceManager.findDevice(entity1.getMacAddress(), -// (short)42, -// entity1.getIpv4Address(), -// entity1.getSwitchDPID(), -// entity1.getSwitchPort())); -// assertEquals(null, deviceManager.findDevice(entity1.getMacAddress(), -// null, -// entity1.getIpv4Address(), -// entity1.getSwitchDPID(), -// entity1.getSwitchPort())); -// assertEquals(d2, deviceManager.findDeviceByEntity(entity2)); -// assertEquals(null, deviceManager.findDeviceByEntity(entity2b)); -// assertEquals(d3, deviceManager.findDevice(entity3.getMacAddress(), -// entity3.getVlan(), -// entity3.getIpv4Address(), -// entity3.getSwitchDPID(), -// entity3.getSwitchPort())); -// // switch and port not set. throws exception -// exceptionCaught = false; -// try { -// assertEquals(null, deviceManager.findDevice(entity3.getMacAddress(), -// entity3.getVlan(), -// entity3.getIpv4Address(), -// null, -// null)); -// } -// catch (IllegalArgumentException e) { -// exceptionCaught = true; -// } -// if (!exceptionCaught) -// fail("findDevice() did not throw IllegalArgumentException"); -// assertEquals(d4, deviceManager.findDeviceByEntity(entity4)); -// assertEquals(d5, deviceManager.findDevice(entity5.getMacAddress(), -// entity5.getVlan(), -// entity5.getIpv4Address(), -// entity5.getSwitchDPID(), -// entity5.getSwitchPort())); -// // switch and port not set. throws exception (swith/port are key -// // fields of IEntityClassifier but not d5.entityClass -// exceptionCaught = false; -// try { -// assertEquals(d5, deviceManager.findDevice(entity5.getMacAddress(), -// entity5.getVlan(), -// entity5.getIpv4Address(), -// null, -// null)); -// } -// catch (IllegalArgumentException e) { -// exceptionCaught = true; -// } -// if (!exceptionCaught) -// fail("findDevice() did not throw IllegalArgumentException"); -// -// -// Entity entityNoClass = new Entity(5L, (short)1, 5, -1L, 1, new Date()); -// assertEquals(null, deviceManager.findDeviceByEntity(entityNoClass)); -// -// -// // Now look up destination devices -// assertEquals(d1, deviceManager.findClassDevice(d2.getEntityClass(), -// entity1.getMacAddress(), -// entity1.getVlan(), -// entity1.getIpv4Address())); -// assertEquals(d1, deviceManager.findClassDevice(d2.getEntityClass(), -// entity1.getMacAddress(), -// entity1.getVlan(), -// null)); -// assertEquals(null, deviceManager.findClassDevice(d2.getEntityClass(), -// entity1.getMacAddress(), -// (short) -1, -// 0)); -// } -// -// -// -// @Test -// public void testGetIPv4Addresses() { -// // Looks like Date is only 1s granularity -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// deviceManager.topology = mockTopology; -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())). -// andReturn(true).anyTimes(); -// expect(mockTopology.getL2DomainId(anyLong())).andReturn(1L).anyTimes(); -// expect(mockTopology.isConsistent(EasyMock.anyLong(), -// EasyMock.anyShort(), -// EasyMock.anyLong(), -// EasyMock.anyShort())) -// .andReturn(false) -// .anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(EasyMock.anyLong(), -// EasyMock.anyShort())) -// .andReturn(false) -// .anyTimes(); -// expect(mockTopology.isInSameBroadcastDomain(EasyMock.anyLong(), -// EasyMock.anyShort(), -// EasyMock.anyLong(), -// EasyMock.anyShort())). -// andReturn(false).anyTimes(); -// replay(mockTopology); -// -// Entity e1 = new Entity(1L, (short)1, null, null, null, new Date(2000)); -// Device d1 = deviceManager.learnDeviceByEntity(e1); -// assertArrayEquals(new Integer[0], d1.getIPv4Addresses()); -// -// -// Entity e2 = new Entity(2L, (short)2, 2, null, null, new Date(2000)); -// Device d2 = deviceManager.learnDeviceByEntity(e2); -// d2 = deviceManager.learnDeviceByEntity(e2); -// assertArrayEquals(new Integer[] { 2 }, d2.getIPv4Addresses()); -// // More than one entity -// Entity e2b = new Entity(2L, (short)2, null, 2L, 2, new Date(3000)); -// d2 = deviceManager.learnDeviceByEntity(e2b); -// assertEquals(2, d2.entities.length); -// assertArrayEquals(new Integer[] { 2 }, d2.getIPv4Addresses()); -// // and now add an entity with an IP -// Entity e2c = new Entity(2L, (short)2, 2, 2L, 3, new Date(3000)); -// d2 = deviceManager.learnDeviceByEntity(e2c); -// assertArrayEquals(new Integer[] { 2 }, d2.getIPv4Addresses()); -// assertEquals(3, d2.entities.length); -// -// // Other devices with different IPs shouldn't interfere -// Entity e3 = new Entity(3L, (short)3, 3, null, null, new Date(4000)); -// Entity e3b = new Entity(3L, (short)3, 3, 3L, 3, new Date(4400)); -// Device d3 = deviceManager.learnDeviceByEntity(e3); -// d3 = deviceManager.learnDeviceByEntity(e3b); -// assertArrayEquals(new Integer[] { 2 }, d2.getIPv4Addresses()); -// assertArrayEquals(new Integer[] { 3 }, d3.getIPv4Addresses()); -// -// // Add another IP to d3 -// Entity e3c = new Entity(3L, (short)3, 33, 3L, 3, new Date(4400)); -// d3 = deviceManager.learnDeviceByEntity(e3c); -// Integer[] ips = d3.getIPv4Addresses(); -// Arrays.sort(ips); -// assertArrayEquals(new Integer[] { 3, 33 }, ips); -// -// // Add another device that also claims IP2 but is older than e2 -// Entity e4 = new Entity(4L, (short)4, 2, null, null, new Date(1000)); -// Entity e4b = new Entity(4L, (short)4, null, 4L, 4, new Date(1000)); -// Device d4 = deviceManager.learnDeviceByEntity(e4); -// assertArrayEquals(new Integer[] { 2 }, d2.getIPv4Addresses()); -// assertArrayEquals(new Integer[0], d4.getIPv4Addresses()); -// // add another entity to d4 -// d4 = deviceManager.learnDeviceByEntity(e4b); -// assertArrayEquals(new Integer[0], d4.getIPv4Addresses()); -// -// // Make e4 and e4a newer -// Entity e4c = new Entity(4L, (short)4, 2, null, null, new Date(5000)); -// Entity e4d = new Entity(4L, (short)4, null, 4L, 5, new Date(5000)); -// d4 = deviceManager.learnDeviceByEntity(e4c); -// d4 = deviceManager.learnDeviceByEntity(e4d); -// assertArrayEquals(new Integer[0], d2.getIPv4Addresses()); -// // FIXME: d4 should not return IP4 -// assertArrayEquals(new Integer[] { 2 }, d4.getIPv4Addresses()); -// -// // Add another newer entity to d2 but with different IP -// Entity e2d = new Entity(2L, (short)2, 22, 4L, 6, new Date(6000)); -// d2 = deviceManager.learnDeviceByEntity(e2d); -// assertArrayEquals(new Integer[] { 22 }, d2.getIPv4Addresses()); -// assertArrayEquals(new Integer[] { 2 }, d4.getIPv4Addresses()); -// -// // new IP for d2,d4 but with same timestamp. Both devices get the IP -// Entity e2e = new Entity(2L, (short)2, 42, 2L, 4, new Date(7000)); -// d2 = deviceManager.learnDeviceByEntity(e2e); -// ips= d2.getIPv4Addresses(); -// Arrays.sort(ips); -// assertArrayEquals(new Integer[] { 22, 42 }, ips); -// Entity e4e = new Entity(4L, (short)4, 42, 4L, 7, new Date(7000)); -// d4 = deviceManager.learnDeviceByEntity(e4e); -// ips= d4.getIPv4Addresses(); -// Arrays.sort(ips); -// assertArrayEquals(new Integer[] { 2, 42 }, ips); -// -// // add a couple more IPs -// Entity e2f = new Entity(2L, (short)2, 4242, 2L, 5, new Date(8000)); -// d2 = deviceManager.learnDeviceByEntity(e2f); -// ips= d2.getIPv4Addresses(); -// Arrays.sort(ips); -// assertArrayEquals(new Integer[] { 22, 42, 4242 }, ips); -// Entity e4f = new Entity(4L, (short)4, 4242, 4L, 8, new Date(9000)); -// d4 = deviceManager.learnDeviceByEntity(e4f); -// ips= d4.getIPv4Addresses(); -// Arrays.sort(ips); -// assertArrayEquals(new Integer[] { 2, 42, 4242 }, ips); -// } -// -// // TODO: this test should really go into a separate class that collects -// // unit tests for Device -// @Test -// public void testGetSwitchPortVlanId() { -// Entity entity1 = new Entity(1L, (short)1, null, 10L, 1, new Date()); -// Entity entity2 = new Entity(1L, null, null, 10L, 1, new Date()); -// Entity entity3 = new Entity(1L, (short)3, null, 1L, 1, new Date()); -// Entity entity4 = new Entity(1L, (short)42, null, 1L, 1, new Date()); -// Entity[] entities = new Entity[] { entity1, entity2, -// entity3, entity4 -// }; -// Device d = new Device(null,1L, null, null, null, -// Arrays.asList(entities), null); -// SwitchPort swp1x1 = new SwitchPort(1L, 1); -// SwitchPort swp1x2 = new SwitchPort(1L, 2); -// SwitchPort swp2x1 = new SwitchPort(2L, 1); -// SwitchPort swp10x1 = new SwitchPort(10L, 1); -// assertArrayEquals(new Short[] { -1, 1}, -// d.getSwitchPortVlanIds(swp10x1)); -// assertArrayEquals(new Short[] { 3, 42}, -// d.getSwitchPortVlanIds(swp1x1)); -// assertArrayEquals(new Short[0], -// d.getSwitchPortVlanIds(swp1x2)); -// assertArrayEquals(new Short[0], -// d.getSwitchPortVlanIds(swp2x1)); -// } -// -// @Test -// public void testReclassifyDevice() throws FloodlightModuleException { -// MockFlexEntityClassifier flexClassifier = -// new MockFlexEntityClassifier(); -// deviceManager.entityClassifier= flexClassifier; -// deviceManager.startUp(null); -// -// ITopologyService mockTopology = createMock(ITopologyService.class); -// deviceManager.topology = mockTopology; -// expect(mockTopology.isAttachmentPointPort(anyLong(), -// anyShort())). -// andReturn(true).anyTimes(); -// expect(mockTopology.getL2DomainId(anyLong())).andReturn(1L).anyTimes(); -// expect(mockTopology.isConsistent(EasyMock.anyLong(), -// EasyMock.anyShort(), -// EasyMock.anyLong(), -// EasyMock.anyShort())) -// .andReturn(false) -// .anyTimes(); -// expect(mockTopology.isBroadcastDomainPort(EasyMock.anyLong(), -// EasyMock.anyShort())) -// .andReturn(false) -// .anyTimes(); -// replay(mockTopology); -// -// //flexClassifier.createTestEntityClass("Class1"); -// -// Entity entity1 = new Entity(1L, (short)1, 1, 1L, 1, new Date()); -// Entity entity1b = new Entity(1L, (short)2, 1, 1L, 1, new Date()); -// Entity entity2 = new Entity(2L, (short)1, 2, 2L, 2, new Date()); -// Entity entity2b = new Entity(2L, (short)2, 2, 2L, 2, new Date()); -// -// -// Device d1 = deviceManager.learnDeviceByEntity(entity1); -// Device d2 = deviceManager.learnDeviceByEntity(entity2); -// Device d1b = deviceManager.learnDeviceByEntity(entity1b); -// Device d2b = deviceManager.learnDeviceByEntity(entity2b); -// -// d1 = deviceManager.getDeviceIteratorForQuery(entity1.getMacAddress(), -// entity1.getVlan(), entity1.getIpv4Address(), -// entity1.getSwitchDPID(), entity1.getSwitchPort()) -// .next(); -// d1b = deviceManager.getDeviceIteratorForQuery(entity1b.getMacAddress(), -// entity1b.getVlan(), entity1b.getIpv4Address(), -// entity1b.getSwitchDPID(), entity1b.getSwitchPort()).next(); -// -// assertEquals(d1, d1b); -// -// d2 = deviceManager.getDeviceIteratorForQuery(entity2.getMacAddress(), -// entity2.getVlan(), entity2.getIpv4Address(), -// entity2.getSwitchDPID(), entity2.getSwitchPort()).next(); -// d2b = deviceManager.getDeviceIteratorForQuery(entity2b.getMacAddress(), -// entity2b.getVlan(), entity2b.getIpv4Address(), -// entity2b.getSwitchDPID(), entity2b.getSwitchPort()).next(); -// assertEquals(d2, d2b); -// -// IEntityClass eC1 = flexClassifier.createTestEntityClass("C1"); -// IEntityClass eC2 = flexClassifier.createTestEntityClass("C2"); -// -// flexClassifier.addVlanEntities((short)1, eC1); -// flexClassifier.addVlanEntities((short)2, eC1); -// -// deviceManager.reclassifyDevice(d1); -// deviceManager.reclassifyDevice(d2); -// -// d1 = deviceManager.deviceMap.get( -// deviceManager.primaryIndex.findByEntity(entity1)); -// d1b = deviceManager.deviceMap.get( -// deviceManager.primaryIndex.findByEntity(entity1b)); -// -// assertEquals(d1, d1b); -// -// d2 = deviceManager.deviceMap.get( -// deviceManager.primaryIndex.findByEntity(entity2)); -// d2b = deviceManager.deviceMap.get( -// deviceManager.primaryIndex.findByEntity(entity2b)); -// -// assertEquals(d2, d2b); -// -// flexClassifier.addVlanEntities((short)1, eC2); -// -// deviceManager.reclassifyDevice(d1); -// deviceManager.reclassifyDevice(d2); -// d1 = deviceManager.deviceMap.get( -// deviceManager.primaryIndex.findByEntity(entity1)); -// d1b = deviceManager.deviceMap.get( -// deviceManager.primaryIndex.findByEntity(entity1b)); -// d2 = deviceManager.deviceMap.get( -// deviceManager.primaryIndex.findByEntity(entity2)); -// d2b = deviceManager.deviceMap.get( -// deviceManager.primaryIndex.findByEntity(entity2b)); -// -// assertNotSame(d1, d1b); -// -// assertNotSame(d2, d2b); -// -// flexClassifier.addVlanEntities((short)1, eC1); -// deviceManager.reclassifyDevice(d1); -// deviceManager.reclassifyDevice(d2); -// ClassState classState = deviceManager.classStateMap.get(eC1.getName()); -// -// Long deviceKey1 = null; -// Long deviceKey1b = null; -// Long deviceKey2 = null; -// Long deviceKey2b = null; -// -// deviceKey1 = -// classState.classIndex.findByEntity(entity1); -// deviceKey1b = -// classState.classIndex.findByEntity(entity1b); -// deviceKey2 = -// classState.classIndex.findByEntity(entity2); -// deviceKey2b = -// classState.classIndex.findByEntity(entity2b); -// -// assertEquals(deviceKey1, deviceKey1b); -// -// assertEquals(deviceKey2, deviceKey2b); -// } -// -// @Test -// public void testSyncEntity() { -// Date d1 = new Date(); -// Date d2 = new Date(0); -// Entity e1 = new Entity(1L, (short)2, 3, 4L, 5, d1); -// e1.setActiveSince(d2); -// SyncEntity se1 = new SyncEntity(e1); -// assertEntityEquals(e1, se1); -// assertEquals(1L, se1.macAddress); -// assertEquals(Short.valueOf((short)2), se1.vlan); -// assertEquals(Integer.valueOf(3), se1.ipv4Address); -// assertEquals(Long.valueOf(4L), se1.switchDPID); -// assertEquals(Integer.valueOf(5), se1.switchPort); -// assertEquals(d1, se1.lastSeenTimestamp); -// assertEquals(d2, se1.activeSince); -// assertNotSame(d1, se1.lastSeenTimestamp); -// assertNotSame(d2, se1.activeSince); -// -// Entity e2 = new Entity(42L, null, null, null, null, null); -// SyncEntity se2 = new SyncEntity(e2); -// assertEntityEquals(e2, se2); -// -// SyncEntity se3 = new SyncEntity(); -// SyncEntity se4 = new SyncEntity(); -// se3.lastSeenTimestamp = new Date(1000); -// se4.lastSeenTimestamp = new Date(2000); -// assertTrue("", se3.compareTo(se4) < 0); -// assertTrue("", se4.compareTo(se3) > 0); -// se4.lastSeenTimestamp = new Date(1000); -// assertTrue("", se3.compareTo(se4) == 0); -// assertTrue("", se4.compareTo(se3) == 0); -// se4.lastSeenTimestamp = new Date(500); -// assertTrue("", se3.compareTo(se4) > 0); -// assertTrue("", se4.compareTo(se3) < 0); -// } -// -// /* Test basic DeviceSyncRepresentation behavior */ -// @Test -// public void testDeviceSyncRepresentationBasics() { -// DeviceSyncRepresentation dsr = new DeviceSyncRepresentation(); -// assertNull(dsr.getKey()); -// assertNull(dsr.getEntities()); -// dsr.setKey("MyKey"); -// assertEquals("MyKey", dsr.getKey()); -// assertEquals("MyKey", dsr.toString()); -// -// List entities = new ArrayList(); -// Entity e1a = new Entity(1L, (short)2, 3, 4L, 5, new Date(1000)); -// Entity e1b = new Entity(1L, (short)2, null, 4L, 5, new Date(0)); -// entities.add(new SyncEntity(e1a)); -// entities.add(new SyncEntity(e1b)); -// // e1b comes before e1 (lastSeen) but we add it after it to test -// // sorting -// dsr.setEntities(entities); -// -// assertEquals(2, dsr.getEntities().size()); -// // e1b has earlier time -// assertEquals(e1b, dsr.getEntities().get(0).asEntity()); -// assertEquals(e1a, dsr.getEntities().get(1).asEntity()); -// -// dsr.setKey(null); -// dsr.setEntities(null); -// assertNull(dsr.getKey()); -// assertNull(dsr.getEntities()); -// } -// -// @Test -// public void testDeviceSyncRepresentationFromDevice() { -// ITopologyService mockTopology = makeMockTopologyAllPortsAp(); -// replay(mockTopology); -// deviceManager.topology = mockTopology; -// -// deviceManager.entityClassifier = new MockEntityClassifier(); -// -// //************************************** -// // Test 1: a single entity -// Entity e1 = new Entity(1L, (short)2, 3, 4L, 5, new Date(1000)); -// Device d1 = deviceManager.learnDeviceByEntity(e1); -// assertEquals("Sanity check failed. Device doesn't have the expected " + -// "entity class. Something with the test setup is strange", -// "DefaultEntityClass", d1.getEntityClass().getName()); -// assertEquals("Sanity check failed. Device doesn't have the expected " + -// "entity class. Something with the test setup is strange", -// EnumSet.of(DeviceField.MAC, DeviceField.VLAN), -// d1.getEntityClass().getKeyFields()); -// -// Long deviceKey = d1.getDeviceKey(); -// DeviceSyncRepresentation dsr1 = new DeviceSyncRepresentation(d1); -// assertEquals("DefaultEntityClass::00:00:00:00:00:01::[2]::", -// dsr1.getKey()); -// assertEquals(1, dsr1.getEntities().size()); -// assertEquals(e1, dsr1.getEntities().get(0).asEntity()); -// -// //************************************** -// // Test 1b: same device, now with a second entity (no IP). -// // this second entity has a lastSeen time that is earlier than the -// // first entity -// Entity e1b = new Entity(1L, (short)2, null, 4L, 5, new Date(0)); -// d1 = deviceManager.learnDeviceByEntity(e1b); -// assertEquals("Sanity check failed. Should still be same device but " + -// "deviceKeys differs", deviceKey, d1.getDeviceKey()); -// dsr1 = new DeviceSyncRepresentation(d1); -// assertEquals("DefaultEntityClass::00:00:00:00:00:01::[2]::", -// dsr1.getKey()); -// assertEquals(2, dsr1.getEntities().size()); -// // Entities are ordered by their lastSeen time. e1b should come -// // before e1. -// assertEquals(e1, dsr1.getEntities().get(1).asEntity()); -// assertEquals(e1b, dsr1.getEntities().get(0).asEntity()); -// -// //************************************** -// // Test 1c: same device with a third entity that does not have a -// // switch port. It should be added to the DeviceSyncRepresentation -// Entity e1c = new Entity(1L, (short)2, 33, null, null, new Date(2000)); -// d1 = deviceManager.learnDeviceByEntity(e1c); -// assertEquals("Sanity check failed. Should still be same device but " + -// "deviceKeys differs", deviceKey, d1.getDeviceKey()); -// dsr1 = new DeviceSyncRepresentation(d1); -// assertEquals("DefaultEntityClass::00:00:00:00:00:01::[2]::", -// dsr1.getKey()); -// assertEquals(3, dsr1.getEntities().size()); -// // Entities are ordered by their lastSeen time -// assertEquals(e1c, dsr1.getEntities().get(2).asEntity()); -// assertEquals(e1, dsr1.getEntities().get(1).asEntity()); -// assertEquals(e1b, dsr1.getEntities().get(0).asEntity()); -// -// //************************************** -// // Test 1d: same device with a fourth entity that has a different -// // attachment point and that is newer. Device should move and -// // non-attachment point entities should be removed (e1b). Although -// // e1 is non-attachment point it will remain because it has an IP -// Entity e1d = new Entity(1L, (short)2, 33, 4L, 6, new Date(3000)); -// d1 = deviceManager.learnDeviceByEntity(e1d); -// assertEquals("Sanity check failed. Should still be same device but " + -// "deviceKeys differs", deviceKey, d1.getDeviceKey()); -// dsr1 = new DeviceSyncRepresentation(d1); -// assertEquals("DefaultEntityClass::00:00:00:00:00:01::[2]::", -// dsr1.getKey()); -// assertEquals(3, dsr1.getEntities().size()); -// assertEquals(e1, dsr1.getEntities().get(0).asEntity()); -// assertEquals(e1c, dsr1.getEntities().get(1).asEntity()); -// assertEquals(e1d, dsr1.getEntities().get(2).asEntity()); -// -// d1 = null; -// -// -// //************************************** -// // Test 2: a second device with a different entity class. The -// // mock entity classifier will return an entity class where all -// // fields are keys if the DPID is > 10L -// Entity e2 = new Entity(2L, (short)23, 24, 11L, 1, new Date(0)); -// Device d2 = deviceManager.learnDeviceByEntity(e2); -// DeviceSyncRepresentation dsr2 = new DeviceSyncRepresentation(d2); -// assertEquals("Sanity check failed. Device doesn't have the expected " + -// "entity class. Something with the test setup is strange", -// "TestEntityClass", d2.getEntityClass().getName()); -// assertEquals("Sanity check failed. Device doesn't have the expected " + -// "entity class. Something with the test setup is strange", -// EnumSet.of(DeviceField.MAC, DeviceField.VLAN, -// DeviceField.SWITCH, DeviceField.PORT), -// d2.getEntityClass().getKeyFields()); -// SwitchPort swp = new SwitchPort(11L, 1, null); -// assertEquals("TestEntityClass::00:00:00:00:00:02::[23]::[" + -// swp.toString() + "]::", -// dsr2.getKey()); -// } -// -// /* interate through all entries in the sync store and return them as -// * list. We don't return the key from the store however, we assert -// * that the key from the store matches the key in the representation. -// * If we have a null value (tombstone) we simply add the null value to -// * the list to return. -// */ -// private List getEntriesFromStore() -// throws Exception { -// List entries = -// new ArrayList(); -// IClosableIterator>> iter = -// storeClient.entries(); -// try { -// while(iter.hasNext()) { -// Entry> entry = -// iter.next(); -// DeviceSyncRepresentation dsr = entry.getValue().getValue(); -// if (dsr != null) -// assertEquals(entry.getKey(), dsr.getKey()); -// entries.add(dsr); -// } -// } finally { -// if (iter != null) -// iter.close(); -// } -// return entries; -// } -// -// /* -// * assert whether the given Entity expected is equals to the given -// * SyncEntity actual. This method also compares the times (lastSeen, -// * activeSince). Entity.equals will not do that! -// */ -// private static void assertEntityEquals(Entity expected, SyncEntity actual) { -// assertNotNull(actual); -// assertNotNull(expected); -// Entity actualEntity = actual.asEntity(); -// assertEquals("entityFields", expected, actualEntity); -// assertEquals("lastSeenTimestamp", -// expected.getLastSeenTimestamp(), -// actualEntity.getLastSeenTimestamp()); -// assertEquals("activeSince", -// expected.getActiveSince(), actualEntity.getActiveSince()); -// } -// -// /* This test tests the normal operation as master when we write to the sync -// * store or delete from the store. -// */ -// @Test -// public void testWriteToSyncStore() throws Exception { -// int syncStoreIntervalMs = 50; -// ITopologyService mockTopology = makeMockTopologyAllPortsAp(); -// replay(mockTopology); -// deviceManager.topology = mockTopology; -// deviceManager.setSyncStoreWriteInterval(syncStoreIntervalMs); -// -// Entity e1a = new Entity(1L, (short)2, 3, 4L, 5, new Date(1000)); -// e1a.setActiveSince(new Date(0)); -// deviceManager.learnDeviceByEntity(e1a); -// -// //storeClient.put("FooBar", new DeviceSyncRepresentation()); -// -// List entries = getEntriesFromStore(); -// assertEquals(1, entries.size()); -// DeviceSyncRepresentation dsr1 = entries.get(0); -// assertEquals(1, dsr1.getEntities().size()); -// assertEntityEquals(e1a, dsr1.getEntities().get(0)); -// -// // Same entity but newer timestamp. Since the device hasn't changed, -// // only the timestamp is updated and the write should be throttled. -// Entity e1b = new Entity(1L, (short)2, 3, 4L, 5, new Date(2000)); -// e1b.setActiveSince(new Date(0)); -// deviceManager.learnDeviceByEntity(e1a); -// entries = getEntriesFromStore(); -// assertEquals(1, entries.size()); -// dsr1 = entries.get(0); -// assertEquals(1, dsr1.getEntities().size()); -// assertEntityEquals(e1a, dsr1.getEntities().get(0)); //e1a not e1b !!! -// -// // Wait for the write interval to expire then write again. -// Thread.sleep(syncStoreIntervalMs+5); -// Entity e1c = new Entity(1L, (short)2, 3, 4L, 5, new Date(3000)); -// e1c.setActiveSince(new Date(0)); -// deviceManager.learnDeviceByEntity(e1c); -// entries = getEntriesFromStore(); -// assertEquals(1, entries.size()); -// dsr1 = entries.get(0); -// assertEquals(1, dsr1.getEntities().size()); -// assertEntityEquals(e1c, dsr1.getEntities().get(0)); // e1c !! -// -// // Entity for same device but with different IP. should be added -// // immediately -// Entity e1d = new Entity(1L, (short)2, 33, 4L, 5, new Date(4000)); -// e1d.setActiveSince(new Date(0)); -// deviceManager.learnDeviceByEntity(e1d); -// entries = getEntriesFromStore(); -// assertEquals(1, entries.size()); -// dsr1 = entries.get(0); -// assertEquals(2, dsr1.getEntities().size()); -// assertEntityEquals(e1c, dsr1.getEntities().get(0)); // e1c !! -// assertEntityEquals(e1d, dsr1.getEntities().get(1)); // e1d !! -// -// // Entity for same device with new switch port ==> moved ==> write -// // update immediately without throttle. -// // Note: the previous entities will still be there because they have -// // IPs (even though they aren't for the current attachment point) -// Entity e1e = new Entity(1L, (short)2, 33, 4L, 6, new Date(5000)); -// e1e.setActiveSince(new Date(0)); -// deviceManager.learnDeviceByEntity(e1e); -// entries = getEntriesFromStore(); -// assertEquals(1, entries.size()); -// dsr1 = entries.get(0); -// assertEquals(3, dsr1.getEntities().size()); -// assertEntityEquals(e1c, dsr1.getEntities().get(0)); -// assertEntityEquals(e1d, dsr1.getEntities().get(1)); -// assertEntityEquals(e1e, dsr1.getEntities().get(2)); -// -// // Add a second device -// Entity e2 = new Entity(2L, null, null, 5L, 5, new Date()); -// deviceManager.learnDeviceByEntity(e2); -// entries = getEntriesFromStore(); -// assertEquals(2, entries.size()); -// for (DeviceSyncRepresentation dsr: entries) { -// // This is a kinda ugly way to ensure we have the two -// // devices we need..... but it will work for now -// if (dsr.getKey().contains("::00:00:00:00:00:01::")) { -// assertEquals(3, dsr.getEntities().size()); -// assertEntityEquals(e1c, dsr.getEntities().get(0)); -// assertEntityEquals(e1d, dsr.getEntities().get(1)); -// assertEntityEquals(e1e, dsr.getEntities().get(2)); -// } else if (dsr.getKey().contains("::00:00:00:00:00:02::")) { -// assertEquals(1, dsr.getEntities().size()); -// assertEntityEquals(e2, dsr.getEntities().get(0)); -// } else { -// fail("Unknown entry in store: " + dsr); -// } -// } -// -// -// // Run entity cleanup. Since we've used phony time stamps for -// // device 1 its entities should be cleared and the device should be -// // removed from the store. Device 2 should remain in the store. -// deviceManager.cleanupEntities(); -// entries = getEntriesFromStore(); -// assertEquals(2, entries.size()); -// for (DeviceSyncRepresentation dsr: entries) { -// if (dsr == null) { -// // pass -// } else if (dsr.getKey().contains("::00:00:00:00:00:02::")) { -// assertEquals(1, dsr.getEntities().size()); -// assertEntityEquals(e2, dsr.getEntities().get(0)); -// } else { -// fail("Unknown entry in store: " + dsr); -// } -// } -// } -// -// -// private void assertDeviceIps(Integer[] expected, IDevice d) { -// List expectedList = Arrays.asList(expected); -// Collections.sort(expectedList); -// List actualList = Arrays.asList(d.getIPv4Addresses()); -// Collections.sort(actualList); -// assertEquals(expectedList, actualList); -// } -// -// private IDevice getSingleDeviceFromDeviceManager(long mac) { -// Iterator diter = -// deviceManager.queryDevices(mac, null, null, null, null); -// assertTrue("Query didn't return a device", diter.hasNext()); -// IDevice d = diter.next(); -// assertFalse("Query returned more than one device", diter.hasNext()); -// return d; -// } -// -// @Test -// public void testToMaster() throws Exception { -// int syncStoreWriteIntervalMs = 0; -// int initialSyncStoreConsolidateIntervalMs = 50; -// ITopologyService mockTopology = makeMockTopologyAllPortsAp(); -// replay(mockTopology); -// deviceManager.topology = mockTopology; -// // We want an EntityClassifier that has switch/port as key fields -// deviceManager.entityClassifier = new MockEntityClassifier(); -// deviceManager.setSyncStoreWriteInterval(syncStoreWriteIntervalMs); -// deviceManager.setInitialSyncStoreConsolidateMs(initialSyncStoreConsolidateIntervalMs); -// -// // Add Device1 with two entities with two different IPs -// Entity e1a = new Entity(1L, null, 3, 4L, 5, new Date(1000)); -// Entity e1b = new Entity(1L, null, 33, 4L, 5, new Date(2000)); -// Device d1 = deviceManager.allocateDevice(1L, e1a, -// DefaultEntityClassifier.entityClass); -// d1 = deviceManager.allocateDevice(d1, e1b, -1); -// DeviceSyncRepresentation dsr = new DeviceSyncRepresentation(d1); -// storeClient.put(dsr.getKey(), dsr); -// -// // Add Device2 with different switch-ports. Only the most recent -// // one should be the attachment point -// Entity e2a = new Entity(2L, null, null, 4L, 4, new Date(1000)); -// Entity e2b = new Entity(2L, null, null, 4L, 5, new Date(2000)); -// Device d2 = deviceManager.allocateDevice(2L, e2a, -// DefaultEntityClassifier.entityClass); -// d2 = deviceManager.allocateDevice(d2, e2b, -1); -// d2.updateAttachmentPoint(4L, (short)5, -// e2b.getLastSeenTimestamp().getTime()); -// SwitchPort swp = new SwitchPort(4L, 5); -// SwitchPort[] aps = d2.getAttachmentPoints(); -// // sanity check -// assertArrayEquals("Sanity check: should only have AP(4L,5)", -// new SwitchPort[] {swp}, aps); -// dsr = new DeviceSyncRepresentation(d2); -// storeClient.put(dsr.getKey(), dsr); -// -// // Add a tombstone entry to the store to make sure we don't trip a -// // NPE -// dsr = null; -// Versioned versionedDsr = -// storeClient.get("FooBar"); -// storeClient.put("FooBar", versionedDsr); -// -// deviceManager.getHAListener().transitionToMaster(); -// -// // Query for the Device1. Make sure we have the two IPs we stored. -// IDevice d = getSingleDeviceFromDeviceManager(1L); -// assertDeviceIps(new Integer[] {3, 33}, d); -// assertArrayEquals(new Short[] { Ethernet.VLAN_UNTAGGED }, d.getVlanId()); -// swp = new SwitchPort(4L, 5); -// assertArrayEquals(new SwitchPort[] { swp }, d.getAttachmentPoints()); -// -// // Query for Device2. Make sure we only have the more recent AP -// // Query for the Device1. Make sure we have the two IPs we stored. -// d = getSingleDeviceFromDeviceManager(2L); -// assertArrayEquals(new Integer[0], d.getIPv4Addresses()); -// assertArrayEquals(new Short[] { Ethernet.VLAN_UNTAGGED }, d.getVlanId()); -// swp = new SwitchPort(4L, 5); -// assertArrayEquals(new SwitchPort[] { swp }, d.getAttachmentPoints()); -// -// //---------------------------- -// // add another entry device to the store. since device manager is -// // already master we won't read this device and it should be -// // removed from the store by the consolidate task -// Entity e3 = new Entity(3L, null, null, 1L, 1, null); -// dsr = new DeviceSyncRepresentation(); -// dsr.setKey("Device3"); -// dsr.setEntities(Collections.singletonList(new SyncEntity(e3))); -// storeClient.put(dsr.getKey(), dsr); -// -// // make sure it's in the store -// List entries = getEntriesFromStore(); -// boolean found = false; -// for (DeviceSyncRepresentation entry: entries) { -// if (entry!=null && entry.getKey().equals("Device3")) -// found = true; -// } -// assertTrue("Device3 not in store. Entries in store: " + entries, found); -// // make sure it's not in DevManager -// Iterator diter = -// deviceManager.queryDevices(3L, null, null, null, null); -// assertFalse("Device3 found in DeviceManager. Should be there", -// diter.hasNext()); -// -// // Wait for consolidate -// Thread.sleep(initialSyncStoreConsolidateIntervalMs + 5); -// // make sure it's in NOT the store -// entries = getEntriesFromStore(); -// found = false; -// for (DeviceSyncRepresentation entry: entries) { -// if (entry!=null && entry.getKey().equals("Device3")) -// found = true; -// } -// assertFalse("Device3 not is still in the store. Entries in store: " -// + entries, found); -// // make sure it's not in DevManager -// diter = deviceManager.queryDevices(3L, null, null, null, null); -// assertFalse("Device3 found in DeviceManager. Should be there", -// diter.hasNext()); -// } -// -// -// @Test -// public void testConsolitateStore() throws Exception { -// int syncStoreInternalMs = 0; -// ITopologyService mockTopology = makeMockTopologyAllPortsAp(); -// replay(mockTopology); -// deviceManager.topology = mockTopology; -// // We want an EntityClassifier that has switch/port as key fields -// deviceManager.entityClassifier = new MockEntityClassifier(); -// deviceManager.setSyncStoreWriteInterval(syncStoreInternalMs); -// -// // Add Device1 with two entities to store and let device manager -// // learn -// Entity e1a = new Entity(1L, null, null, 4L, 5, new Date(1000)); -// Entity e1b = new Entity(1L, null, 3, 4L, 5, new Date(2000)); -// Device d1 = deviceManager.learnDeviceByEntity(e1a); -// deviceManager.learnDeviceByEntity(e1b); -// String dev1Key = DeviceSyncRepresentation.computeKey(d1); -// -// -// // Add a second device to the store but do NOT add to device manager -// Entity e2 = new Entity(2L, null, null, 5L, 5, new Date()); -// Device d2 = deviceManager.allocateDevice(42L, e2, -// DefaultEntityClassifier.entityClass); -// DeviceSyncRepresentation dsr = new DeviceSyncRepresentation(d2); -// storeClient.put(dsr.getKey(), dsr); -// String dev2Key = DeviceSyncRepresentation.computeKey(d2); -// -// // Make sure we have two devices in the store -// List entries = getEntriesFromStore(); -// assertEquals(2, entries.size()); -// -// deviceManager.scheduleConsolidateStoreNow(); -// Thread.sleep(25); // give the scheduler time to run the task -// -// // We should still have two entries, however one of them will be a -// // tombstone -// entries = getEntriesFromStore(); -// assertEquals(2, entries.size()); -// -// // Device 1 should still be in store -// Versioned versioned = -// storeClient.get(dev1Key); -// dsr = versioned.getValue(); -// assertNotNull(dsr); -// assertEquals(2, dsr.getEntities().size()); -// assertEntityEquals(e1a, dsr.getEntities().get(0)); -// assertEntityEquals(e1b, dsr.getEntities().get(1)); -// -// // Device2 should be gone -// versioned = storeClient.get(dev2Key); -// assertNull(versioned.getValue()); -// -// // Run consolitate again. This time we check that tombstones in -// // the store are handled correctly -// deviceManager.scheduleConsolidateStoreNow(); -// Thread.sleep(25); // give the scheduler time to run the task -// -// // Now write a device to the store that doesn't have any switch-port -// // it should be removed -// Entity e3 = new Entity(3L, null, null, null, null, null); -// dsr.setKey("Device3"); -// dsr.setEntities(Collections.singletonList(new SyncEntity(e3))); -// storeClient.put(dsr.getKey(), dsr); -// -// // Run consolitate again. This time we check that tombstones in -// // the store are handled correctly -// deviceManager.scheduleConsolidateStoreNow(); -// Thread.sleep(25); // give the scheduler time to run the task -// versioned = storeClient.get("Device3"); -// assertNull(versioned.getValue()); -// -// } -// -// } diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndexTest.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndexTest.java deleted file mode 100644 index a2a10048eb..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/internal/DeviceUniqueIndexTest.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (c) 2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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.opendaylight.controller.hosttracker.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import junit.framework.TestCase; - -import org.junit.Test; -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; - -/** - * - * @author gregor - * - */ -public class DeviceUniqueIndexTest extends TestCase { - protected Entity e1a; - protected Entity e1b; - protected Device d1; - protected Entity e2; - protected Entity e2alt; - protected Entity e3; - protected Entity e3_ip; - protected Entity e4; - - @Override - protected void setUp() throws Exception { - super.setUp(); - Node n1 = new Node(Node.NodeIDType.OPENFLOW, Long.valueOf(1L)); - NodeConnector n1_1 = new NodeConnector(NodeConnectorIDType.OPENFLOW, - Short.valueOf((short) 1), n1); - e1a = new Entity(1L, (short) 1, 1, n1_1, new Date()); - e1b = new Entity(1L, (short) 2, 1, n1_1, new Date()); - List d1Entities = new ArrayList(2); - d1Entities.add(e1a); - d1Entities.add(e1b); - d1 = new Device(null, Long.valueOf(1), null, null, null, d1Entities, - null); - - Node n2 = new Node(Node.NodeIDType.OPENFLOW, Long.valueOf(2L)); - NodeConnector n2_2 = new NodeConnector(NodeConnectorIDType.OPENFLOW, - Short.valueOf((short) 2), n2); - Node n3 = new Node(Node.NodeIDType.OPENFLOW, Long.valueOf(3L)); - NodeConnector n3_3 = new NodeConnector(NodeConnectorIDType.OPENFLOW, - Short.valueOf((short) 3), n3); - - // e2 and e2 alt match in MAC and VLAN - e2 = new Entity(2L, (short) 2, 2, n2_2, new Date()); - e2alt = new Entity(2, (short) 2, null, null, null); - - // IP is null - e3 = new Entity(3L, (short) 3, null, n3_3, new Date()); - e3_ip = new Entity(3L, (short) 3, 3, n3_3, new Date()); - - // IP and switch and port are null - e4 = new Entity(4L, (short) 4, null, null, new Date()); - } - - /* - * Checks that the iterator it returns the elements in the Set expected - * Doesn't check how often an element is returned as long it's at least once - */ - protected void verifyIterator(Set expected, Iterator it) { - HashSet actual = new HashSet(); - while (it.hasNext()) { - actual.add(it.next()); - } - assertEquals(expected, actual); - } - - @Test - public void testDeviceUniqueIndex() { - DeviceUniqueIndex idx1 = new DeviceUniqueIndex(EnumSet.of( - DeviceField.MAC, DeviceField.VLAN)); - - idx1.updateIndex(d1, d1.getDeviceKey()); - idx1.updateIndex(e2, 2L); - - // ------------- - // Test findByEntity lookups - assertEquals(Long.valueOf(1L), idx1.findByEntity(e1a)); - assertEquals(Long.valueOf(1L), idx1.findByEntity(e1b)); - assertEquals(Long.valueOf(2L), idx1.findByEntity(e2)); - // we didn't add e2alt but since they key fields are the same we - // should find it - assertEquals(Long.valueOf(2L), idx1.findByEntity(e2alt)); - assertEquals(null, idx1.findByEntity(e3)); - assertEquals(null, idx1.findByEntity(e4)); - - // ------------- - // Test getAll() - HashSet expectedKeys = new HashSet(); - expectedKeys.add(1L); - expectedKeys.add(2L); - verifyIterator(expectedKeys, idx1.getAll()); - - // ------------- - // Test queryByEntity() - verifyIterator(Collections. singleton(1L), - idx1.queryByEntity(e1a)); - verifyIterator(Collections. singleton(1L), - idx1.queryByEntity(e1b)); - verifyIterator(Collections. singleton(2L), idx1.queryByEntity(e2)); - verifyIterator(Collections. singleton(2L), - idx1.queryByEntity(e2alt)); - assertEquals(false, idx1.queryByEntity(e3).hasNext()); - assertEquals(false, idx1.queryByEntity(e3).hasNext()); - - // ------------- - // Test removal - idx1.removeEntity(e1a, 42L); // No-op. e1a isn't mapped to this key - assertEquals(Long.valueOf(1L), idx1.findByEntity(e1a)); - idx1.removeEntity(e1a, 1L); - assertEquals(null, idx1.findByEntity(e1a)); - assertEquals(Long.valueOf(1L), idx1.findByEntity(e1b)); - assertEquals(Long.valueOf(2L), idx1.findByEntity(e2)); - idx1.removeEntity(e2); - assertEquals(null, idx1.findByEntity(e2)); - assertEquals(Long.valueOf(1L), idx1.findByEntity(e1b)); - - // ------------- - // Test null keys - DeviceUniqueIndex idx2 = new DeviceUniqueIndex(EnumSet.of( - DeviceField.IPV4, DeviceField.SWITCHPORT)); - // only one key field is null - idx2.updateIndex(e3, 3L); - assertEquals(Long.valueOf(3L), idx2.findByEntity(e3)); - assertEquals(null, idx2.findByEntity(e3_ip)); - // all key fields are null - idx2.updateIndex(e4, 4L); - assertEquals(null, idx2.findByEntity(e4)); - Device d4 = new Device(null, 4L, null, null, null, - Collections. singleton(e4), null); - idx2.updateIndex(d4, 4L); - assertEquals(null, idx2.findByEntity(e4)); - - // ------------- - // entity already exists with different deviceKey - DeviceUniqueIndex idx3 = new DeviceUniqueIndex(EnumSet.of( - DeviceField.MAC, DeviceField.VLAN)); - idx3.updateIndex(e1a, 42L); - assertEquals(false, idx3.updateIndex(d1, 1L)); - // TODO: shouldn't this fail as well so that the behavior - // is consistent? - idx3.updateIndex(e1a, 1L); - // anyways. We can now add d1 ;-) - assertEquals(true, idx3.updateIndex(d1, 1L)); - } -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDevice.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDevice.java deleted file mode 100644 index 03f0598df8..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDevice.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2011,2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.hosttracker.test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.TreeSet; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IEntityClass; -import org.opendaylight.controller.hosttracker.SwitchPort; -import org.opendaylight.controller.hosttracker.internal.AttachmentPoint; -import org.opendaylight.controller.hosttracker.internal.Device; -import org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl; - -/** - * This mock device removes the dependency on topology and a parent device - * manager and simply assumes all its entities are current and correct - */ -public class MockDevice extends Device { - - public MockDevice(DeviceManagerImpl deviceManager, Long deviceKey, - Entity entity, IEntityClass entityClass) { - super(deviceManager, deviceKey, entity, entityClass); - } - - public MockDevice(Device device, Entity newEntity, int insertionpoint) { - super(device, newEntity, insertionpoint); - } - - public MockDevice(DeviceManagerImpl deviceManager, Long deviceKey, - List aps, List trueAPs, - Collection entities, IEntityClass entityClass) { - super(deviceManager, deviceKey, null, aps, trueAPs, entities, - entityClass); - } - - @Override - public Integer[] getIPv4Addresses() { - TreeSet vals = new TreeSet(); - for (Entity e : entities) { - if (e.getIpv4Address() == null) - continue; - vals.add(e.getIpv4Address()); - } - - return vals.toArray(new Integer[vals.size()]); - } - - @Override - public SwitchPort[] getAttachmentPoints() { - ArrayList vals = new ArrayList(entities.length); - for (Entity e : entities) { - if (e.getPort() != null - && deviceManager.isValidAttachmentPoint(e.getPort())) { - SwitchPort sp = new SwitchPort(e.getPort()); - vals.add(sp); - } - } - return vals.toArray(new SwitchPort[vals.size()]); - } - - @Override - public String toString() { - return "MockDevice [getEntityClass()=" + getEntityClass() - + ", getEntities()=" + Arrays.toString(getEntities()) + "]"; - } - -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDeviceManager.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDeviceManager.java deleted file mode 100644 index af2feb14b1..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockDeviceManager.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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.opendaylight.controller.hosttracker.test; - -import java.util.Collection; -import java.util.Date; -import java.util.List; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDevice; -import org.opendaylight.controller.hosttracker.IDeviceListener; -import org.opendaylight.controller.hosttracker.IEntityClass; -import org.opendaylight.controller.hosttracker.IEntityClassifierService; -import org.opendaylight.controller.hosttracker.internal.AttachmentPoint; -import org.opendaylight.controller.hosttracker.internal.Device; -import org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl; -import org.opendaylight.controller.sal.core.NodeConnector; - -/** - * Mock device manager useful for unit tests - * - * @author readams - */ -public class MockDeviceManager extends DeviceManagerImpl { - /** - * Set a new IEntityClassifier Use this as a quick way to use a particular - * entity classifier in a single test without having to setup the full - * FloodlightModuleContext again. - * - * @param ecs - */ - public void setEntityClassifier(IEntityClassifierService ecs) { - this.entityClassifier = ecs; - // setSyncServiceIfNotSet(new MockSyncService()); - this.start(); - } - - /** - * Learn a device using the given characteristics. - * - * @param macAddress - * the MAC - * @param vlan - * the VLAN (can be null) - * @param ipv4Address - * the IP (can be null) - * @param switchDPID - * the attachment point switch DPID (can be null) - * @param switchPort - * the attachment point switch port (can be null) - * @param processUpdates - * if false, will not send updates. Note that this method is not - * thread safe if this is false - * @return the device, either new or not - */ - public IDevice learnEntity(long macAddress, Short vlan, - Integer ipv4Address, NodeConnector port, boolean processUpdates) { - List listeners = deviceListeners.getOrderedListeners(); - if (!processUpdates) { - deviceListeners.clearListeners(); - } - - if (vlan != null && vlan.shortValue() <= 0) - vlan = null; - if (ipv4Address != null && ipv4Address == 0) - ipv4Address = null; - IDevice res = learnDeviceByEntity(new Entity(macAddress, vlan, - ipv4Address, port, new Date())); - // Restore listeners - if (listeners != null) { - for (IDeviceListener listener : listeners) { - deviceListeners.addListener("device", listener); - } - } - return res; - } - - @Override - public void deleteDevice(Device device) { - super.deleteDevice(device); - } - - /** - * Learn a device using the given characteristics. - * - * @param macAddress - * the MAC - * @param vlan - * the VLAN (can be null) - * @param ipv4Address - * the IP (can be null) - * @param switchDPID - * the attachment point switch DPID (can be null) - * @param switchPort - * the attachment point switch port (can be null) - * @return the device, either new or not - */ - public IDevice learnEntity(long macAddress, Short vlan, - Integer ipv4Address, NodeConnector port) { - return learnEntity(macAddress, vlan, ipv4Address, port, true); - } - - @Override - protected Device allocateDevice(Long deviceKey, Entity entity, - IEntityClass entityClass) { - return new MockDevice(this, deviceKey, entity, entityClass); - } - - @Override - protected Device allocateDevice(Long deviceKey, String dhcpClientName, - List aps, List trueAPs, - Collection entities, IEntityClass entityClass) { - return new MockDevice(this, deviceKey, aps, trueAPs, entities, - entityClass); - } - - @Override - protected Device allocateDevice(Device device, Entity entity, - int insertionpoint) { - return new MockDevice(device, entity, insertionpoint); - } -} diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifier.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifier.java deleted file mode 100644 index e9f919e7f2..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifier.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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.opendaylight.controller.hosttracker.test; - -import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.MAC; -import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.SWITCHPORT; -import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.VLAN; - -import java.util.EnumSet; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDeviceService; -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; -import org.opendaylight.controller.hosttracker.IEntityClass; -import org.opendaylight.controller.hosttracker.internal.DefaultEntityClassifier; - -/** - * A simple IEntityClassifier. Useful for tests that need IEntityClassifiers and - * IEntityClass'es with switch and/or port key fields - */ -public class MockEntityClassifier extends DefaultEntityClassifier { - public static class TestEntityClass implements IEntityClass { - @Override - public EnumSet getKeyFields() { - return EnumSet.of(MAC, VLAN, SWITCHPORT); - } - - @Override - public String getName() { - return "TestEntityClass"; - } - } - - public static IEntityClass testEC = new MockEntityClassifier.TestEntityClass(); - - @Override - public IEntityClass classifyEntity(Entity entity) { - if (((Long) entity.getPort().getNode().getID()) >= 10L) { - return testEC; - } - return DefaultEntityClassifier.entityClass; - } - - @Override - public EnumSet getKeyFields() { - return EnumSet.of(MAC, VLAN, SWITCHPORT); - } - -} \ No newline at end of file diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifierMac.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifierMac.java deleted file mode 100644 index 436e6fa30e..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockEntityClassifierMac.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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.opendaylight.controller.hosttracker.test; - -import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.MAC; -import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.SWITCHPORT; -import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.VLAN; - -import java.util.EnumSet; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDeviceService; -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; -import org.opendaylight.controller.hosttracker.IEntityClass; -import org.opendaylight.controller.hosttracker.internal.DefaultEntityClassifier; - -/** - * A simple IEntityClassifier. Useful for tests that need an IEntityClassifier - * with switch/port as key fields. - */ -public class MockEntityClassifierMac extends DefaultEntityClassifier { - public static class TestEntityClassMac implements IEntityClass { - protected String name; - - public TestEntityClassMac(String name) { - this.name = name; - } - - @Override - public EnumSet getKeyFields() { - return EnumSet.of(MAC, VLAN); - } - - @Override - public String getName() { - return name; - } - } - - public static IEntityClass testECMac1 = new MockEntityClassifierMac.TestEntityClassMac( - "testECMac1"); - public static IEntityClass testECMac2 = new MockEntityClassifierMac.TestEntityClassMac( - "testECMac2"); - - @Override - public IEntityClass classifyEntity(Entity entity) { - if (((Long) entity.getPort().getNode().getID()) == null) { - throw new IllegalArgumentException("Not all key fields specified." - + " Required fields: " + getKeyFields()); - } else if (((Long) entity.getPort().getNode().getID()) == 1L) { - return testECMac1; - } else if (((Long) entity.getPort().getNode().getID()) == 2L) { - return testECMac2; - } else if (((Long) entity.getPort().getNode().getID()) == -1L) { - return null; - } - return DefaultEntityClassifier.entityClass; - } - - @Override - public EnumSet getKeyFields() { - return EnumSet.of(MAC, VLAN, SWITCHPORT); - } -} \ No newline at end of file diff --git a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockFlexEntityClassifier.java b/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockFlexEntityClassifier.java deleted file mode 100644 index fe2dd300d3..0000000000 --- a/opendaylight/adsal/hosttracker_new/implementation/src/test/java/org/opendaylight/controller/hosttracker/test/MockFlexEntityClassifier.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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.opendaylight.controller.hosttracker.test; - -import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.MAC; -import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.SWITCHPORT; -import static org.opendaylight.controller.hosttracker.IDeviceService.DeviceField.VLAN; - -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -import org.opendaylight.controller.hosttracker.Entity; -import org.opendaylight.controller.hosttracker.IDeviceService; -import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField; -import org.opendaylight.controller.hosttracker.IEntityClass; -import org.opendaylight.controller.hosttracker.internal.DefaultEntityClassifier; - -/** - * Extension to simple entity classifier to help in unit tests to provide table - * based multiple entity classification mock for reclassification tests - * - */ -public class MockFlexEntityClassifier extends DefaultEntityClassifier { - Map switchEntities; - Map vlanEntities; - - public static class TestEntityClass implements IEntityClass { - String name; - - public TestEntityClass(String name) { - this.name = name; - } - - @Override - public EnumSet getKeyFields() { - return EnumSet.of(MAC); - } - - @Override - public String getName() { - return name; - } - } - - public static IEntityClass defaultClass = new TestEntityClass("default"); - - public MockFlexEntityClassifier() { - switchEntities = new HashMap(); - vlanEntities = new HashMap(); - } - - public IEntityClass createTestEntityClass(String name) { - return new TestEntityClass(name); - } - - public void addSwitchEntity(Long dpid, IEntityClass entityClass) { - switchEntities.put(dpid, entityClass); - } - - public void removeSwitchEntity(Long dpid) { - switchEntities.remove(dpid); - } - - public void addVlanEntities(Short vlan, IEntityClass entityClass) { - vlanEntities.put(vlan, entityClass); - } - - public void removeVlanEntities(Short vlan) { - vlanEntities.remove(vlan); - } - - @Override - public IEntityClass classifyEntity(Entity entity) { - if (switchEntities.containsKey((Long) entity.getPort().getNode() - .getID())) - return switchEntities - .get((Long) entity.getPort().getNode().getID()); - if (vlanEntities.containsKey(entity.getVlan())) - return vlanEntities.get(entity.getVlan()); - return defaultClass; - } - - @Override - public EnumSet getKeyFields() { - return EnumSet.of(MAC, VLAN, SWITCHPORT); - } -} diff --git a/opendaylight/adsal/karaf-tomcat-security/pom.xml b/opendaylight/adsal/karaf-tomcat-security/pom.xml deleted file mode 100644 index d40b7f5f7f..0000000000 --- a/opendaylight/adsal/karaf-tomcat-security/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../commons/opendaylight - - - karaf-tomcat-security - 0.6.0-SNAPSHOT - bundle - - - orbit - org.apache.catalina - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.apache.catalina - org.slf4j, - javax.servlet, - org.apache.catalina, - org.apache.catalina.connector, - org.apache.catalina.valves, - org.apache.catalina.realm - - org.opendaylight.controller.karafsecurity - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/karaf-tomcat-security/src/main/java/org/opendaylight/controller/karafsecurity/ControllerCustomRealm.java b/opendaylight/adsal/karaf-tomcat-security/src/main/java/org/opendaylight/controller/karafsecurity/ControllerCustomRealm.java deleted file mode 100644 index 316067c3a6..0000000000 --- a/opendaylight/adsal/karaf-tomcat-security/src/main/java/org/opendaylight/controller/karafsecurity/ControllerCustomRealm.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.karafsecurity; - -import java.security.Principal; -import java.util.ArrayList; -import java.util.List; - -import org.apache.catalina.realm.GenericPrincipal; -import org.apache.catalina.realm.RealmBase; - -public class ControllerCustomRealm extends RealmBase { - - private static final String name = "ControllerCustomRealm"; - - @Override - protected String getName() { - return name; - } - - @Override - protected String getPassword(String username) { - return "admin"; - } - - @Override - protected Principal getPrincipal(String username) { - List controllerRoles = new ArrayList(); - controllerRoles.add("System-Admin"); - return new GenericPrincipal(username, "", controllerRoles); - } - - @Override - public Principal authenticate(String username, String credentials) { - return this.getPrincipal(username); - } -} diff --git a/opendaylight/adsal/logging/bridge/pom.xml b/opendaylight/adsal/logging/bridge/pom.xml deleted file mode 100644 index c9caabec6a..0000000000 --- a/opendaylight/adsal/logging/bridge/pom.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - logging.bridge - 0.6.0-SNAPSHOT - bundle - - - - equinoxSDK381 - org.eclipse.osgi - - - org.slf4j - slf4j-api - - - ch.qos.logback - logback-classic - test - - - junit - junit - test - - - org.opendaylight.yangtools - mockito-configuration - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.slf4j, - org.osgi.framework, - org.osgi.service.log - org.opendaylight.controller.logging.bridge.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/Activator.java b/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/Activator.java deleted file mode 100644 index fcd27d9a0a..0000000000 --- a/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/Activator.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.logging.bridge.internal; - -import org.osgi.service.log.LogEntry; - -import java.lang.Thread.UncaughtExceptionHandler; -import java.util.Enumeration; - -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.ILoggerFactory; -import org.osgi.service.log.LogReaderService; - -public class Activator implements BundleActivator { - private static final String UNCAUGHT_EXCEPTION_POLICY_PROP = "controller.uncaughtExceptionPolicy"; - private static final UncaughtExceptionPolicy DEFAULT_UNCAUGHT_EXCEPTION_POLICY = UncaughtExceptionPolicy.IGNORE; - - private LogListenerImpl listener = null; - private ShutdownHandler shutdownHandler = null; - private Logger log = null; - - @Override - public void start(BundleContext context) { - // Lets trigger the resolution of the slf4j logger factory - ILoggerFactory f = LoggerFactory.getILoggerFactory(); - - // Now retrieve a logger for the bridge - log = f - .getLogger("org.opendaylight.controller.logging.bridge.OSGI2SLF4J"); - - if (this.log != null) { - this.listener = new LogListenerImpl(log); - - ServiceReference service = null; - service = context.getServiceReference(LogReaderService.class - .getName()); - if (service != null) { - LogReaderService reader = (LogReaderService) context - .getService(service); - if (reader == null) { - this.log.error("Cannot register the LogListener because " - + "cannot retrieve LogReaderService"); - } else { - reader.addLogListener(this.listener); - // Now lets walk all the exiting messages - Enumeration entries = reader.getLog(); - if (entries != null) { - while (entries.hasMoreElements()) { - LogEntry entry = entries.nextElement(); - this.listener.logged(entry); - } - } - } - - /* - * Install the default exception handler so that the uncaught - * exceptions are handled by our customized handler. This new - * handler will display the exceptions to OSGI console as well - * as log to file. - */ - UncaughtExceptionHandler handler = DEFAULT_UNCAUGHT_EXCEPTION_POLICY; - final String policy = context.getProperty(UNCAUGHT_EXCEPTION_POLICY_PROP); - if (policy != null) { - try { - handler = UncaughtExceptionPolicy.valueOf(policy.toUpperCase()); - } catch (IllegalArgumentException ex) { - log.warn("Invalid policy name \"{}\", defaulting to {}", policy, handler); - } - } - log.trace("Setting uncaught exception policy to {}", handler); - Thread.setDefaultUncaughtExceptionHandler(handler); - - /* - * Install the Shutdown handler. This will intercept SIGTERM signal and - * close the system bundle. This allows for a graceful closing of OSGI - * framework. - */ - shutdownHandler = new ShutdownHandler(context); - Runtime.getRuntime().addShutdownHook(shutdownHandler); - } else { - this.log.error("Cannot register the LogListener because " - + "cannot retrieve LogReaderService"); - } - } else { - System.err - .println("Could not initialize the logging bridge subsytem"); - } - } - - @Override - public void stop(BundleContext context) { - ServiceReference serviceRef = context.getServiceReference( - LogReaderService.class.getName()); - if (serviceRef != null) { - LogReaderService reader = (LogReaderService) context.getService(serviceRef); - reader.removeLogListener(this.listener); - } - if (this.shutdownHandler != null) { - Runtime.getRuntime().removeShutdownHook(this.shutdownHandler); - } - this.listener = null; - this.log = null; - this.shutdownHandler = null; - } - - private class ShutdownHandler extends Thread { - BundleContext bundlecontext; - public ShutdownHandler(BundleContext ctxt) { - this.bundlecontext = ctxt; - } - - @Override - public void run () { - try { - this.bundlecontext.getBundle(0).stop(); - log.debug("shutdown handler thread called"); - } catch (BundleException e) { - log.debug("Bundle couldn't be stopped"); - } catch (Exception e) { - log.debug("Unhandled exception"); - } - } - } - -} diff --git a/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImpl.java b/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImpl.java deleted file mode 100644 index 2f45c6f91b..0000000000 --- a/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImpl.java +++ /dev/null @@ -1,47 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.logging.bridge.internal; - -import org.osgi.service.log.LogEntry; -import org.osgi.service.log.LogListener; -import org.osgi.service.log.LogService; -import org.slf4j.Logger; - -public class LogListenerImpl implements LogListener { - private Logger logger = null; - - public LogListenerImpl(Logger l) { - this.logger = l; - } - - @Override - public void logged(LogEntry entry) { - if (this.logger != null) { - switch (entry.getLevel()) { - case LogService.LOG_DEBUG: - this.logger.debug("Bundle:{} Message:{}", entry.getBundle() - .getSymbolicName(), entry.getMessage(), entry.getException()); - break; - case LogService.LOG_INFO: - this.logger.info("Bundle:{} Message:{}", entry.getBundle() - .getSymbolicName(), entry.getMessage(), entry.getException()); - break; - case LogService.LOG_WARNING: - this.logger.warn("Bundle:{} Message:{}", entry.getBundle() - .getSymbolicName(), entry.getMessage(), entry.getException()); - break; - case LogService.LOG_ERROR: - this.logger.error("Bundle:{} Message:{}", entry.getBundle() - .getSymbolicName(), entry.getMessage(), entry.getException()); - break; - } - } - } -} diff --git a/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/UncaughtExceptionPolicy.java b/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/UncaughtExceptionPolicy.java deleted file mode 100644 index 0545578b7f..0000000000 --- a/opendaylight/adsal/logging/bridge/src/main/java/org/opendaylight/controller/logging/bridge/internal/UncaughtExceptionPolicy.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.logging.bridge.internal; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -enum UncaughtExceptionPolicy implements Thread.UncaughtExceptionHandler { - ABORT { - public static final int EXIT_CODE = 1; - - @Override - public void uncaughtException(final Thread t, final Throwable e) { - log.error("Thread {} died because of an uncaught exception, forcing virtual machine shutdown", t, e); - System.exit(EXIT_CODE); - } - }, - IGNORE { - @Override - public void uncaughtException(final Thread t, final Throwable e) { - log.error("Thread {} died because of an uncaught exception", t, e); - } - }; - - private static final Logger log = LoggerFactory.getLogger(UncaughtExceptionPolicy.class); -} diff --git a/opendaylight/adsal/logging/bridge/src/test/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImplTest.java b/opendaylight/adsal/logging/bridge/src/test/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImplTest.java deleted file mode 100644 index 2490c39171..0000000000 --- a/opendaylight/adsal/logging/bridge/src/test/java/org/opendaylight/controller/logging/bridge/internal/LogListenerImplTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.logging.bridge.internal; - -import org.junit.Test; -import org.osgi.framework.Bundle; -import org.osgi.framework.ServiceReference; -import org.osgi.service.log.LogEntry; -import org.osgi.service.log.LogService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -public class LogListenerImplTest { - private static final Logger logger = LoggerFactory.getLogger(LogListenerImplTest.class); - - @Test - public void test() { - LogListenerImpl tested = new LogListenerImpl(logger); - tested.logged(getEntry("m1", null)); - tested.logged(getEntry("m2", new RuntimeException())); - } - - private LogEntry getEntry(final String message, final Exception e) { - return new LogEntry() { - @Override - public Bundle getBundle() { - Bundle mock = mock(Bundle.class); - doReturn(null).when(mock).getSymbolicName(); - return mock; - } - - @Override - public ServiceReference getServiceReference() { - return null; - } - - @Override - public int getLevel() { - return LogService.LOG_INFO; - } - - @Override - public String getMessage() { - return message; - } - - @Override - public Throwable getException() { - return e; - } - - @Override - public long getTime() { - return 0; - } - }; - } - -} diff --git a/opendaylight/adsal/northbound/archetype-app-northbound/pom.xml b/opendaylight/adsal/northbound/archetype-app-northbound/pom.xml deleted file mode 100644 index cc49fc9ca4..0000000000 --- a/opendaylight/adsal/northbound/archetype-app-northbound/pom.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - app-northbound - 0.2.0-SNAPSHOT - maven-archetype - - app-northbound - - - - - org.apache.maven.archetype - archetype-packaging - 2.2 - - - - - - - maven-archetype-plugin - 2.2 - - - - - diff --git a/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/META-INF/maven/archetype-metadata.xml b/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/META-INF/maven/archetype-metadata.xml deleted file mode 100644 index 3c9223d3c7..0000000000 --- a/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/META-INF/maven/archetype-metadata.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - src/main/java - - **/*.java - - - - src/main/resources - - **/*.xml - - - - .settings - - **/*.prefs - - - - - - .classpath - .project - - - - diff --git a/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/pom.xml b/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/pom.xml deleted file mode 100644 index 521584605a..0000000000 --- a/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ -#set( $dollar = '$' ) - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - ${artifactId} - - ${groupId} - bundle - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - - org.opendaylight.controller.northbound.commons, - com.sun.jersey.spi.container.servlet, - com.fasterxml.jackson.annotation, - javax.ws.rs, - javax.ws.rs.core, - javax.xml.bind, - javax.xml.bind.annotation, - org.slf4j, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - /northbound/${artifactId} - ,${dollar}{classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - ${version} - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - junit - junit - - - diff --git a/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/java/Northbound.java b/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/java/Northbound.java deleted file mode 100644 index 788dec855f..0000000000 --- a/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/java/Northbound.java +++ /dev/null @@ -1,70 +0,0 @@ -#set( $symbol_pound = '#' ) -#set( $symbol_dollar = '$' ) -#set( $symbol_escape = '\' ) -package ${package}; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.SecurityContext; - -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; - -/** - * Northbound REST API - * - *
- *
- * Authentication scheme : HTTP Basic
- * Authentication realm : opendaylight
- * Transport : HTTP and HTTPS
- *
- * HTTPS Authentication is disabled by default. - */ - -@Path("/") -public class Northbound { - - private String username; - - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - - /** - * - * Sample REST API call - * - * @return A response string - * - *

-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/northbound/${artifactId}/api
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * Sample Northbound API
-     *
-     * Response body in JSON:
-     * Sample Northbound API
-     * 
- */ - @Path("/api") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(String.class) - @StatusCodes() - public String getWidget() { - String result = "Sample Northbound API - ${artifactId}"; - return result; - } - -} diff --git a/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index a1d837610c..0000000000 --- a/opendaylight/adsal/northbound/archetype-app-northbound/src/main/resources/archetype-resources/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,92 +0,0 @@ -#set( $symbol_pound = '#' ) -#set( $symbol_dollar = '$' ) -#set( $symbol_escape = '\' ) - - - - JAXRS${artifactId} - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRS${artifactId} - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - ${artifactId} - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - diff --git a/opendaylight/adsal/northbound/archetype-app-northbound/src/test/resources/projects/basic/archetype.properties b/opendaylight/adsal/northbound/archetype-app-northbound/src/test/resources/projects/basic/archetype.properties deleted file mode 100644 index 40d9d656ac..0000000000 --- a/opendaylight/adsal/northbound/archetype-app-northbound/src/test/resources/projects/basic/archetype.properties +++ /dev/null @@ -1,5 +0,0 @@ -#Fri Mar 07 21:17:20 CST 2014 -package=it.pkg -version=0.1-SNAPSHOT -groupId=archetype.it -artifactId=basic diff --git a/opendaylight/adsal/northbound/archetype-app-northbound/src/test/resources/projects/basic/goal.txt b/opendaylight/adsal/northbound/archetype-app-northbound/src/test/resources/projects/basic/goal.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/opendaylight/adsal/northbound/bundlescanner/api/pom.xml b/opendaylight/adsal/northbound/bundlescanner/api/pom.xml deleted file mode 100644 index c0acffddbe..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/api/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../commons/opendaylight - - - bundlescanner - 0.6.0-SNAPSHOT - bundle - - - - org.osgi - org.osgi.core - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.osgi.framework, - org.slf4j, - javax.ws.rs, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.opendaylight.controller.northbound.bundlescanner - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/bundlescanner/api/src/main/java/org/opendaylight/controller/northbound/bundlescanner/IBundleScanService.java b/opendaylight/adsal/northbound/bundlescanner/api/src/main/java/org/opendaylight/controller/northbound/bundlescanner/IBundleScanService.java deleted file mode 100644 index dde205acd6..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/api/src/main/java/org/opendaylight/controller/northbound/bundlescanner/IBundleScanService.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.bundlescanner; - -import java.util.List; -import java.util.Set; - -import org.osgi.framework.BundleContext; - -/** - * The bundle scan service provides services which allow introspection of - * bundle classes for detecting annotated classes. The scanning is performed - * when a bundle is RESOLVED. - */ -public interface IBundleScanService { - /** - * The list of annotations to be scanned - */ - public final String[] ANNOTATIONS_TO_SCAN = { - "javax.xml.bind.annotation.*", // JAXB annotatinos - "javax.ws.rs.*" // JAX-RS annotatinos - }; - - - public List> getAnnotatedClasses( - BundleContext context, - String[] annotations, - Set excludes, - boolean includeDependentBundleClasses); -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/pom.xml b/opendaylight/adsal/northbound/bundlescanner/implementation/pom.xml deleted file mode 100644 index dbf2f9e742..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../commons/opendaylight - - - bundlescanner.implementation - 0.6.0-SNAPSHOT - bundle - - - - junit - junit - - - org.opendaylight.controller - bundlescanner - - - org.opendaylight.controller - sal - - - org.ow2.asm - asm-all - - - org.springframework.osgi - spring-osgi-mock - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.apache.felix.dm, - org.objectweb.asm, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.northbound.bundlescanner, - org.osgi.framework, - org.slf4j, - javax.ws.rs, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.opendaylight.controller.northbound.bundlescanner.internal.Activator - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/Activator.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/Activator.java deleted file mode 100644 index abe8618d9b..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/Activator.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.bundlescanner.internal; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.northbound.bundlescanner.IBundleScanService; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; - -/** - * The activator registers the BundleScanner. - */ -public class Activator extends ComponentActivatorAbstractBase { - - @Override - protected void init() { - BundleContext context = FrameworkUtil.getBundle(BundleScanner.class).getBundleContext(); - context.addBundleListener(BundleScanner.getInstance()); - } - - @Override - public void destroy() { - BundleContext context = FrameworkUtil.getBundle(BundleScanner.class).getBundleContext(); - context.removeBundleListener(BundleScanner.getInstance()); - } - - @Override - protected Object[] getGlobalImplementations() { - return new Object[] { BundleScanServiceImpl.class }; - } - - @Override - protected void configureGlobalInstance(Component c, Object imp) { - if (!imp.equals(BundleScanServiceImpl.class)) { - return; - } - // export service - c.setInterface( - new String[] { IBundleScanService.class.getName() }, - null); - } - -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleInfo.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleInfo.java deleted file mode 100644 index 31c81dab7e..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleInfo.java +++ /dev/null @@ -1,187 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.bundlescanner.internal; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Dictionary; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -import org.osgi.framework.Bundle; -import org.osgi.framework.Constants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * BundleInfo holds information related to the bundle obtained during the - * bundle scan process. - */ -/*package*/ class BundleInfo { - private static final Logger LOGGER = LoggerFactory.getLogger(BundleInfo.class); - - private final Bundle bundle; - private final Map> annotatedClasses; - private final Set exportPkgs; - private final Set importPkgs; - - public BundleInfo(Bundle bundle, Map> classes) { - this.bundle = bundle; - this.annotatedClasses = classes; - Dictionary dict = bundle.getHeaders(); - this.importPkgs = parsePackages(dict.get(Constants.IMPORT_PACKAGE)); - this.exportPkgs = parsePackages(dict.get(Constants.EXPORT_PACKAGE)); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(super.toString()); - sb.append("{name:").append(bundle.getSymbolicName()) - .append(" id:").append(getId()) - .append(" annotated-classes:").append(annotatedClasses) - .append(" imports:").append(importPkgs) - .append(" exports:").append(exportPkgs).append("}"); - return sb.toString(); - } - - public Bundle getBundle() { - return bundle; - } - - public long getId() { - return bundle.getBundleId(); - } - - public List> getAnnotatedClasses(Pattern pattern, Set excludes) { - List result = new ArrayList(); - for (Map.Entry> entry : annotatedClasses.entrySet()) { - if (matches(pattern, entry.getValue())) { - result.add(entry.getKey()); - } - } - return BundleScanner.loadClasses(result, bundle, excludes); - } - - private boolean matches(Pattern pattern, Set values) { - if (pattern == null) { - return true; - } - //LOGGER.debug("Matching: {} {}", pattern.toString(), values); - for (String s : values) { - if (pattern.matcher(s).find()) { - return true; - } - } - return false; - } - - /** - * Get classes with annotations matching a pattern - * - * @param allbundles - all bundles - * @param pattern - annotation pattern to match - * @param initBundle - the bundle which initiated this call - * @param excludes - set of class names to be excluded - * - * @return list of annotated classes matching the pattern - */ - public List> getAnnotatedClasses( - Collection allbundles, - Pattern pattern, Bundle initBundle, - Set excludes) - { - List> classes = getAnnotatedClasses(pattern, excludes); - processAnnotatedClassesInternal(this, allbundles, pattern, - new HashSet(), classes, initBundle, excludes); - return classes; - } - - private List getExportedAnnotatedClasses(Pattern pattern) { - List classes = new ArrayList(); - for (Map.Entry> entry : annotatedClasses.entrySet()) { - String cls = entry.getKey(); - int idx = cls.lastIndexOf("."); - String pkg = (idx == -1 ? "" : cls.substring(0, idx)); - // for a class to match, the package has to be exported and - // annotations should match the given pattern - if (exportPkgs.contains(pkg) && matches(pattern, entry.getValue())) { - classes.add(cls); - } - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Found in bundle:{} exported classes:[{}]", - getBundle().getSymbolicName(), classes); - } - return classes; - } - - private static void processAnnotatedClassesInternal( - BundleInfo target, - Collection bundlesToScan, - Pattern pattern, - Collection visited, - List> classes, - Bundle initBundle, Set excludes) - { - for (BundleInfo other : bundlesToScan) { - if (other.getId() == target.getId()) { - continue; - } - if (target.isDependantOn(other)) { - if (!visited.contains(other)) { - classes.addAll(BundleScanner.loadClasses( - other.getExportedAnnotatedClasses(pattern), - initBundle, excludes)); - visited.add(other); - processAnnotatedClassesInternal(other, bundlesToScan, - pattern, visited, classes, initBundle, excludes); - } - } - } - } - - private boolean isDependantOn(BundleInfo other) { - for (String pkg : importPkgs) { - if (other.exportPkgs.contains(pkg)) { - return true; - } - } - return false; - } - - public List getDependencies(Collection bundles) { - List result = new ArrayList(); - for(BundleInfo bundle : bundles) { - if (isDependantOn(bundle)) { - result.add(bundle); - } - } - return result; - } - - - private static Set parsePackages(String packageString) { - if (packageString == null) { - return Collections.emptySet(); - } - String[] packages = packageString.split(","); - Set result = new HashSet(); - for (int i=0; i> getAnnotatedClasses(BundleContext context, - String[] annotations, - Set excludes, - boolean includeDependentBundleClasses) - { - return BundleScanner.getInstance().getAnnotatedClasses( - context, annotations, excludes, includeDependentBundleClasses); - } - -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanner.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanner.java deleted file mode 100644 index f6b604d8b6..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/main/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScanner.java +++ /dev/null @@ -1,330 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.bundlescanner.internal; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; - -import javax.xml.bind.annotation.XmlRootElement; - -import org.objectweb.asm.AnnotationVisitor; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.Opcodes; -import org.opendaylight.controller.northbound.bundlescanner.IBundleScanService; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleEvent; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.SynchronousBundleListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The custom bundle scanner scans annotations on bundles and is used for - * constructing JAXBContext instances. It listens for bundle events and updates - * the metadata in realtime. - */ -/*package*/ class BundleScanner implements SynchronousBundleListener { - private static final Logger LOGGER = LoggerFactory.getLogger(BundleScanner.class); - private static BundleScanner INSTANCE; // singleton - - private final Pattern annotationPattern; - private final Map bundleAnnotations = - new HashMap(); - - public static synchronized BundleScanner getInstance() { - if (INSTANCE == null) { - INSTANCE = new BundleScanner(); - } - return INSTANCE; - } - - /*package*/ BundleScanner(Bundle[] bundles) { - annotationPattern = mergePatterns(IBundleScanService.ANNOTATIONS_TO_SCAN, true); - init(bundles); - } - - /*package*/ BundleScanner() { - this(FrameworkUtil.getBundle(BundleScanner.class).getBundleContext().getBundles()); - } - - public List> getAnnotatedClasses(BundleContext context, - String[] annotations, - Set excludes, - boolean includeDependentBundleClasses) - { - BundleInfo info = bundleAnnotations.get(context.getBundle().getBundleId()); - if (info == null) { - return Collections.emptyList(); - } - Pattern pattern = mergePatterns(annotations, false); - List> result = null; - if (includeDependentBundleClasses) { - result = info.getAnnotatedClasses(bundleAnnotations.values(), - pattern, context.getBundle(), excludes); - // reverse the list to give precedence to the types loaded from the - // initiating bundle - Collections.reverse(result); - // validate for conflicts only when searching dependencies - validate(result); - } else { - result = info.getAnnotatedClasses(pattern, excludes); - } - LOGGER.debug("Annotated classes detected: {} matching: {}", result, pattern); - return result; - } - - //////////////////////////////////////////////////////////////// - // SynchronousBundleListener implementation - //////////////////////////////////////////////////////////////// - - @Override - public void bundleChanged(BundleEvent event) { - Bundle bundle = event.getBundle(); - long id = bundle.getBundleId(); - switch(event.getType()) { - case BundleEvent.RESOLVED : - scan(bundle); - return; - case BundleEvent.UNRESOLVED : - case BundleEvent.UNINSTALLED : - bundleAnnotations.remove(id); - return; - } - } - - - //////////////////////////////////////////////////////////////// - // ClassVisitor implementation - //////////////////////////////////////////////////////////////// - - private static class AnnotationDetector extends ClassVisitor { - private final Map> matchedClasses = - new HashMap>(); - - private final Pattern annotationsPattern; - private Set annotations; - private String className; - private boolean accessible; - private boolean matchedAnnotation; - - public AnnotationDetector(Pattern pattern) { - super(Opcodes.ASM4); - this.annotationsPattern = pattern; - } - - public Map> getMatchedClasses() { - return new HashMap>(matchedClasses); - } - - @Override - public void visit(int version, int access, String name, String signature, - String superName, String[] interfaces) - { - //LOGGER.debug("Visiting class:" + name); - className = name; - accessible = ((access & Opcodes.ACC_PUBLIC) == Opcodes.ACC_PUBLIC); - matchedAnnotation = false; - annotations = new HashSet(); - } - - @Override - public AnnotationVisitor visitAnnotation(String desc, boolean visible) { - //LOGGER.debug("Visiting annotation:" + desc); - annotations.add(signature2class(desc)); - if (!matchedAnnotation) { - matchedAnnotation = (annotationsPattern == null || - annotationsPattern.matcher(desc).find()); - } - return null; - } - - @Override - public void visitEnd() { - if (matchedAnnotation && accessible) { - className = path2class(className); - matchedClasses.put(className, new HashSet(annotations)); - } - } - } - - //////////////////////////////////////////////////////////////// - // Helpers - //////////////////////////////////////////////////////////////// - - private synchronized void init(Bundle[] bundles) { - for (Bundle bundle : bundles) { - int state = bundle.getState(); - if (state == Bundle.RESOLVED || - state == Bundle.STARTING || - state == Bundle.ACTIVE) - { - scan(bundle); - } - } - } - - private static String path2class(String path) { - return path.replace(".class", "").replaceAll("/", "."); - } - - private static String class2path(String clz) { - return clz.replaceAll("\\.", "/"); - } - - @SuppressWarnings("unused") - private static String class2signature(String clz) { - return "L" + class2path(clz) + ";"; - } - - private static String signature2class(String sig) { - if (sig.startsWith("L") && sig.endsWith(";")) { - sig = sig.substring(1, sig.length()-1); - } - return path2class(sig); - } - - private static List getBundleClasses(Bundle bundle, String[] pkgs) { - List result = new ArrayList(); - boolean recurse = false; - if (pkgs == null) { - recurse = true; - pkgs = new String[] { "/" } ; - } - for (String pkg : pkgs) { - pkg = class2path(pkg); - final Enumeration e = bundle.findEntries(pkg, "*.class", recurse); - if (e != null) { - while (e.hasMoreElements()) { - URL url = e.nextElement(); - result.add(url); - } - } - } - return result; - } - - private synchronized void scan(Bundle bundle) { - AnnotationDetector detector = new AnnotationDetector(annotationPattern); - try { - for (URL u : getBundleClasses(bundle, null)) { - InputStream is = u.openStream(); - new ClassReader(is).accept(detector, 0); - is.close(); - } - } catch (IOException ioe) { - LOGGER.error("Error scanning classes in bundle: {}", bundle.getSymbolicName(), ioe); - } - Map> classes = detector.getMatchedClasses(); - if (classes != null && classes.size() > 0) { - BundleInfo info = new BundleInfo(bundle, classes); - bundleAnnotations.put(bundle.getBundleId(),info); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("bindings found in bundle: {}[{}] " + - "dependencies {} classes {}", bundle.getSymbolicName(), - bundle.getBundleId(), - info.getDependencies(bundleAnnotations.values()), - classes); - } - } - // find bundle dependencies - } - - public static List> loadClasses( - Collection annotatedClasses, - Bundle initBundle, Set excludes) - { - List> result = new ArrayList>(); - StringBuilder errors = new StringBuilder(); - for (String name : annotatedClasses) { - try { - if (excludes != null && excludes.contains(name)) { - continue; - } - result.add(initBundle.loadClass(name)); - } catch (ClassNotFoundException e) { - errors.append(name).append(", "); - } - } - if (LOGGER.isDebugEnabled() && errors.length() > 0) { - LOGGER.debug("Bundle: {} could not load classes: {}", - initBundle.getSymbolicName(), errors.toString()); - } - return result; - } - - public static Pattern mergePatterns(String[] patterns, boolean convert2signature) { - if (patterns == null || patterns.length == 0) { - return null; - } - StringBuilder regex = new StringBuilder(); - for (String c : patterns) { - if (c.endsWith("*")) { - c = c.substring(0, c.length() - 1); - } - if (regex.length() > 0) { - regex.append("|"); - } - regex.append("^"); - if (convert2signature) { - regex.append("L").append(c.replaceAll("\\.", "/")); - } else { - regex.append(c); - } - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Merged regex: [{}]", regex.toString()); - } - return Pattern.compile(regex.toString()); - } - - private void validate(List> classes) { - if (classes == null || classes.size() == 0) { - return; - } - Map names = new HashMap(); - StringBuilder conflictsMsg = new StringBuilder(); - for (Class c : classes) { - XmlRootElement root = c.getAnnotation(XmlRootElement.class); - if (root == null) { - continue; - } - String rootName = root.name(); - if ("##default".equals(rootName)) { - String clsName = c.getSimpleName(); - rootName = Character.toLowerCase(clsName.charAt(0)) + clsName.substring(1); - } - String other = names.get(rootName); - if (other != null && !other.equals(c.getName())) { - conflictsMsg.append(System.lineSeparator()) - .append("[").append(rootName).append(":") - .append(c.getName()).append(",").append(other) - .append("]"); - } else { - names.put(rootName, c.getName()); - } - } - if (conflictsMsg.length() > 0) { - LOGGER.warn("JAXB type conflicts detected : {}", conflictsMsg.toString()); - } - } - -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Animal.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Animal.java deleted file mode 100644 index 693c6aeb85..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Animal.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_base; - -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -public abstract class Animal { } diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/BasePerson.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/BasePerson.java deleted file mode 100644 index bfb8b35265..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/BasePerson.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_base; - -import javax.xml.bind.annotation.XmlRootElement; - - -@XmlRootElement -public class BasePerson { } diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Mammal.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Mammal.java deleted file mode 100644 index d6162b6939..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Mammal.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_base; - -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -public class Mammal extends Animal { } diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/NoAnnotation.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/NoAnnotation.java deleted file mode 100644 index 7e9069b599..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/NoAnnotation.java +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_base; - -public class NoAnnotation { } diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/NonRelevantAnnotation.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/NonRelevantAnnotation.java deleted file mode 100644 index 4a04a3b6c9..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/NonRelevantAnnotation.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_base; - -@Deprecated -public class NonRelevantAnnotation { - -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Person.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Person.java deleted file mode 100644 index edd3782817..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_base/Person.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_base; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -@XmlTransient -@Deprecated -public class Person extends BasePerson { - - @XmlElement - protected String name; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @XmlRootElement - public static class Info { } - - @XmlRootElement - private static class PrivateInfo { } -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_misc/Misc.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_misc/Misc.java deleted file mode 100644 index eb49eb0fb9..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_misc/Misc.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_misc; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -public class Misc { - -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/NoAnnotation.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/NoAnnotation.java deleted file mode 100644 index 19f2b0ddf0..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/NoAnnotation.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_sub1; - -public class NoAnnotation { - -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/Zoo.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/Zoo.java deleted file mode 100644 index c44e48e22f..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub1/Zoo.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_sub1; - -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlRootElement; - -import bundle_base.Animal; -import bundle_base.Mammal; - - -@XmlRootElement -public class Zoo { - private Animal creature; - - @XmlElementRef - public Animal getCreature() { - return creature; - } - - public void setCreature(Animal creature) { - this.creature = creature; - } - - public Zoo() { - creature = new Mammal(); - } -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Agent.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Agent.java deleted file mode 100644 index 025f35af9a..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Agent.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_sub2; - -import javax.xml.bind.annotation.XmlRootElement; - -import bundle_base.Person; - - -@XmlRootElement -public class Agent extends Person { - -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Customer.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Customer.java deleted file mode 100644 index d822ce757b..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/Customer.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_sub2; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -import bundle_base.BasePerson; -import bundle_base.Person; - - -@XmlRootElement -public class Customer extends Person { - - private String password; - private List phoneNumbers; - @XmlElementRef - @XmlElementWrapper - private final List agents = new ArrayList(); - - @XmlTransient - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @XmlElement(name = "phone-number") - public List getPhoneNumbers() { - return phoneNumbers; - } - - public void setPhoneNumbers(List phoneNumbers) { - this.phoneNumbers = phoneNumbers; - } - - public void addAgent(Person mgr) { - this.agents.add(mgr); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(super.toString()); - sb.append(" password:").append(password); - sb.append(" phoneNumbers:").append(phoneNumbers); - sb.append(" agents:").append(agents); - return sb.toString(); - } -} - diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/NoAnnotation.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/NoAnnotation.java deleted file mode 100644 index e477e61959..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/bundle_sub2/NoAnnotation.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package bundle_sub2; - -public class NoAnnotation { - -} diff --git a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScannerTest.java b/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScannerTest.java deleted file mode 100644 index c2efbe67a9..0000000000 --- a/opendaylight/adsal/northbound/bundlescanner/implementation/src/test/java/org/opendaylight/controller/northbound/bundlescanner/internal/BundleScannerTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.bundlescanner.internal; - -import java.io.File; -import java.io.FileFilter; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Dictionary; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.List; -import java.util.Set; -import java.util.regex.Pattern; - -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleEvent; -import org.osgi.framework.Constants; -import org.springframework.osgi.mock.MockBundle; -import org.springframework.osgi.mock.MockBundleContext; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public class BundleScannerTest { - - private static BundleScanner bundleScanner; - private static List bundles; - @Rule - public final TestName testName = new TestName(); - - @BeforeClass - public static void init() throws Exception { - bundles = makeMockBundles(); - bundleScanner = new BundleScanner(bundles.toArray(new Bundle[bundles.size()])); - } - - @AfterClass - public static void destroy() throws Exception { - } - - @Before - public void setup() { - System.out.println("==== " + testName.getMethodName()); - } - - @Test - public void testValidateBundles() { - assertNotNull(bundleScanner); - BundleContext context = bundles.get(0).getBundleContext(); - assertNotNull(context.getBundle()); - assertNotNull(context.getBundles()); - assertNotNull(context.getBundles().length >= 4); - } - - @Test - public void testBundleEvents() throws Exception { - MockBundle newBundle = new TestMockBundle("misc", "", "bundle_misc"); - assertTrue(bundleScanner.getAnnotatedClasses( - newBundle.getBundleContext(), null, null, false).size() == 0); - BundleEvent event = new BundleEvent(BundleEvent.RESOLVED, newBundle); - bundleScanner.bundleChanged(event); - assertTrue(bundleScanner.getAnnotatedClasses( - newBundle.getBundleContext(), null, null, false).size() == 1); - } - - @Test - public void testAnnotatedClassesWithDependencies() throws Exception { - for (Bundle bundle : bundles) { - List> classes = bundleScanner.getAnnotatedClasses( - bundle.getBundleContext(), null, null, true); - String name = bundle.getSymbolicName(); - System.out.println("name:" + name + " classes:" + classes.size()); - if ("misc".equals(name)) { - assertTrue(classes.size() == 1); - } else if ("base".equals(name)) { - assertTrue(classes.size() == 5); - } else if ("sub1".equals(name)) { - assertTrue(classes.size() == 6); - } else if ("sub2".equals(name)) { - assertTrue(classes.size() == 7); - } - } - } - - @Test - public void testExactFiltering() { - Bundle bundle = findBundle("sub1"); - String[] annos = { "javax.xml.bind.annotation.XmlTransient" }; - List> classes = bundleScanner.getAnnotatedClasses( - bundle.getBundleContext(), annos, null, true); - assertTrue(classes.size() == 1); - } - - @Test - public void testNonExactFiltering() { - Bundle bundle = findBundle("sub1"); - String[] annos = { "javax.xml.bind.annotation.*" }; - List> classes = bundleScanner.getAnnotatedClasses( - bundle.getBundleContext(), annos, null, true); - assertTrue(classes.size() == 6); - } - - @Test - public void testFilteringUnmatched() { - Bundle bundle = findBundle("sub1"); - String[] annos = { "non.existent.pkg" }; - List> classes = bundleScanner.getAnnotatedClasses( - bundle.getBundleContext(), annos, null, true); - assertTrue(classes.size() == 0); - } - - @Test - public void testRegexMerge() { - Pattern pattern = BundleScanner.mergePatterns( - new String[] { - "javax.xml.bind.annotation.*", - "javax.ws.rs.Path" - }, - true - ); - assertTrue(pattern.matcher("Ljavax/xml/bind/annotation/FOO;").find()); - assertFalse(pattern.matcher("Ljavax/servlet/FOO;").find()); - } - - @Test - public void testExclude() { - Set excludes = new HashSet(); - excludes.add("bundle_base.Animal"); - Bundle bundle = findBundle("sub1"); - String[] annos = { "javax.xml.bind.annotation.*" }; - List> classes = bundleScanner.getAnnotatedClasses( - bundle.getBundleContext(), annos, excludes, true); - assertTrue(classes.size() == 5); - } - - private static Bundle findBundle(String symName) { - for (Bundle bundle : bundles) { - if (bundle.getSymbolicName().equals(symName)) return bundle; - } - return null; - } - - private static List makeMockBundles() throws Exception { - List result = new ArrayList(); - result.add(new MockBundle()); - result.add(new TestMockBundle("base", "", "bundle_base")); - result.add(new TestMockBundle("sub1", "bundle_base", "bundle_sub1")); - result.add(new TestMockBundle("sub2", "bundle_base", "bundle_sub2")); - return result; - } - - private static List findClasses(String pkg) throws URISyntaxException { - if (pkg == null) return Collections.EMPTY_LIST; - String npkg = pkg.replaceAll("\\.", "/"); - URL dirUrl = BundleScannerTest.class.getClassLoader().getResource(npkg); - final List result = new ArrayList(); - File dir = new File(dirUrl.toURI()); - dir.listFiles(new FileFilter() { - - @Override - public boolean accept(File file) { - if (file.isFile() && file.getName().endsWith(".class")) { - try { - result.add(file.toURI().toURL()); - } catch (MalformedURLException e) { - throw new IllegalStateException(e); - } - } - return false; - } - - }); - return result; - } - - public static class TestMockBundle extends MockBundle { - List classes; - public TestMockBundle(String name, String imports, String exports) throws Exception { - super(name, makeHeaders(name, imports, exports), new MockBundleContext() { - @Override - public Bundle[] getBundles() { - return bundles.toArray(new Bundle[bundles.size()]); - } - }); - MockBundleContext ctx = (MockBundleContext) this.getBundleContext(); - ctx.setBundle(this); - this.classes = findClasses(exports); - } - - private static Dictionary makeHeaders( - String name, String imports, String exports) - { - Dictionary headers = new Hashtable(); - headers.put(Constants.IMPORT_PACKAGE, imports); - headers.put(Constants.EXPORT_PACKAGE, exports); - headers.put(Constants.BUNDLE_SYMBOLICNAME, name); - return headers; - } - - @Override - public Enumeration findEntries(String path, String filePattern, boolean recurse) { - return Collections.enumeration(classes); - } - - @Override - public long getBundleId() { - return hashCode(); - } - } -} diff --git a/opendaylight/adsal/northbound/commons/pom.xml b/opendaylight/adsal/northbound/commons/pom.xml deleted file mode 100644 index 6dfcff24e1..0000000000 --- a/opendaylight/adsal/northbound/commons/pom.xml +++ /dev/null @@ -1,156 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - commons.northbound - 0.6.0-SNAPSHOT - bundle - - - com.fasterxml.jackson.core - jackson-databind - - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-base - - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - - - com.sun.jersey - jersey-client - - - - com.sun.jersey - jersey-core - - - com.sun.jersey - jersey-server - - - - junit - junit - - - org.opendaylight.controller - bundlescanner - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - usermanager - - - - ch.qos.logback - logback-classic - test - - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.types, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.northbound.commons.query, - org.opendaylight.controller.northbound.commons - javax.ws.rs, - javax.ws.rs.ext, - javax.ws.rs.core, - javax.xml.bind, - javax.xml.bind.annotation, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.usermanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.northbound.bundlescanner, - org.osgi.framework, - org.osgi.service.packageadmin, - org.osgi.util.tracker, - javax.servlet.http, - com.fasterxml.jackson.core, - com.fasterxml.jackson.databind, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - org.slf4j - - ${project.basedir}/META-INF - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - add-source - - add-source - - generate-sources - - - ${project.build.directory}/generated-sources/javacc - - - - - - - - org.codehaus.mojo - javacc-maven-plugin - 2.6 - - - javacc - - javacc - - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/JacksonJsonProcessingExceptionMapper.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/JacksonJsonProcessingExceptionMapper.java deleted file mode 100644 index eb43920826..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/JacksonJsonProcessingExceptionMapper.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons; - -import javax.ws.rs.Consumes; -import javax.ws.rs.core.GenericEntity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; - -import com.fasterxml.jackson.core.JsonProcessingException; - - -/** - * A custom exception mapper for handling Jackson JsonProcessingException types - */ -@Provider -@Consumes({MediaType.APPLICATION_JSON}) -public class JacksonJsonProcessingExceptionMapper - implements ExceptionMapper -{ - - @Override - public Response toResponse(JsonProcessingException exception) { - GenericEntity entity = - new GenericEntity(exception.getMessage()) {}; - return Response.status(Response.Status.BAD_REQUEST).entity(entity).build(); - } -} - diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/NorthboundApplication.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/NorthboundApplication.java deleted file mode 100644 index cf48729113..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/NorthboundApplication.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.ws.rs.core.Application; -import javax.ws.rs.ext.ContextResolver; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.northbound.bundlescanner.IBundleScanService; -import org.opendaylight.controller.northbound.commons.exception.GenericExceptionMapper; -import org.opendaylight.controller.northbound.commons.query.QueryContextProvider; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleReference; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceException; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; - -/** - * Instance of javax.ws.rs.core.Application used to return the classes - * that will be instantiated for JAXRS processing. This hooks onto the - * bundle scanner service to provide JAXB classes to JAX-RS for prorcessing. - */ -public class NorthboundApplication extends Application { - public static final String JAXRS_RESOURCES_MANIFEST_NAME = "Jaxrs-Resources"; - public static final String JAXRS_EXCLUDES_MANIFEST_NAME = "Jaxrs-Exclude-Types"; - private static final Logger LOGGER = LoggerFactory.getLogger(NorthboundApplication.class); - private final Set _singletons; - - public NorthboundApplication() { - _singletons = new HashSet(); - _singletons.add(new ContextResolver() { - JAXBContext jaxbContext; - @Override - public synchronized JAXBContext getContext(Class type) { - if (jaxbContext == null) { - jaxbContext = newJAXBContext(); - } - return jaxbContext; - } - - } ); - _singletons.add(getJsonProvider()); - _singletons.add(new JacksonJsonProcessingExceptionMapper()); - _singletons.add(new QueryContextProvider()); - _singletons.add(new GenericExceptionMapper()); - } - - //////////////////////////////////////////////////////////////// - // Application overrides - //////////////////////////////////////////////////////////////// - - @Override - public Set getSingletons() { - return _singletons; - } - - @Override - public Set> getClasses() { - Set> result = new HashSet>(); - result.addAll(findJAXRSResourceClasses()); - return result; - } - - private static final JacksonJaxbJsonProvider getJsonProvider() { - JacksonJaxbJsonProvider jsonProvider = new JacksonJaxbJsonProvider(); - jsonProvider.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, - false); - return jsonProvider; - } - - private BundleContext getBundleContext() { - ClassLoader tlcl = Thread.currentThread().getContextClassLoader(); - Bundle bundle = null; - - if (tlcl instanceof BundleReference) { - bundle = ((BundleReference) tlcl).getBundle(); - } else { - LOGGER.warn("Unable to determine the bundle context based on " + - "thread context classloader."); - bundle = FrameworkUtil.getBundle(this.getClass()); - } - return (bundle == null ? null : bundle.getBundleContext()); - } - - private static final IBundleScanService lookupBundleScanner(BundleContext ctx) { - ServiceReference svcRef = ctx.getServiceReference(IBundleScanService.class); - if (svcRef == null) { - throw new ServiceException("Unable to lookup IBundleScanService"); - } - return IBundleScanService.class.cast(ctx.getService(svcRef)); - } - - private final JAXBContext newJAXBContext() { - BundleContext ctx = getBundleContext(); - IBundleScanService svc = lookupBundleScanner(ctx); - try { - List> cls = svc.getAnnotatedClasses(ctx, - new String[] { XmlRootElement.class.getPackage().getName() }, - parseManifestEntry(ctx, JAXRS_EXCLUDES_MANIFEST_NAME), - true); - return JAXBContext.newInstance(cls.toArray(new Class[cls.size()])); - } catch (JAXBException je) { - LOGGER.error("Error creating JAXBContext", je); - return null; - } - } - - private final Set> findJAXRSResourceClasses() { - BundleContext ctx = getBundleContext(); - String bundleName = ctx.getBundle().getSymbolicName(); - Set> result = new HashSet>(); - ServiceException recordException = null; - try { - IBundleScanService svc = lookupBundleScanner(ctx); - result.addAll(svc.getAnnotatedClasses(ctx, - new String[] { javax.ws.rs.Path.class.getName() }, - null, false)); - } catch (ServiceException se) { - recordException = se; - LOGGER.debug("Error finding JAXRS resource annotated classes in " + - "bundle: {} error: {}.", bundleName, se.getMessage()); - // the bundle scan service cannot be lookedup. Lets attempt to - // lookup the resources from the bundle manifest header - for (String c : parseManifestEntry(ctx, JAXRS_RESOURCES_MANIFEST_NAME)) { - try { - result.add(ctx.getBundle().loadClass(c)); - } catch (ClassNotFoundException cnfe) { - LOGGER.error("Cannot load class: {} in bundle: {} " + - "defined as MANIFEST JAX-RS resource", c, bundleName, cnfe); - } - } - } - - if (result.size() == 0) { - if (recordException != null) { - throw recordException; - } else { - throw new ServiceException("No resource classes found in bundle:" + - ctx.getBundle().getSymbolicName()); - } - } - return result; - } - - private final Set parseManifestEntry(BundleContext ctx, String name) { - Set result = new HashSet(); - Dictionary headers = ctx.getBundle().getHeaders(); - String header = headers.get(name); - if (header != null) { - for (String s : header.split(",")) { - s = s.trim(); - if (s.length() > 0) { - result.add(s); - } - } - } - return result; - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/RestMessages.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/RestMessages.java deleted file mode 100644 index ba2476a137..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/RestMessages.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons; - -public enum RestMessages { - SUCCESS("Success"), NOCONTAINER("Container does not exist"), NOSUBNET("Subnet does not exist"), NOSTATICROUTE( - "Static Route does not exist"), NOHOST("Host does not exist"), NOFLOW("Flow does not exist"), NONODE( - "Node does not exist"), NOPOLICY("Policy does not exist"), NORESOURCE("Resource does not exist"), RESOURCECONFLICT( - "Operation failed due to Resource Conflict"), NODEFAULT("Container default is not a custom container"), DEFAULTDISABLED( - "Container(s) are configured. Container default is not operational"), NOTALLOWEDONDEFAULT( - "Container default is a static resource, no modification allowed on it"), UNKNOWNACTION("Unknown action"), INVALIDJSON( - "JSON message is invalid"), INVALIDADDRESS("Invalid InetAddress"), AVAILABLESOON( - "Resource is not implemented yet"), INTERNALERROR("Internal Error"), SERVICEUNAVAILABLE( - "Service is not available. Could be down for maintanence"), INVALIDDATA( - "Data is invalid or conflicts with URI"); - - private String message; - - private RestMessages(String msg) { - message = msg; - } - - @Override - public String toString() { - return message; - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/BadRequestException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/BadRequestException.java deleted file mode 100644 index c1b832d3c6..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/BadRequestException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -/** - * Status Code 400 (Bad Request) - * - * The request could not be understood by the server due to malformed syntax. - * The client SHOULD NOT repeat the request without modifications. - */ -public class BadRequestException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - public BadRequestException(String string) { - super(Response.status(Response.Status.BAD_REQUEST).entity(string).type(MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/GenericExceptionMapper.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/GenericExceptionMapper.java deleted file mode 100644 index d2bbfea870..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/GenericExceptionMapper.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; -import javax.ws.rs.ext.Provider; - -@Provider -public class GenericExceptionMapper implements ExceptionMapper { - - @Override - public Response toResponse(Exception exception) { - //check if WebApplicationException and reuse status code - if (exception instanceof WebApplicationException) { - WebApplicationException ex = (WebApplicationException) exception; - return Response.status(ex.getResponse().getStatus()). - entity(ex.getResponse().getEntity()).build(); - } - // throw 500 for all other errors - return Response.status(Response.Status.INTERNAL_SERVER_ERROR). - entity(exception.getMessage()).build(); - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/InternalServerErrorException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/InternalServerErrorException.java deleted file mode 100644 index aa47a33557..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/InternalServerErrorException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; - -/** - * Status Code 500 (Internal Server Error) - * - * The server encountered an unexpected condition which prevented - * it from fulfilling the request. - * - * - * - */ -public class InternalServerErrorException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - /** - * Constructor for the INTERNAL_SERVER_ERROR custom handler - * - * @param string Error message to specify further the - * INTERNAL_SERVER_ERROR response - * - */ - public InternalServerErrorException(String string) { - super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( - string).type(MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowed.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowed.java deleted file mode 100644 index 2495bdca0b..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowed.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.core.Response; - -/** - * Implementation of StatusType for error 405 as in: - * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6 - * - * - */ -public class MethodNotAllowed implements Response.StatusType { - @Override - public int getStatusCode() { - return 405; - } - - @Override - public String getReasonPhrase() { - return "Method Not Allowed"; - } - - @Override - public Response.Status.Family getFamily() { - return Response.Status.Family.CLIENT_ERROR; - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowedException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowedException.java deleted file mode 100644 index 8a7de2c450..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/MethodNotAllowedException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; - -/** - * Status Code 405 (Method Not Allowed) - * - * The method specified in the Request-Line is not allowed for the - * resource identified by the Request-URI. The response MUST include - * an Allow header containing a list of valid methods for the - * requested resource. - * - * - * - */ -public class MethodNotAllowedException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - public MethodNotAllowedException(String string) { - super(Response.status(new MethodNotAllowed()).entity(string).type( - MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotAcceptableException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotAcceptableException.java deleted file mode 100644 index 3b926d6050..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotAcceptableException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; - -/** - * Status Code 406 (Not Acceptable) - * - * The resource identified by the request is only capable of - * generating response entities which have content characteristics not - * acceptable according to the accept headers sent in the request. - * - * - * - */ -public class NotAcceptableException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - public NotAcceptableException(String string) { - super(Response.status(Response.Status.NOT_ACCEPTABLE).entity(string) - .type(MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplemented.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplemented.java deleted file mode 100644 index 16d0cd6e29..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplemented.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.core.Response; - -/** - * Implementation of StatusType for error 501 as in: - * http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6 - */ -public class NotImplemented implements Response.StatusType { - @Override - public int getStatusCode() { - return 501; - } - - @Override - public String getReasonPhrase() { - return "Not Implemented"; - } - - @Override - public Response.Status.Family getFamily() { - return Response.Status.Family.SERVER_ERROR; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplementedException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplementedException.java deleted file mode 100644 index 5c931d2b47..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/NotImplementedException.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -/** - * Status Code 501 (Not Implemented) - * - * The server does not support the functionality required to fulfill the - * request. This is the appropriate response when the server does not recognize - * the request method and is not capable of supporting it for any resource. - */ -public class NotImplementedException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - public NotImplementedException(String string) { - super(Response.status(new NotImplemented()).entity(string).type(MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceConflictException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceConflictException.java deleted file mode 100644 index 2f1754b83d..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceConflictException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; - -/** - * Status Code 409 (Conflict) - * - * The request could not be completed due to a conflict with the - * current state of the resource. This code is only allowed in - * situations where it is expected that the user might be able to - * resolve the conflict and resubmit the request. The response body - * SHOULD include enough information for the user to recognize the - * source of the conflict. Ideally, the response entity would include - * enough information for the user or user agent to fix the problem; - * however, that might not be possible and is not required. - * - * - * - */ -public class ResourceConflictException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - public ResourceConflictException(String string) { - super(Response.status(Response.Status.CONFLICT).entity(string).type( - MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceForbiddenException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceForbiddenException.java deleted file mode 100644 index 599793503d..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceForbiddenException.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; - -/** - * Status Code 403 (Forbidden) - * - * The server understood the request, but is refusing to fulfill it. - * Authorization will not help and the request SHOULD NOT be repeated. - * If the request method was not HEAD and the server wishes to make public - * why the request has not been fulfilled, it SHOULD describe the reason - * for the refusal in the entity. - * If the server does not wish to make this information available to - * the client, the status code 404 (Not Found) can be used instead. - * - * - * - */ -public class ResourceForbiddenException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - public ResourceForbiddenException(String string) { - super(Response.status(Response.Status.FORBIDDEN).entity(string).type( - MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceGoneException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceGoneException.java deleted file mode 100644 index f38e8b3a2b..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceGoneException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; - -/** - * Status Code 410 (Gone) - * - * The requested resource is no longer available at the server and no - * forwarding address is known. This condition is expected to be - * considered permanent. Clients with link editing capabilities SHOULD - * delete references to the Request-URI after user approval. If the - * server does not know, or has no facility to determine, whether or - * not the condition is permanent, the status code 404 (Not Found) - * SHOULD be used instead. This response is cacheable unless indicated - * otherwise. - * - * - * - */ -public class ResourceGoneException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - public ResourceGoneException(String string) { - super(Response.status(Response.Status.GONE).entity(string).type( - MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceNotFoundException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceNotFoundException.java deleted file mode 100644 index 7bd09b7841..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ResourceNotFoundException.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; - -/** - * Status Code 404 (Not Found) - * - * The server has not found anything matching the Request-URI. - * No indication is given of whether the condition is temporary or permanent. - * The 410 (Gone) status code SHOULD be used if the server knows, - * through some internally configurable mechanism, that an old resource - * is permanently unavailable and has no forwarding address. - * This status code is commonly used when the server does not wish to - * reveal exactly why the request has been refused, or when no other - * response is applicable. - * - * - * - */ -public class ResourceNotFoundException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - public ResourceNotFoundException(String string) { - super(Response.status(Response.Status.NOT_FOUND).entity(string).type( - MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ServiceUnavailableException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ServiceUnavailableException.java deleted file mode 100644 index 74a8a94c98..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/ServiceUnavailableException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; - -/** - * Status Code 503 (Service Unavailable Error) - * - * The server is currently unable to handle the request due to a temporary - * overloading or maintenance of the server. - * The implication is that this is a temporary condition which will be alleviated - * after some delay. - * - * - */ -public class ServiceUnavailableException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - /** - * Constructor for the SERVICE_UNAVAILABLE custom handler - * - * @param string Error message to specify further the - * SERVICE_UNAVAILABLE response - * - */ - public ServiceUnavailableException(String string) { - super(Response.status(Response.Status.SERVICE_UNAVAILABLE).entity( - string).type(MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnauthorizedException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnauthorizedException.java deleted file mode 100644 index c7cb90026f..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnauthorizedException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; - -/** - * Status Code 401 (Unauthorized) - * - * The request requires user authentication. The response MUST include - * a WWW-Authenticate header field (section 14.47) containing a - * challenge applicable to the requested resource. - * - * - * - */ -public class UnauthorizedException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - public UnauthorizedException(String string) { - super(Response.status(Response.Status.UNAUTHORIZED).entity(string) - .type(MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnsupportedMediaTypeException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnsupportedMediaTypeException.java deleted file mode 100644 index c54d2cf203..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/UnsupportedMediaTypeException.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; - -/** - * Status Code 415 (Unsupported Media Type) - * - * The server is refusing to service the request because the entity of - * the request is in a format not supported by the requested resource - * for the requested method. - * - * - * - */ -public class UnsupportedMediaTypeException extends WebApplicationException { - private static final long serialVersionUID = 1L; - - public UnsupportedMediaTypeException(String string) { - super(Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).entity( - string).type(MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/package-info.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/package-info.java deleted file mode 100644 index d1f182b7dd..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/package-info.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * Provides the necessary class that represent exception in REST - * API. - * - */ -package org.opendaylight.controller.northbound.commons.exception; diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Accessor.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Accessor.java deleted file mode 100644 index 2d910edc6d..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Accessor.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.opendaylight.controller.northbound.commons.query; - -import java.lang.annotation.Annotation; -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Type; - -/*package*/ class Accessor { - protected final AccessibleObject _accessorObj; - - public Accessor(AccessibleObject accessor) { - _accessorObj = accessor; - _accessorObj.setAccessible(true); - } - - public AccessibleObject getAccessibleObject() { - return _accessorObj; - } - - public Annotation[] getAnnotations() { - return _accessorObj.getAnnotations(); - } - - public Object getValue(Object parent) throws QueryException { - try { - if (_accessorObj instanceof Field) { - return ((Field)_accessorObj).get(parent); - } else { - // assume method - return ((Method)_accessorObj).invoke(parent); - } - } catch (Exception e) { - throw new QueryException("Failure in retrieving value", e); - } - } - public Type getGenericType() { - if (_accessorObj instanceof Field) { - return ((Field)_accessorObj).getGenericType(); - } else { - // assume method - return ((Method)_accessorObj).getGenericReturnType(); - } - } - public Class getType() { - - if (_accessorObj instanceof Field) { - return ((Field)_accessorObj).getType(); - } else { - // assume method - return ((Method)_accessorObj).getReturnType(); - } - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/CompareExpression.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/CompareExpression.java deleted file mode 100644 index 6b972e641c..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/CompareExpression.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -/*package*/ class CompareExpression implements Expression { - - public static enum OP { RE, EQ, NE, GT, GE, LT, LE }; - - private final OP _operation; - private final String _selector; - private final String _arg; - - public CompareExpression(OP op, String selector, String arg) { - _operation = op; - _selector = selector; - _arg = unQuote(arg); - } - - - public OP getOperator() { - return _operation; - } - - public String getSelector() { - return _selector; - } - - public String getArgument() { - return _arg; - } - - @Override - public boolean accept(Visitor visitor) throws QueryException { - return visitor.visit(this); - } - - @Override - public String toString() { - return "[" + _selector + " " + _operation + " " + _arg + "]"; - } - - private static String unQuote(String s) { - if (s.startsWith("\"") && s.endsWith("\"")) { - s = s.substring(1, s.length()-1); - } else if (s.startsWith("\'") && s.endsWith("\'")) { - s = s.substring(1, s.length()-1); - } - return s; - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Expression.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Expression.java deleted file mode 100644 index fbc22a016d..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Expression.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -/*package*/ interface Expression { - boolean accept(Visitor visitor) throws QueryException; -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/ExpressionBuilder.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/ExpressionBuilder.java deleted file mode 100644 index f1b2999b77..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/ExpressionBuilder.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import java.util.Stack; - -/*package*/ class ExpressionBuilder { - private final Stack _stack = new Stack(); - private LogicalExpression.OP _lastOp = null; - - public ExpressionBuilder() {} - - public ExpressionBuilder withAnd() { - _lastOp = LogicalExpression.OP.AND; - return this; - } - - public ExpressionBuilder withOr() { - _lastOp = LogicalExpression.OP.OR; - return this; - } - - public ExpressionBuilder withTerm(Expression exp) { - if (_lastOp != null) { - exp = new LogicalExpression(_lastOp, _stack.pop(), exp); - _lastOp = null; - } - _stack.push(exp); - return this; - } - - public Expression build() { - return _stack.pop(); - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/IteratableTypeInfo.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/IteratableTypeInfo.java deleted file mode 100644 index d0386ed2c5..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/IteratableTypeInfo.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.opendaylight.controller.northbound.commons.query; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -/** - */ -/*package*/ class IteratableTypeInfo extends TypeInfo { - - public IteratableTypeInfo(String name, Accessor accessor) { - super(name, accessor.getType(), accessor); - } - - @Override - public Object retrieve(Object target, String[] query, int index) throws QueryException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("retrieve collection: {}/{} type:{}", index, query.length, - target.getClass()); - } - explore(); - Collection c = (Collection) target; - Iterator it = c.iterator(); - List objects = new ArrayList(); - while (it.hasNext()) { - Object item = it.next(); - for (TypeInfo child : _types.values()) { - Object val = child.retrieve(item, query, index); - if (val != null) { - objects.add(val); - } - } - } - return objects; - - } - - @Override - public synchronized void explore() { - if (_explored) { - return; - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exploring iteratable type: {} gtype: {}", _class, - _accessor.getGenericType()); - } - Type t = _accessor.getGenericType(); - if (t instanceof ParameterizedType) { - Type[] pt = ((ParameterizedType) t).getActualTypeArguments(); - // First type is a child, ignore rest - if (pt.length > 0) { - _types.put(_name, new TypeInfo(_name, (Class)pt[0], null)); - } - } - _explored = true; - } - - @Override - public TypeInfo getCollectionChild(Class childType) { - explore(); - for (TypeInfo ti : _types.values()) { - if (ti.getType().equals(childType)) { - return ti; - } - } - return null; - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/LogicalExpression.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/LogicalExpression.java deleted file mode 100644 index 4e99820983..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/LogicalExpression.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -/*package*/ class LogicalExpression implements Expression { - - public static enum OP { AND, OR } - - private final OP _op; - private final Expression _arg1; - private final Expression _arg2; - - public LogicalExpression(OP op, Expression first, Expression second) { - _op = op; - _arg1 = first; - _arg2 = second; - } - - public OP getOperator() { - return _op; - } - - public Expression getFirst() { - return _arg1; - } - - public Expression getSecond() { - return _arg2; - } - - @Override - public boolean accept(Visitor visitor) throws QueryException { - return visitor.visit(this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(_arg1.toString()) - .append(_op.toString()) - .append(_arg2.toString()); - return sb.toString(); - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Query.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Query.java deleted file mode 100644 index 15dcaebe27..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Query.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import java.util.Collection; -import java.util.List; - - -/** - * Represents a parsed query used in filtering of collections. - */ -public interface Query { - - /** - * Find items in the given collection and return them as a new list. The - * original collection is not changed. - * - * @param collection to search in. - * @return list of items which match the query. - * @throws QueryException - */ - public List find(Collection collection) throws QueryException; - - /** - * Apply the query on the given collection. Note that this method will modify - * the given object by removing any items which don't match the query criteria. - * If the collection is 'singleton' or unmodifiable, invocation will result in - * an exception. - * - * @param collection - * @return the number matched items - * @throws QueryException - */ - public int filter(Collection collection) throws QueryException; - - /** - * Search the given root for a child collection and them apply the query on. - * Note that this method will modify the given object by removing any items - * which don't match the query criteria. - * - * @param root - top level object to search in - * @param childType - the child type which represents the collection. - * @return the number of matched items - * @throws QueryException - */ - public int filter(T root, Class childType) throws QueryException; -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContext.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContext.java deleted file mode 100644 index 59a78ac113..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContext.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -/** - * Query context - */ -public interface QueryContext { - - /** - * Create a Query - * @param queryString - query string to parse - * @param clazz - The class which represents the top level jaxb object - * @return a query object - * @throws QueryException if the query cannot be parsed. - */ - Query createQuery(String queryString, Class clazz) - throws QueryException; - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextImpl.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextImpl.java deleted file mode 100644 index 8f83c147c8..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/*package*/ class QueryContextImpl implements QueryContext { - - private static final Logger LOGGER = LoggerFactory.getLogger(QueryContext.class); - - @Override - public Query createQuery(String queryString, Class type) throws QueryException { - if (queryString == null || queryString.trim().length() == 0) { - return null; - } - try { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Processing query: {}", queryString); - } - // FiqlParser is a parser generated by javacc - Expression expression = FiqlParser.parse(queryString); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Query expression: {}", expression); - } - // create Query and return; - return new QueryImpl(type, expression); - } catch (Exception ex) { - if (LOGGER.isDebugEnabled()) { - LOGGER.error("Query processing failed = {}", - queryString, ex); - } - throw new QueryException("Unable to parse query.", ex); - } - } -} \ No newline at end of file diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextProvider.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextProvider.java deleted file mode 100644 index 65a232c245..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Provider; - -/** - * A provider for getting hold of the QueryContext. - */ -@Provider -public class QueryContextProvider implements ContextResolver { - - // Singleton Query Context instance - private static final QueryContext queryContext = new QueryContextImpl(); - - @Override - public QueryContext getContext(Class type) { - return queryContext; - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryException.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryException.java deleted file mode 100644 index 9ff78eddfc..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryException.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -/** - * Signals that an error happened during the parsing or processing of a query. - */ -public class QueryException extends WebApplicationException { - - private static final long serialVersionUID = 1L; - - public QueryException(String msg) { - super(Response.status(Response.Status.BAD_REQUEST) - .entity(msg).type(MediaType.TEXT_PLAIN).build()); - } - - public QueryException(String msg, Throwable cause) { - super(cause, Response.status(Response.Status.BAD_REQUEST) - .entity(msg).type(MediaType.TEXT_PLAIN).build()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryImpl.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryImpl.java deleted file mode 100644 index cb77e04a59..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryImpl.java +++ /dev/null @@ -1,241 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.regex.Pattern; - -import org.opendaylight.controller.northbound.commons.query.CompareExpression.OP; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -/*package*/ class QueryImpl implements Query { - public static final Logger LOGGER = LoggerFactory.getLogger(QueryImpl.class); - private static final boolean ALLOW_OBJECT_STRING_COMPARE = true; - - private final Expression expression; - private final TypeInfo rootType ; - /** - * Set the expression and cache - * @param type - * @param expression - */ - public QueryImpl(Class type, Expression expression) { - this.expression = expression; - this.rootType = TypeInfo.createRoot(null, type); - } - - @Override - public List find(Collection collection) throws QueryException { - // new arraylist for result - List result = new ArrayList(); - for (T item : collection) { - if (match(item, rootType)) { - result.add(item); - } - } - return result; - } - - @Override - public int filter(Collection collection) throws QueryException { - // find items - List matched = new ArrayList(); - for (T item : collection) { - if (match(item, rootType)) { - matched.add(item); - } - } - collection.clear(); - collection.addAll(matched); - return matched.size(); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public int filter(T rootObject, Class childClass) throws QueryException { - // retrieve underlying collection - TypeInfo childType = rootType.getCollectionChild(childClass); - if (childType == null || !(childType instanceof IteratableTypeInfo)) { - return 0; - } - Collection collection = (Collection) - childType.getAccessor().getValue(rootObject); - // get the child type of the collection type - TypeInfo ti = childType.getCollectionChild(childClass); - List matched = new ArrayList(); - for (Object item : collection) { - if (match(item, ti)) { - matched.add(item); - } - } - collection.clear(); - collection.addAll(matched); - return matched.size(); - } - - private boolean match(final Object object, final TypeInfo rootType) - throws QueryException { - return expression.accept(new Visitor () { - @Override - public boolean visit(LogicalExpression le) throws QueryException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Logical exp {}|{}|{}", le.getOperator(), le.getFirst(), - le.getSecond()); - } - return (le.getOperator() == LogicalExpression.OP.AND) ? - le.getFirst().accept(this) && le.getSecond().accept(this) : - le.getFirst().accept(this) || le.getSecond().accept(this); - } - - @Override - public boolean visit(CompareExpression ce) throws QueryException { - boolean result = visitInternal(ce); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("=== Compare exp {}|{}|{} == {}", ce.getOperator(), - ce.getSelector(), ce.getArgument(), result); - } - return result; - } - - public boolean visitInternal(CompareExpression ce) throws QueryException { - String[] selector = ce.getSelector().split("\\."); - if (!rootType.getName().equals(selector[0])) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Root name mismatch: {} != {}", - rootType.getName(), selector[0]); - } - return false; - } - Object value = rootType.retrieve(object, selector, 1); - if(value == null){ // nothing to compare against - return false; - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Comparing [{}] {} [{}]", ce.getArgument(), - ce.getOperator(), value.toString()); - } - if (value instanceof Collection) { - Collection collection = (Collection) value; - if(collection.size() == 0 && ce.getOperator() == OP.NE) { - // collection doesn't contain query string - return true; - } - // If there are elements iterate - Iterator it = collection.iterator(); - OP operator = ce.getOperator(); - if (operator == OP.NE) { - // negate the operator - operator = OP.EQ; - } - while (it.hasNext()) { - Object item = it.next(); - if (compare(parse(ce.getArgument(), item), item, operator)) { - // if match found check the operator and return false for NE - return (ce.getOperator() != OP.NE); - } - } - // return true for NE and false for rest - return (ce.getOperator() == OP.NE); - } else { - return compare(parse(ce.getArgument(), value), value, - ce.getOperator()); - } - } - - }); - } - - private boolean compare(Object valueToMatch, Object actualValue, OP operator) { - if (valueToMatch == null || actualValue == null) { - return false; - } - if (ALLOW_OBJECT_STRING_COMPARE && (valueToMatch instanceof String) - && !(actualValue instanceof String)) { - actualValue = actualValue.toString(); - } - - int compareResult = -1; - if (valueToMatch instanceof Comparable) { - compareResult = ((Comparable)actualValue).compareTo(valueToMatch); - } else { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Not a comparable type: {} {}", - valueToMatch.getClass().getName(), - actualValue.getClass().getName()); - } - return false; - } - switch(operator) { - case EQ : - return compareResult == 0; - case RE : - // Regex match, - if (valueToMatch instanceof String) { - return Pattern.matches((String)valueToMatch, actualValue.toString()); - } else { - return compareResult == 0; - } - case NE: - return compareResult != 0; - case GT : - return compareResult > 0; - case GE : - return compareResult >= 0; - case LT : - return compareResult < 0; - case LE : - return compareResult <= 0; - default: - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Unrecognized comparator - {}", operator); - } - return false; - } - } - private Object parse(String arg, Object value) { - if (value == null) { - return null; - } - - try { - if (value instanceof String) { - return arg; - } else if (value instanceof Byte) { - return Byte.decode(arg); - } else if (value instanceof Double) { - return Double.parseDouble(arg); - } else if (value instanceof Float) { - return Float.parseFloat(arg); - } else if (value instanceof Integer) { - return Integer.parseInt(arg); - } else if (value instanceof Long) { - return Long.parseLong(arg); - } else if (value instanceof Short) { - return Short.parseShort(arg); - } - } catch (NumberFormatException ignore) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Exception parsing {}", arg, value); - } - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Using string comparision for type - {}", - value.getClass().getName()); - } - // Not a number or string. Convert to a string and compare as last resort - return ALLOW_OBJECT_STRING_COMPARE ? arg.toString() : null; - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/TypeInfo.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/TypeInfo.java deleted file mode 100644 index 6c0c5dc816..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/TypeInfo.java +++ /dev/null @@ -1,316 +0,0 @@ -package org.opendaylight.controller.northbound.commons.query; - -import java.beans.BeanInfo; -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementRef; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; -import javax.xml.bind.annotation.XmlType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A wrapper over a JAXB type to allow traversal of the object graph and - * search for specific values in the object tree. - */ -/*package*/ class TypeInfo { - - public static final Logger LOGGER = LoggerFactory.getLogger(TypeInfo.class); - public static final String DEFAULT_NAME = "##default"; - - protected final String _name; // the jaxb name - protected Class _class; // jaxb type class - protected final XmlAccessType _accessType; // jaxb access type - protected final Accessor _accessor; // accessor to access object value - protected Map _types = new HashMap(); - protected volatile boolean _explored = false; - /** - * Create a TypeInfo with a name and a class type. The accessor will be null - * for a root node. - */ - protected TypeInfo(String name, Class clz, Accessor accessor) { - _name = name; - _class = clz; - _accessor = accessor; - XmlAccessorType accessorType = null; - if(clz == null) { - throw new NullPointerException("Type class can not be null"); - } - accessorType = clz.getAnnotation(XmlAccessorType.class); - _accessType = (accessorType == null ? - XmlAccessType.PUBLIC_MEMBER : accessorType.value()); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Created type info name:{} type:{}", _name, _class); - } - } - - /** - * @return the Accessor to access the value - */ - public final Accessor getAccessor() { - return _accessor; - } - - /** - * @return get the child by name - */ - public final TypeInfo getChild(String name) { - return _types.get(name); - } - - public TypeInfo getCollectionChild(Class childType) { - explore(); - for (TypeInfo ti : _types.values()) { - if (Collection.class.isAssignableFrom(ti.getType())) { - ParameterizedType p = (ParameterizedType) - ti.getAccessor().getGenericType(); - Type[] pts = p.getActualTypeArguments(); - if (pts.length == 1 && pts[0].equals(childType)) { - return ti; - } - } - } - return null; - } - - public Class getType() { - return _class; - } - - public String getName() { - return _name; - } - - /** - * @return the object value by a selector query - */ - public Object retrieve(Object target, String[] query, int index) - throws QueryException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("retrieve: {}/{} type:{}", index, query.length, target.getClass()); - } - if (index >= query.length) { - return null; - } - explore(); - if (!target.getClass().equals(_class)) { - if (_class.isAssignableFrom(target.getClass())) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Handling subtype {} of {} ", target.getClass(), _class); - } - // explore the subtype - TypeInfo subTypeInfo = new TypeInfo(getRootName(target.getClass()), - target.getClass(), _accessor); - return subTypeInfo.retrieve(target, query, index); - } else { - // non compatible object; bail out - return null; - } - } - TypeInfo child = getChild(query[index]); - if (child == null) { - return null; - } - target = child.getAccessor().getValue(target); - if (index+1 == query.length) { - // match found - return target; - } - return child.retrieve(target, query, index+1); - } - - /** - * Explore the type info for children. - */ - public synchronized void explore() { - if (_explored) { - return; - } - for (Class c = _class; c != null; c = c.getSuperclass()) { - if (c.equals(Object.class)) { - break; - } - // Currently only fields and methods annotated with JAXB annotations are - // considered as valid for search purposes. - //check methods first - for (Method m : c.getDeclaredMethods()) { - String tn = getTypeName(m, _accessType); - if (tn != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - "exploring type: {} name: {} method: {}", - _class.getSimpleName(), tn, m); - } - _types.put(tn, createTypeInfo(tn, new Accessor(m))); - } - } - for (Field f : c.getDeclaredFields()) { - String tn = getTypeName(f, _accessType); - if (tn != null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - "exploring type: {} name: {} field: {}", - _class.getSimpleName(), tn, f); - } - _types.put(tn, createTypeInfo(tn, new Accessor(f))); - } - } - } - _explored = true; - } - - public static final String getTypeName(Field f, XmlAccessType access) { - // ignore static, transient and xmltransient fields - if (Modifier.isTransient(f.getModifiers()) || - Modifier.isStatic(f.getModifiers()) || - f.getAnnotation(XmlTransient.class) != null ) { - return null; - } - // try to read annotation - String name = getTypeName(f.getAnnotations(), f.getName()); - if (name != null) return name; - // no annotation present check accesstype - else if (access == XmlAccessType.NONE) { // none return name - return name; - } else if (access == XmlAccessType.FIELD) { - // return field name if no annotation present - return f.getName(); - } else if (access == XmlAccessType.PUBLIC_MEMBER - && Modifier.isPublic(f.getModifiers())) { // look for public access - return f.getName(); - } - // return annotated name ( if any ) - return null; - } - - public static final String getTypeName(Method m, XmlAccessType access) { - // ignore static, transient and xmltransient fields - if (Modifier.isStatic(m.getModifiers()) || - m.getAnnotation(XmlTransient.class) != null ) { - return null; - } - // try to read annotation - String name = getTypeName(m.getAnnotations(), m.getName()); - if (name != null) return name; - //check acces type - else if (access == XmlAccessType.NONE) { // none return name - return name; - } else if (access == XmlAccessType.PROPERTY) { - // return bean property name if no annotation present - return getBeanPropertyName(m); - } else if (access == XmlAccessType.PUBLIC_MEMBER - && Modifier.isPublic(m.getModifiers())) { // look for public access - return getBeanPropertyName(m); - } - return null; - } - - private static String getBeanPropertyName(Method m){ - try - { - Class clazz=m.getDeclaringClass(); - BeanInfo info = Introspector.getBeanInfo(clazz); - PropertyDescriptor[] props = info.getPropertyDescriptors(); - for (PropertyDescriptor pd : props) - { - if (m.equals(pd.getReadMethod())) { - return pd.getName(); - } - } - } - catch (IntrospectionException e) - { - LOGGER.error("Could not read bean property name for method = {}", - m.getName(), e); - } - return null; - } - - public static TypeInfo createRoot(String name, Class clz) { - // root is always a composite type - // FIXME assert its a JAXB type - XmlRootElement root = clz.getAnnotation(XmlRootElement.class); - if (root == null) { - throw new IllegalArgumentException("Not a JAXB type: " + clz); - } - if (name == null) { - name = getRootName(clz); - } - return new TypeInfo(name, clz, null); - } - - public static TypeInfo createTypeInfo(String name, Accessor accessor) { - if (accessor.getAccessibleObject().getAnnotation(XmlElementWrapper.class) != null) { - //XmlElementWrapperType - return new WrapperTypeInfo(name, accessor); - } else if (Collection.class.isAssignableFrom(accessor.getType())) { - // collection type - return new IteratableTypeInfo(name, accessor); - } - return new TypeInfo(name, accessor.getType(), accessor); - } - - public static String getRootName(Class cls) { - XmlRootElement root = cls.getAnnotation(XmlRootElement.class); - if (root == null) { - return null; - } - String rootName = root.name(); - if (DEFAULT_NAME.equals(rootName)) { - String clsName = cls.getSimpleName(); - rootName = Character.toLowerCase(clsName.charAt(0)) + clsName.substring(1); - } - return rootName; - } - - protected static String getTypeName(Annotation[] annotations, String dflt) { - String name = null; - for (Annotation a : annotations) { - if (a.annotationType() == XmlAttribute.class) { - name = ((XmlAttribute)a).name(); - } else if (a.annotationType() == XmlElement.class) { - name = ((XmlElement)a).name(); - } else if (a.annotationType() == XmlElementRef.class) { - name = ((XmlElementRef)a).name(); - } else if (a.annotationType() == XmlElementWrapper.class) { - name = ((XmlElementWrapper)a).name(); - // break the loop as we don't want name to be overwritten by XmlElement - break; - } else if (a.annotationType() == XmlType.class) { - name = ((XmlType)a).name(); - } else if (a.annotationType() == XmlTransient.class) { - // transient type - return null; - } - } - if (DEFAULT_NAME.equals(name)) { - return dflt; - } - return name; - } - - @Override - public String toString() { - return " TypeInfo [_name=" + _name + ", _class=" + _class - + ", _accessType=" + _accessType + ", _accessor=" + _accessor - + ", _types=" + _types + ", _explored=" + _explored + " ] "; - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Visitor.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Visitor.java deleted file mode 100644 index 0c1d2be236..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Visitor.java +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -/*package*/ interface Visitor { - - boolean visit(LogicalExpression exp) throws QueryException; - - boolean visit(CompareExpression exp) throws QueryException; - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/WrapperTypeInfo.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/WrapperTypeInfo.java deleted file mode 100644 index 156942c61d..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/WrapperTypeInfo.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -import javax.xml.bind.annotation.XmlElement; - -public class WrapperTypeInfo extends TypeInfo { - - protected WrapperTypeInfo(String name, Accessor accessor) { - super(name, accessor.getType(), accessor); - } - - @Override - public Object retrieve(Object target, String[] query, int index) throws QueryException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("retrieve collection: {}/{}", index, query.length); - } - if (index >= query.length) { - return null; - } - explore(); - TypeInfo child = getChild(query[index]); - if (child == null) { - return null; - } - if (query.length == index+1) { // skipping this node - return target; - }else { // if list of list go to next node to get value - return child.retrieve(target, query, index+1); - } - } - - @Override - public synchronized void explore() { - if (_explored) { - return; - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("exploring wrapper type: {} gtype: {}", _class, - _accessor.getGenericType()); - } - String tn = null; - AccessibleObject accessibleObject = _accessor.getAccessibleObject(); - XmlElement xmlElement = accessibleObject.getAnnotation(XmlElement.class); - if (accessibleObject instanceof Field) { - Field f = (Field) accessibleObject; - tn = DEFAULT_NAME.equals(xmlElement.name())?f.getName() : xmlElement.name(); - }else if (accessibleObject instanceof Method) { - Method m = (Method) accessibleObject; - tn = DEFAULT_NAME.equals(xmlElement.name())?m.getName() : xmlElement.name(); - } - this._types.put(tn, new IteratableTypeInfo(tn, this._accessor)); - _explored = true; - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/types/StringList.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/types/StringList.java deleted file mode 100644 index 62d1608098..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/types/StringList.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northbound.commons.types; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Represents a list of string values - */ -@XmlRootElement(name = "list") -@XmlAccessorType(XmlAccessType.NONE) -public class StringList { - @XmlElement(name = "item") - private List list; - - public StringList() { - } - - public StringList(List list) { - this.list = list; - } - - public List getList() { - return list; - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/utils/NorthboundUtils.java b/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/utils/NorthboundUtils.java deleted file mode 100644 index 4e78c201c1..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/utils/NorthboundUtils.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.utils; - -import java.util.HashMap; -import java.util.Map; - -import javax.ws.rs.core.Response; - -import org.opendaylight.controller.containermanager.IContainerAuthorization; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.core.Description; -import org.opendaylight.controller.sal.core.Name; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.usermanager.IUserManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NorthboundUtils { - - private static final Map ResponseStatusMapping = new HashMap() { - private static final long serialVersionUID = 1L; - { - put(StatusCode.SUCCESS, Response.Status.OK); - put(StatusCode.BADREQUEST, Response.Status.BAD_REQUEST); - put(StatusCode.UNAUTHORIZED, Response.Status.UNAUTHORIZED); - put(StatusCode.FORBIDDEN, Response.Status.FORBIDDEN); - put(StatusCode.NOTFOUND, Response.Status.NOT_FOUND); - put(StatusCode.NOTALLOWED, Response.Status.FORBIDDEN); - put(StatusCode.NOTACCEPTABLE, Response.Status.NOT_ACCEPTABLE); - put(StatusCode.TIMEOUT, Response.Status.GONE); - put(StatusCode.CONFLICT, Response.Status.CONFLICT); - put(StatusCode.GONE, Response.Status.GONE); - put(StatusCode.UNSUPPORTED, Response.Status.BAD_REQUEST); - put(StatusCode.INTERNALERROR, Response.Status.INTERNAL_SERVER_ERROR); - put(StatusCode.NOTIMPLEMENTED, Response.Status.NOT_ACCEPTABLE); - put(StatusCode.NOSERVICE, Response.Status.SERVICE_UNAVAILABLE); - put(StatusCode.UNDEFINED, Response.Status.BAD_REQUEST); - } - }; - - private static final String AUDIT = "audit"; - - private static final Logger logger = LoggerFactory.getLogger(AUDIT); - - // Suppress default constructor for noninstantiability - private NorthboundUtils() { - } - - /** - * Returns Response.Status for a given status. If the status is null or if - * the corresponding StatusCode is not present in the ResponseStatusMapping, - * it returns null. - * - * @param status - * The Status - * @return The Response.Status for a given status - */ - public static Response.Status getResponseStatus(Status status) { - return ResponseStatusMapping.get(status.getCode()); - } - - /** - * Returns Response for a given status. If the status provided is null or if - * the corresponding StatusCode is not present in the ResponseStatusMapping, - * it returns Response with StatusType as INTERNAL_SERVER_ERROR. - * - * @param status - * The Status - * @return The Response for a given status. - */ - public static Response getResponse(Status status) { - if ((status == null) || (!ResponseStatusMapping.containsKey(status.getCode()))) { - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Action Result Unknown").build(); - } - return Response.status(ResponseStatusMapping.get(status.getCode())).entity(status.getDescription()).build(); - } - - /** - * Returns whether the current user has the required privilege on the - * specified container - * - * @param userName - * The user name - * @param containerName - * The container name - * @param required - * Operation to be performed - READ/WRITE - * @param bundle - * Class from where the function is invoked - * @return The Status of the request, either Success or Unauthorized - */ - public static boolean isAuthorized(String userName, String containerName, Privilege required, Object bundle) { - - if (containerName.equals(GlobalConstants.DEFAULT.toString())) { - IUserManager auth = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, bundle); - - switch (required) { - case WRITE: - return (auth.getUserLevel(userName).ordinal() <= UserLevel.NETWORKADMIN.ordinal()); - case READ: - return (auth.getUserLevel(userName).ordinal() <= UserLevel.NETWORKOPERATOR.ordinal()); - default: - return false; - } - - } else { - IContainerAuthorization auth = (IContainerAuthorization) ServiceHelper.getGlobalInstance( - IContainerAuthorization.class, bundle); - - if (auth == null) { - return false; - } - - Privilege current = auth.getResourcePrivilege(userName, containerName); - if (required.ordinal() > current.ordinal()) { - return false; - } - } - return true; - } - - public static void auditlog(String moduleName, String user, String action, String resource, - String containerName) { - String auditMsg = ""; - String mode = "REST"; - if (containerName != null) { - auditMsg = "Mode: " + mode + " User " + user + " " + action + " " + moduleName + " " + resource + " in container " - + containerName; - } else { - auditMsg = "Mode: " + mode + " User " + user + " " + action + " " + moduleName + " " + resource; - } - logger.trace(auditMsg); - } - - public static void auditlog(String moduleName, String user, String action, String resource) { - auditlog(moduleName, user, action, resource, null); - } - - public static String getNodeDesc(Node node, ISwitchManager switchManager) { - Description desc = (Description) switchManager.getNodeProp(node, - Description.propertyName); - String description = (desc == null) ? "" : desc.getValue(); - return (description.isEmpty() || description.equalsIgnoreCase("none")) ? node - .toString() : description; - } - - public static String getNodeDesc(Node node, String containerName, - Object bundle) { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, containerName, bundle); - if (switchManager == null) { - return null; - } - - return getNodeDesc(node, switchManager); - } - - public static String getNodeDesc(Node node, Object bundle) { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, - GlobalConstants.DEFAULT.toString(), bundle); - if (switchManager == null) { - return null; - } - - return getNodeDesc(node, switchManager); - } - - public static String getPortName(NodeConnector nodeConnector, - String container, Object bundle) { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, container, bundle); - return getPortName(nodeConnector, switchManager); - } - - public static String getPortName(NodeConnector nodeConnector, Object bundle) { - return getPortName(nodeConnector, GlobalConstants.DEFAULT.toString(), bundle); - } - - public static String getPortName(NodeConnector nodeConnector, - ISwitchManager switchManager) { - Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector, - Name.NamePropName)); - String nodeConnectorName = (ncName != null) ? ncName.getValue() : nodeConnector.getNodeConnectorIdAsString(); - nodeConnectorName = nodeConnectorName + "@" - + getNodeDesc(nodeConnector.getNode(), switchManager); - return nodeConnectorName.substring(0, nodeConnectorName.length()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/main/javacc/fiql.jj b/opendaylight/adsal/northbound/commons/src/main/javacc/fiql.jj deleted file mode 100644 index b447a32a54..0000000000 --- a/opendaylight/adsal/northbound/commons/src/main/javacc/fiql.jj +++ /dev/null @@ -1,124 +0,0 @@ - -options { - STATIC = false; -} - -PARSER_BEGIN(FiqlParser) -package org.opendaylight.controller.northbound.commons.query; - -import java.util.regex.*; - -/*package*/ class FiqlParser { - public static Expression parse(String query) throws ParseException { - FiqlParser parser = new FiqlParser(new java.io.StringReader(query)); - return parser.START(); - } -} - -PARSER_END(FiqlParser) - -/* whitespace */ -SKIP : -{ - " " | "\t" -} - -TOKEN : { - <#ALPHA : ( ["a"-"z", "A"-"Z", "0"-"9"] )+ > -} - -TOKEN : { - - | - - | - -} - -/* comparision ops */ -TOKEN : { - - | - ") > - | - =") > -} - -/* ops */ -TOKEN : { - - | - -} - -/* strings */ -TOKEN : { - ", "!", "~", " "] )+ > - | - - | - -} - -/* Root production */ -Expression START() : -{ - Expression e; -} -{ - e = EXPR() - - { - return e; - } -} - -Expression EXPR(): -{ - ExpressionBuilder builder = new ExpressionBuilder(); - Expression t; -} -{ - t = TERM() { builder.withTerm(t); } - ( - ( t = TERM()) { builder.withAnd().withTerm(t); } - | - ( t = TERM() ) { builder.withOr().withTerm(t); } - )* - { - return builder.build(); - } -} - -Expression TERM() : -{ - Token selector, arg; - Expression exp; - CompareExpression.OP op; -} -{ - selector = - ( - ( {op=CompareExpression.OP.EQ;} | - {op=CompareExpression.OP.RE;} | - {op=CompareExpression.OP.NE;} | - {op=CompareExpression.OP.LT;} | - {op=CompareExpression.OP.LE;} | - {op=CompareExpression.OP.GT;} | - {op=CompareExpression.OP.GE;} - ) - ( arg = | arg = | arg = | arg = ) - ) { return new CompareExpression(op, selector.image, arg.image); } - | - ( - exp = EXPR() - ) { return exp; } -} diff --git a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/CommonsNorthboundTest.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/CommonsNorthboundTest.java deleted file mode 100644 index ec9590b442..0000000000 --- a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/CommonsNorthboundTest.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons; - -import org.junit.Assert; -import org.junit.Test; - -public class CommonsNorthboundTest { - - @Test - public void testRestMessages() { - Assert.assertTrue(RestMessages.SUCCESS.toString().equals("Success")); - Assert.assertTrue(RestMessages.INTERNALERROR.toString().equals( - "Internal Error")); - Assert.assertTrue(RestMessages.INVALIDDATA.toString().equals( - "Data is invalid or conflicts with URI")); - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/exception/CommonsNorthboundExceptionTest.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/exception/CommonsNorthboundExceptionTest.java deleted file mode 100644 index 8784950330..0000000000 --- a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/exception/CommonsNorthboundExceptionTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.exception; - -import javax.ws.rs.core.Response; - -import org.junit.Assert; -import org.junit.Test; - -public class CommonsNorthboundExceptionTest { - - @Test - public void testMethodNotAllowed() { - MethodNotAllowed mna = new MethodNotAllowed(); - Assert.assertTrue(mna.getStatusCode() == 405); - Assert.assertTrue(mna.getReasonPhrase().equals("Method Not Allowed")); - Assert.assertTrue(mna.getFamily().equals( - Response.Status.Family.CLIENT_ERROR)); - } - - @Test - public void testInternalServerErrorException() { - try { - throw new InternalServerErrorException("Internal Server Exception"); - } catch (InternalServerErrorException e) { - Assert.assertTrue(e.getResponse().getEntity() - .equals("Internal Server Exception")); - } - } - - @Test - public void testMethodNotAllowedException() { - try { - throw new MethodNotAllowedException("Method Not Allowed Exception"); - } catch (MethodNotAllowedException e) { - Assert.assertTrue(e.getResponse().getEntity() - .equals("Method Not Allowed Exception")); - } - } - - @Test - public void testNotAcceptableException() { - try { - throw new NotAcceptableException("Not Acceptable Exception"); - } catch (NotAcceptableException e) { - Assert.assertTrue(e.getResponse().getEntity() - .equals("Not Acceptable Exception")); - } - } - - @Test - public void testResourceConflictException() { - try { - throw new ResourceConflictException("Resource Conflict Exception"); - } catch (ResourceConflictException e) { - Assert.assertTrue(e.getResponse().getEntity() - .equals("Resource Conflict Exception")); - } - } - - @Test - public void testResourceForbiddenException() { - try { - throw new ResourceForbiddenException("Resource Forbidden Exception"); - } catch (ResourceForbiddenException e) { - Assert.assertTrue(e.getResponse().getEntity() - .equals("Resource Forbidden Exception")); - } - } - - @Test - public void testResourceGoneException() { - try { - throw new ResourceGoneException("Resource Gone Exception"); - } catch (ResourceGoneException e) { - Assert.assertTrue(e.getResponse().getEntity() - .equals("Resource Gone Exception")); - } - } - - @Test - public void testResourceNotFoundException() { - try { - throw new ResourceNotFoundException("Resource Not Found Exception"); - } catch (ResourceNotFoundException e) { - Assert.assertTrue(e.getResponse().getEntity() - .equals("Resource Not Found Exception")); - } - } - - @Test - public void testServiceUnavailableException() { - try { - throw new ServiceUnavailableException( - "Service Unavailable Exception"); - } catch (ServiceUnavailableException e) { - Assert.assertTrue(e.getResponse().getEntity() - .equals("Service Unavailable Exception")); - } - } - - @Test - public void testUnauthorizedException() { - try { - throw new UnauthorizedException("Unauthorized Exception"); - } catch (UnauthorizedException e) { - Assert.assertTrue(e.getResponse().getEntity() - .equals("Unauthorized Exception")); - } - } - - @Test - public void testUnsupportedMediaTypeException() { - try { - throw new UnsupportedMediaTypeException( - "Unsupported Media Type Exception"); - } catch (UnsupportedMediaTypeException e) { - Assert.assertTrue(e.getResponse().getEntity() - .equals("Unsupported Media Type Exception")); - } - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/BookBean.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/BookBean.java deleted file mode 100644 index 5d518f684d..0000000000 --- a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/BookBean.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.opendaylight.controller.northbound.commons.query; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.northbound.commons.types.StringList; - -/** - */ - -@XmlRootElement(name="book") -public class BookBean { - - @XmlElement(name="name") - private String _name; // simple type - - private String _isbn; // method annotation - - @XmlElement(name="author") - private PersonBean _author; // composite type - - @XmlElementWrapper//for XMLWrapper iterative composite types - @XmlElement(name="review") - private final List reviews = new ArrayList(); - - @XmlElement - private List soldBy; //Iterative Type - - @XmlElementWrapper(name="test") - @XmlElement - private final List testList = new ArrayList(); //XMLWrapper list of list - - @XmlElementWrapper(name="parent") - @XmlElement(name="child") - private final List wrapperList = new ArrayList(); // XMLWrapper of XMLWrapper - - public BookBean(){} - - public BookBean(String name, String id, PersonBean person) { - _name = name; - _isbn = id; - _author = person; - soldBy = new ArrayList(); - } - - public BookBean addReview(ReviewBean review) { - reviews.add(review); - return this; - } - - public void setSellerInfo(List sellers) { - soldBy = new ArrayList(sellers); - } - - public void addWrapperList(WrapperList list){ - wrapperList.add(list); - } - - public void addToTestList(StringList testList){ - this.testList.add(testList); - } - public String getName() { - return "1"+_name; - } - - @XmlElement(name="isbn") - public String get_isbn() { - return "pre"+_isbn; - } - - public PersonBean getauthor() { - return _author; - } - - @Override - public String toString() { - return "BookBean [_name=" + _name + ", _isbn=" + _isbn + ", _author=" - + _author + ", reviews=" + reviews + ", soldBy=" + soldBy - + ", testList=" + testList + ", wrapperList=" + wrapperList + "]"; - } - -} - -class WrapperList { - @XmlElementWrapper(name="items") - @XmlElement - public List item = new ArrayList(); -} diff --git a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ExpresssionTest.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ExpresssionTest.java deleted file mode 100644 index 3e2e1538e2..0000000000 --- a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ExpresssionTest.java +++ /dev/null @@ -1,207 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.regex.Pattern; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.opendaylight.controller.northbound.commons.query.CompareExpression.OP; - -public class ExpresssionTest { - - private static final List people = new ArrayList(); - private static final ArrayList books = new ArrayList(); - - public static void p(String msg) { - //System.out.println("======= " + msg); - } - - public static boolean matches(Expression exp, final PersonBean person) throws Exception { - - boolean result = exp.accept(new Visitor() { - @Override - public boolean visit(LogicalExpression le) throws QueryException { - p("=== LE " + le.getOperator() + "|" + le.getFirst() + "|" + le.getSecond()); - return (le.getOperator() == LogicalExpression.OP.AND) ? - le.getFirst().accept(this) && le.getSecond().accept(this) : - le.getFirst().accept(this) || le.getSecond().accept(this); - } - - @Override - public boolean visit(CompareExpression ce) { - p("=== CE " + ce.getOperator() + "|" + ce.getSelector() + "|" + ce.getArgument()); - if (person == null) { - return false; - } - try { - // check if the selector matches any of the fields - Field field = PersonBean.class.getDeclaredField(ce.getSelector()); - if (field == null) { - p("No field found by name : " + ce.getSelector()); - return false; - } - Object value = field.get(person); - if (value instanceof String) { - p("Comparing [" + ce.getArgument() + "] "+ ce.getOperator() + " [" + value.toString() + "]"); - if (ce.getOperator() == OP.EQ) { - return ce.getArgument().equals(value.toString()); - } else if (ce.getOperator() == OP.RE) { - return Pattern.matches(ce.getArgument(), value.toString()); - } else if (ce.getOperator() == OP.NE) { - return !ce.getArgument().equals(value.toString()); - } else { - p("Comparator : " + ce.getOperator() + " cannot apply to Strings"); - return false; - } - } else { - // assume its a # - int valToMatch = Integer.parseInt(ce.getArgument()); - int actualValue = (Integer)value; - p("Comparing: " + valToMatch + " " + ce.getOperator() + " " + actualValue); - switch(ce.getOperator()) { - case EQ : - case RE : - return actualValue == valToMatch; - case NE : - return actualValue != valToMatch; - case GT : - return actualValue > valToMatch; - case GE : - return actualValue >= valToMatch; - case LT : - return actualValue < valToMatch; - case LE : - return actualValue <= valToMatch; - default: - p("Unrecognized compare operator: " + ce.getOperator()); - return false; - } - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - }); - p("RESULT: " + result); - return result; - } - - @BeforeClass - public static void load() { - System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug"); - - people.add(new PersonBean(100, "John", "Doe", "San Jose")); - people.add(new PersonBean(200, "Foo", "Bar", "San Francisco")); - people.add(new PersonBean(300, "A", "B", "San Francisco")); - people.add(new PersonBean(400, "X", "Y", "New York")); - - books.add(new BookBean("Book1", "A001", people.get(0))); - books.add(new BookBean("Book2", "A002", people.get(1))); - books.add(new BookBean("Book3", "A003", people.get(2))); - - ReviewBean review1 = new ReviewBean("cool", people.get(2)); - ReviewBean review2 = new ReviewBean("kewl", people.get(3)); - ReviewBean review3 = new ReviewBean("+++", people.get(0)); - ReviewBean review4 = new ReviewBean("---", people.get(1)); - - books.get(0).addReview(review1).addReview(review2).addReview(review3).addReview(review4); - books.get(1).addReview(review1).addReview(review2).addReview(review3).addReview(review4); - books.get(2).addReview(review1).addReview(review2).addReview(review3).addReview(review4); - } - - @Test - public void testCXFQueries() throws Exception { - // following queries copied from apache cxf - Assert.assertFalse(matches(parseQuery("id=gt=100;name=Fred"), null)); - Assert.assertFalse(matches(parseQuery("id=gt=100;name==Fred"), null)); - Assert.assertFalse(matches(parseQuery("id=lt=123"), null)); - Assert.assertFalse(matches(parseQuery("date=le=2010-03-11"), null)); - Assert.assertFalse(matches(parseQuery("time=le=2010-03-11T18:00:00"), null)); - Assert.assertFalse(matches(parseQuery("name==CXF;version=ge=2.2"), null)); - Assert.assertFalse(matches(parseQuery("(age=lt=25,age=gt=35);city==London"), null)); - Assert.assertFalse(matches(parseQuery("date=lt=2000-01-01;date=gt=1999-01-01;(sub==math,sub==physics)"), null)); - } - - public Expression parseQuery(String query) throws Exception { - p("PARSING query: " + query); - // FiqlParser is a parser generated by javacc - Expression exp = FiqlParser.parse(query); - p(exp.toString()); - return exp; - } - - public int find(String query) throws Exception { - int found = 0; - Expression exp = parseQuery(query); - TypeInfo.createRoot("person", PersonBean.class); - for (PersonBean person : people) { - if (matches(exp, person)) found++; - } - return found; - } - - @Test - public void testPeopleQueries() throws Exception { - Assert.assertTrue(find("id==200") == 1); - Assert.assertTrue(find("id!=100;(city='San.*')") == 2); - Assert.assertTrue(find("id>200;(city='San.*')") == 1); - Assert.assertTrue(find("city='San.*'") == 3); - } - - @Test - public void testTypeTree() throws Exception { - TypeInfo bookType = TypeInfo.createRoot("book", BookBean.class); - Assert.assertEquals("John", bookType.retrieve(books.get(0), - "book.author.firstName".split("\\."), 1)); - Object result = bookType.retrieve(books.get(0), - "book.reviews.review.comment".split("\\."), 1); - Assert.assertTrue( result instanceof List); - List commentList = (List) result; - Assert.assertTrue(commentList.contains("cool")); - } - - @Test - public void testQueryAPI() throws Exception { - QueryContext qc = new QueryContextImpl(); - - // find all books written by author with firstName "John" - Query q1 = qc.createQuery("book.author.firstName==John", BookBean.class); - Collection r1 = q1.find(books); - p("Filtered books: " + r1.size()); - Assert.assertEquals(1, r1.size()); - - // find all books reviewed by people in a city "San*" - Query q2 = qc.createQuery("book.reviews.review.reviewer.city=San.*", BookBean.class); - Collection r2 = q2.find(books); - - p("Filtered books: " + r2.size()); - Assert.assertEquals(3, r2.size()); - - // find all books reviewed by people in a city "San*" - Query q3 = qc.createQuery("book==foo", BookBean.class); - Collection r3 = q3.find(books); - Assert.assertEquals(0, r3.size()); - } - - @Test - public void testFilter() throws Exception { - Library library = new Library((List)books.clone()); - QueryContext qc = new QueryContextImpl(); - // find all books written by author with firstName "John" - Query q1 = qc.createQuery("book.author.firstName==John", Library.class); - int sizeBefore = library.getList().size(); - System.out.println(q1.filter(library, BookBean.class)); - Assert.assertEquals(1, library.getList().size()); - } -} diff --git a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/Library.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/Library.java deleted file mode 100644 index c54b0e719e..0000000000 --- a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/Library.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name="library") -public class Library { - - @XmlElement(name="book") - private final List _list; - - public Library(List list) { - _list = list; - } - - public List getList() { - return _list; - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/PersonBean.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/PersonBean.java deleted file mode 100644 index b4b9ed5599..0000000000 --- a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/PersonBean.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name="person") - -public class PersonBean { - - @XmlElement - public String firstName; - @XmlElement - public String lastName; - @XmlElement - public String city; - @XmlElement - public int id; - - @XmlElementWrapper(name="emails") // ElementWrapper iteratable type - @XmlElement - public List email; - - public PersonBean(){} - public PersonBean(int n, String f, String l, String c) { - firstName = f; - lastName = l; - city = c; - id = n; - } - - public void setEmail(List emails){ - email = emails; - } - @Override - public String toString() { - return "PersonBean [firstName=" + firstName + ", lastName=" + lastName - + ", city=" + city + ", id=" + id + "]"; - } - -} diff --git a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/QueryContextTest.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/QueryContextTest.java deleted file mode 100644 index b6e582ba50..0000000000 --- a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/QueryContextTest.java +++ /dev/null @@ -1,269 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.commons.query; - -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.opendaylight.controller.northbound.commons.types.StringList; - -public class QueryContextTest { - - protected static final List people = new ArrayList(); - protected static final List books = new ArrayList(); - - public static void p(String msg) { - System.out.println("=== " + msg); - } - - @BeforeClass - public static void load() { - people.add(new PersonBean(100, "John", "Doe", "San Jose")); - people.add(new PersonBean(200, "Foo", "Bar", "San Francisco")); - people.add(new PersonBean(300, "A", "B", "San Francisco")); - people.add(new PersonBean(400, "X", "Y", "New York")); - - books.add(new BookBean("Book1", "A001", people.get(0))); - books.add(new BookBean("Book2", "A002", people.get(1))); - books.add(new BookBean("Book3", "A003", people.get(2))); - - ReviewBean review1 = new ReviewBean("cool", people.get(2)); - ReviewBean review2 = new ReviewBean("kewl", people.get(3)); - - books.get(0).addReview(review1).addReview(review2); - books.get(1).addReview(review1); - books.get(2).addReview(review2).addReview(review1); - - } - - @Test - public void testQueryContext() { - QueryContext queryContext = new QueryContextImpl(); - Assert.assertNotNull(queryContext); - } - - @Test - public void testSimpleQuery() throws QueryException { - QueryContext queryContext = new QueryContextImpl(); - Query query = queryContext.createQuery( - "person.id==200", PersonBean.class); - Assert.assertNotNull(query); - - List found = query.find(people); - Assert.assertNotNull(found); - Assert.assertTrue(found.size() == 1); - Assert.assertEquals("Foo", found.get(0).firstName); - } - - @Test - public void testAndQuery() throws QueryException { - QueryContext queryContext = new QueryContextImpl(); - Query query = queryContext.createQuery( - "person.id!=200;(person.city='San.*')", PersonBean.class); - Assert.assertNotNull(query); - - List found = query.find(people); - Assert.assertNotNull(found); - Assert.assertTrue(found.size() == 2); - Assert.assertEquals("John", found.get(0).firstName); - Assert.assertEquals("A", found.get(1).firstName); - } - - @Test - public void testOrQuery() throws QueryException { - QueryContext queryContext = new QueryContextImpl(); - Query query = queryContext.createQuery( - "person.id==200,(person.city='San.*')", PersonBean.class); - Assert.assertNotNull(query); - - List found = query.find(people); - Assert.assertNotNull(found); - Assert.assertTrue(found.size() == 3); - Assert.assertEquals("John", found.get(0).firstName); - Assert.assertEquals("Foo", found.get(1).firstName); - Assert.assertEquals("A", found.get(2).firstName); - } - - @Test - public void testXmlElementWrapper() throws QueryException { - List emails = new ArrayList(); - emails.add("john@cisco.com"); - emails.add("john@gmail.com"); - people.get(0).setEmail(emails); - - p(toXml(people.get(0))); - QueryContext queryContext = new QueryContextImpl(); - Query query = queryContext.createQuery( - "person.emails.email==john@cisco.com", PersonBean.class); - Assert.assertNotNull(query); - - List found = query.find(people); - Assert.assertNotNull(found); - Assert.assertEquals(1,found.size()); - Assert.assertEquals("John", found.get(0).firstName); - } - - @Test - public void testXmlWrapperOfWrapper() throws QueryException{ - WrapperList wrapper = new WrapperList(); - wrapper.item.add("Test1"); - wrapper.item.add("Test2"); - - books.get(0).addWrapperList(wrapper); - books.get(1).addWrapperList(wrapper); - - System.out.println(toXml(books.get(0))); - QueryContext queryContext = new QueryContextImpl(); - Query query = queryContext.createQuery( - "book.parent.child.items.item==Test1", BookBean.class); - Assert.assertNotNull(query); - } - - @Test - public void testXmlElementWrapperListofList() throws QueryException { - // create Stringlist - List testList = new ArrayList(); - testList.add("A"); - testList.add("B"); - StringList itemList = new StringList(testList); - books.get(0).addToTestList(itemList); - - System.out.println(toXml(books.get(0))); - QueryContext queryContext = new QueryContextImpl(); - Query query = queryContext.createQuery( - "book.test.testList.item==A", BookBean.class); - Assert.assertNotNull(query); - } - - @Test - public void testPrimitiveIteratableTypes() throws QueryException { - // Load data for this test - List sellers = new ArrayList(); - sellers.add("Amazon"); - - books.get(0).setSellerInfo(sellers); - sellers.add("Barners & Nobles"); - books.get(1).setSellerInfo(sellers); - sellers.add("Borders"); - sellers.remove("Amazon"); - sellers.add("BookShop"); - books.get(2).setSellerInfo(sellers); - - System.out.println(toXml(books.get(0))); - - QueryContext queryContext = new QueryContextImpl(); - Query query = queryContext.createQuery( - "book.soldBy==Amazon", BookBean.class); - Assert.assertNotNull(query); - - List found = query.find(books); - Assert.assertNotNull(found); - Assert.assertEquals(2,found.size()); - Assert.assertEquals("John", found.get(0).getauthor().firstName); - - query = queryContext.createQuery( - "book.soldBy!=Amazon", BookBean.class); - Assert.assertNotNull(query); - - found = query.find(books); - System.out.println("books" +found); - Assert.assertNotNull(found); - Assert.assertEquals(1,found.size()); - Assert.assertEquals("A", found.get(0).getauthor().firstName); - } - - @Test - public void testCompositeIteratableTypes() throws QueryException { - QueryContext queryContext = new QueryContextImpl(); - Query query = queryContext.createQuery("book.reviews.review.reviewer.firstName==X", - BookBean.class); - Assert.assertNotNull(query); - - List found = query.find(books); - Assert.assertNotNull(found); - Assert.assertEquals(2, found.size()); - Assert.assertEquals("John", found.get(0).getauthor().firstName); - - query = queryContext.createQuery("book.reviews.review.comment==kewl", - BookBean.class); - Assert.assertNotNull(query); - - found = query.find(books); - Assert.assertNotNull(found); - Assert.assertEquals(2, found.size()); - p("Book 0" + found.get(0)); - Assert.assertEquals("John", found.get(0).getauthor().firstName); - - query = queryContext.createQuery("book.reviews.review.reviewer.id>300", - BookBean.class); - Assert.assertNotNull(query); - - found = query.find(books); - Assert.assertNotNull(found); - Assert.assertEquals(2, found.size()); - p("Book 0" + found.get(0)); - Assert.assertEquals("John", found.get(0).getauthor().firstName); - - query = queryContext.createQuery("book.reviews.review.reviewer.firstName!=X", - BookBean.class); - Assert.assertNotNull(query); - - found = query.find(books); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - p("Book 0" + found.get(0)); - Assert.assertEquals("Foo", found.get(0).getauthor().firstName); - } - - @Test - public void testXMLAccessorType() { - //Assert.fail("implement"); - } - - @Test - public void testMethodAnnotation() throws QueryException { - System.out.println(toXml(books.get(0))); - QueryContext queryContext = new QueryContextImpl(); - Query query = queryContext.createQuery( - "book.isbn==preA003", BookBean.class); - Assert.assertNotNull(query); - - List found = query.find(books); - Assert.assertNotNull(found); - Assert.assertEquals(1,found.size()); - Assert.assertEquals("A", found.get(0).getauthor().firstName); - } - - public static String toXml(Object element) { - try { - JAXBContext jc = JAXBContext.newInstance(element.getClass()); - Marshaller marshaller = jc.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - marshaller.marshal(element, baos); - return baos.toString(); - } catch (Exception e) { - e.printStackTrace(); - } - return ""; - } - - @Test - public void testXMLElementWrapperForCompositeTypes(){ - //Assert.fail("implement"); - } - -} \ No newline at end of file diff --git a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ReviewBean.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ReviewBean.java deleted file mode 100644 index ea2f873ff6..0000000000 --- a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ReviewBean.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.opendaylight.controller.northbound.commons.query; - -import java.util.Date; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - */ -@XmlRootElement(name="review") -public class ReviewBean { - @XmlElement(name="date") - private Date _publishedDate; - @XmlElement(name="comment") - private String _comment; - @XmlElement(name="reviewer") - private PersonBean _reviewer; - @XmlElement - private int _upVotes; - @XmlElement - private int _downVotes; - public ReviewBean(){} - - public ReviewBean(String comment, PersonBean user) { - _comment = comment; - _reviewer = user; - _publishedDate = new Date(); - } - - public void vote(int up, int down) { - _upVotes += up; - _downVotes += down; - } - - @Override - public String toString() { - return "ReviewBean " + _publishedDate + " " - + _comment + " " + _reviewer + " " + _upVotes - + " " + _downVotes + ""; - } -} diff --git a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/XMLAccessorTypeTest.java b/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/XMLAccessorTypeTest.java deleted file mode 100644 index 25cb69214e..0000000000 --- a/opendaylight/adsal/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/XMLAccessorTypeTest.java +++ /dev/null @@ -1,374 +0,0 @@ -package org.opendaylight.controller.northbound.commons.query; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -import org.junit.Assert; -import org.junit.Test; - -public class XMLAccessorTypeTest { - - @Test - public void testPublicAccessType() throws Exception { - // create bean - List testList = new ArrayList(); - testList.add(new PublicAccessBean("John", "Scott", "private", 1, - "transient", "elem1")); - testList.add(new PublicAccessBean("Foo", "Bar", "private1", 2, - "transient1", "elem2")); - QueryContextTest.p(QueryContextTest.toXml(testList.get(0))); - - QueryContext queryContext = new QueryContextImpl(); - Assert.assertNotNull(queryContext); - // search for public field - Query query = queryContext.createQuery( - "publicbean.firstName==Foo", PublicAccessBean.class); - Assert.assertNotNull(query); - - List found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("Foo", found.get(0).firstName); - - // search for public getter - query = queryContext.createQuery("publicbean.privateGetterField<2", - PublicAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("John", found.get(0).firstName); - - // test for transient field - query = queryContext.createQuery("publicbean.transientField='trans*'", - PublicAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(0, found.size()); - - // test for private field - query = queryContext.createQuery("publicbean.privateField==private", - PublicAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(0, found.size()); - - // test for XML Element - query = queryContext.createQuery("publicbean.element==elem1", - PublicAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("John", found.get(0).firstName); - } - - @Test - public void testFieldAccessType() throws QueryException { - // create bean - List testList = new ArrayList(); - testList.add(new FieldAccessBean("John", "Scott", "private", 1, "elem1")); - testList.add(new FieldAccessBean("Foo", "Bar", "private1", 2, "elem2")); - - QueryContextTest.p(QueryContextTest.toXml(testList.get(0))); - QueryContext queryContext = new QueryContextImpl(); - Assert.assertNotNull(queryContext); - // test private field - Query query = queryContext.createQuery( - "field.privateField==private", FieldAccessBean.class); - Assert.assertNotNull(query); - - List found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("John", found.get(0).firstName); - - // test public field - query = queryContext.createQuery("field.firstName==Foo", - FieldAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("Foo", found.get(0).firstName); - - // test annotated field - query = queryContext.createQuery("field.element==elem2", - FieldAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("Foo", found.get(0).firstName); - - // test annotated method - query = queryContext.createQuery("field.privateGetterField==11", - FieldAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("John", found.get(0).firstName); - } - - @Test - public void testPropertyAccessType() throws QueryException { - // create bean - List testList = new ArrayList(); - testList.add(new PropertyAccessBean("John", "Scott", "private", 1, "elem1", - "transient1")); - testList.add(new PropertyAccessBean("Foo", "Bar", "private1", 2, "elem2", - "transient2")); - - QueryContextTest.p(QueryContextTest.toXml(testList.get(0))); - QueryContext queryContext = new QueryContextImpl(); - Assert.assertNotNull(queryContext); - // test public getter public field - Query query = queryContext.createQuery( - "property.firstName==John", PropertyAccessBean.class); - Assert.assertNotNull(query); - - List found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("John", found.get(0).firstName); - - // test public field no getter - query = queryContext.createQuery("property.lastName==Bar", - PropertyAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(0, found.size()); - - // test annotated field - query = queryContext.createQuery("property.element==elem2", - PropertyAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("Foo", found.get(0).firstName); - - // test annotated method - query = queryContext.createQuery("property.field==private", - PropertyAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("John", found.get(0).firstName); - - // test transient method - query = queryContext.createQuery("property.transientField==transient1", - PropertyAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(0, found.size()); - } - - @Test - public void testNoneAccessType() throws QueryException { - // create bean - List testList = new ArrayList(); - testList.add(new NoneAccessBean("John", "Scott", "private")); - testList.add(new NoneAccessBean("Foo", "Bar", "private1")); - - QueryContextTest.p(QueryContextTest.toXml(testList.get(0))); - QueryContext queryContext = new QueryContextImpl(); - Assert.assertNotNull(queryContext); - // test annotated field - Query query = queryContext.createQuery( - "test.firstName==John", NoneAccessBean.class); - Assert.assertNotNull(query); - - List found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("John", found.get(0).getFirstName()); - // test unannotated field - query = queryContext - .createQuery("test.lastName==Bar", NoneAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(0, found.size()); - // test annotated method - query = queryContext.createQuery("test.testField==private", - NoneAccessBean.class); - Assert.assertNotNull(query); - - found = query.find(testList); - Assert.assertNotNull(found); - Assert.assertEquals(1, found.size()); - Assert.assertEquals("John", found.get(0).getFirstName()); - - } - -} - -// default ( public memeber ) -@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) -@XmlRootElement(name = "publicbean") -class PublicAccessBean { - - public String firstName; - public String lastName; - private String privateField; - private int privateGetterField; - @XmlTransient - public String transientField; - @XmlElement(name = "element") - private String xmlElem; - - public PublicAccessBean() { - } - - public PublicAccessBean(String firstName, String lastName, - String privateField, int privateGetterField, String transientField, - String xmlElem) { - this.firstName = firstName; - this.lastName = lastName; - this.privateField = privateField; - this.privateGetterField = privateGetterField; - this.transientField = transientField; - this.xmlElem = xmlElem; - } - - public int getPrivateGetterField() { - return privateGetterField; - } - - public void setPrivateGetterField(int field) { - this.privateGetterField = field; - } -} - -// default ( public memeber ) -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "field") -class FieldAccessBean { - - public String firstName; - public String lastName; - private String privateField; - private int test; - @XmlElement(name = "element") - private String xmlElem; - - public FieldAccessBean() { - } - - public FieldAccessBean(String firstName, String lastName, - String privateField, int privateGetterField, String xmlElem) { - this.firstName = firstName; - this.lastName = lastName; - this.privateField = privateField; - this.xmlElem = xmlElem; - this.test = privateGetterField; - } - - public String getPrivateField() { - return privateField; - } - - @XmlElement(name = "privateGetterField") - public int getPrivateGetterField() { - return test + 10; - } -} - -// default ( public memeber ) -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlRootElement(name = "property") -class PropertyAccessBean { - - public String firstName; - public String lastName; - private String privateField; - private int privateGetterField; - @XmlElement(name = "element") - private String xmlElem; - private String transientField; - - public PropertyAccessBean() { - } - - public PropertyAccessBean(String firstName, String lastName, - String privateField, int privateGetterField, String xmlElem, - String transientField) { - this.firstName = firstName; - this.lastName = lastName; - this.privateField = privateField; - this.privateGetterField = privateGetterField; - this.xmlElem = xmlElem; - this.transientField = transientField; - } - - public int getPrivateGetterField() { - return privateGetterField; - } - - @XmlElement(name = "field") - public String getPrivateField() { - return privateField; - } - - public String getFirstName() { - return firstName; - } - - @XmlTransient - public String getTransientField() { - return transientField; - } -} - -// default ( public memeber ) -@XmlAccessorType(XmlAccessType.NONE) -@XmlRootElement(name = "test") -class NoneAccessBean { - @XmlElement - private String firstName; - public String lastName; - private String testField; - - public NoneAccessBean() { - } - - public NoneAccessBean(String firstName, String lastName, String testField) { - this.firstName = firstName; - this.lastName = lastName; - this.testField = testField; - } - - @XmlElement(name = "testField") - public String getTestField() { - return testField; - } - - public String getFirstName() { - return firstName; - } -} diff --git a/opendaylight/adsal/northbound/commons/src/test/resources/logback.xml b/opendaylight/adsal/northbound/commons/src/test/resources/logback.xml deleted file mode 100644 index 97e15deb94..0000000000 --- a/opendaylight/adsal/northbound/commons/src/test/resources/logback.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/connectionmanager/enunciate.xml b/opendaylight/adsal/northbound/connectionmanager/enunciate.xml deleted file mode 100644 index cb21d7c167..0000000000 --- a/opendaylight/adsal/northbound/connectionmanager/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/connectionmanager/pom.xml b/opendaylight/adsal/northbound/connectionmanager/pom.xml deleted file mode 100644 index e1789bde4d..0000000000 --- a/opendaylight/adsal/northbound/connectionmanager/pom.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../adsal-enunciate-parent - - - connectionmanager.northbound - 0.3.0-SNAPSHOT - bundle - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.usermanager, - com.sun.jersey.spi.container.servlet, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.northbound.commons.query, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.connectionmanager, - org.opendaylight.controller.sal.connection, - org.slf4j, - javax.ws.rs, - javax.ws.rs.ext, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - - /controller/nb/v2/connectionmanager - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/ConnectionManagerNorthbound.java b/opendaylight/adsal/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/ConnectionManagerNorthbound.java deleted file mode 100644 index 3f64b07ab6..0000000000 --- a/opendaylight/adsal/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/ConnectionManagerNorthbound.java +++ /dev/null @@ -1,364 +0,0 @@ - -/* - * Copyright (c) 2013 Red Hat, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.connectionmanager.northbound; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.ext.ContextResolver; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.northbound.commons.exception.NotAcceptableException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.query.QueryContext; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.connection.ConnectionConstants; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; - -/** - * Connection Manager Northbound APIs - */ -@Path("/") -public class ConnectionManagerNorthbound { - private String username; - private QueryContext queryContext; - - @Context - public void setQueryContext(ContextResolver queryCtxResolver) { - if (queryCtxResolver != null) { - queryContext = queryCtxResolver.getContext(QueryContext.class); - } - } - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - protected String getUserName() { - return username; - } - - private IConnectionManager getConnectionManager() { - return (IConnectionManager) ServiceHelper - .getGlobalInstance(IConnectionManager.class, this); - } - - /** - * - * Retrieve a list of all the nodes connected to a given controller in the cluster. - * - * @param controllerAddress Optional parameter to retrieve the nodes connected to another - * controller in the cluster - * @return A list of Nodes {@link org.opendaylight.controller.sal.core.Node} - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/connectionmanager/nodes?controller=1.1.1.1
-     *
-     * Response body in XML:
-     *  <list>
-     *       <node>
-     *           <id>00:00:00:00:00:00:00:52</id>
-     *           <type>OF</type>
-     *       </node>
-     *       <node>
-     *           <id>00:00:00:00:00:00:00:3e</id>
-     *           <type>OF</type>
-     *       </node>
-     *   </list>
-     *
-     *  Response body in JSON:
-     *  {
-     *       "node": [
-     *           {
-     *               "type": "OF",
-     *               "id": "00:00:00:00:00:00:00:52"
-     *           },
-     *           {
-     *               "type": "OF",
-     *               "id": "00:00:00:00:00:00:00:3e"
-     *           }
-     *       ]
-     *   }
-     * 
- */ - @Path("/nodes") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Nodes.class) - @StatusCodes( { - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 406, condition = "Invalid Controller IP Address passed."), - @ResponseCode(code = 503, condition = "Connection Manager Service not available")}) - - public Nodes getNodes(@DefaultValue("") @QueryParam("controller") String controllerAddress, - @QueryParam("_q") String queryString) { - if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container"); - } - - IConnectionManager connectionManager = getConnectionManager(); - if (connectionManager == null) { - throw new ServiceUnavailableException("IConnectionManager not available."); - } - - if ((controllerAddress != null) && (controllerAddress.trim().length() > 0) && - !NetUtils.isIPv4AddressValid(controllerAddress)) { - throw new NotAcceptableException("Invalid ip address "+controllerAddress); - } - Set nodeSet = null; - - if (controllerAddress != null) { - try { - nodeSet = connectionManager.getNodes(InetAddress.getByName(controllerAddress)); - } catch (UnknownHostException e) { - throw new NotAcceptableException("Invalid ip address "+controllerAddress); - } - } else { - nodeSet = connectionManager.getLocalNodes(); - } - Nodes nodes = new Nodes(nodeSet); - if (queryString != null) { - queryContext.createQuery(queryString, Nodes.class) - .filter(nodes, Node.class); - } - return nodes; - } - - /** - * If a Network Configuration Service needs a Management Connection and if the - * Node Type is unknown, use this REST api to connect to the management session. - *
-     *
-     * Example :
-     *
-     * Request :
-     * PUT http://localhost:8080/controller/nb/v2/connectionmanager/node/mgmt1/address/1.1.1.1/port/6634
-     *
-     * Response :
-     * Node :
-     * xml :
-     * <node>
-     *    <id>mgmt1</id>
-     *    <type>STUB</type>
-     * </node>
-     *
-     * json:
-     * {"id": "mgmt1","type": "STUB"}
-     *
-     *
- * @param nodeId User-Defined name of the node to connect with. This can be any alpha numeric value - * @param ipAddress IP Address of the Node to connect with. - * @param port Layer4 Port of the management session to connect with. - * @return Node If the connection is successful, HTTP 404 otherwise. - */ - - @Path("/node/{nodeId}/address/{ipAddress}/port/{port}/") - @PUT - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Node.class) - @StatusCodes( { - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "Could not connect to the Node with the specified parameters"), - @ResponseCode(code = 406, condition = "Invalid IP Address or Port parameter passed."), - @ResponseCode(code = 503, condition = "Connection Manager Service not available")} ) - public Node connect( - @PathParam(value = "nodeId") String nodeId, - @PathParam(value = "ipAddress") String ipAddress, - @PathParam(value = "port") String port) { - - if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container"); - } - - IConnectionManager connectionManager = getConnectionManager(); - if (connectionManager == null) { - throw new ServiceUnavailableException("IConnectionManager not available."); - } - - if (!NetUtils.isIPv4AddressValid(ipAddress)) { - throw new NotAcceptableException("Invalid ip address "+ipAddress); - } - - try { - Integer.parseInt(port); - } catch (Exception e) { - throw new NotAcceptableException("Invalid Layer4 Port "+port); - } - - Map params = new HashMap(); - params.put(ConnectionConstants.ADDRESS, ipAddress); - params.put(ConnectionConstants.PORT, port); - - Node node = null; - try { - node = connectionManager.connect(nodeId, params); - if (node == null) { - throw new ResourceNotFoundException("Failed to connect to Node at "+ipAddress+":"+port); - } - return node; - } catch (Exception e) { - throw new ResourceNotFoundException("Failed to connect to Node with Exception "+e.getMessage()); - } - } - - /** - * If a Network Configuration Service needs a Management Connection, and if the - * node Type is known, the user can choose to use this REST api to connect to the management session. - *
-     *
-     * Example :
-     *
-     * Request :
-     * PUT http://localhost:8080/controller/nb/v2/connectionmanager/node/STUB/mgmt1/address/1.1.1.1/port/6634
-     *
-     * Response : Node :
-     * xml :
-     * <node>
-     *    <id>mgmt1</id>
-     *    <type>STUB</type>
-     * </node>
-     *
-     * json:
-     * {"id": "mgmt1","type": "STUB"}
-     *
-     *
- * @param nodeType Type of the Node the connection is made for. - * @param nodeId User-Defined name of the node to connect with. This can be any alpha numeric value - * @param ipAddress IP Address of the Node to connect with. - * @param port Layer4 Port of the management session to connect with. - * @return Node If the connection is successful, HTTP 404 otherwise. - */ - - @Path("/node/{nodeType}/{nodeId}/address/{ipAddress}/port/{port}/") - @PUT - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Node.class) - @StatusCodes( { - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "Could not connect to the Node with the specified parameters"), - @ResponseCode(code = 406, condition = "Invalid IP Address or Port parameter passed."), - @ResponseCode(code = 503, condition = "Connection Manager Service not available")} ) - public Node connect( - @PathParam(value = "nodeType") String nodeType, - @PathParam(value = "nodeId") String nodeId, - @PathParam(value = "ipAddress") String ipAddress, - @PathParam(value = "port") String port) { - - if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container"); - } - - IConnectionManager connectionManager = getConnectionManager(); - if (connectionManager == null) { - throw new ServiceUnavailableException("IConnectionManager not available."); - } - - if (!NetUtils.isIPv4AddressValid(ipAddress)) { - throw new NotAcceptableException("Invalid ip address "+ipAddress); - } - - try { - Integer.parseInt(port); - } catch (Exception e) { - throw new NotAcceptableException("Invalid Layer4 Port "+port); - } - - Map params = new HashMap(); - params.put(ConnectionConstants.ADDRESS, ipAddress); - params.put(ConnectionConstants.PORT, port); - - Node node = null; - try { - node = connectionManager.connect(nodeType, nodeId, params); - if (node == null) { - throw new ResourceNotFoundException("Failed to connect to Node at "+ipAddress+":"+port); - } - return node; - } catch (Exception e) { - throw new ResourceNotFoundException(e.getMessage()); - } - } - - /** - * Disconnect an existing Connection. - *
-     *
-     * Example :
-     *
-     * Request :
-     * DELETE http://localhost:8080/controller/nb/v2/connectionmanager/node/STUB/mgmt1
-     *
-     *
- * @param nodeType Type of the Node - * @param nodeId Connection's NodeId. - */ - - @Path("/node/{nodeType}/{nodeId}/") - @DELETE - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Response.class) - @StatusCodes( { - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 200, condition = "Node disconnected successfully"), - @ResponseCode(code = 404, condition = "Could not find a connection with the specified Node identifier"), - @ResponseCode(code = 503, condition = "Connection Manager Service not available")} ) - public Response disconnect( - @PathParam(value = "nodeType") String nodeType, - @PathParam(value = "nodeId") String nodeId) { - - if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container"); - } - IConnectionManager connectionManager = getConnectionManager(); - if (connectionManager == null) { - throw new ServiceUnavailableException("IConnectionManager not available."); - } - - try { - Node node = Node.fromString(nodeType, nodeId); - Status status = connectionManager.disconnect(node); - if (status.isSuccess()) { - return Response.ok().build(); - } - return NorthboundUtils.getResponse(status); - } catch (Exception e) { - throw new ResourceNotFoundException(e.getMessage()); - } - } -} diff --git a/opendaylight/adsal/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/Nodes.java b/opendaylight/adsal/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/Nodes.java deleted file mode 100644 index aefd4b2451..0000000000 --- a/opendaylight/adsal/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/Nodes.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.opendaylight.controller.connectionmanager.northbound; -/* - * Copyright (c) 2013 Red Hat, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.Node; - -@XmlRootElement(name="list") -@XmlAccessorType(XmlAccessType.NONE) - -public class Nodes { - @XmlElement - Set node; - //To satisfy JAXB - private Nodes() { - } - - public Nodes(Set nodes) { - this.node = nodes; - } - - public Set getNode() { - return node; - } - - public void setNode(Set nodes) { - this.node = nodes; - } -} diff --git a/opendaylight/adsal/northbound/connectionmanager/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/connectionmanager/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index f0b23aaf6c..0000000000 --- a/opendaylight/adsal/northbound/connectionmanager/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - ConnectionManager - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - ConnectionManager - /* - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - - BASIC - opendaylight - - \ No newline at end of file diff --git a/opendaylight/adsal/northbound/containermanager/enunciate.xml b/opendaylight/adsal/northbound/containermanager/enunciate.xml deleted file mode 100644 index c4e08ae897..0000000000 --- a/opendaylight/adsal/northbound/containermanager/enunciate.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/containermanager/pom.xml b/opendaylight/adsal/northbound/containermanager/pom.xml deleted file mode 100644 index 4c3cea1f57..0000000000 --- a/opendaylight/adsal/northbound/containermanager/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - enunciate-parent - 1.6.0-SNAPSHOT - ../../../commons/enunciate-parent - - - containermanager.northbound - 0.6.0-SNAPSHOT - bundle - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - appauth - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - web - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.appauth.authorization, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.usermanager, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.northbound.commons.query, - com.sun.jersey.spi.container.servlet, - javax.ws.rs, - javax.ws.rs.ext, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.slf4j, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - /controller/nb/v2/containermanager - ,${classes;ANNOTATION;javax.ws.rs.Path} - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerConfigs.java b/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerConfigs.java deleted file mode 100644 index 582c0766dd..0000000000 --- a/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerConfigs.java +++ /dev/null @@ -1,48 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - - -package org.opendaylight.controller.containermanager.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.containermanager.ContainerConfig; - - -@XmlRootElement(name = "containerConfig-list") -@XmlAccessorType(XmlAccessType.NONE) -public class ContainerConfigs { - @XmlElement(name = "containerConfig") - List containerConfig; - - //To satisfy JAXB - @SuppressWarnings("unused") - private ContainerConfigs() { - - } - - - public ContainerConfigs(List containerconfig) { - this.containerConfig = containerconfig; - } - - - public List getcontainerConfig() { - return containerConfig; - } - - public void setcontainerConfig(List containerConfig) { - this.containerConfig = containerConfig; - } -} diff --git a/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthbound.java b/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthbound.java deleted file mode 100644 index 754167814d..0000000000 --- a/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthbound.java +++ /dev/null @@ -1,828 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager.northbound; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.ContextResolver; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.containermanager.ContainerConfig; -import org.opendaylight.controller.containermanager.ContainerFlowConfig; -import org.opendaylight.controller.containermanager.IContainerAuthorization; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.BadRequestException; -import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException; -import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException; -import org.opendaylight.controller.northbound.commons.exception.ResourceForbiddenException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.query.QueryContext; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.usermanager.IUserManager; - -/** - * Container Manager Northbound API - * - *
- *
- * Authentication scheme : HTTP Basic
- * Authentication realm : opendaylight
- * Transport : HTTP and HTTPS
- *
- * HTTPS Authentication is disabled by default. Administrator can enable it in - * tomcat-server.xml after adding a proper keystore / SSL certificate from a - * trusted authority.
- * More info : - * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration - * - */ -@Path("/") -public class ContainerManagerNorthbound { - private String username; - private QueryContext queryContext; - - @Context - public void setQueryContext(ContextResolver queryCtxResolver) { - if (queryCtxResolver != null) { - queryContext = queryCtxResolver.getContext(QueryContext.class); - } - } - - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - - protected String getUserName() { - return username; - } - - private IContainerManager getContainerManager() { - IContainerManager containerMgr = (IContainerManager) ServiceHelper.getGlobalInstance(IContainerManager.class, this); - if (containerMgr == null) { - throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString()); - } - return containerMgr; - } - - private void handleNameMismatch(String name, String nameinURL) { - if (name == null || nameinURL == null) { - throw new BadRequestException(RestMessages.INVALIDJSON.toString()); - } - - if (name.equalsIgnoreCase(nameinURL)) { - return; - } - throw new BadRequestException(RestMessages.INVALIDJSON.toString()); - } - - - - /** - * Get all the containers configured in the system - * - * @return a List of all {@link org.opendaylight.controller.containermanager.ContainerConfig} - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/containermanager/containers
-     *
-     * Response body in XML:
-     * <containerConfig-list>
-     *       <containerConfig>
-     *          <container>black</container>
-     *          <staticVlan>10</staticVlan>
-     *          <nodeConnectors>OF|1@OF|00:00:00:00:00:00:00:01</nodeConnectors>
-     *          <nodeConnectors>OF|23@OF|00:00:00:00:00:00:20:21</nodeConnectors>
-     *          <flowSpecs>
-     *           <name>tcp</name>
-     *           <protocol>TCP</protocol>
-     *          </flowSpecs>
-     *        </containerConfig>
-     *        <containerConfig>
-     *          <container>red</container>
-     *          <staticVlan>20</staticVlan>
-     *          <nodeConnectors>OF|1@OF|00:00:00:00:00:00:00:01</nodeConnectors>
-     *          <nodeConnectors>OF|23@OF|00:00:00:00:00:00:20:21</nodeConnectors>
-     *          <flowSpecs>
-     *           <name>udp</name>
-     *           <protocol>UDP</protocol>
-     *          </flowSpecs>
-     *      </containerConfig>
-     * </containerConfig-list>
-     *
-     * Response body in JSON:
-     * { "containerConfig" : [
-     *     { "container" : "black",
-     *       "nodeConnectors" : [
-     *          "OF|1@OF|00:00:00:00:00:00:00:01", "OF|23@OF|00:00:00:00:00:00:20:21"
-     *       ],
-     *       "staticVlan" : "10",
-     *       "flowSpecs : [
-     *          { "name": "udp",
-     *            "protocol": "UDP" }
-     *       ]
-     *     },
-     *     { "container" : "red",
-     *       "nodeConnectors" : [
-     *          "OF|1@OF|00:00:00:00:00:00:00:01",
-     *          "OF|23@OF|00:00:00:00:00:00:20:21"
-     *       ],
-     *       "staticVlan" : "20",
-     *       "flowSpecs": [
-     *          { "name": "tcp",
-     *            "protocol": "TCP"
-     *          }
-     *       ]
-     *     }
-     *   ]
-     * }
-     * 
- */ - @Path("/containers") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(ContainerConfigs.class) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User is not authorized to perform this operation"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public ContainerConfigs viewAllContainers(@QueryParam("_q") String queryString) { - - handleNetworkAuthorization(getUserName()); - - IContainerManager containerManager = getContainerManager(); - ContainerConfigs result = new ContainerConfigs( - containerManager.getContainerConfigList()); - if (queryString != null) { - queryContext.createQuery(queryString, ContainerConfigs.class) - .filter(result, ContainerConfig.class); - } - return result; - } - - /** - * Get the container configuration for container name requested - * - * @param container - * name of the Container (eg. blue) - * @return a List of {@link org.opendaylight.controller.containermanager.ContainerConfig} - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/containermanager/container/blue
-     *
-     * Response body in XML:
-     * <containerConfig>
-     *      <container>blue</container>
-     *      <staticVlan>10</staticVlan>
-     *      <nodeConnectors>OF|1@OF|00:00:00:00:00:00:00:01</nodeConnectors>
-     *      <nodeConnectors>OF|23@OF|00:00:00:00:00:00:20:21</nodeConnectors>
-     * </containerConfig>
-     *
-     * Response body in JSON:
-     * {
-     *    "containerConfig": [
-     *       {
-     *        "container": "yellow",
-     *        "staticVlan": "10",
-     *        "nodeConnectors": [
-     *           "OF|1@OF|00:00:00:00:00:00:00:01",
-     *           "OF|2@OF|00:00:00:00:00:00:00:02"
-     *        ],
-     *        "flowSpecs": []
-     *       }
-     *    ]
-     * }
-     * 
- */ - @Path("/container/{container}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(ContainerConfig.class) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User is not authorized to perform this operation"), - @ResponseCode(code = 403, condition = "Operation forbidden on default"), - @ResponseCode(code = 404, condition = "The container is not found") }) - public ContainerConfigs viewContainer(@PathParam(value = "container") String container) { - - handleContainerAuthorization(container, getUserName()); - handleForbiddenOnDefault(container); - - handleContainerNotExists(container); - - IContainerManager containerManager = getContainerManager(); - List containerConfigs = new ArrayList(); - containerConfigs.add(containerManager.getContainerConfig(container)); - return new ContainerConfigs(containerConfigs); - } - - /** - * Create a container - * - * @param uriInfo - * @param container - * name of the Container (eg. yellow) - * @param containerConfig - * details of the container as specified by: - * {@link org.opendaylight.controller.containermanager.ContainerConfig} - * @return Response as dictated by the HTTP Response Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/containermanager/container/yellow
-     *
-     * Request body in XML:
-     * <containerConfig>
-     *       <container>yellow</container>
-     *       <staticVlan>10</staticVlan>
-     *       <nodeConnectors></nodeConnectors>
-     * </containerConfig>
-     *
-     * Request body in JSON:
-     * {
-     *    "container" : "yellow",
-     *    "nodeConnectors" : [
-     *       "OF|1@OF|00:00:00:00:00:00:00:01",
-     *       "OF|23@OF|00:00:00:00:00:00:20:21"
-     *    ],
-     *    "staticVlan" : "10"
-     * }
-     *
-     * 
- */ - @Path("/container/{container}") - @PUT - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ @ResponseCode(code = 201, condition = "Container created successfully"), - @ResponseCode(code = 400, condition = "Invalid Container configuration."), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 403, condition = "Operation forbidden on default"), - @ResponseCode(code = 404, condition = "Container Name is not found"), - @ResponseCode(code = 409, condition = "Failed to create Container due to Conflicting Name"), - @ResponseCode(code = 500, condition = "Failure Reason included in HTTP Error response") }) - public Response createContainer(@Context UriInfo uriInfo, - @PathParam(value = "container") String container, - @TypeHint(ContainerConfig.class) ContainerConfig containerConfig) { - - handleAdminAuthorization(getUserName()); - handleContainerExists(container); - - handleNameMismatch(containerConfig.getContainerName(), container); - handleForbiddenOnDefault(container); - - IContainerManager containerManager = getContainerManager(); - Status status = containerManager.addContainer(containerConfig); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Container", username, "added", container); - return Response.created(uriInfo.getRequestUri()).build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Delete a container - * - * @param container - * name of the Container (eg. green) - * @return Response as dictated by the HTTP Response code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/containermanager/container/green
-     *
-     * 
- */ - @Path("/container/{container}") - @DELETE - @StatusCodes({ - @ResponseCode(code = 204, condition = "Container deleted successfully"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 403, condition = "Operation forbidden on default"), - @ResponseCode(code = 404, condition = "The container is not found") }) - public Response removeContainer(@PathParam(value = "container") String container) { - - handleAdminAuthorization(getUserName()); - handleForbiddenOnDefault(container); - handleContainerNotExists(container); - IContainerManager containerManager = getContainerManager(); - Status status = containerManager.removeContainer(container); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Container", username, "removed", container); - return Response.noContent().build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Get flowspec within a given container - * - * @param container - * name of the Container (eg. green) - * @param name - * name of the flowspec (eg. ssh) - * @return flowspec detail as specified by: - * {@link org.opendaylight.controller.containermanager.ContainerFlowConfig} - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/containermanager/container/green/flowspec/ssh
-     *
-     * Response body in XML:
-     * <flow-spec-config>
-     *      <name>ssh</name>
-     *      <dlVlan>52</dlVlan>
-     *      <nwSrc>10.0.0.101</nwSrc>
-     *      <nwDst>10.0.0.102</nwDst>
-     *      <protocol>IPv4</protocol>
-     *      <tpSrc>80</tpSrc>
-     *      <tpDst>100</tpDst>
-     * </flow-spec-config>
-     *
-     * Response body in JSON:
-     * {
-     *    "protocol" : "IPv4",
-     *    "dlVlan" : "52",
-     *    "nwDst" : "10.0.0.102",
-     *    "name" : "ssh",
-     *    "nwSrc" : "10.0.0.101",
-     *    "tpSrc" : "80",
-     *    "tpDst" : "100"
-     * }
-     *
-     * 
- */ - @Path("/container/{container}/flowspec/{flowspec}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(ContainerFlowConfig.class) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The container is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public ContainerFlowConfig viewContainerFlowSpec(@PathParam(value = "container") String container, - @PathParam(value = "flowspec") String flowspec) { - - handleContainerAuthorization(container, getUserName()); - handleForbiddenOnDefault(container); - - handleContainerNotExists(container); - IContainerManager containerManager = getContainerManager(); - List flowSpecs = containerManager.getContainerFlows(container); - - for (ContainerFlowConfig containerFlowConfig : flowSpecs) { - if (containerFlowConfig.equalsByName(flowspec)) { - return containerFlowConfig; - } - } - throw new ResourceNotFoundException("Flow Spec not found"); - } - - /** - * Get all the flowspec in a given container - * - * @param container - * name of the Container (eg. red) - * @return list of all flowspec configured for a container. Flowspec as - * specified by: - * {@link org.opendaylight.controller.containermanager.ContainerFlowConfig} - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/containermanager/container/red/flowspec
-     *
-     * Response body in XML:
-     * <flow-spec-configs>
-     *       <flow-spec-config>
-     *           <name>ssh</name>
-     *           <dlVlan>52</dlVlan>
-     *           <nwSrc>10.0.0.101</nwSrc>
-     *           <nwDst>10.0.0.102</nwDst>
-     *           <protocol>IPv4</protocol>
-     *           <tpSrc>23</tpSrc>
-     *           <tpDst>100</tpDst>
-     *       </flow-spec-config>
-     *       <flow-spec-config>
-     *           <name>http2</name>
-     *           <dlVlan>123</dlVlan>
-     *           <nwSrc>10.0.0.201</nwSrc>
-     *           <nwDst>10.0.0.202</nwDst>
-     *           <protocol></protocol>
-     *           <tpSrc>80</tpSrc>
-     *           <tpDst>100</tpDst>
-     *       </flow-spec-config>
-     * </flow-spec-configs>
-     *
-      * Response body in JSON:
-     * {
-     *   "flow-spec-config": [
-     *     {
-     *       "name": "http",
-     *       "dlVlan" : "52",
-     *       "nwSrc": "10.0.0.201",
-     *       "nwDst": "10.0.0.202",
-     *       "protocol": "",
-     *       "tpSrc": "80",
-     *       "tpDst": "100"
-     *     },
-     *     {
-     *       "name": "ssh",
-     *       "dlVlan" : "123",
-     *       "nwSrc": "10.0.0.101",
-     *       "nwDst": "10.0.0.102",
-     *       "protocol": "IPv4",
-     *       "tpSrc": "23",
-     *       "tpDst": "100"
-     *     }
-     *   ]
-     * }
-     *
-     * 
- */ - @Path("/container/{container}/flowspecs") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(FlowSpecConfigs.class) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The container is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public FlowSpecConfigs viewContainerFlowSpecs(@PathParam(value = "container") String container, - @QueryParam("_q") String queryString) { - - handleContainerAuthorization(container, getUserName()); - handleForbiddenOnDefault(container); - - handleContainerNotExists(container); - - IContainerManager containerManager = getContainerManager(); - FlowSpecConfigs result = new FlowSpecConfigs( - containerManager.getContainerFlows(container)); - if (queryString != null) { - queryContext.createQuery(queryString, FlowSpecConfigs.class) - .filter(result, ContainerFlowConfig.class); - } - return result; - } - - /** - * Add flowspec to a container - * - * @param container - * name of the container (eg. purple) - * @param name - * name of the flowspec (eg. http) - * @param flowspec - * configuration as specified by: - * {@link org.opendaylight.controller.containermanager.ContainerFlowConfig} - * - * @return Response as dictated by the HTTP Response code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/containermanager/container/purple/flowspec/http
-     *
-     * Request body in XML:
-     *   <flow-spec-config>
-     *         <name>http</name>
-     *         <dlVlan>25</dlVlan>
-     *         <nwSrc>10.0.0.101</nwSrc>
-     *         <nwDst>10.0.0.102</nwDst>
-     *         <protocol></protocol>
-     *         <tpSrc>80</tpSrc>
-     *         <tpDst>100</tpDst>
-     *   </flow-spec-config>
-     *
-     * Request body in JSON:
-     * {
-     *    "name" : "http",
-     *    "dlVlan" : "25",
-     *    "nwSrc" : "10.0.0.101",
-     *    "nwDst" : "10.0.0.102",
-     *    "protocol" : "",
-     *    "tpSrc" : "80",
-     *    "tpDst" : "100"
-     * }
-     *
-     * 
- */ - @Path("/container/{container}/flowspec/{flowspec}") - @PUT - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ - @ResponseCode(code = 201, condition = "FlowSpec created successfully"), - @ResponseCode(code = 400, condition = "Invalid flowspec configuration"), - @ResponseCode(code = 404, condition = "The container is not found"), - @ResponseCode(code = 409, condition = "Container Entry already exists"), - @ResponseCode(code = 500, condition = "Failed to create Flow specifications. Failure Reason included in HTTP Error response") }) - public Response createFlowSpec(@Context UriInfo uriInfo, - @PathParam(value = "container") String container, - @PathParam(value = "flowspec") String flowspec, - @TypeHint(ContainerFlowConfig.class) ContainerFlowConfig containerFlowConfig) { - - handleAdminAuthorization(getUserName()); - handleForbiddenOnDefault(container); - - handleContainerNotExists(container); - handleNameMismatch(containerFlowConfig.getName(), flowspec); - - IContainerManager containerManager = getContainerManager(); - List list = new ArrayList(); - list.add(containerFlowConfig); - Status status = containerManager.addContainerFlows(container, list); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Flow Spec", username, "added", containerFlowConfig.getName()); - return Response.created(uriInfo.getRequestUri()).build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Remove flowspec from a container - * - * @param name - * name of the flowspec (eg. telnet) - * @param container - * name of the Container (eg. black) - * @return Response as dictated by the HTTP Response code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/containermanager/container/black/flowspec/telnet
-     *
-     * 
- */ - @Path("/container/{container}/flowspec/{flowspec}") - @DELETE - @StatusCodes({ - @ResponseCode(code = 204, condition = "Flow Spec deleted successfully"), - @ResponseCode(code = 400, condition = "Invalid flowspec configuration"), - @ResponseCode(code = 404, condition = "Container or Container Entry not found"), - @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active"), - @ResponseCode(code = 500, condition = "Failed to delete Flowspec. Failure Reason included in HTTP Error response"), - @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") }) - public Response removeFlowSpec(@PathParam(value = "container") String container, - @PathParam(value = "flowspec") String flowspec) { - - handleAdminAuthorization(getUserName()); - handleForbiddenOnDefault(container); - - handleContainerNotExists(container); - - IContainerManager containerManager = getContainerManager(); - Set set = new HashSet(); - set.add(flowspec); - Status status = containerManager.removeContainerFlows(container, set); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Flow Spec", username, "added", flowspec); - return Response.noContent().build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Add node connectors to a container - * - * @param container - * name of the container (eg. green) - * @param list - * The list of strings each representing a node connector in the form "|@|", as "OF|1@OF|00:00:00:ab:00:00:00:01" - * @return response as dictated by the HTTP Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/containermanager/container/green/nodeconnector
-     *
-     * Request body in XML:
-     * <nodeConnectors>
-     *     <nodeConnectors>OF|1@OF|00:00:00:00:00:00:00:01</nodeConnectors>
-     *     <nodeConnectors>OF|2@OF|00:00:00:00:00:00:00:01</nodeConnectors>
-     *     <nodeConnectors>OF|3@OF|00:00:00:00:00:00:00:22</nodeConnectors>
-     *     <nodeConnectors>OF|4@OF|00:00:00:00:00:00:00:22</nodeConnectors>
-     * </nodeConnectors>
-     *
-     * Request body in JSON:
-     * {
-     *    "nodeConnectors" : [
-     *       "OF|1@OF|00:00:00:00:00:00:00:01",
-     *       "OF|2@OF|00:00:00:00:00:00:00:01",
-     *       "OF|3@OF|00:00:00:00:00:00:00:22",
-     *       "OF|4@OF|00:00:00:00:00:00:00:22"
-     *    ]
-     * }
-     *
-     * 
- */ - @Path("/container/{container}/nodeconnector/") - @PUT - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Response.class) - @StatusCodes({ - @ResponseCode(code = 200, condition = "NodeConnectors added successfully"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 403, condition = "Operation forbidden on default"), - @ResponseCode(code = 404, condition = "The Container is not found"), - @ResponseCode(code = 409, condition = "Container Entry already exists"), - @ResponseCode(code = 500, condition = "Failed to create nodeconnectors. Failure Reason included in HTTP Error response") }) - public Response addNodeConnectors(@PathParam(value = "container") String container, - @TypeHint(StringList.class) StringList list) { - - handleAdminAuthorization(getUserName()); - handleForbiddenOnDefault(container); - handleContainerNotExists(container); - - IContainerManager containerManager = getContainerManager(); - Status status = containerManager.addContainerEntry(container, list.getList()); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Node ", username, "added", " Ports:" + list.getList()); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Remove node connectors from a container - * - * @param container - * name of the container (eg. red) - * @param list - * The list of strings each representing a node connector in the form "|@|", as "OF|1@OF|00:00:00:ab:00:00:00:01" - * @return response as dictated by the HTTP Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/containermanager/container/red/nodeconnector
-     *
-     * Request body in XML:
-     * <nodeConnectors>
-     *     <nodeConnectors>OF|1@OF|00:00:00:00:00:00:00:01</nodeConnectors>
-     *     <nodeConnectors>OF|2@OF|00:00:00:00:00:00:00:01</nodeConnectors>
-     *     <nodeConnectors>OF|3@OF|00:00:00:00:00:00:00:22</nodeConnectors>
-     *     <nodeConnectors>OF|4@OF|00:00:00:00:00:00:00:22</nodeConnectors>
-     * </nodeConnectors>
-     *
-     * Request body in JSON:
-     * {
-     *    "nodeConnectors" : [
-     *       "OF|1@OF|00:00:00:00:00:00:00:01",
-     *       "OF|2@OF|00:00:00:00:00:00:00:01",
-     *       "OF|3@OF|00:00:00:00:00:00:00:22",
-     *       "OF|4@OF|00:00:00:00:00:00:00:22"
-     *       ]
-     * }
-     *
-     * 
- */ - @Path("/container/{container}/nodeconnector/") - @DELETE - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ - @ResponseCode(code = 204, condition = "Container Entry deleted successfully"), - @ResponseCode(code = 400, condition = "Invalid Container Entry configuration"), - @ResponseCode(code = 404, condition = "The Container is not found"), - @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active"), - @ResponseCode(code = 500, condition = "Failed to delete node connector. Failure Reason included in HTTP Error response") }) - public Response removeNodeConnectors(@PathParam(value = "container") String container, - @TypeHint(StringList.class) StringList portList) { - - handleAdminAuthorization(getUserName()); - handleForbiddenOnDefault(container); - handleContainerNotExists(container); - - IContainerManager containerManager = getContainerManager(); - Status status = containerManager.removeContainerEntry(container, portList.getList()); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Node", username, "removed", " Ports:" + portList.getList()); - return Response.noContent().build(); - } - return NorthboundUtils.getResponse(status); - } - - /* - * Check If the function is not allowed on default container, Throw a - * ResourceForbiddenException exception if forbidden - */ - private void handleForbiddenOnDefault(String container) { - if (container.equalsIgnoreCase(GlobalConstants.DEFAULT.toString())) { - throw new ResourceForbiddenException(RestMessages.NODEFAULT.toString() + ": " + container); - } - } - - /* - * Check if container exists, Throw a ResourceNotFoundException exception if it - * does not exist - */ - private void handleContainerNotExists(String container) { - IContainerManager containerManager = getContainerManager(); - if (!containerManager.doesContainerExist(container)) { - throw new ResourceNotFoundException(RestMessages.NOCONTAINER.toString() + ": " + container); - } - } - - private void handleContainerExists(String container) { - IContainerManager containerManager = getContainerManager(); - if (containerManager.doesContainerExist(container)) { - throw new ResourceConflictException(RestMessages.RESOURCECONFLICT.toString() + ": " + container); - } - } - - private void handleAdminAuthorization(String userName) { - IUserManager usrMgr = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - - UserLevel level = usrMgr.getUserLevel(userName); - if (level.ordinal() <= UserLevel.NETWORKADMIN.ordinal()) { - return; - } - - throw new UnauthorizedException("User is not authorized to perform this operation"); - } - - private void handleNetworkAuthorization(String userName) { - IUserManager usrMgr = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - - UserLevel level = usrMgr.getUserLevel(userName); - if (level.ordinal() <= UserLevel.NETWORKOPERATOR.ordinal()) { - return; - } - throw new UnauthorizedException("User is not authorized to perform this operation"); - } - - private void handleContainerAuthorization(String container, String userName) { - IContainerAuthorization auth = (IContainerAuthorization) ServiceHelper.getGlobalInstance( - IContainerAuthorization.class, this); - - UserLevel level = auth.getUserLevel(userName); - if (level.ordinal() <= UserLevel.NETWORKOPERATOR.ordinal()) { - return; - } - - Privilege current = (auth == null) ? Privilege.NONE : auth.getResourcePrivilege(userName, container); - - if (current.ordinal() > Privilege.NONE.ordinal()) { - return; - } - throw new UnauthorizedException("User is not authorized to perform this operation"); - } - -} diff --git a/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthboundRSApplication.java b/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthboundRSApplication.java deleted file mode 100644 index db3d543a69..0000000000 --- a/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthboundRSApplication.java +++ /dev/null @@ -1,37 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager.northbound; - -import java.util.HashSet; -import java.util.Set; - -import javax.ws.rs.core.Application; - -import org.opendaylight.controller.northbound.commons.query.QueryContextProvider; - -import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; - -/** - * Instance of javax.ws.rs.core.Application used to return the classes - * that will be instantiated for JAXRS processing, this is necessary - * because the package scanning in jersey doesn't yet work in OSGi - * environment. - * - */ -public class ContainerManagerNorthboundRSApplication extends Application { - @Override - public Set> getClasses() { - Set> classes = new HashSet>(); - classes.add(ContainerManagerNorthbound.class); - classes.add(JacksonJaxbJsonProvider.class); - classes.add(QueryContextProvider.class); - return classes; - } -} diff --git a/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/FlowSpecConfigs.java b/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/FlowSpecConfigs.java deleted file mode 100644 index cc7505505c..0000000000 --- a/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/FlowSpecConfigs.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.containermanager.ContainerFlowConfig; - - -@XmlRootElement(name = "flow-spec-configs") -@XmlAccessorType(XmlAccessType.NONE) -public class FlowSpecConfigs { - @XmlElement(name = "flow-spec-config") - List containerFlowConfig; - - // To satisfy JAXB - @SuppressWarnings("unused") - private FlowSpecConfigs() { - - } - - public FlowSpecConfigs(List containerFlowConfig) { - this.containerFlowConfig = containerFlowConfig; - } - - public List getContainerFlowConfig() { - return containerFlowConfig; - } - - public void setContainerFlowConfig(List containerFlowConfig) { - this.containerFlowConfig = containerFlowConfig; - } -} diff --git a/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/StringList.java b/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/StringList.java deleted file mode 100644 index 7cba528b2e..0000000000 --- a/opendaylight/adsal/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/StringList.java +++ /dev/null @@ -1,38 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.containermanager.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -//TODO: Remove this once StringList is provided by commons.northboud - -@XmlRootElement(name = "nodeConnectors") -@XmlAccessorType(XmlAccessType.NONE) -public class StringList { - @XmlElement(name = "nodeConnectors") - private List list; - - public StringList() { - } - - public StringList(List list) { - this.list = list; - } - - public List getList() { - return list; - } - -} diff --git a/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 6aeb8caa14..0000000000 --- a/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler - diff --git a/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index acf748af72..0000000000 --- a/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,46 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd diff --git a/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/northbound/containermanager/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/northbound/containermanager/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/containermanager/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 5f74a4419d..0000000000 --- a/opendaylight/adsal/northbound/containermanager/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - JAXRSContainerManager - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.containermanager.northbound.ContainerManagerNorthboundRSApplication - - 1 - - - JAXRSContainerManager - /* - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - diff --git a/opendaylight/adsal/northbound/controllermanager/enunciate.xml b/opendaylight/adsal/northbound/controllermanager/enunciate.xml deleted file mode 100644 index 5382d54138..0000000000 --- a/opendaylight/adsal/northbound/controllermanager/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/controllermanager/pom.xml b/opendaylight/adsal/northbound/controllermanager/pom.xml deleted file mode 100644 index 20c0886dc3..0000000000 --- a/opendaylight/adsal/northbound/controllermanager/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../adsal-enunciate-parent - - controllermanager.northbound - 0.2.0-SNAPSHOT - bundle - - - junit - junit - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller.thirdparty - com.sun.jersey.jersey-servlet - - - org.opendaylight.controller.thirdparty - org.apache.catalina.filters.CorsFilter - - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - ${project.artifactId} - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.configuration, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.usermanager, - org.apache.commons.lang3.tuple, - org.apache.commons.logging, - com.sun.jersey.spi.container.servlet, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.northbound.commons.query, - org.opendaylight.controller.sal.authorization, - javax.ws.rs, - javax.ws.rs.ext, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.slf4j, - org.apache.catalina.filters, - com.fasterxml.jackson.annotation, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - /controller/nb/v2/controllermanager - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthbound.java b/opendaylight/adsal/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthbound.java deleted file mode 100644 index aaf93d1f4b..0000000000 --- a/opendaylight/adsal/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthbound.java +++ /dev/null @@ -1,326 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.controllermanager.northbound; - -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.ContextResolver; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.configuration.IConfigurationService; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.BadRequestException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.query.QueryContext; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.switchmanager.ISwitchManager; - -/** - * The class provides Northbound REST APIs to manager the controller. Currently - * it supports getting controller property(ies), setting a property, and - * removing a property - * - */ - -@Path("/") -public class ControllerManagerNorthbound { - - private String username; - private QueryContext queryContext; - - @Context - public void setQueryContext(ContextResolver queryCtxResolver) { - if (queryCtxResolver != null) { - queryContext = queryCtxResolver.getContext(QueryContext.class); - } - } - - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - - protected String getUserName() { - return username; - } - - private ISwitchManager getISwitchManagerService(String containerName) { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - - if (switchManager == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - return switchManager; - } - - /** - * Retrieve a property or all properties for the controller in the network - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param propertyName - * Name of the Property specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * - * Example: - * - * Request URL: - * http://localhost:8080/controller/nb/v2/controllermanager/default/properties/?propertyName=macAddress - * - * Response Body in XML: - * - * - * - * - * 3e:04:ef:11:13:80 - * - * - * - * - * Response Body in JSON: - * { "controllerProperties": - * {"properties": - * { "macAddress": - * { "value": "3e:04:ef:11:13:80" } - * } - * } - * } - * - */ - @Path("/{containerName}/properties/") - @GET - @TypeHint(Property.class) - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName or property is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public ControllerProperties getControllerProperties(@PathParam("containerName") String containerName, - @QueryParam("propertyName") String propertyName, - @QueryParam("_q") String queryString) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - ISwitchManager switchManager = getISwitchManagerService(containerName); - - if (propertyName == null) { - Map propertyMap = switchManager.getControllerProperties(); - Set properties = new HashSet(propertyMap.values()); - return new ControllerProperties(properties); - } - - Set properties = new HashSet(); - Property property = switchManager.getControllerProperty(propertyName); - if (property == null) { - throw new ResourceNotFoundException("Unable to find property with name: " + propertyName); - } - properties.add(property); - ControllerProperties result = new ControllerProperties(properties); - if (queryString != null) { - queryContext.createQuery(queryString, ControllerProperties.class) - .filter(result, Property.class); - } - return result; - - } - - /** - * Add a controller property to the controller. This method overrides - * previously set property values if the property already exist. - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param propertyName - * Name of the Property specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * @param propertyValue - * Value of the Property specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * @return Response as dictated by the HTTP Response Status code - * - * Example: - * - * Request URL: - * http://localhost:8080/controller/nb/v2/controllermanager/default/properties/description/defaultController - */ - @Path("/{containerName}/properties/{propertyName}/{propertyValue}") - @PUT - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ @ResponseCode(code = 201, condition = "Operation successful"), - @ResponseCode(code = 400, condition = "Invalid property parameters"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName or property is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public Response setControllerProperty(@Context UriInfo uriInfo, @PathParam("containerName") String containerName, - @PathParam("propertyName") String propertyName, @PathParam("propertyValue") String propertyValue) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - ISwitchManager switchManager = getISwitchManagerService(containerName); - - Property prop = switchManager.createProperty(propertyName, propertyValue); - if (prop == null) { - throw new BadRequestException("Property with name " + propertyName + " cannot be created."); - } - - Status status = switchManager.setControllerProperty(prop); - - if (status.isSuccess()) { - NorthboundUtils.auditlog("Controller Property", username, "updated", propertyName); - return Response.created(uriInfo.getRequestUri()).build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Delete a property of the controller - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param propertyName - * Name of the Property specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * @return Response as dictated by the HTTP Response Status code - * - * Example: - * - * Request URL: - * http://localhost:8080/controller/nb/v2/controllermanager/default/properties/description - */ - @Path("/{containerName}/properties/{propertyName}") - @DELETE - @StatusCodes({ @ResponseCode(code = 204, condition = "Property removed successfully"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public Response removeControllerProperty(@PathParam("containerName") String containerName, - @PathParam("propertyName") String propertyName) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - ISwitchManager switchManager = getISwitchManagerService(containerName); - - Status status = switchManager.removeControllerProperty(propertyName); - - if (status.isSuccess()) { - NorthboundUtils.auditlog("Controller Property", username, "removed", propertyName); - - return Response.noContent().build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Save controller configuration - * - * Request URL: - * http://localhost:8080/controller/nb/v2/controllermanager/configuration - * - * Request body is empty - */ - @Path("/configuration") - @PUT - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ - @ResponseCode(code = 204, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 503, condition = "Configuration service is unavailable.") - }) - public Response saveConfiguration() { - - if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation"); - } - - IConfigurationService configService = (IConfigurationService) - ServiceHelper.getGlobalInstance(IConfigurationService.class, this); - - if (configService == null) { - throw new ServiceUnavailableException("Configuration Service " + - RestMessages.SERVICEUNAVAILABLE.toString()); - } - Status status = configService.saveConfigurations(); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Controller Configuration", username, - "save", "configuration"); - return Response.noContent().build(); - } - return NorthboundUtils.getResponse(status); - } - - private boolean isValidContainer(String containerName) { - if (containerName.equals(GlobalConstants.DEFAULT.toString())) { - return true; - } - IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance( - IContainerManager.class, this); - if (containerManager == null) { - throw new ServiceUnavailableException("Container Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - if (containerManager.getContainerNames().contains(containerName)) { - return true; - } - return false; - } - -} diff --git a/opendaylight/adsal/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerProperties.java b/opendaylight/adsal/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerProperties.java deleted file mode 100644 index cec5a93a9e..0000000000 --- a/opendaylight/adsal/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerProperties.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.controllermanager.northbound; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.Property; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * The class describes set of properties attached to a controller - */ - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class ControllerProperties { - - /** - * Set to store the controller properties - */ - @XmlElement(name="property") - @XmlElementWrapper - @JsonIgnore - private Set properties; - - // JAXB required constructor - private ControllerProperties() { - this.properties = null; - } - - public ControllerProperties(Set properties) { - this.properties = properties; - } - - @JsonProperty(value="properties") - public Map getMapProperties() { - Map map = new HashMap(); - for (Property p : properties) { - map.put(p.getName(), p); - } - return map; - } - - public void setMapProperties(Map propertiesMap) { - this.properties = new HashSet(propertiesMap.values()); - } - - public Set getProperties() { - return properties; - } - - public void setProperties(Set properties) { - this.properties = properties; - } -} diff --git a/opendaylight/adsal/northbound/controllermanager/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/controllermanager/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 2efd81c44e..0000000000 --- a/opendaylight/adsal/northbound/controllermanager/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - JAXRSSwitchManager - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSSwitchManager - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - \ No newline at end of file diff --git a/opendaylight/adsal/northbound/controllermanager/src/test/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthboundTest.java b/opendaylight/adsal/northbound/controllermanager/src/test/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthboundTest.java deleted file mode 100644 index a25c75928d..0000000000 --- a/opendaylight/adsal/northbound/controllermanager/src/test/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthboundTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.controllermanager.northbound; - -import java.util.HashSet; -import java.util.Set; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.Property; - -public class ControllerManagerNorthboundTest { - - @Test - public void testControllerProperties() { - ControllerProperties controllerProperties = new ControllerProperties(null); - Assert.assertTrue(controllerProperties.getProperties() == null); - - Set properties = new HashSet(); - controllerProperties.setProperties(properties); - Assert.assertTrue(controllerProperties.getProperties().equals(properties)); - } - -} diff --git a/opendaylight/adsal/northbound/flowprogrammer/enunciate.xml b/opendaylight/adsal/northbound/flowprogrammer/enunciate.xml deleted file mode 100644 index 8a87876af3..0000000000 --- a/opendaylight/adsal/northbound/flowprogrammer/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/flowprogrammer/pom.xml b/opendaylight/adsal/northbound/flowprogrammer/pom.xml deleted file mode 100644 index e97816f4ca..0000000000 --- a/opendaylight/adsal/northbound/flowprogrammer/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../adsal-enunciate-parent - - - flowprogrammer.northbound - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.forwardingrulesmanager, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.northbound.commons.query, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.usermanager, - com.sun.jersey.spi.container.servlet, - org.apache.catalina.filters, - javax.ws.rs, - javax.ws.rs.ext, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.slf4j, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - - /controller/nb/v2/flowprogrammer - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowConfigs.java b/opendaylight/adsal/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowConfigs.java deleted file mode 100644 index e05aa10365..0000000000 --- a/opendaylight/adsal/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowConfigs.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.flowprogrammer.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.forwardingrulesmanager.FlowConfig; - -@XmlRootElement (name = "list") -@XmlAccessorType(XmlAccessType.NONE) - -public class FlowConfigs { - @XmlElement - List flowConfig; - //To satisfy JAXB - private FlowConfigs() { - - } - - public FlowConfigs(List flowConfig) { - this.flowConfig = flowConfig; - } - - public List getFlowConfig() { - return flowConfig; - } - - public void setFlowConfig(List flowConfig) { - this.flowConfig = flowConfig; - } -} diff --git a/opendaylight/adsal/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthbound.java b/opendaylight/adsal/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthbound.java deleted file mode 100644 index 42bd59ea45..0000000000 --- a/opendaylight/adsal/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthbound.java +++ /dev/null @@ -1,676 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.flowprogrammer.northbound; - -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.ext.ContextResolver; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.forwardingrulesmanager.FlowConfig; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException; -import org.opendaylight.controller.northbound.commons.exception.MethodNotAllowedException; -import org.opendaylight.controller.northbound.commons.exception.NotAcceptableException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.query.QueryContext; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.switchmanager.ISwitchManager; - -/** - * Flow Configuration Northbound API provides capabilities to program flows. - * - *
- *
- * Authentication scheme : HTTP Basic
- * Authentication realm : opendaylight
- * Transport : HTTP and HTTPS
- *
- * HTTPS Authentication is disabled by default. - * - */ -@Path("/") -public class FlowProgrammerNorthbound { - - private String username; - - private QueryContext queryContext; - @Context - public void setQueryContext(ContextResolver queryCtxResolver) { - if (queryCtxResolver != null) { - queryContext = queryCtxResolver.getContext(QueryContext.class); - } - } - - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - - protected String getUserName() { - return username; - } - - private IForwardingRulesManager getForwardingRulesManagerService(String containerName) { - IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance( - IContainerManager.class, this); - if (containerManager == null) { - throw new ServiceUnavailableException("Container " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - boolean found = false; - List containerNames = containerManager.getContainerNames(); - for (String cName : containerNames) { - if (cName.trim().equalsIgnoreCase(containerName.trim())) { - found = true; - } - } - - if (found == false) { - throw new ResourceNotFoundException(containerName + " " + RestMessages.NOCONTAINER.toString()); - } - - IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( - IForwardingRulesManager.class, containerName, this); - - if (frm == null) { - throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - return frm; - } - - private List getStaticFlowsInternal(String containerName, Node node) { - IForwardingRulesManager frm = getForwardingRulesManagerService(containerName); - - if (frm == null) { - throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - List flows = new ArrayList(); - - if (node == null) { - for (FlowConfig flow : frm.getStaticFlows()) { - flows.add(flow); - } - } else { - ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this); - - if (sm == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if (!sm.getNodes().contains(node)) { - throw new ResourceNotFoundException(node.toString() + " : " + RestMessages.NONODE.toString()); - } - - for (FlowConfig flow : frm.getStaticFlows(node)) { - flows.add(flow); - } - } - return flows; - } - - /** - * Returns a list of Flows configured on the given container - * - * @param containerName - * Name of the Container (Eg. 'default') - * @return List of flows configured on a given container - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/flowprogrammer/default
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <list>
-     *        <flowConfig>
-     *               <installInHw>true</installInHw>
-     *               <name>flow1</name>
-     *               <node>
-     *                      <id>00:00:00:00:00:00:00:01</id>
-     *                      <type>OF</type>
-     *               </node>
-     *               <ingressPort>1</ingressPort>
-     *               <priority>500</priority>
-     *               <etherType>0x800</etherType>
-     *               <nwSrc>9.9.1.1</nwSrc>
-     *               <actions>OUTPUT=2</actions>
-     *        </flowConfig>
-     * </list>
-     *
-     * Response body in JSON:
-     * {
-     *   "flowConfig": [
-     *      {
-     *         "installInHw": "true",
-     *         "name": "flow1",
-     *         "node": {
-     *            "type": "OF",
-     *            "id": "00:00:00:00:00:00:00:01"
-     *         },
-     *         "ingressPort": "1",
-     *         "priority": "500",
-     *         "etherType": "0x800",
-     *         "nwSrc":"9.9.1.1",
-     *         "actions": [
-     *           "OUTPUT=2"
-     *         ]
-     *      }
-     *    ]
-     * }
-     * 
- */ - @Path("/{containerName}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(FlowConfigs.class) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable"), - @ResponseCode(code = 400, condition = "Incorrect query syntex")}) - public FlowConfigs getStaticFlows(@PathParam("containerName") String containerName, - @QueryParam("_q") String queryString) { - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - FlowConfigs result = new FlowConfigs(getStaticFlowsInternal(containerName, null)); - if (queryString != null) { - queryContext.createQuery(queryString, FlowConfigs.class) - .filter(result, FlowConfig.class); - } - return result; - } - - /** - * Returns a list of Flows configured on a Node in a given container - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier (Eg. '00:00:00:00:00:00:00:01') - * @return List of flows configured on a Node in a container - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/flowprogrammer/default/node/OF/00:00:00:00:00:00:00:01
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <list>
-     *        <flowConfig>
-     *               <installInHw>true</installInHw>
-     *               <name>flow1</name>
-     *               <node>
-     *                      <id>00:00:00:00:00:00:00:01</id>
-     *                      <type>OF</type>
-     *               </node>
-     *               <ingressPort>1</ingressPort>
-     *               <priority>500</priority>
-     *               <etherType>0x800</etherType>
-     *               <nwSrc>9.9.1.1</nwSrc>
-     *               <actions>OUTPUT=2</actions>
-     *        </flowConfig>
-     * </list>
-     *
-    * Response body in JSON:
-     * {
-     *   "flowConfig": [
-     *      {
-     *         "installInHw": "true",
-     *         "name": "flow1",
-     *         "node": {
-     *            "type": "OF",
-     *            "id": "00:00:00:00:00:00:00:01"
-     *         },
-     *         "ingressPort": "1",
-     *         "priority": "500",
-     *         "etherType": "0x800",
-     *         "nwSrc":"9.9.1.1",
-     *         "actions": [
-     *           "OUTPUT=2"
-     *         ]
-     *       }
-     *    ]
-     * }
-     * 
- */ - @Path("/{containerName}/node/{nodeType}/{nodeId}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(FlowConfigs.class) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName or nodeId is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public FlowConfigs getStaticFlows(@PathParam("containerName") String containerName, - @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId, - @QueryParam("_q") String queryString) { - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - Node node = Node.fromString(nodeType, nodeId); - if (node == null) { - throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString()); - } - FlowConfigs flows = new FlowConfigs(getStaticFlowsInternal(containerName, node)); - if (queryString != null) { - queryContext.createQuery(queryString, FlowConfigs.class) - .filter(flows, FlowConfig.class); - } - return flows; - } - - /** - * Returns the flow configuration matching a human-readable name and nodeId - * on a given Container. - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier (Eg. '00:00:00:00:00:00:00:01') - * @param name - * Human-readable name for the configured flow (Eg. 'Flow1') - * @return Flow configuration matching the name and nodeId on a Container - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/flowprogrammer/default/node/OF/00:00:00:00:00:00:00:01/staticFlow/flow1
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <flowConfig>
-     *        <installInHw>true</installInHw>
-     *        <name>flow1</name>
-     *        <node>
-     *               <id>00:00:00:00:00:00:00:01</id>
-     *               <type>OF</type>
-     *        </node>
-     *        <ingressPort>1</ingressPort>
-     *        <priority>500</priority>
-     *        <etherType>0x800</etherType>
-     *        <nwSrc>9.9.1.1</nwSrc>
-     *        <actions>OUTPUT=2</actions>
-     * </flowConfig>
-     *
-    * Response body in JSON:
-     * {
-     *    "installInHw":"true",
-     *    "name":"flow1",
-     *    "node":{
-     *       "id":"00:00:00:00:00:00:00:01",
-     *       "type":"OF"
-     *    },
-     *    "ingressPort":"1",
-     *    "priority":"500",
-     *    "etherType":"0x800",
-     *    "nwSrc":"9.9.1.1",
-     *    "actions":[
-     *       "OUTPUT=2"
-     *    ]
-     * }
-     *
-     * 
- */ - @Path("/{containerName}/node/{nodeType}/{nodeId}/staticFlow/{name}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(FlowConfig.class) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName or NodeId or Configuration name is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public FlowConfig getStaticFlow(@PathParam("containerName") String containerName, - @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId, @PathParam("name") String name) { - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - IForwardingRulesManager frm = getForwardingRulesManagerService(containerName); - - if (frm == null) { - throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - Node node = handleNodeAvailability(containerName, nodeType, nodeId); - - FlowConfig staticFlow = frm.getStaticFlow(name, node); - if (staticFlow == null) { - throw new ResourceNotFoundException(RestMessages.NOFLOW.toString()); - } - - return new FlowConfig(staticFlow); - } - - /** - * Add or Modify a flow configuration. If the flow exists already, it will replace the current flow. - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier (Eg. '00:00:00:00:00:00:00:01') - * @param name - * Name of the Static Flow configuration (Eg. 'Flow2') - * @param FlowConfig - * Flow Configuration in JSON or XML format - * @return Response as dictated by the HTTP Response Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/flowprogrammer/default/node/OF/00:00:00:00:00:00:00:01/staticFlow/flow1
-     *
-     * Request body in XML:
-     * <flowConfig>
-     *            <installInHw>true</installInHw>
-     *            <name>flow1</name>
-     *            <node>
-     *                   <id>00:00:00:00:00:00:00:01</id>
-     *                   <type>OF</type>
-     *            </node>
-     *            <ingressPort>1</ingressPort>
-     *            <priority>500</priority>
-     *            <etherType>0x800</etherType>
-     *            <nwSrc>9.9.1.1</nwSrc>
-     *            <actions>OUTPUT=2</actions>
-     * </flowConfig>
-     *
-     * Request body in JSON:
-      * {
-     *    "installInHw":"true",
-     *    "name":"flow1",
-     *    "node":{
-     *       "id":"00:00:00:00:00:00:00:01",
-     *       "type":"OF"
-     *    },
-     *    "ingressPort":"1",
-     *    "priority":"500",
-     *    "etherType":"0x800",
-     *    "nwSrc":"9.9.1.1",
-     *    "actions":[
-     *       "OUTPUT=2"
-     *    ]
-     * }
-     * 
- */ - - @Path("/{containerName}/node/{nodeType}/{nodeId}/staticFlow/{name}") - @PUT - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Static Flow modified successfully"), - @ResponseCode(code = 201, condition = "Flow Config processed successfully"), - @ResponseCode(code = 400, condition = "Failed to create Static Flow entry due to invalid flow configuration"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The Container Name or nodeId is not found"), - @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active"), - @ResponseCode(code = 409, condition = "Failed to create Static Flow entry due to Conflicting Name or configuration"), - @ResponseCode(code = 500, condition = "Failed to create Static Flow entry. Failure Reason included in HTTP Error response"), - @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") }) - public Response addOrModifyFlow(@PathParam(value = "containerName") String containerName, - @PathParam(value = "name") String name, @PathParam("nodeType") String nodeType, - @PathParam(value = "nodeId") String nodeId, @TypeHint(FlowConfig.class) FlowConfig flowConfig) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - if (flowConfig.getNode() == null) { - return Response.status(Response.Status.BAD_REQUEST).entity("Invalid Configuration. Node is null or empty") - .build(); - } - handleResourceCongruence(name, flowConfig.getName()); - handleResourceCongruence(nodeType, flowConfig.getNode().getType()); - handleResourceCongruence(nodeId, flowConfig.getNode().getID() == null ? null : flowConfig.getNode().getNodeIDString()); - handleDefaultDisabled(containerName); - - IForwardingRulesManager frm = getForwardingRulesManagerService(containerName); - - if (frm == null) { - throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - Node node = handleNodeAvailability(containerName, nodeType, nodeId); - Status status; - - FlowConfig staticFlow = frm.getStaticFlow(name, node); - - if (staticFlow == null) { - status = frm.addStaticFlow(flowConfig); - if(status.isSuccess()){ - NorthboundUtils.auditlog("Flow Entry", username, "added", - name + " on Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName); - return Response.status(Response.Status.CREATED).entity("Success").build(); - } - } else { - status = frm.modifyStaticFlow(flowConfig); - if(status.isSuccess()){ - NorthboundUtils.auditlog("Flow Entry", username, "updated", - name + " on Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName); - return NorthboundUtils.getResponse(status); - } - } - return NorthboundUtils.getResponse(status); - } - - /** - * Delete a Flow configuration - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier (Eg. '00:00:00:00:00:00:00:01') - * @param name - * Name of the Static Flow configuration (Eg. 'Flow1') - * @return Response as dictated by the HTTP Response code - * - *
-     *
-     * Example:
-     *
-     * RequestURL:
-     * http://localhost:8080/controller/nb/v2/flowprogrammer/default/node/OF/00:00:00:00:00:00:00:01/staticFlow/flow1
-     *
-     * 
- */ - - @Path("/{containerName}/node/{nodeType}/{nodeId}/staticFlow/{name}") - @DELETE - @StatusCodes({ - @ResponseCode(code = 204, condition = "Flow Config deleted successfully"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The Container Name or Node-id or Flow Name passed is not found"), - @ResponseCode(code = 406, condition = "Failed to delete Flow config due to invalid operation. Failure details included in HTTP Error response"), - @ResponseCode(code = 500, condition = "Failed to delete Flow config. Failure Reason included in HTTP Error response"), - @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") }) - public Response deleteFlow(@PathParam(value = "containerName") String containerName, - @PathParam(value = "name") String name, @PathParam("nodeType") String nodeType, - @PathParam(value = "nodeId") String nodeId) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - handleDefaultDisabled(containerName); - - IForwardingRulesManager frm = getForwardingRulesManagerService(containerName); - - if (frm == null) { - throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - Node node = handleNodeAvailability(containerName, nodeType, nodeId); - - FlowConfig staticFlow = frm.getStaticFlow(name, node); - if (staticFlow == null) { - throw new ResourceNotFoundException(name + " : " + RestMessages.NOFLOW.toString()); - } - - Status status = frm.removeStaticFlow(name, node); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Flow Entry", username, "removed", - name + " from Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName); - return Response.noContent().build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Toggle a Flow configuration - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier (Eg. '00:00:00:00:00:00:00:01') - * @param name - * Name of the Static Flow configuration (Eg. 'Flow1') - * @return Response as dictated by the HTTP Response code - * - *
-     *
-     * Example:
-     *
-     * RequestURL:
-     * http://localhost:8080/controller/nb/v2/flowprogrammer/default/node/OF/00:00:00:00:00:00:00:01/staticFlow/flow1
-     *
-     * 
- */ - @Path("/{containerName}/node/{nodeType}/{nodeId}/staticFlow/{name}") - @POST - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Flow Config processed successfully"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The Container Name or Node-id or Flow Name passed is not found"), - @ResponseCode(code = 406, condition = "Failed to delete Flow config due to invalid operation. Failure details included in HTTP Error response"), - @ResponseCode(code = 500, condition = "Failed to delete Flow config. Failure Reason included in HTTP Error response"), - @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") }) - public Response toggleFlow(@PathParam(value = "containerName") String containerName, - @PathParam("nodeType") String nodeType, @PathParam(value = "nodeId") String nodeId, - @PathParam(value = "name") String name) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - handleDefaultDisabled(containerName); - - IForwardingRulesManager frm = getForwardingRulesManagerService(containerName); - - if (frm == null) { - throw new ServiceUnavailableException("Flow Programmer " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - Node node = handleNodeAvailability(containerName, nodeType, nodeId); - - FlowConfig staticFlow = frm.getStaticFlow(name, node); - if (staticFlow == null) { - throw new ResourceNotFoundException(name + " : " + RestMessages.NOFLOW.toString()); - } - - Status status = frm.toggleStaticFlowStatus(staticFlow); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Flow Entry", username, "toggled", - name + " on Node " + NorthboundUtils.getNodeDesc(node, containerName, this), containerName); - } - return NorthboundUtils.getResponse(status); - } - - private Node handleNodeAvailability(String containerName, String nodeType, String nodeId) { - - Node node = Node.fromString(nodeType, nodeId); - if (node == null) { - throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString()); - } - - ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this); - - if (sm == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if (!sm.getNodes().contains(node)) { - throw new ResourceNotFoundException(node.toString() + " : " + RestMessages.NONODE.toString()); - } - return node; - } - - private void handleDefaultDisabled(String containerName) { - IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance( - IContainerManager.class, this); - if (containerManager == null) { - throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString()); - } - if (containerName.equals(GlobalConstants.DEFAULT.toString()) && containerManager.hasNonDefaultContainer()) { - throw new NotAcceptableException(RestMessages.DEFAULTDISABLED.toString()); - } - } - - private void handleResourceCongruence(String resource, String configured) { - if (!resource.equals(configured)) { - throw new MethodNotAllowedException("Path's resource name conflicts with payload's resource name"); - } - } - -} diff --git a/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 315403054d..0000000000 --- a/opendaylight/adsal/northbound/flowprogrammer/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - - - JAXRSFlowProgrammer - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSFlowProgrammer - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - diff --git a/opendaylight/adsal/northbound/flowprogrammer/src/test/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthboundTest.java b/opendaylight/adsal/northbound/flowprogrammer/src/test/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthboundTest.java deleted file mode 100644 index 10767e8777..0000000000 --- a/opendaylight/adsal/northbound/flowprogrammer/src/test/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthboundTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.flowprogrammer.northbound; - -import java.util.ArrayList; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.forwardingrulesmanager.FlowConfig; - -public class FlowProgrammerNorthboundTest { - - @Test - public void testFlowConfigs() { - FlowConfigs fc = new FlowConfigs(null); - Assert.assertNull(fc.getFlowConfig()); - - FlowConfig conf = new FlowConfig(); - FlowConfig conf2 = new FlowConfig(); - ArrayList list = new ArrayList(); - - list.add(conf); - list.add(conf2); - FlowConfigs fc2 = new FlowConfigs(list); - Assert.assertTrue(fc2.getFlowConfig().equals(list)); - - fc.setFlowConfig(list); - Assert.assertTrue(fc.getFlowConfig().equals(fc2.getFlowConfig())); - - fc.setFlowConfig(null); - Assert.assertNull(fc.getFlowConfig()); - - } - -} diff --git a/opendaylight/adsal/northbound/hosttracker/enunciate.xml b/opendaylight/adsal/northbound/hosttracker/enunciate.xml deleted file mode 100644 index a8be00a3d3..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/hosttracker/pom.xml b/opendaylight/adsal/northbound/hosttracker/pom.xml deleted file mode 100644 index 9acd6649fb..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../adsal-enunciate-parent - - hosttracker.northbound - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.hosttracker, - org.opendaylight.controller.hosttracker.hostAware, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.usermanager, - org.apache.commons.logging, - com.sun.jersey.spi.container.servlet, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.query, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.packet.address, - javax.ws.rs, - javax.ws.rs.core, - javax.ws.rs.ext, - javax.xml.bind.annotation, - javax.xml.bind, - org.slf4j, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - /controller/nb/v2/hosttracker - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostConfig.java b/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostConfig.java deleted file mode 100644 index b66da34236..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostConfig.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.northbound; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.packet.address.DataLinkAddress; -import org.opendaylight.controller.sal.packet.address.EthernetAddress; - -/** - * Configuration Java Object which represents a Host configuration information - * for HostTracker. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class HostConfig implements Serializable { - private static final long serialVersionUID = 1L; - - @XmlElement - public String dataLayerAddress; - @XmlElement - private String nodeType; - @XmlElement - private String nodeId; - @XmlElement - private String nodeConnectorType; - @XmlElement - private String nodeConnectorId; - @XmlElement - private String vlan; - @XmlElement - private boolean staticHost; - @XmlElement - private String networkAddress; - - public HostConfig() { - - } - - protected String getDataLayerAddress() { - return this.dataLayerAddress; - } - - protected String getNodeType() { - return this.nodeType; - } - - protected String getNodeId() { - return this.nodeId; - } - - protected String getNodeConnectorType() { - return this.nodeConnectorType; - } - - protected String getNodeConnectorId() { - return this.nodeConnectorId; - } - - protected String getVlan() { - return this.vlan; - } - - protected boolean isStaticHost() { - return staticHost; - } - - protected String getNetworkAddress() { - return networkAddress; - } - - public static HostConfig convert(HostNodeConnector hnc) { - if(hnc == null) { - return null; - } - HostConfig hc = new HostConfig(); - DataLinkAddress dl = hnc.getDataLayerAddress(); - if(dl instanceof EthernetAddress) { - EthernetAddress et = (EthernetAddress) dl; - hc.dataLayerAddress = et.getMacAddress(); - } else { - hc.dataLayerAddress = dl.getName(); - } - NodeConnector nc = hnc.getnodeConnector(); - if(nc != null) { - hc.nodeConnectorType = nc.getType(); - hc.nodeConnectorId = nc.getNodeConnectorIDString(); - Node n = hnc.getnodeconnectorNode(); - if(n != null) { - hc.nodeType = n.getType(); - hc.nodeId = n.getNodeIDString(); - } - } - hc.vlan = String.valueOf(hnc.getVlan()); - hc.staticHost = hnc.isStaticHost(); - hc.networkAddress = hnc.getNetworkAddressAsString(); - return hc; - } -} diff --git a/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthbound.java b/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthbound.java deleted file mode 100644 index 3769cc7818..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthbound.java +++ /dev/null @@ -1,569 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.northbound; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.ContextResolver; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.BadRequestException; -import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.query.QueryContext; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.switchmanager.ISwitchManager; - -/** - * Host Tracker Northbound REST APIs.
- * This class provides REST APIs to track host location in a network. Host - * Location is represented by Host node connector which is essentially a logical - * entity that represents a Switch/Port. A host is represented by it's - * IP-address and mac-address. - * - *
- *
- * Authentication scheme : HTTP Basic
- * Authentication realm : opendaylight
- * Transport : HTTP and HTTPS
- *
- * HTTPS Authentication is disabled by default. - * - */ - -@Path("/") -public class HostTrackerNorthbound { - - private String username; - private QueryContext queryContext; - - @Context - public void setQueryContext(ContextResolver queryCtxResolver) { - if (queryCtxResolver != null) { - queryContext = queryCtxResolver.getContext(QueryContext.class); - } - } - - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - - protected String getUserName() { - return username; - } - - private IfIptoHost getIfIpToHostService(String containerName) { - IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance( - IContainerManager.class, this); - if (containerManager == null) { - throw new ServiceUnavailableException("Container " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - boolean found = false; - List containerNames = containerManager.getContainerNames(); - for (String cName : containerNames) { - if (cName.trim().equalsIgnoreCase(containerName.trim())) { - found = true; - break; - } - } - - if (!found) { - throw new ResourceNotFoundException(containerName + " " + RestMessages.NOCONTAINER.toString()); - } - - IfIptoHost hostTracker = (IfIptoHost) ServiceHelper.getInstance(IfIptoHost.class, containerName, this); - if (hostTracker == null) { - throw new ServiceUnavailableException("Host Tracker " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - return hostTracker; - } - - private Set convertHosts(Set hostNodeConnectors) { - if(hostNodeConnectors == null) { - return null; - } - Set hosts = new HashSet(); - for(HostNodeConnector hnc : hostNodeConnectors) { - hosts.add(HostConfig.convert(hnc)); - } - return hosts; - } - - /** - * Returns a list of all Hosts : both configured via PUT API and dynamically - * learnt on the network. - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * @return List of Active Hosts. - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/hosttracker/default/hosts/active
-     *
-     * Response body in XML
-     *
-     * <list>
-     *  <hostConfig>
-     *   <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
-     *   <networkAddress>1.1.1.1</networkAddress>
-     *   <nodeType>OF</nodeType>
-     *   <nodeId>00:00:00:00:00:00:00:01</nodeId>
-     *   <nodeConnectorType>OF</nodeConnectorType>
-     *   <nodeConnectorId>9</nodeConnectorId>
-     *   <vlan>0</vlan>
-     *   <staticHost>false</staticHost>
-     *  </hostConfig>
-     *  <hostConfig>
-     *   <dataLayerAddress>00:00:00:00:02:02</dataLayerAddress>
-     *   <networkAddress>2.2.2.2</networkAddress>
-     *   <nodeType>OF</nodeType>
-     *   <nodeId>00:00:00:00:00:00:00:02</nodeId>
-     *   <nodeConnectorType>OF</nodeConnectorType>
-     *   <nodeConnectorId>5</nodeConnectorId>
-     *   <vlan>0</vlan>
-     *   <staticHost>false</staticHost>
-     *  </hostConfig>
-     * </list>
-     *
-     * Response body in JSON:
-     *
-     * {
-     *  "hostConfig":[
-     *   {
-     *    "dataLayerAddress":"00:00:00:00:01:01",
-     *    "nodeType":"OF",
-     *    "nodeId":"00:00:00:00:00:00:00:01",
-     *    "nodeConnectorType":"OF",
-     *    "nodeConnectorId":"9",
-     *    "vlan":"0",
-     *    "staticHost":"false",
-     *    "networkAddress":"1.1.1.1"
-     *   },
-     *   {
-     *    "dataLayerAddress":"00:00:00:00:02:02",
-     *    "nodeType":"OF",
-     *    "nodeId":"00:00:00:00:00:00:00:02",
-     *    "nodeConnectorType":"OF",
-     *    "nodeConnectorId":"5",
-     *    "vlan":"0",
-     *    "staticHost":"false",
-     *    "networkAddress":"2.2.2.2"
-     *   }
-     *  ]
-     * }
-     * 
- */ - @Path("/{containerName}/hosts/active") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Hosts.class) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public Hosts getActiveHosts(@PathParam("containerName") String containerName, - @QueryParam("_q") String queryString) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - IfIptoHost hostTracker = getIfIpToHostService(containerName); - Hosts hosts = new Hosts(convertHosts(hostTracker.getAllHosts())); - if (queryString != null) { - queryContext.createQuery(queryString, Hosts.class) - .filter(hosts, HostConfig.class); - } - return hosts; - } - - /** - * Returns a list of Hosts that are statically configured and are connected - * to a NodeConnector that is down. - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * @return List of inactive Hosts. - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/hosttracker/default/hosts/inactive
-     *
-     * Response body in XML
-     *
-     * <list>
-     *  <hostConfig>
-     *   <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
-     *   <networkAddress>1.1.1.1</networkAddress>
-     *   <nodeType>OF</nodeType>
-     *   <nodeId>00:00:00:00:00:00:00:01</nodeId>
-     *   <nodeConnectorType>OF</nodeConnectorType>
-     *   <nodeConnectorId>9</nodeConnectorId>
-     *   <vlan>0</vlan>
-     *   <staticHost>false</staticHost>
-     *  </hostConfig>
-     *  <hostConfig>
-     *   <dataLayerAddress>00:00:00:00:02:02</dataLayerAddress>
-     *   <networkAddress>2.2.2.2</networkAddress>
-     *   <nodeType>OF</nodeType>
-     *   <nodeId>00:00:00:00:00:00:00:02</nodeId>
-     *   <nodeConnectorType>OF</nodeConnectorType>
-     *   <nodeConnectorId>5</nodeConnectorId>
-     *   <vlan>0</vlan>
-     *   <staticHost>false</staticHost>
-     *  </hostConfig>
-     * </list>
-     *
-     * Response body in JSON:
-     *
-     * {
-     *  "hostConfig":[
-     *   {
-     *    "dataLayerAddress":"00:00:00:00:01:01",
-     *    "nodeType":"OF",
-     *    "nodeId":"00:00:00:00:00:00:00:01",
-     *    "nodeConnectorType":"OF",
-     *    "nodeConnectorId":"9",
-     *    "vlan":"0",
-     *    "staticHost":"false",
-     *    "networkAddress":"1.1.1.1"
-     *   },
-     *   {
-     *    "dataLayerAddress":"00:00:00:00:02:02",
-     *    "nodeType":"OF",
-     *    "nodeId":"00:00:00:00:00:00:00:02",
-     *    "nodeConnectorType":"OF",
-     *    "nodeConnectorId":"5",
-     *    "vlan":"0",
-     *    "staticHost":"false",
-     *    "networkAddress":"2.2.2.2"
-     *   }
-     *  ]
-     * }
-     * 
- */ - @Path("/{containerName}/hosts/inactive") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Hosts.class) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public Hosts getInactiveHosts( - @PathParam("containerName") String containerName, - @QueryParam("_q") String queryString) { - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - IfIptoHost hostTracker = getIfIpToHostService(containerName); - Hosts hosts = new Hosts(convertHosts(hostTracker.getInactiveStaticHosts())); - if (queryString != null) { - queryContext.createQuery(queryString, Hosts.class) - .filter(hosts, HostConfig.class); - } - return hosts; - } - - /** - * Returns a host that matches the IP Address value passed as parameter. - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * @param networkAddress - * IP Address being looked up - * @return host that matches the IP Address - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/hosttracker/default/address/1.1.1.1
-     *
-     * Response body in XML
-     *
-     * <hostConfig>
-     *  <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
-     *  <networkAddress>1.1.1.1</networkAddress>
-     *  <nodeType>OF</nodeType>
-     *  <nodeId>00:00:00:00:00:00:00:01</nodeId>
-     *  <nodeConnectorType>OF</nodeConnectorType>
-     *  <nodeConnectorId>9</nodeConnectorId>
-     *  <vlan>0</vlan>
-     *  <staticHost>false</staticHost>
-     * </hostConfig>
-     *
-     * Response body in JSON:
-     *
-     * {
-     *  "dataLayerAddress":"00:00:00:00:01:01",
-     *  "nodeType":"OF",
-     *  "nodeId":"00:00:00:00:00:00:00:01",
-     *  "nodeConnectorType":"OF",
-     *  "nodeConnectorId":"9",
-     *  "vlan":"0",
-     *  "staticHost":"false",
-     *  "networkAddress":"1.1.1.1"
-     * }
-     * 
- */ - @Path("/{containerName}/address/{networkAddress}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(HostConfig.class) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 400, condition = "Invalid IP specified in networkAddress parameter"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public HostConfig getHostDetails( - @PathParam("containerName") String containerName, - @PathParam("networkAddress") String networkAddress) { - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - IfIptoHost hostTracker = getIfIpToHostService(containerName); - - InetAddress ip; - try { - ip = InetAddress.getByName(networkAddress); - } catch (UnknownHostException e) { - throw new BadRequestException(RestMessages.INVALIDADDRESS.toString() + " " + networkAddress); - } - for (HostNodeConnector host : hostTracker.getAllHosts()) { - if (host.getNetworkAddress().equals(ip)) { - return HostConfig.convert(host); - } - } - throw new ResourceNotFoundException(RestMessages.NOHOST.toString()); - } - - /** - * Add a Static Host configuration. If a host by the given address already - * exists, this method will respond with a non-successful status response. - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * @param networkAddress - * Host IP Address - * @param hostConfig - * Host Config Details - * @return Response as dictated by the HTTP Response Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/hosttracker/default/address/1.1.1.1
-     *
-     * Request body in XML
-     *
-     * <hostConfig>
-     *  <dataLayerAddress>00:00:00:00:01:01</dataLayerAddress>
-     *  <networkAddress>1.1.1.1</networkAddress>
-     *  <nodeType>OF</nodeType>
-     *  <nodeId>00:00:00:00:00:00:00:01</nodeId>
-     *  <nodeConnectorType>OF</nodeConnectorType>
-     *  <nodeConnectorId>9</nodeConnectorId>
-     *  <vlan>1</vlan>
-     *  <staticHost>true</staticHost>
-     * </hostConfig>
-     *
-     * Request body in JSON:
-     *
-     * {
-     *  "dataLayerAddress":"00:00:00:00:01:01",
-     *  "nodeType":"OF",
-     *  "nodeId":"00:00:00:00:00:00:00:01",
-     *  "nodeConnectorType":"OF",
-     *  "nodeConnectorId":"9",
-     *  "vlan":"1",
-     *  "staticHost":"true",
-     *  "networkAddress":"1.1.1.1"
-     * }
-     * 
- */ - - @Path("/{containerName}/address/{networkAddress}") - @PUT - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ - @ResponseCode(code = 201, condition = "Static host created successfully"), - @ResponseCode(code = 400, condition = "Invalid parameters specified, see response body for details"), - @ResponseCode(code = 404, condition = "The container or resource is not found"), - @ResponseCode(code = 409, condition = "Resource conflict, see response body for details"), - @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") }) - public Response addHost(@Context UriInfo uriInfo, @PathParam("containerName") String containerName, - @PathParam("networkAddress") String networkAddress, - @TypeHint(HostConfig.class) HostConfig hostConfig) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - return Response.status(Response.Status.UNAUTHORIZED) - .entity("User is not authorized to perform this operation on container " + containerName) - .build(); - } - handleDefaultDisabled(containerName); - - IfIptoHost hostTracker = getIfIpToHostService(containerName); - - HostConfig hc = hostConfig; - if (!networkAddress.equals(hc.getNetworkAddress())) { - return Response.status(Response.Status.CONFLICT) - .entity("Resource name in config object doesn't match URI") - .build(); - } - if (!hc.isStaticHost()) { - return Response.status(Response.Status.BAD_REQUEST) - .entity("Can only add static host.") - .build(); - } - Node node = handleNodeAvailability(containerName, hc.getNodeType(), hc.getNodeId()); - NodeConnector nc = NodeConnector.fromStringNoNode(hc.getNodeConnectorType(), hc.getNodeConnectorId(), node); - - Status status = hostTracker.addStaticHost(networkAddress, hc.getDataLayerAddress(), nc, hc.getVlan()); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Static Host", username, "added", networkAddress, containerName); - return Response.created(uriInfo.getRequestUri()).build(); - } - - return NorthboundUtils.getResponse(status); - } - - /** - * Delete a Static Host configuration - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * @param networkAddress - * IP Address - * @return Response as dictated by the HTTP Response code. - * - * Example: - * - * Request URL: - * http://localhost:8080/controller/nb/v2/hosttracker/default/address/1.1.1.1 - * - */ - - @Path("/{containerName}/address/{networkAddress}") - @DELETE - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ - @ResponseCode(code = 204, condition = "Static host deleted successfully"), - @ResponseCode(code = 404, condition = "The container or a specified resource was not found"), - @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active"), - @ResponseCode(code = 503, condition = "One or more of Controller service is unavailable") }) - public Response deleteHost( - @PathParam(value = "containerName") String containerName, - @PathParam(value = "networkAddress") String networkAddress) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - return Response.status(Response.Status.UNAUTHORIZED) - .entity("User is not authorized to perform this operation on container " + containerName) - .build(); - } - handleDefaultDisabled(containerName); - IfIptoHost hostTracker = getIfIpToHostService(containerName); - - Status status = hostTracker.removeStaticHost(networkAddress); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Static Host", username, "removed", networkAddress, containerName); - return Response.noContent().build(); - } - return NorthboundUtils.getResponse(status); - - } - - private void handleDefaultDisabled(String containerName) { - IContainerManager containerManager = (IContainerManager) ServiceHelper - .getGlobalInstance(IContainerManager.class, this); - if (containerManager == null) { - throw new ServiceUnavailableException( - RestMessages.SERVICEUNAVAILABLE.toString()); - } - if (containerName.equals(GlobalConstants.DEFAULT.toString()) - && containerManager.hasNonDefaultContainer()) { - throw new ResourceConflictException( - RestMessages.DEFAULTDISABLED.toString()); - } - } - - private Node handleNodeAvailability(String containerName, String nodeType, String nodeId) { - - Node node = Node.fromString(nodeType, nodeId); - if (node == null) { - throw new ResourceNotFoundException(nodeId + " : " - + RestMessages.NONODE.toString()); - } - - ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance( - ISwitchManager.class, containerName, this); - - if (sm == null) { - throw new ServiceUnavailableException("Switch Manager " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if (!sm.getNodes().contains(node)) { - throw new ResourceNotFoundException(node.toString() + " : " - + RestMessages.NONODE.toString()); - } - return node; - } - -} diff --git a/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/Hosts.java b/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/Hosts.java deleted file mode 100644 index dec5a35498..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/Hosts.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.hosttracker.northbound; - -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name="list") -@XmlAccessorType(XmlAccessType.NONE) - -public class Hosts { - @XmlElement - Set hostConfig; - - public Hosts() { - } - public Hosts (Set hostConfig) { - this.hostConfig = hostConfig; - } - public Set getHostConfig() { - return hostConfig; - } - public void setHostConfig(Set hostConfig) { - this.hostConfig = hostConfig; - } -} diff --git a/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/northbound/hosttracker/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/hosttracker/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 2e9d9d0f68..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - JAXRSHostTracker - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSHostTracker - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - \ No newline at end of file diff --git a/opendaylight/adsal/northbound/hosttracker/src/test/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthboundTest.java b/opendaylight/adsal/northbound/hosttracker/src/test/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthboundTest.java deleted file mode 100644 index 14d6cf7667..0000000000 --- a/opendaylight/adsal/northbound/hosttracker/src/test/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthboundTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.hosttracker.northbound; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashSet; -import java.util.Set; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.ConstructionException; - -public class HostTrackerNorthboundTest { - - @Test - public void testHosts() throws UnknownHostException, ConstructionException { - Hosts h1 = new Hosts(); - Assert.assertNull(h1.getHostConfig()); - - Hosts h2 = new Hosts(null); - Assert.assertNull(h2.getHostConfig()); - - Set conn = new HashSet(); - InetAddress addr = InetAddress.getByName("10.1.1.1"); - HostNodeConnector c1 = new HostNodeConnector(addr); - conn.add(HostConfig.convert(c1)); - h1.setHostConfig(conn); - Assert.assertTrue(h1.getHostConfig().equals(conn)); - - Hosts h3 = new Hosts(conn); - Assert.assertTrue(h3.getHostConfig().equals(conn)); - h3.setHostConfig(null); - Assert.assertNull(h3.getHostConfig()); - - } -} diff --git a/opendaylight/adsal/northbound/httpservice-bridge/pom.xml b/opendaylight/adsal/northbound/httpservice-bridge/pom.xml deleted file mode 100644 index edd6964366..0000000000 --- a/opendaylight/adsal/northbound/httpservice-bridge/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - httpservice-bridge - 0.2.0-SNAPSHOT - bundle - HttpService bridge web application - - - - - org.apache.felix - maven-bundle-plugin - true - - - - javax.servlet, - javax.servlet.http, - org.eclipse.equinox.http.servlet, - org.opendaylight.controller.web, - org.osgi.framework, - org.osgi.service.http, - org.slf4j, - /controller/osgi - - - - - - diff --git a/opendaylight/adsal/northbound/httpservice-bridge/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/httpservice-bridge/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 0622e9061b..0000000000 --- a/opendaylight/adsal/northbound/httpservice-bridge/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - BridgeServlet - org.eclipse.equinox.http.servlet.HttpServiceServlet - 1 - - - - BridgeServlet - /* - - - - - HttpService - /* - - - System-Admin - Network-Admin - - - - - System-Admin - - - - Network-Admin - - - - BASIC - opendaylight - - - diff --git a/opendaylight/adsal/northbound/integrationtest/pom.xml b/opendaylight/adsal/northbound/integrationtest/pom.xml deleted file mode 100644 index 59eec0eba5..0000000000 --- a/opendaylight/adsal/northbound/integrationtest/pom.xml +++ /dev/null @@ -1,571 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.integrationtest - 0.7.0-SNAPSHOT - ../../commons/integrationtest - - - northbound.integrationtest - 0.6.0-SNAPSHOT - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - - com.fasterxml.jackson.core - jackson-annotations - - - - com.fasterxml.jackson.core - jackson-core - - - - com.fasterxml.jackson.core - jackson-databind - - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-json-provider - - - - com.fasterxml.jackson.module - jackson-module-jaxb-annotations - - - com.google.code.gson - gson - compile - - - com.sun.jersey - jersey-client - - - - com.sun.jersey - jersey-core - - - com.sun.jersey - jersey-server - - - commons-codec - commons-codec - - - commons-fileupload - commons-fileupload - - - commons-io - commons-io - - - eclipselink - javax.persistence - - - eclipselink - javax.resource - - - equinoxSDK381 - javax.servlet - - - equinoxSDK381 - javax.servlet.jsp - - - equinoxSDK381 - org.apache.felix.gogo.command - - - equinoxSDK381 - org.apache.felix.gogo.runtime - - - equinoxSDK381 - org.apache.felix.gogo.shell - - - equinoxSDK381 - org.eclipse.equinox.cm - - - equinoxSDK381 - org.eclipse.equinox.console - - - equinoxSDK381 - org.eclipse.equinox.ds - - - equinoxSDK381 - org.eclipse.equinox.launcher - - - equinoxSDK381 - org.eclipse.equinox.util - - - equinoxSDK381 - org.eclipse.osgi - - - equinoxSDK381 - org.eclipse.osgi.services - - - - geminiweb - org.eclipse.gemini.web.core - - - geminiweb - org.eclipse.gemini.web.extender - - - geminiweb - org.eclipse.gemini.web.tomcat - - - geminiweb - org.eclipse.virgo.kernel.equinox.extensions - - - geminiweb - org.eclipse.virgo.util.common - - - geminiweb - org.eclipse.virgo.util.io - - - geminiweb - org.eclipse.virgo.util.math - - - geminiweb - org.eclipse.virgo.util.osgi - - - geminiweb - org.eclipse.virgo.util.osgi.manifest - - - geminiweb - org.eclipse.virgo.util.parser.manifest - - - orbit - javax.activation - - - orbit - javax.annotation - - - orbit - javax.ejb - - - orbit - javax.el - - - orbit - javax.mail.glassfish - - - orbit - javax.servlet.jsp.jstl - - - orbit - javax.servlet.jsp.jstl.impl - - - orbit - javax.xml.rpc - - - orbit - org.apache.catalina - - - orbit - org.apache.catalina.ha - - - orbit - org.apache.catalina.tribes - - - orbit - org.apache.coyote - - - orbit - org.apache.el - - - orbit - org.apache.jasper - - - orbit - org.apache.juli.extras - - - orbit - org.apache.tomcat.api - - - orbit - org.apache.tomcat.util - - - org.aopalliance - com.springsource.org.aopalliance - - - org.apache.commons - commons-lang3 - - - org.apache.felix - org.apache.felix.dependencymanager - - - org.apache.felix - org.apache.felix.dependencymanager.shell - - - org.apache.felix - org.apache.felix.fileinstall - - - - org.codehaus.enunciate - enunciate-core-annotations - - - - org.codehaus.jettison - jettison - - - org.jboss.spec.javax.transaction - jboss-transaction-api_1.1_spec - - - org.opendaylight.controller - arphandler - - - - org.opendaylight.controller - bundlescanner - - - - org.opendaylight.controller - bundlescanner.implementation - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - clustering.services-implementation - - - org.opendaylight.controller - commons.httpclient - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - configuration.implementation - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - connectionmanager.implementation - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.it.implementation - - - org.opendaylight.controller - flowprogrammer.northbound - - - org.opendaylight.controller - forwarding.staticrouting - - - org.opendaylight.controller - forwarding.staticrouting.northbound - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - forwardingrulesmanager.implementation - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - hosttracker.implementation - - - org.opendaylight.controller - hosttracker.northbound - - - - org.opendaylight.controller - logging.bridge - - - - org.opendaylight.controller - protocol_plugins.stub - - - org.opendaylight.controller - routing.dijkstra_implementation - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller - sal.connection.implementation - - - org.opendaylight.controller - sal.implementation - - - org.opendaylight.controller - security - - - org.opendaylight.controller - statistics.northbound - - - org.opendaylight.controller - statisticsmanager - - - org.opendaylight.controller - statisticsmanager.implementation - - - org.opendaylight.controller - subnets.northbound - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - switchmanager.implementation - - - org.opendaylight.controller - switchmanager.northbound - - - org.opendaylight.controller - topology.northbound - - - org.opendaylight.controller - topologymanager - - - org.opendaylight.controller - usermanager - - - org.opendaylight.controller - usermanager.implementation - - - org.opendaylight.controller.thirdparty - com.sun.jersey.jersey-servlet - - - org.opendaylight.controller.thirdparty - org.apache.catalina.filters.CorsFilter - - - org.ow2.asm - asm-all - - - - org.ow2.chameleon.management - chameleon-mbeans - - - org.slf4j - jcl-over-slf4j - - - org.slf4j - log4j-over-slf4j - - - org.slf4j - slf4j-api - - - org.springframework - org.springframework.aop - - - org.springframework - org.springframework.asm - - - org.springframework - org.springframework.beans - - - org.springframework - org.springframework.context - - - org.springframework - org.springframework.context.support - - - org.springframework - org.springframework.core - - - org.springframework - org.springframework.expression - - - org.springframework - org.springframework.transaction - - - org.springframework - org.springframework.web - - - org.springframework - org.springframework.web.servlet - - - - org.springframework.security - spring-security-config - - - org.springframework.security - spring-security-core - - - org.springframework.security - spring-security-taglibs - - - org.springframework.security - spring-security-web - - - virgomirror - org.eclipse.jdt.core.compiler.batch - - - - org.ops4j.pax.exam - pax-exam-container-native - test - - - org.ops4j.pax.exam - pax-exam-junit4 - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - test - - - org.ops4j.pax.url - pax-url-aether - test - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - - - - true - - - false - - central - maven repo1 - http://repo1.maven.org/maven2 - - - diff --git a/opendaylight/adsal/northbound/integrationtest/src/test/java/org/opendaylight/controller/northbound/integrationtest/NorthboundIT.java b/opendaylight/adsal/northbound/integrationtest/src/test/java/org/opendaylight/controller/northbound/integrationtest/NorthboundIT.java deleted file mode 100644 index d2b354b82b..0000000000 --- a/opendaylight/adsal/northbound/integrationtest/src/test/java/org/opendaylight/controller/northbound/integrationtest/NorthboundIT.java +++ /dev/null @@ -1,1505 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.northbound.integrationtest; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; -import static org.ops4j.pax.exam.CoreOptions.options; -import static org.ops4j.pax.exam.CoreOptions.systemPackages; -import static org.ops4j.pax.exam.CoreOptions.systemProperty; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.inject.Inject; -import org.apache.commons.codec.binary.Base64; -import org.codehaus.jettison.json.JSONArray; -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; -import org.codehaus.jettison.json.JSONTokener; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.commons.httpclient.HTTPClient; -import org.opendaylight.controller.commons.httpclient.HTTPRequest; -import org.opendaylight.controller.commons.httpclient.HTTPResponse; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Latency; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.topology.IListenTopoUpdates; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.usermanager.IUserManager; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.util.PathUtils; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(PaxExam.class) -public class NorthboundIT { - private final Logger log = LoggerFactory.getLogger(NorthboundIT.class); - // get the OSGI bundle context - @Inject - private BundleContext bc; - private IUserManager userManager = null; - private IInventoryListener invtoryListener = null; - private IListenTopoUpdates topoUpdates = null; - private static final String baseUrlPrefix = "http://127.0.0.1:8180/controller/nb/v2/"; - private final Boolean debugMsg = false; - - private String stateToString(int state) { - switch (state) { - case Bundle.ACTIVE: - return "ACTIVE"; - case Bundle.INSTALLED: - return "INSTALLED"; - case Bundle.RESOLVED: - return "RESOLVED"; - case Bundle.UNINSTALLED: - return "UNINSTALLED"; - default: - return "Not CONVERTED"; - } - } - - @Before - public void areWeReady() { - assertNotNull(bc); - boolean debugit = false; - Bundle b[] = bc.getBundles(); - for (Bundle element : b) { - int state = element.getState(); - if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) { - log.debug("Bundle:" + element.getSymbolicName() + " state:" + stateToString(state)); - debugit = true; - } - } - if (debugit) { - log.debug("Do some debugging because some bundle is " + "unresolved"); - } - // Assert if true, if false we are good to go! - assertFalse(debugit); - - ServiceReference r = bc.getServiceReference(IUserManager.class.getName()); - if (r != null) { - this.userManager = (IUserManager) bc.getService(r); - } - // If UserManager is null, cannot login to run tests. - assertNotNull(this.userManager); - - r = bc.getServiceReference(IfIptoHost.class.getName()); - if (r != null) { - this.invtoryListener = (IInventoryListener) bc.getService(r); - } - - // If inventoryListener is null, cannot run hosttracker tests. - assertNotNull(this.invtoryListener); - - r = bc.getServiceReference(IListenTopoUpdates.class.getName()); - if (r != null) { - this.topoUpdates = (IListenTopoUpdates) bc.getService(r); - } - - // If topologyManager is null, cannot run topology North tests. - assertNotNull(this.topoUpdates); - - } - - // static variable to pass response code from getJsonResult() - private static Integer httpResponseCode = null; - - private String getJsonResult(String restUrl) { - return getJsonResult(restUrl, "GET", null); - } - - private String getJsonResult(String restUrl, String method) { - return getJsonResult(restUrl, method, null); - } - - private String getJsonResult(String restUrl, String method, String body) { - // initialize response code to indicate error - httpResponseCode = 400; - - if (debugMsg) { - System.out.println("HTTP method: " + method + " url: " + restUrl.toString()); - if (body != null) { - System.out.println("body: " + body); - } - } - - try { - this.userManager.getAuthorizationList(); - this.userManager.authenticate("admin", "admin"); - HTTPRequest request = new HTTPRequest(); - - request.setUri(restUrl); - request.setMethod(method); - request.setTimeout(0); // HostTracker doesn't respond - // within default timeout during - // IT so setting an indefinite - // timeout till the issue is - // sorted out - - Map> headers = new HashMap>(); - String authString = "admin:admin"; - byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); - String authStringEnc = new String(authEncBytes); - List header = new ArrayList(); - header.add("Basic "+authStringEnc); - headers.put("Authorization", header); - header = new ArrayList(); - header.add("application/json"); - headers.put("Accept", header); - request.setHeaders(headers); - request.setContentType("application/json"); - if (body != null) { - request.setEntity(body); - } - - HTTPResponse response = HTTPClient.sendRequest(request); - - // Response code for success should be 2xx - httpResponseCode = response.getStatus(); - if (httpResponseCode > 299) { - return httpResponseCode.toString(); - } - - if (debugMsg) { - System.out.println("HTTP response code: " + response.getStatus()); - System.out.println("HTTP response message: " + response.getEntity()); - } - return response.getEntity(); - } catch (Exception e) { - if (debugMsg) { - e.printStackTrace(); - } - return null; - } - } - - private void testNodeProperties(JSONObject node, Integer nodeId, String nodeType, Integer timestamp, - String timestampName, Integer actionsValue, Integer capabilitiesValue, Integer tablesValue, - Integer buffersValue) throws JSONException { - - JSONObject nodeInfo = node.getJSONObject("node"); - Assert.assertEquals(nodeId, (Integer) nodeInfo.getInt("id")); - Assert.assertEquals(nodeType, nodeInfo.getString("type")); - - JSONObject properties = node.getJSONObject("properties"); - - if (timestamp == null || timestampName == null) { - Assert.assertFalse(properties.has("timeStamp")); - } else { - Assert.assertEquals(timestamp, (Integer) properties.getJSONObject("timeStamp").getInt("value")); - Assert.assertEquals(timestampName, properties.getJSONObject("timeStamp").getString("name")); - } - if (actionsValue == null) { - Assert.assertFalse(properties.has("actions")); - } else { - Assert.assertEquals(actionsValue, (Integer) properties.getJSONObject("actions").getInt("value")); - } - if (capabilitiesValue == null) { - Assert.assertFalse(properties.has("capabilities")); - } else { - Assert.assertEquals(capabilitiesValue, - (Integer) properties.getJSONObject("capabilities").getInt("value")); - } - if (tablesValue == null) { - Assert.assertFalse(properties.has("tables")); - } else { - Assert.assertEquals(tablesValue, (Integer) properties.getJSONObject("tables").getInt("value")); - } - if (buffersValue == null) { - Assert.assertFalse(properties.has("buffers")); - } else { - Assert.assertEquals(buffersValue, (Integer) properties.getJSONObject("buffers").getInt("value")); - } - } - - private void testNodeConnectorProperties(JSONObject nodeConnectorProperties, Integer ncId, String ncType, - Integer nodeId, String nodeType, Integer state, Integer capabilities, Integer bandwidth) - throws JSONException { - - JSONObject nodeConnector = nodeConnectorProperties.getJSONObject("nodeconnector"); - JSONObject node = nodeConnector.getJSONObject("node"); - JSONObject properties = nodeConnectorProperties.getJSONObject("properties"); - - Assert.assertEquals(ncId, (Integer) nodeConnector.getInt("id")); - Assert.assertEquals(ncType, nodeConnector.getString("type")); - Assert.assertEquals(nodeId, (Integer) node.getInt("id")); - Assert.assertEquals(nodeType, node.getString("type")); - if (state == null) { - Assert.assertFalse(properties.has("state")); - } else { - Assert.assertEquals(state, (Integer) properties.getJSONObject("state").getInt("value")); - } - if (capabilities == null) { - Assert.assertFalse(properties.has("capabilities")); - } else { - Assert.assertEquals(capabilities, - (Integer) properties.getJSONObject("capabilities").getInt("value")); - } - if (bandwidth == null) { - Assert.assertFalse(properties.has("bandwidth")); - } else { - Assert.assertEquals(bandwidth, (Integer) properties.getJSONObject("bandwidth").getInt("value")); - } - } - - @Test - public void testSubnetsNorthbound() throws JSONException, ConstructionException { - System.out.println("Starting Subnets JAXB client."); - String baseURL = baseUrlPrefix + "subnetservice/"; - - String name1 = "testSubnet1"; - String subnet1 = "1.1.1.1/24"; - - String name2 = "testSubnet2"; - String subnet2 = "2.2.2.2/24"; - - String name3 = "testSubnet3"; - String subnet3 = "3.3.3.3/24"; - - /* - * Create the node connector string list for the two subnets as: - * portList2 = {"OF|1@OF|00:00:00:00:00:00:00:02", "OF|2@OF|00:00:00:00:00:00:00:02", "OF|3@OF|00:00:00:00:00:00:00:02", "OF|4@OF|00:00:00:00:00:00:00:02"}; - * portList3 = {"OF|1@OF|00:00:00:00:00:00:00:03", "OF|2@OF|00:00:00:00:00:00:00:03", "OF|3@OF|00:00:00:00:00:00:00:03"}; - */ - Node node2 = new Node(Node.NodeIDType.OPENFLOW, 2L); - List portList2 = new ArrayList(); - NodeConnector nc21 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)1, node2); - NodeConnector nc22 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)2, node2); - NodeConnector nc23 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)3, node2); - NodeConnector nc24 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)3, node2); - portList2.add(nc21.toString()); - portList2.add(nc22.toString()); - portList2.add(nc23.toString()); - portList2.add(nc24.toString()); - - List portList3 = new ArrayList(); - Node node3 = new Node(Node.NodeIDType.OPENFLOW, 3L); - NodeConnector nc31 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)1, node3); - NodeConnector nc32 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)2, node3); - NodeConnector nc33 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)3, node3); - portList3.add(nc31.toString()); - portList3.add(nc32.toString()); - portList3.add(nc33.toString()); - - // Test GET subnets in default container - String result = getJsonResult(baseURL + "default/subnets"); - JSONTokener jt = new JSONTokener(result); - JSONObject json = new JSONObject(jt); - JSONArray subnetConfigs = json.getJSONArray("subnetConfig"); - Assert.assertEquals(subnetConfigs.length(), 1); // should only get the default subnet - - // Test GET subnet1 expecting 404 - result = getJsonResult(baseURL + "default/subnet/" + name1); - Assert.assertEquals(404, httpResponseCode.intValue()); - - // Test POST subnet1 - JSONObject jo = new JSONObject().put("name", name1).put("subnet", subnet1); - // execute HTTP request and verify response code - result = getJsonResult(baseURL + "default/subnet/" + name1, "PUT", jo.toString()); - Assert.assertTrue(httpResponseCode == 201); - - // Test GET subnet1 - result = getJsonResult(baseURL + "default/subnet/" + name1); - jt = new JSONTokener(result); - json = new JSONObject(jt); - Assert.assertEquals(200, httpResponseCode.intValue()); - Assert.assertEquals(name1, json.getString("name")); - Assert.assertEquals(subnet1, json.getString("subnet")); - - // Test PUT subnet2 - JSONObject jo2 = new JSONObject().put("name", name2).put("subnet", subnet2).put("nodeConnectors", portList2); - // execute HTTP request and verify response code - result = getJsonResult(baseURL + "default/subnet/" + name2, "PUT", jo2.toString()); - Assert.assertEquals(201, httpResponseCode.intValue()); - // Test PUT subnet3 - JSONObject jo3 = new JSONObject().put("name", name3).put("subnet", subnet3); - // execute HTTP request and verify response code - result = getJsonResult(baseURL + "default/subnet/" + name3, "PUT", jo3.toString()); - Assert.assertEquals(201, httpResponseCode.intValue()); - // Test POST subnet3 (modify port list: add) - JSONObject jo3New = new JSONObject().put("name", name3).put("subnet", subnet3).put("nodeConnectors", portList3); - // execute HTTP request and verify response code - result = getJsonResult(baseURL + "default/subnet/" + name3, "POST", jo3New.toString()); - Assert.assertEquals(200, httpResponseCode.intValue()); - - // Test GET all subnets in default container - result = getJsonResult(baseURL + "default/subnets"); - jt = new JSONTokener(result); - json = new JSONObject(jt); - JSONArray subnetConfigArray = json.getJSONArray("subnetConfig"); - JSONObject subnetConfig; - Assert.assertEquals(3, subnetConfigArray.length()); - for (int i = 0; i < subnetConfigArray.length(); i++) { - subnetConfig = subnetConfigArray.getJSONObject(i); - if (subnetConfig.getString("name").equals(name1)) { - Assert.assertEquals(subnet1, subnetConfig.getString("subnet")); - } else if (subnetConfig.getString("name").equals(name2)) { - Assert.assertEquals(subnet2, subnetConfig.getString("subnet")); - JSONArray portListGet = subnetConfig.getJSONArray("nodeConnectors"); - Assert.assertEquals(portList2.get(0), portListGet.get(0)); - Assert.assertEquals(portList2.get(1), portListGet.get(1)); - Assert.assertEquals(portList2.get(2), portListGet.get(2)); - Assert.assertEquals(portList2.get(3), portListGet.get(3)); - } else if (subnetConfig.getString("name").equals(name3)) { - Assert.assertEquals(subnet3, subnetConfig.getString("subnet")); - JSONArray portListGet = subnetConfig.getJSONArray("nodeConnectors"); - Assert.assertEquals(portList3.get(0), portListGet.get(0)); - Assert.assertEquals(portList3.get(1), portListGet.get(1)); - Assert.assertEquals(portList3.get(2), portListGet.get(2)); - } else { - // Unexpected config name - Assert.assertTrue(false); - } - } - - // Test POST subnet2 (modify port list: remove one port only) - List newPortList2 = new ArrayList(portList2); - newPortList2.remove(3); - JSONObject jo2New = new JSONObject().put("name", name2).put("subnet", subnet2).put("nodeConnectors", newPortList2); - // execute HTTP request and verify response code - result = getJsonResult(baseURL + "default/subnet/" + name2, "POST", jo2New.toString()); - Assert.assertEquals(200, httpResponseCode.intValue()); - - // Test GET subnet2: verify contains only the first three ports - result = getJsonResult(baseURL + "default/subnet/" + name2); - jt = new JSONTokener(result); - subnetConfig = new JSONObject(jt); - Assert.assertEquals(200, httpResponseCode.intValue()); - JSONArray portListGet2 = subnetConfig.getJSONArray("nodeConnectors"); - Assert.assertEquals(portList2.get(0), portListGet2.get(0)); - Assert.assertEquals(portList2.get(1), portListGet2.get(1)); - Assert.assertEquals(portList2.get(2), portListGet2.get(2)); - Assert.assertTrue(portListGet2.length() == 3); - - // Test DELETE subnet1 - result = getJsonResult(baseURL + "default/subnet/" + name1, "DELETE"); - Assert.assertEquals(204, httpResponseCode.intValue()); - - // Test GET deleted subnet1 - result = getJsonResult(baseURL + "default/subnet/" + name1); - Assert.assertEquals(404, httpResponseCode.intValue()); - - // TEST PUT bad subnet, expect 400, validate JSON exception mapper - JSONObject joBad = new JSONObject().put("foo", "bar"); - result = getJsonResult(baseURL + "default/subnet/foo", "PUT", joBad.toString()); - Assert.assertEquals(400, httpResponseCode.intValue()); - } - - @Test - public void testStaticRoutingNorthbound() throws JSONException { - System.out.println("Starting StaticRouting JAXB client."); - String baseURL = baseUrlPrefix + "staticroute/"; - - String name1 = "testRoute1"; - String prefix1 = "192.168.1.1/24"; - String nextHop1 = "0.0.0.0"; - String name2 = "testRoute2"; - String prefix2 = "192.168.1.1/16"; - String nextHop2 = "1.1.1.1"; - - // Test GET static routes in default container, expecting no results - String result = getJsonResult(baseURL + "default/routes"); - JSONTokener jt = new JSONTokener(result); - JSONObject json = new JSONObject(jt); - JSONArray staticRoutes = json.getJSONArray("staticRoute"); - Assert.assertEquals(staticRoutes.length(), 0); - - // Test insert static route - String requestBody = "{\"name\":\"" + name1 + "\", \"prefix\":\"" + prefix1 + "\", \"nextHop\":\"" + nextHop1 - + "\"}"; - result = getJsonResult(baseURL + "default/route/" + name1, "PUT", requestBody); - Assert.assertEquals(201, httpResponseCode.intValue()); - - requestBody = "{\"name\":\"" + name2 + "\", \"prefix\":\"" + prefix2 + "\", \"nextHop\":\"" + nextHop2 + "\"}"; - result = getJsonResult(baseURL + "default/route/" + name2, "PUT", requestBody); - Assert.assertEquals(201, httpResponseCode.intValue()); - - // Test Get all static routes - result = getJsonResult(baseURL + "default/routes"); - jt = new JSONTokener(result); - json = new JSONObject(jt); - JSONArray staticRouteArray = json.getJSONArray("staticRoute"); - Assert.assertEquals(2, staticRouteArray.length()); - JSONObject route; - for (int i = 0; i < staticRoutes.length(); i++) { - route = staticRoutes.getJSONObject(i); - if (route.getString("name").equals(name1)) { - Assert.assertEquals(prefix1, route.getString("prefix")); - Assert.assertEquals(nextHop1, route.getString("nextHop")); - } else if (route.getString("name").equals(name2)) { - Assert.assertEquals(prefix2, route.getString("prefix")); - Assert.assertEquals(nextHop2, route.getString("nextHop")); - } else { - // static route has unknown name - Assert.assertTrue(false); - } - } - - // Test get specific static route - result = getJsonResult(baseURL + "default/route/" + name1); - jt = new JSONTokener(result); - json = new JSONObject(jt); - - Assert.assertEquals(name1, json.getString("name")); - Assert.assertEquals(prefix1, json.getString("prefix")); - Assert.assertEquals(nextHop1, json.getString("nextHop")); - - result = getJsonResult(baseURL + "default/route/" + name2); - jt = new JSONTokener(result); - json = new JSONObject(jt); - - Assert.assertEquals(name2, json.getString("name")); - Assert.assertEquals(prefix2, json.getString("prefix")); - Assert.assertEquals(nextHop2, json.getString("nextHop")); - - // Test delete static route - result = getJsonResult(baseURL + "default/route/" + name1, "DELETE"); - Assert.assertEquals(204, httpResponseCode.intValue()); - - result = getJsonResult(baseURL + "default/routes"); - jt = new JSONTokener(result); - json = new JSONObject(jt); - - staticRouteArray = json.getJSONArray("staticRoute"); - JSONObject singleStaticRoute = staticRouteArray.getJSONObject(0); - Assert.assertEquals(name2, singleStaticRoute.getString("name")); - - } - - @Test - public void testSwitchManager() throws JSONException { - System.out.println("Starting SwitchManager JAXB client."); - String baseURL = baseUrlPrefix + "switchmanager/default/"; - - // define Node/NodeConnector attributes for test - int nodeId_1 = 51966; - int nodeId_2 = 3366; - int nodeId_3 = 4477; - int nodeConnectorId_1 = 51966; - int nodeConnectorId_2 = 12; - int nodeConnectorId_3 = 34; - String nodeType = "STUB"; - String ncType = "STUB"; - int timestamp_1 = 100000; - String timestampName_1 = "connectedSince"; - int actionsValue_1 = 2; - int capabilitiesValue_1 = 3; - int tablesValue_1 = 1; - int buffersValue_1 = 1; - int ncState = 1; - int ncCapabilities = 1; - int ncBandwidth = 1000000000; - - // Test GET all nodes - - String result = getJsonResult(baseURL + "nodes"); - JSONTokener jt = new JSONTokener(result); - JSONObject json = new JSONObject(jt); - - // Test for first node - JSONObject node = getJsonInstance(json, "nodeProperties", nodeId_1); - Assert.assertNotNull(node); - testNodeProperties(node, nodeId_1, nodeType, timestamp_1, timestampName_1, actionsValue_1, capabilitiesValue_1, - tablesValue_1, buffersValue_1); - - // Test 2nd node, properties of 2nd node same as first node - node = getJsonInstance(json, "nodeProperties", nodeId_2); - Assert.assertNotNull(node); - testNodeProperties(node, nodeId_2, nodeType, timestamp_1, timestampName_1, actionsValue_1, capabilitiesValue_1, - tablesValue_1, buffersValue_1); - - // Test 3rd node, properties of 3rd node same as first node - node = getJsonInstance(json, "nodeProperties", nodeId_3); - Assert.assertNotNull(node); - testNodeProperties(node, nodeId_3, nodeType, timestamp_1, timestampName_1, actionsValue_1, capabilitiesValue_1, - tablesValue_1, buffersValue_1); - - // Test GET nodeConnectors of a node - // Test first node - result = getJsonResult(baseURL + "node/STUB/" + nodeId_1); - jt = new JSONTokener(result); - json = new JSONObject(jt); - JSONArray nodeConnectorPropertiesArray = json.getJSONArray("nodeConnectorProperties"); - JSONObject nodeConnectorProperties = nodeConnectorPropertiesArray.getJSONObject(0); - - testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_1, ncType, nodeId_1, nodeType, ncState, - ncCapabilities, ncBandwidth); - - // Test second node - result = getJsonResult(baseURL + "node/STUB/" + nodeId_2); - jt = new JSONTokener(result); - json = new JSONObject(jt); - - nodeConnectorPropertiesArray = json.getJSONArray("nodeConnectorProperties"); - nodeConnectorProperties = nodeConnectorPropertiesArray.getJSONObject(0); - - - testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_2, ncType, nodeId_2, nodeType, ncState, - ncCapabilities, ncBandwidth); - - // Test third node - result = getJsonResult(baseURL + "node/STUB/" + nodeId_3); - jt = new JSONTokener(result); - json = new JSONObject(jt); - - nodeConnectorPropertiesArray = json.getJSONArray("nodeConnectorProperties"); - nodeConnectorProperties = nodeConnectorPropertiesArray.getJSONObject(0); - testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_3, ncType, nodeId_3, nodeType, ncState, - ncCapabilities, ncBandwidth); - - // Test add property to node - // Add Tier and Description property to node1 - result = getJsonResult(baseURL + "node/STUB/" + nodeId_1 + "/property/tier/1001", "PUT"); - Assert.assertEquals(201, httpResponseCode.intValue()); - result = getJsonResult(baseURL + "node/STUB/" + nodeId_1 + "/property/description/node1", "PUT"); - Assert.assertEquals(201, httpResponseCode.intValue()); - - // Test for first node - result = getJsonResult(baseURL + "nodes"); - jt = new JSONTokener(result); - json = new JSONObject(jt); - node = getJsonInstance(json, "nodeProperties", nodeId_1); - Assert.assertNotNull(node); - Assert.assertEquals(1001, node.getJSONObject("properties").getJSONObject("tier").getInt("value")); - Assert.assertEquals("node1", node.getJSONObject("properties").getJSONObject("description").getString("value")); - - // Test delete nodeConnector property - // Delete state property of nodeconnector1 - result = getJsonResult(baseURL + "nodeconnector/STUB/" + nodeId_1 + "/STUB/" + nodeConnectorId_1 - + "/property/state", "DELETE"); - Assert.assertEquals(204, httpResponseCode.intValue()); - - result = getJsonResult(baseURL + "node/STUB/" + nodeId_1); - jt = new JSONTokener(result); - json = new JSONObject(jt); - nodeConnectorPropertiesArray = json.getJSONArray("nodeConnectorProperties"); - nodeConnectorProperties = nodeConnectorPropertiesArray.getJSONObject(0); - - testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_1, ncType, nodeId_1, nodeType, null, - ncCapabilities, ncBandwidth); - - // Delete capabilities property of nodeconnector2 - result = getJsonResult(baseURL + "nodeconnector/STUB/" + nodeId_2 + "/STUB/" + nodeConnectorId_2 - + "/property/capabilities", "DELETE"); - Assert.assertEquals(204, httpResponseCode.intValue()); - - result = getJsonResult(baseURL + "node/STUB/" + nodeId_2); - jt = new JSONTokener(result); - json = new JSONObject(jt); - nodeConnectorPropertiesArray = json.getJSONArray("nodeConnectorProperties"); - nodeConnectorProperties = nodeConnectorPropertiesArray.getJSONObject(0); - - testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_2, ncType, nodeId_2, nodeType, ncState, - null, ncBandwidth); - - // Test PUT nodeConnector property - int newBandwidth = 1001; - - // Add Name/Bandwidth property to nodeConnector1 - result = getJsonResult(baseURL + "nodeconnector/STUB/" + nodeId_1 + "/STUB/" + nodeConnectorId_1 - + "/property/bandwidth/" + newBandwidth, "PUT"); - Assert.assertEquals(201, httpResponseCode.intValue()); - - result = getJsonResult(baseURL + "node/STUB/" + nodeId_1); - jt = new JSONTokener(result); - json = new JSONObject(jt); - nodeConnectorPropertiesArray = json.getJSONArray("nodeConnectorProperties"); - nodeConnectorProperties = nodeConnectorPropertiesArray.getJSONObject(0); - - // Check for new bandwidth value, state value removed from previous - // test - testNodeConnectorProperties(nodeConnectorProperties, nodeConnectorId_1, ncType, nodeId_1, nodeType, null, - ncCapabilities, newBandwidth); - - } - - @Test - public void testStatistics() throws JSONException { - final String actionTypes[] = { "DROP", "LOOPBACK", "FLOOD", "FLOOD_ALL", "CONTROLLER", "SW_PATH", "HW_PATH", "OUTPUT", - "SET_DL_SRC", "SET_DL_DST", "SET_DL_TYPE", "SET_VLAN_ID", "SET_VLAN_PCP", "SET_VLAN_CFI", "POP_VLAN", "PUSH_VLAN", - "SET_NW_SRC", "SET_NW_DST", "SET_NW_TOS", "SET_TP_SRC", "SET_TP_DST" }; - System.out.println("Starting Statistics JAXB client."); - - String baseURL = baseUrlPrefix + "statistics/default/"; - - String result = getJsonResult(baseURL + "flow"); - JSONTokener jt = new JSONTokener(result); - JSONObject json = new JSONObject(jt); - JSONObject flowStatistics = getJsonInstance(json, "flowStatistics", 0xCAFE); - JSONObject node = flowStatistics.getJSONObject("node"); - // test that node was returned properly - Assert.assertTrue(node.getInt("id") == 0xCAFE); - Assert.assertEquals(node.getString("type"), "STUB"); - - // test that flow statistics results are correct - JSONArray flowStats = flowStatistics.getJSONArray("flowStatistic"); - for (int i = 0; i < flowStats.length(); i++) { - - JSONObject flowStat = flowStats.getJSONObject(i); - testFlowStat(flowStat, actionTypes[i], i); - - } - - // for /controller/nb/v2/statistics/default/port - result = getJsonResult(baseURL + "port"); - jt = new JSONTokener(result); - json = new JSONObject(jt); - JSONObject portStatistics = getJsonInstance(json, "portStatistics", 0xCAFE); - JSONObject node2 = portStatistics.getJSONObject("node"); - // test that node was returned properly - Assert.assertTrue(node2.getInt("id") == 0xCAFE); - Assert.assertEquals(node2.getString("type"), "STUB"); - - // test that port statistic results are correct - JSONArray portStatArray = portStatistics.getJSONArray("portStatistic"); - JSONObject portStat = portStatArray.getJSONObject(0); - Assert.assertTrue(portStat.getInt("receivePackets") == 250); - Assert.assertTrue(portStat.getInt("transmitPackets") == 500); - Assert.assertTrue(portStat.getInt("receiveBytes") == 1000); - Assert.assertTrue(portStat.getInt("transmitBytes") == 5000); - Assert.assertTrue(portStat.getInt("receiveDrops") == 2); - Assert.assertTrue(portStat.getInt("transmitDrops") == 50); - Assert.assertTrue(portStat.getInt("receiveErrors") == 3); - Assert.assertTrue(portStat.getInt("transmitErrors") == 10); - Assert.assertTrue(portStat.getInt("receiveFrameError") == 5); - Assert.assertTrue(portStat.getInt("receiveOverRunError") == 6); - Assert.assertTrue(portStat.getInt("receiveCrcError") == 1); - Assert.assertTrue(portStat.getInt("collisionCount") == 4); - - // test for getting one specific node's stats - result = getJsonResult(baseURL + "flow/node/STUB/51966"); - jt = new JSONTokener(result); - json = new JSONObject(jt); - node = json.getJSONObject("node"); - // test that node was returned properly - Assert.assertTrue(node.getInt("id") == 0xCAFE); - Assert.assertEquals(node.getString("type"), "STUB"); - - // test that flow statistics results are correct - flowStats = json.getJSONArray("flowStatistic"); - for (int i = 0; i < flowStats.length(); i++) { - JSONObject flowStat = flowStats.getJSONObject(i); - testFlowStat(flowStat, actionTypes[i], i); - } - - result = getJsonResult(baseURL + "port/node/STUB/51966"); - jt = new JSONTokener(result); - json = new JSONObject(jt); - node2 = json.getJSONObject("node"); - // test that node was returned properly - Assert.assertTrue(node2.getInt("id") == 0xCAFE); - Assert.assertEquals(node2.getString("type"), "STUB"); - - // test that port statistic results are correct - portStatArray = json.getJSONArray("portStatistic"); - portStat = portStatArray.getJSONObject(0); - - Assert.assertTrue(portStat.getInt("receivePackets") == 250); - Assert.assertTrue(portStat.getInt("transmitPackets") == 500); - Assert.assertTrue(portStat.getInt("receiveBytes") == 1000); - Assert.assertTrue(portStat.getInt("transmitBytes") == 5000); - Assert.assertTrue(portStat.getInt("receiveDrops") == 2); - Assert.assertTrue(portStat.getInt("transmitDrops") == 50); - Assert.assertTrue(portStat.getInt("receiveErrors") == 3); - Assert.assertTrue(portStat.getInt("transmitErrors") == 10); - Assert.assertTrue(portStat.getInt("receiveFrameError") == 5); - Assert.assertTrue(portStat.getInt("receiveOverRunError") == 6); - Assert.assertTrue(portStat.getInt("receiveCrcError") == 1); - Assert.assertTrue(portStat.getInt("collisionCount") == 4); - } - - private void testFlowStat(JSONObject flowStat, String actionType, int actIndex) throws JSONException { - Assert.assertTrue(flowStat.getInt("tableId") == 1); - Assert.assertTrue(flowStat.getInt("durationSeconds") == 40); - Assert.assertTrue(flowStat.getInt("durationNanoseconds") == 400); - Assert.assertTrue(flowStat.getInt("packetCount") == 200); - Assert.assertTrue(flowStat.getInt("byteCount") == 100); - - // test that flow information is correct - JSONObject flow = flowStat.getJSONObject("flow"); - Assert.assertTrue(flow.getInt("priority") == (3500 + actIndex)); - Assert.assertTrue(flow.getInt("idleTimeout") == 1000); - Assert.assertTrue(flow.getInt("hardTimeout") == 2000); - Assert.assertTrue(flow.getInt("id") == 12345); - - JSONArray matches = (flow.getJSONObject("match").getJSONArray("matchField")); - Assert.assertEquals(matches.length(), 1); - JSONObject match = matches.getJSONObject(0); - Assert.assertTrue(match.getString("type").equals("NW_DST")); - Assert.assertTrue(match.getString("value").equals("1.1.1.1")); - - JSONArray actionsArray = flow.getJSONArray("actions"); - Assert.assertEquals(actionsArray.length(), 1); - JSONObject act = actionsArray.getJSONObject(0); - Assert.assertTrue(act.getString("type").equals(actionType)); - - if (act.getString("type").equals("OUTPUT")) { - JSONObject port = act.getJSONObject("port"); - JSONObject port_node = port.getJSONObject("node"); - Assert.assertTrue(port.getInt("id") == 51966); - Assert.assertTrue(port.getString("type").equals("STUB")); - Assert.assertTrue(port_node.getInt("id") == 51966); - Assert.assertTrue(port_node.getString("type").equals("STUB")); - } - - if (act.getString("type").equals("SET_DL_SRC")) { - byte srcMatch[] = { (byte) 5, (byte) 4, (byte) 3, (byte) 2, (byte) 1 }; - String src = act.getString("address"); - byte srcBytes[] = new byte[5]; - srcBytes[0] = Byte.parseByte(src.substring(0, 2)); - srcBytes[1] = Byte.parseByte(src.substring(2, 4)); - srcBytes[2] = Byte.parseByte(src.substring(4, 6)); - srcBytes[3] = Byte.parseByte(src.substring(6, 8)); - srcBytes[4] = Byte.parseByte(src.substring(8, 10)); - Assert.assertTrue(Arrays.equals(srcBytes, srcMatch)); - } - - if (act.getString("type").equals("SET_DL_DST")) { - byte dstMatch[] = { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5 }; - String dst = act.getString("address"); - byte dstBytes[] = new byte[5]; - dstBytes[0] = Byte.parseByte(dst.substring(0, 2)); - dstBytes[1] = Byte.parseByte(dst.substring(2, 4)); - dstBytes[2] = Byte.parseByte(dst.substring(4, 6)); - dstBytes[3] = Byte.parseByte(dst.substring(6, 8)); - dstBytes[4] = Byte.parseByte(dst.substring(8, 10)); - Assert.assertTrue(Arrays.equals(dstBytes, dstMatch)); - } - if (act.getString("type").equals("SET_DL_TYPE")) { - Assert.assertTrue(act.getInt("dlType") == 10); - } - if (act.getString("type").equals("SET_VLAN_ID")) { - Assert.assertTrue(act.getInt("vlanId") == 2); - } - if (act.getString("type").equals("SET_VLAN_PCP")) { - Assert.assertTrue(act.getInt("pcp") == 3); - } - if (act.getString("type").equals("SET_VLAN_CFI")) { - Assert.assertTrue(act.getInt("cfi") == 1); - } - - if (act.getString("type").equals("SET_NW_SRC")) { - Assert.assertTrue(act.getString("address").equals("2.2.2.2")); - } - if (act.getString("type").equals("SET_NW_DST")) { - Assert.assertTrue(act.getString("address").equals("1.1.1.1")); - } - - if (act.getString("type").equals("PUSH_VLAN")) { - int head = act.getInt("VlanHeader"); - // parsing vlan header - int id = head & 0xfff; - int cfi = (head >> 12) & 0x1; - int pcp = (head >> 13) & 0x7; - int tag = (head >> 16) & 0xffff; - Assert.assertTrue(id == 1234); - Assert.assertTrue(cfi == 1); - Assert.assertTrue(pcp == 1); - Assert.assertTrue(tag == 0x8100); - } - if (act.getString("type").equals("SET_NW_TOS")) { - Assert.assertTrue(act.getInt("tos") == 16); - } - if (act.getString("type").equals("SET_TP_SRC")) { - Assert.assertTrue(act.getInt("port") == 4201); - } - if (act.getString("type").equals("SET_TP_DST")) { - Assert.assertTrue(act.getInt("port") == 8080); - } - } - - @Test - public void testFlowProgrammer() throws JSONException { - System.out.println("Starting FlowProgrammer JAXB client."); - String baseURL = baseUrlPrefix + "flowprogrammer/default/"; - // Attempt to get a flow that doesn't exit. Should return 404 - // status. - String result = getJsonResult(baseURL + "node/STUB/51966/staticFlow/test1", "GET"); - Assert.assertTrue(result.equals("404")); - - // test add flow1 - String fc = "{\"name\":\"test1\", \"node\":{\"id\":\"51966\",\"type\":\"STUB\"}, \"actions\":[\"DROP\"]}"; - result = getJsonResult(baseURL + "node/STUB/51966/staticFlow/test1", "PUT", fc); - Assert.assertTrue(httpResponseCode == 201); - - // test get returns flow that was added. - result = getJsonResult(baseURL + "node/STUB/51966/staticFlow/test1", "GET"); - // check that result came out fine. - Assert.assertTrue(httpResponseCode == 200); - JSONTokener jt = new JSONTokener(result); - JSONObject json = new JSONObject(jt); - Assert.assertEquals(json.getString("name"), "test1"); - JSONArray actionsArray = json.getJSONArray("actions"); - Assert.assertEquals(actionsArray.getString(0), "DROP"); - Assert.assertEquals(json.getString("installInHw"), "true"); - JSONObject node = json.getJSONObject("node"); - Assert.assertEquals(node.getString("type"), "STUB"); - Assert.assertEquals(node.getString("id"), "51966"); - // test adding same flow again succeeds with a change in any field ..return Success - // code - fc = "{\"name\":\"test1\", \"node\":{\"id\":\"51966\",\"type\":\"STUB\"}, \"actions\":[\"LOOPBACK\"]}"; - result = getJsonResult(baseURL + "node/STUB/51966/staticFlow/test1", "PUT", fc); - Assert.assertTrue(result.contains("Success")); - - fc = "{\"name\":\"test2\", \"node\":{\"id\":\"51966\",\"type\":\"STUB\"}, \"actions\":[\"DROP\"]}"; - result = getJsonResult(baseURL + "node/STUB/51966/staticFlow/test2", "PUT", fc); - // test should return 409 for error due to same flow being added. - Assert.assertTrue(result.equals("409")); - - // add second flow that's different - fc = "{\"name\":\"test2\", \"nwSrc\":\"1.1.1.1\", \"node\":{\"id\":\"51966\",\"type\":\"STUB\"}, \"actions\":[\"DROP\"]}"; - result = getJsonResult(baseURL + "node/STUB/51966/staticFlow/test2", "PUT", fc); - Assert.assertTrue(httpResponseCode == 201); - - // check that request returns both flows given node. - result = getJsonResult(baseURL + "node/STUB/51966/", "GET"); - jt = new JSONTokener(result); - json = new JSONObject(jt); - Assert.assertTrue(json.get("flowConfig") instanceof JSONArray); - JSONArray ja = json.getJSONArray("flowConfig"); - Integer count = ja.length(); - Assert.assertTrue(count == 2); - - // check that request returns both flows given just container. - result = getJsonResult(baseURL); - jt = new JSONTokener(result); - json = new JSONObject(jt); - Assert.assertTrue(json.get("flowConfig") instanceof JSONArray); - ja = json.getJSONArray("flowConfig"); - count = ja.length(); - Assert.assertTrue(count == 2); - - // delete a flow, check that it's no longer in list. - result = getJsonResult(baseURL + "node/STUB/51966/staticFlow/test2", "DELETE"); - Assert.assertTrue(httpResponseCode == 204); - - result = getJsonResult(baseURL + "node/STUB/51966/staticFlow/test2", "GET"); - Assert.assertTrue(result.equals("404")); - } - - // method to extract a JSONObject with specified node ID from a JSONObject - // that may contain an array of JSONObjects - // This is specifically written for statistics manager northbound REST - // interface - // array_name should be either "flowStatistics" or "portStatistics" - private JSONObject getJsonInstance(JSONObject json, String array_name, Integer nodeId) throws JSONException { - JSONObject result = null; - if (json.get(array_name) instanceof JSONArray) { - JSONArray json_array = json.getJSONArray(array_name); - for (int i = 0; i < json_array.length(); i++) { - result = json_array.getJSONObject(i); - Integer nid = result.getJSONObject("node").getInt("id"); - if (nid.equals(nodeId)) { - break; - } - } - } else { - result = json.getJSONObject(array_name); - Integer nid = result.getJSONObject("node").getInt("id"); - if (!nid.equals(nodeId)) { - result = null; - } - } - return result; - } - - // a class to construct query parameter for HTTP request - private class QueryParameter { - StringBuilder queryString = null; - - // constructor - QueryParameter(String key, String value) { - queryString = new StringBuilder(); - queryString.append("?").append(key).append("=").append(value); - } - - // method to add more query parameter - QueryParameter add(String key, String value) { - this.queryString.append("&").append(key).append("=").append(value); - return this; - } - - // method to get the query parameter string - String getString() { - return this.queryString.toString(); - } - - } - - @Test - public void testHostTracker() throws JSONException { - - System.out.println("Starting HostTracker JAXB client."); - - // setup 2 host models for @POST method - // 1st host - String networkAddress_1 = "192.168.0.8"; - String dataLayerAddress_1 = "11:22:33:44:55:66"; - String nodeType_1 = "STUB"; - Integer nodeId_1 = 3366; - String nodeConnectorType_1 = "STUB"; - Integer nodeConnectorId_1 = 12; - String vlan_1 = ""; - - // 2nd host - String networkAddress_2 = "10.1.1.1"; - String dataLayerAddress_2 = "1A:2B:3C:4D:5E:6F"; - String nodeType_2 = "STUB"; - Integer nodeId_2 = 4477; - String nodeConnectorType_2 = "STUB"; - Integer nodeConnectorId_2 = 34; - String vlan_2 = "123"; - - String baseURL = baseUrlPrefix + "hosttracker/default"; - - // test PUT method: addHost() - JSONObject fc_json = new JSONObject(); - fc_json.put("dataLayerAddress", dataLayerAddress_1); - fc_json.put("nodeType", nodeType_1); - fc_json.put("nodeId", nodeId_1); - fc_json.put("nodeConnectorType", nodeType_1); - fc_json.put("nodeConnectorId", nodeConnectorId_1.toString()); - fc_json.put("vlan", vlan_1); - fc_json.put("staticHost", "true"); - fc_json.put("networkAddress", networkAddress_1); - - String result = getJsonResult(baseURL + "/address/" + networkAddress_1, "PUT", fc_json.toString()); - Assert.assertTrue(httpResponseCode == 201); - - fc_json = new JSONObject(); - fc_json.put("dataLayerAddress", dataLayerAddress_2); - fc_json.put("nodeType", nodeType_2); - fc_json.put("nodeId", nodeId_2); - fc_json.put("nodeConnectorType", nodeType_2); - fc_json.put("nodeConnectorId", nodeConnectorId_2.toString()); - fc_json.put("vlan", vlan_2); - fc_json.put("staticHost", "true"); - fc_json.put("networkAddress", networkAddress_2); - - result = getJsonResult(baseURL + "/address/" + networkAddress_2 , "PUT", fc_json.toString()); - Assert.assertTrue(httpResponseCode == 201); - - // define variables for decoding returned strings - String networkAddress; - JSONObject host_jo; - - // the two hosts should be in inactive host DB - // test GET method: getInactiveHosts() - result = getJsonResult(baseURL + "/hosts/inactive", "GET"); - Assert.assertTrue(httpResponseCode == 200); - - JSONTokener jt = new JSONTokener(result); - JSONObject json = new JSONObject(jt); - // there should be at least two hosts in the DB - Assert.assertTrue(json.get("hostConfig") instanceof JSONArray); - JSONArray ja = json.getJSONArray("hostConfig"); - Integer count = ja.length(); - Assert.assertTrue(count == 2); - - for (int i = 0; i < count; i++) { - host_jo = ja.getJSONObject(i); - networkAddress = host_jo.getString("networkAddress"); - if (networkAddress.equalsIgnoreCase(networkAddress_1)) { - Assert.assertTrue(host_jo.getString("dataLayerAddress").equalsIgnoreCase(dataLayerAddress_1)); - Assert.assertTrue(host_jo.getString("nodeConnectorType").equalsIgnoreCase(nodeConnectorType_1)); - Assert.assertTrue(host_jo.getInt("nodeConnectorId") == nodeConnectorId_1); - Assert.assertTrue(host_jo.getString("nodeType").equalsIgnoreCase(nodeType_1)); - Assert.assertTrue(host_jo.getInt("nodeId") == nodeId_1); - Assert.assertTrue(host_jo.getString("vlan").equals("0")); - Assert.assertTrue(host_jo.getBoolean("staticHost")); - } else if (networkAddress.equalsIgnoreCase(networkAddress_2)) { - Assert.assertTrue(host_jo.getString("dataLayerAddress").equalsIgnoreCase(dataLayerAddress_2)); - Assert.assertTrue(host_jo.getString("nodeConnectorType").equalsIgnoreCase(nodeConnectorType_2)); - Assert.assertTrue(host_jo.getInt("nodeConnectorId") == nodeConnectorId_2); - Assert.assertTrue(host_jo.getString("nodeType").equalsIgnoreCase(nodeType_2)); - Assert.assertTrue(host_jo.getInt("nodeId") == nodeId_2); - Assert.assertTrue(host_jo.getString("vlan").equalsIgnoreCase(vlan_2)); - Assert.assertTrue(host_jo.getBoolean("staticHost")); - } else { - Assert.assertTrue(false); - } - } - - // test GET method: getActiveHosts() - no host expected - result = getJsonResult(baseURL + "/hosts/active", "GET"); - Assert.assertTrue(httpResponseCode == 200); - - jt = new JSONTokener(result); - json = new JSONObject(jt); - Assert.assertFalse(hostInJson(json, networkAddress_1)); - Assert.assertFalse(hostInJson(json, networkAddress_2)); - - // put the 1st host into active host DB - Node nd; - NodeConnector ndc; - try { - nd = new Node(nodeType_1, nodeId_1); - ndc = new NodeConnector(nodeConnectorType_1, nodeConnectorId_1, nd); - this.invtoryListener.notifyNodeConnector(ndc, UpdateType.ADDED, null); - } catch (ConstructionException e) { - ndc = null; - nd = null; - } - - // verify the host shows up in active host DB - - result = getJsonResult(baseURL + "/hosts/active", "GET"); - Assert.assertTrue(httpResponseCode == 200); - - jt = new JSONTokener(result); - json = new JSONObject(jt); - - Assert.assertTrue(hostInJson(json, networkAddress_1)); - - // test GET method for getHostDetails() - - result = getJsonResult(baseURL + "/address/" + networkAddress_1, "GET"); - Assert.assertTrue(httpResponseCode == 200); - - jt = new JSONTokener(result); - json = new JSONObject(jt); - - Assert.assertFalse(json.length() == 0); - - Assert.assertTrue(json.getString("dataLayerAddress").equalsIgnoreCase(dataLayerAddress_1)); - Assert.assertTrue(json.getString("nodeConnectorType").equalsIgnoreCase(nodeConnectorType_1)); - Assert.assertTrue(json.getInt("nodeConnectorId") == nodeConnectorId_1); - Assert.assertTrue(json.getString("nodeType").equalsIgnoreCase(nodeType_1)); - Assert.assertTrue(json.getInt("nodeId") == nodeId_1); - Assert.assertTrue(json.getString("vlan").equals("0")); - Assert.assertTrue(json.getBoolean("staticHost")); - - // test DELETE method for deleteFlow() - - result = getJsonResult(baseURL + "/address/" + networkAddress_1, "DELETE"); - Assert.assertTrue(httpResponseCode == 204); - - // verify host_1 removed from active host DB - // test GET method: getActiveHosts() - no host expected - - result = getJsonResult(baseURL + "/hosts/active", "GET"); - Assert.assertTrue(httpResponseCode == 200); - - jt = new JSONTokener(result); - json = new JSONObject(jt); - - Assert.assertFalse(hostInJson(json, networkAddress_1)); - - } - - private Boolean hostInJson(JSONObject json, String hostIp) throws JSONException { - // input JSONObject may be empty - if (json.length() == 0) { - return false; - } - if (json.get("hostConfig") instanceof JSONArray) { - JSONArray ja = json.getJSONArray("hostConfig"); - for (int i = 0; i < ja.length(); i++) { - String na = ja.getJSONObject(i).getString("networkAddress"); - if (na.equalsIgnoreCase(hostIp)) { - return true; - } - } - return false; - } else { - JSONObject ja = json.getJSONObject("hostConfig"); - String na = ja.getString("networkAddress"); - return na.equalsIgnoreCase(hostIp); - } - } - - @Test - public void testTopology() throws JSONException, ConstructionException { - System.out.println("Starting Topology JAXB client."); - String baseURL = baseUrlPrefix + "topology/default"; - - // === test GET method for getTopology() - short state_1 = State.EDGE_UP, state_2 = State.EDGE_DOWN; - long bw_1 = Bandwidth.BW10Gbps, bw_2 = Bandwidth.BW100Mbps; - long lat_1 = Latency.LATENCY100ns, lat_2 = Latency.LATENCY1ms; - String nodeType = "STUB"; - String nodeConnType = "STUB"; - int headNC1_nodeId = 1, headNC1_nodeConnId = 11; - int tailNC1_nodeId = 2, tailNC1_nodeConnId = 22; - int headNC2_nodeId = 2, headNC2_nodeConnId = 21; - int tailNC2_nodeId = 1, tailNC2_nodeConnId = 12; - - List topoedgeupdateList = new ArrayList(); - NodeConnector headnc1 = new NodeConnector(nodeConnType, headNC1_nodeConnId, new Node(nodeType, headNC1_nodeId)); - NodeConnector tailnc1 = new NodeConnector(nodeConnType, tailNC1_nodeConnId, new Node(nodeType, tailNC1_nodeId)); - Edge e1 = new Edge(tailnc1, headnc1); - Set props_1 = new HashSet(); - props_1.add(new State(state_1)); - props_1.add(new Bandwidth(bw_1)); - props_1.add(new Latency(lat_1)); - TopoEdgeUpdate teu1 = new TopoEdgeUpdate(e1, props_1, UpdateType.ADDED); - topoedgeupdateList.add(teu1); - - NodeConnector headnc2 = new NodeConnector(nodeConnType, headNC2_nodeConnId, new Node(nodeType, headNC2_nodeId)); - NodeConnector tailnc2 = new NodeConnector(nodeConnType, tailNC2_nodeConnId, new Node(nodeType, tailNC2_nodeId)); - Edge e2 = new Edge(tailnc2, headnc2); - Set props_2 = new HashSet(); - props_2.add(new State(state_2)); - props_2.add(new Bandwidth(bw_2)); - props_2.add(new Latency(lat_2)); - - TopoEdgeUpdate teu2 = new TopoEdgeUpdate(e2, props_2, UpdateType.ADDED); - topoedgeupdateList.add(teu2); - - topoUpdates.edgeUpdate(topoedgeupdateList); - - // HTTP request - String result = getJsonResult(baseURL, "GET"); - Assert.assertTrue(httpResponseCode == 200); - if (debugMsg) { - System.out.println("Get Topology: " + result); - } - - // returned data must be an array of edges - JSONTokener jt = new JSONTokener(result); - JSONObject json = new JSONObject(jt); - Assert.assertTrue(json.get("edgeProperties") instanceof JSONArray); - JSONArray ja = json.getJSONArray("edgeProperties"); - - for (int i = 0; i < ja.length(); i++) { - JSONObject edgeProp = ja.getJSONObject(i); - JSONObject edge = edgeProp.getJSONObject("edge"); - JSONObject tailNC = edge.getJSONObject("tailNodeConnector"); - JSONObject tailNode = tailNC.getJSONObject("node"); - - JSONObject headNC = edge.getJSONObject("headNodeConnector"); - JSONObject headNode = headNC.getJSONObject("node"); - JSONObject Props = edgeProp.getJSONObject("properties"); - JSONObject bandw = Props.getJSONObject("bandwidth"); - JSONObject stt = Props.getJSONObject("state"); - JSONObject ltc = Props.getJSONObject("latency"); - - if (headNC.getInt("id") == headNC1_nodeConnId) { - Assert.assertEquals(headNode.getString("type"), nodeType); - Assert.assertEquals(headNode.getLong("id"), headNC1_nodeId); - Assert.assertEquals(headNC.getString("type"), nodeConnType); - Assert.assertEquals(tailNode.getString("type"),nodeType); - Assert.assertEquals(tailNode.getString("type"), nodeConnType); - Assert.assertEquals(tailNC.getLong("id"), tailNC1_nodeConnId); - Assert.assertEquals(bandw.getLong("value"), bw_1); - Assert.assertTrue((short) stt.getInt("value") == state_1); - Assert.assertEquals(ltc.getLong("value"), lat_1); - } else if (headNC.getInt("id") == headNC2_nodeConnId) { - Assert.assertEquals(headNode.getString("type"),nodeType); - Assert.assertEquals(headNode.getLong("id"), headNC2_nodeId); - Assert.assertEquals(headNC.getString("type"), nodeConnType); - Assert.assertEquals(tailNode.getString("type"), nodeType); - Assert.assertTrue(tailNode.getInt("id") == tailNC2_nodeId); - Assert.assertEquals(tailNC.getString("type"), nodeConnType); - Assert.assertEquals(tailNC.getLong("id"), tailNC2_nodeConnId); - Assert.assertEquals(bandw.getLong("value"), bw_2); - Assert.assertTrue((short) stt.getInt("value") == state_2); - Assert.assertEquals(ltc.getLong("value"), lat_2); - } - } - - // === test POST method for addUserLink() - // define 2 sample nodeConnectors for user link configuration tests - String nodeType_1 = "STUB"; - Integer nodeId_1 = 3366; - String nodeConnectorType_1 = "STUB"; - Integer nodeConnectorId_1 = 12; - String nodeType_2 = "STUB"; - Integer nodeId_2 = 4477; - String nodeConnectorType_2 = "STUB"; - Integer nodeConnectorId_2 = 34; - - JSONObject jo = new JSONObject() - .put("name", "userLink_1") - .put("srcNodeConnector", - nodeConnectorType_1 + "|" + nodeConnectorId_1 + "@" + nodeType_1 + "|" + nodeId_1) - .put("dstNodeConnector", - nodeConnectorType_2 + "|" + nodeConnectorId_2 + "@" + nodeType_2 + "|" + nodeId_2); - // execute HTTP request and verify response code - result = getJsonResult(baseURL + "/userLink/userLink_1", "PUT", jo.toString()); - Assert.assertTrue(httpResponseCode == 201); - - // === test GET method for getUserLinks() - result = getJsonResult(baseURL + "/userLinks", "GET"); - Assert.assertTrue(httpResponseCode == 200); - if (debugMsg) { - System.out.println("result:" + result); - } - - jt = new JSONTokener(result); - json = new JSONObject(jt); - - // should have at least one object returned - Assert.assertFalse(json.length() == 0); - JSONObject userlink = new JSONObject(); - - if (json.get("userLinks") instanceof JSONArray) { - ja = json.getJSONArray("userLinks"); - int i; - for (i = 0; i < ja.length(); i++) { - userlink = ja.getJSONObject(i); - if (userlink.getString("name").equalsIgnoreCase("userLink_1")) { - break; - } - } - Assert.assertFalse(i == ja.length()); - } else { - userlink = json.getJSONObject("userLinks"); - Assert.assertTrue(userlink.getString("name").equalsIgnoreCase("userLink_1")); - } - - String[] level_1, level_2; - level_1 = userlink.getString("srcNodeConnector").split("\\@"); - level_2 = level_1[0].split("\\|"); - Assert.assertTrue(level_2[0].equalsIgnoreCase(nodeConnectorType_1)); - Assert.assertTrue(Integer.parseInt(level_2[1]) == nodeConnectorId_1); - level_2 = level_1[1].split("\\|"); - Assert.assertTrue(level_2[0].equalsIgnoreCase(nodeType_1)); - Assert.assertTrue(Integer.parseInt(level_2[1]) == nodeId_1); - level_1 = userlink.getString("dstNodeConnector").split("\\@"); - level_2 = level_1[0].split("\\|"); - Assert.assertTrue(level_2[0].equalsIgnoreCase(nodeConnectorType_2)); - Assert.assertTrue(Integer.parseInt(level_2[1]) == nodeConnectorId_2); - level_2 = level_1[1].split("\\|"); - Assert.assertTrue(level_2[0].equalsIgnoreCase(nodeType_2)); - Assert.assertTrue(Integer.parseInt(level_2[1]) == nodeId_2); - - // === test DELETE method for deleteUserLink() - String userName = "userLink_1"; - result = getJsonResult(baseURL + "/userLink/" + userName, "DELETE"); - Assert.assertTrue(httpResponseCode == 204); - - // execute another getUserLinks() request to verify that userLink_1 is - // removed - result = getJsonResult(baseURL + "/userLinks", "GET"); - Assert.assertTrue(httpResponseCode == 200); - if (debugMsg) { - System.out.println("result:" + result); - } - jt = new JSONTokener(result); - json = new JSONObject(jt); - - if (json.length() != 0) { - if (json.get("userLinks") instanceof JSONArray) { - ja = json.getJSONArray("userLinks"); - for (int i = 0; i < ja.length(); i++) { - userlink = ja.getJSONObject(i); - Assert.assertFalse(userlink.getString("name").equalsIgnoreCase("userLink_1")); - } - } else { - userlink = json.getJSONObject("userLinks"); - Assert.assertFalse(userlink.getString("name").equalsIgnoreCase("userLink_1")); - } - } - } - // Configure the OSGi container - @Configuration - public Option[] config() { - return options( - // - systemProperty("logback.configurationFile").value( - "file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"), - // To start OSGi console for inspection remotely - systemProperty("osgi.console").value("2401"), - systemProperty("org.eclipse.gemini.web.tomcat.config.path").value( - PathUtils.getBaseDir() + "/src/test/resources/tomcat-server.xml"), - - // setting default level. Jersey bundles will need to be started - // earlier. - systemProperty("osgi.bundles.defaultStartLevel").value("4"), - - // Set the systemPackages (used by clustering) - systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"), - mavenBundle("org.slf4j", "jcl-over-slf4j").versionAsInProject(), - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), - mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(), - mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager").versionAsInProject(), - - // the plugin stub to get data for the tests - mavenBundle("org.opendaylight.controller", "protocol_plugins.stub").versionAsInProject(), - - // List all the opendaylight modules - mavenBundle("org.opendaylight.controller", "configuration").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "configuration.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "containermanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "containermanager.it.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "clustering.services").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "clustering.services-implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "security").versionAsInProject().noStart(), - mavenBundle("org.opendaylight.controller", "sal").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.connection").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.connection.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "switchmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "connectionmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "connectionmanager.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "switchmanager.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "forwardingrulesmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "forwardingrulesmanager.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "statisticsmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "statisticsmanager.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "arphandler").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "hosttracker").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "hosttracker.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "arphandler").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "routing.dijkstra_implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "topologymanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "usermanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "usermanager.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "logging.bridge").versionAsInProject(), -// mavenBundle("org.opendaylight.controller", "clustering.test").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "forwarding.staticrouting").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "bundlescanner").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "bundlescanner.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "commons.httpclient").versionAsInProject(), - - // Northbound bundles - mavenBundle("org.opendaylight.controller", "commons.northbound").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "forwarding.staticrouting.northbound").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "statistics.northbound").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "topology.northbound").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "hosttracker.northbound").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "switchmanager.northbound").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "flowprogrammer.northbound").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "subnets.northbound").versionAsInProject(), - - mavenBundle("com.fasterxml.jackson.core", "jackson-annotations").versionAsInProject(), - mavenBundle("com.fasterxml.jackson.core", "jackson-core").versionAsInProject(), - mavenBundle("com.fasterxml.jackson.core", "jackson-databind").versionAsInProject(), - mavenBundle("com.fasterxml.jackson.jaxrs", "jackson-jaxrs-json-provider").versionAsInProject(), - mavenBundle("com.fasterxml.jackson.jaxrs", "jackson-jaxrs-base").versionAsInProject(), - mavenBundle("com.fasterxml.jackson.module", "jackson-module-jaxb-annotations").versionAsInProject(), - - mavenBundle("org.codehaus.jettison", "jettison").versionAsInProject(), - - mavenBundle("commons-io", "commons-io").versionAsInProject(), - - mavenBundle("commons-fileupload", "commons-fileupload").versionAsInProject(), - - mavenBundle("equinoxSDK381", "javax.servlet").versionAsInProject(), - mavenBundle("equinoxSDK381", "javax.servlet.jsp").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds").versionAsInProject(), - mavenBundle("orbit", "javax.xml.rpc").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.util").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.osgi.services").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.cm").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.console").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.launcher").versionAsInProject(), - - mavenBundle("geminiweb", "org.eclipse.gemini.web.core").versionAsInProject(), - mavenBundle("geminiweb", "org.eclipse.gemini.web.extender").versionAsInProject(), - mavenBundle("geminiweb", "org.eclipse.gemini.web.tomcat").versionAsInProject(), - mavenBundle("geminiweb", "org.eclipse.virgo.kernel.equinox.extensions").versionAsInProject().noStart(), - mavenBundle("geminiweb", "org.eclipse.virgo.util.common").versionAsInProject(), - mavenBundle("geminiweb", "org.eclipse.virgo.util.io").versionAsInProject(), - mavenBundle("geminiweb", "org.eclipse.virgo.util.math").versionAsInProject(), - mavenBundle("geminiweb", "org.eclipse.virgo.util.osgi").versionAsInProject(), - mavenBundle("geminiweb", "org.eclipse.virgo.util.osgi.manifest").versionAsInProject(), - mavenBundle("geminiweb", "org.eclipse.virgo.util.parser.manifest").versionAsInProject(), - - mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager").versionAsInProject(), - mavenBundle("org.apache.felix", "org.apache.felix.dependencymanager.shell").versionAsInProject(), - - mavenBundle("com.google.code.gson", "gson").versionAsInProject(), - mavenBundle("org.jboss.spec.javax.transaction", "jboss-transaction-api_1.1_spec").versionAsInProject(), - mavenBundle("org.apache.felix", "org.apache.felix.fileinstall").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(), - mavenBundle("commons-codec", "commons-codec").versionAsInProject(), - mavenBundle("virgomirror", "org.eclipse.jdt.core.compiler.batch").versionAsInProject(), - mavenBundle("eclipselink", "javax.persistence").versionAsInProject(), - mavenBundle("eclipselink", "javax.resource").versionAsInProject(), - - mavenBundle("orbit", "javax.activation").versionAsInProject(), - mavenBundle("orbit", "javax.annotation").versionAsInProject(), - mavenBundle("orbit", "javax.ejb").versionAsInProject(), - mavenBundle("orbit", "javax.el").versionAsInProject(), - mavenBundle("orbit", "javax.mail.glassfish").versionAsInProject(), - mavenBundle("orbit", "javax.xml.rpc").versionAsInProject(), - mavenBundle("orbit", "org.apache.catalina").versionAsInProject(), - // these are bundle fragments that can't be started on its own - mavenBundle("orbit", "org.apache.catalina.ha").versionAsInProject().noStart(), - mavenBundle("orbit", "org.apache.catalina.tribes").versionAsInProject().noStart(), - mavenBundle("orbit", "org.apache.coyote").versionAsInProject().noStart(), - mavenBundle("orbit", "org.apache.jasper").versionAsInProject().noStart(), - - mavenBundle("orbit", "org.apache.el").versionAsInProject(), - mavenBundle("orbit", "org.apache.juli.extras").versionAsInProject(), - mavenBundle("orbit", "org.apache.tomcat.api").versionAsInProject(), - mavenBundle("orbit", "org.apache.tomcat.util").versionAsInProject().noStart(), - mavenBundle("orbit", "javax.servlet.jsp.jstl").versionAsInProject(), - mavenBundle("orbit", "javax.servlet.jsp.jstl.impl").versionAsInProject(), - - mavenBundle("org.ops4j.pax.exam", "pax-exam-container-native").versionAsInProject(), - mavenBundle("org.ops4j.pax.exam", "pax-exam-junit4").versionAsInProject(), - mavenBundle("org.ops4j.pax.exam", "pax-exam-link-mvn").versionAsInProject(), - mavenBundle("org.ops4j.pax.url", "pax-url-aether").versionAsInProject(), - - mavenBundle("org.ow2.asm", "asm-all").versionAsInProject(), - - mavenBundle("org.springframework", "org.springframework.asm").versionAsInProject(), - mavenBundle("org.springframework", "org.springframework.aop").versionAsInProject(), - mavenBundle("org.springframework", "org.springframework.context").versionAsInProject(), - mavenBundle("org.springframework", "org.springframework.context.support").versionAsInProject(), - mavenBundle("org.springframework", "org.springframework.core").versionAsInProject(), - mavenBundle("org.springframework", "org.springframework.beans").versionAsInProject(), - mavenBundle("org.springframework", "org.springframework.expression").versionAsInProject(), - mavenBundle("org.springframework", "org.springframework.web").versionAsInProject(), - - mavenBundle("org.aopalliance", "com.springsource.org.aopalliance").versionAsInProject(), - mavenBundle("org.springframework", "org.springframework.web.servlet").versionAsInProject(), - mavenBundle("org.springframework.security", "spring-security-config").versionAsInProject(), - mavenBundle("org.springframework.security", "spring-security-core").versionAsInProject(), - mavenBundle("org.springframework.security", "spring-security-web").versionAsInProject(), - mavenBundle("org.springframework.security", "spring-security-taglibs").versionAsInProject(), - mavenBundle("org.springframework", "org.springframework.transaction").versionAsInProject(), - - mavenBundle("org.ow2.chameleon.management", "chameleon-mbeans").versionAsInProject(), - mavenBundle("org.opendaylight.controller.thirdparty", "net.sf.jung2").versionAsInProject(), - mavenBundle("org.opendaylight.controller.thirdparty", "com.sun.jersey.jersey-servlet") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller.thirdparty", "org.apache.catalina.filters.CorsFilter") - .versionAsInProject().noStart(), - - // Jersey needs to be started before the northbound application - // bundles, using a lower start level - mavenBundle("com.sun.jersey", "jersey-client").versionAsInProject(), - mavenBundle("com.sun.jersey", "jersey-server").versionAsInProject().startLevel(2), - mavenBundle("com.sun.jersey", "jersey-core").versionAsInProject().startLevel(2), - junitBundles()); - } - -} diff --git a/opendaylight/adsal/northbound/integrationtest/src/test/resources/exam.properties b/opendaylight/adsal/northbound/integrationtest/src/test/resources/exam.properties deleted file mode 100644 index d5f9ae1fcd..0000000000 --- a/opendaylight/adsal/northbound/integrationtest/src/test/resources/exam.properties +++ /dev/null @@ -1,4 +0,0 @@ -#pax.exam.system = default -pax.exam.logging = none -pax.exam.service.timeout = 5000 - diff --git a/opendaylight/adsal/northbound/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/northbound/integrationtest/src/test/resources/logback.xml deleted file mode 100644 index 2d63ce5744..0000000000 --- a/opendaylight/adsal/northbound/integrationtest/src/test/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/opendaylight/adsal/northbound/integrationtest/src/test/resources/tomcat-server.xml b/opendaylight/adsal/northbound/integrationtest/src/test/resources/tomcat-server.xml deleted file mode 100644 index ee88f2330c..0000000000 --- a/opendaylight/adsal/northbound/integrationtest/src/test/resources/tomcat-server.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/java-client/enunciate.xml b/opendaylight/adsal/northbound/java-client/enunciate.xml deleted file mode 100644 index c78243766e..0000000000 --- a/opendaylight/adsal/northbound/java-client/enunciate.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/java-client/pom.xml b/opendaylight/adsal/northbound/java-client/pom.xml deleted file mode 100644 index 46f8e9006a..0000000000 --- a/opendaylight/adsal/northbound/java-client/pom.xml +++ /dev/null @@ -1,194 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - enunciate-parent - 1.6.0-SNAPSHOT - ../../../commons/enunciate-parent - - - northbound.client - 0.2.0-SNAPSHOT - pom - - - ${project.build.directory}/rest-api-docs - ${project.build.directory}/enunciate/build/java-client/full-client.jar - ${project.build.directory}/enunciate/build/java-client/full-client-sources.jar - - - - - org.codehaus.enunciate - enunciate-core-annotations - - - - - org.opendaylight.controller - connectionmanager.northbound - - - org.opendaylight.controller - controllermanager.northbound - - - org.opendaylight.controller - flowprogrammer.northbound - - - org.opendaylight.controller - forwarding.staticrouting.northbound - - - org.opendaylight.controller - hosttracker.northbound - - - org.opendaylight.controller - networkconfig.bridgedomain.northbound - - - org.opendaylight.controller - statistics.northbound - - - org.opendaylight.controller - subnets.northbound - - - org.opendaylight.controller - switchmanager.northbound - - - org.opendaylight.controller - topology.northbound - - - org.opendaylight.controller - usermanager.northbound - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <![CDATA[ - <html> - <head> - <title> OpenDaylight REST API Documentation </title> - </head> - <body> - <h2>OpenDaylight REST API Documentation</h2> - <p> OpenDaylight supports the following <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">Representational State Transfer (REST)</a> APIs: </p> - <h4> - ]]> - - - - - - - - - <![CDATA[ - </h4> - <i>---</i> - </body> - </html> - ]]> - - - - - - - - - - - - - ant-contrib - ant-contrib - 20020829 - - - - - - run - - package - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - attach-artifacts - - attach-artifact - - package - - - - ${java-client} - jar - full-java-client - - - ${java-client-sources} - jar - full-java-client-sources - - - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/jolokia/pom.xml b/opendaylight/adsal/northbound/jolokia/pom.xml deleted file mode 100644 index 158003a403..0000000000 --- a/opendaylight/adsal/northbound/jolokia/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - jolokia-bridge - 0.2.0-SNAPSHOT - bundle - Jolokia bridge web application - - - - - org.apache.felix - maven-bundle-plugin - true - - - - javax.servlet, - javax.servlet.http, - org.eclipse.equinox.http.servlet, - org.opendaylight.controller.web, - org.osgi.framework, - org.jolokia.osgi.servlet, - org.apache.catalina.filters, - org.slf4j, - /controller/nb/v2/jolokia - - - - - - diff --git a/opendaylight/adsal/northbound/jolokia/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/jolokia/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 126396de6b..0000000000 --- a/opendaylight/adsal/northbound/jolokia/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - JolokiaServlet - org.jolokia.osgi.servlet.JolokiaServlet - 1 - - - - JolokiaServlet - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - JolokiaService - /* - - - System-Admin - Network-Admin - - - - - System-Admin - - - - Network-Admin - - - - BASIC - opendaylight - - diff --git a/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/enunciate.xml b/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/enunciate.xml deleted file mode 100644 index 1555743ea8..0000000000 --- a/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/pom.xml b/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/pom.xml deleted file mode 100644 index df2ba4e8ce..0000000000 --- a/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../../adsal-enunciate-parent - - - networkconfig.bridgedomain.northbound - 0.2.0-SNAPSHOT - bundle - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller - sal.networkconfiguration - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.networkconfig.bridgedomain, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.usermanager, - com.sun.jersey.spi.container.servlet, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.connectionmanager, - org.opendaylight.controller.sal.connection, - org.slf4j, - javax.ws.rs, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - - /controller/nb/v2/networkconfig/bridgedomain - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/src/main/java/org/opendaylight/controller/networkconfig/bridgedomain/northbound/BridgeDomainNorthbound.java b/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/src/main/java/org/opendaylight/controller/networkconfig/bridgedomain/northbound/BridgeDomainNorthbound.java deleted file mode 100644 index 8aea7e57f8..0000000000 --- a/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/src/main/java/org/opendaylight/controller/networkconfig/bridgedomain/northbound/BridgeDomainNorthbound.java +++ /dev/null @@ -1,342 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.networkconfig.bridgedomain.northbound; - -import java.util.HashMap; -import java.util.Map; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.northbound.commons.exception.NotAcceptableException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.networkconfig.bridgedomain.BridgeDomainConfigServiceException; -import org.opendaylight.controller.sal.networkconfig.bridgedomain.ConfigConstants; -import org.opendaylight.controller.sal.networkconfig.bridgedomain.IBridgeDomainConfigService; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; - -/** - * BridgeDomain Configuration Northbound APIs - * - *

- * Authentication scheme : HTTP Basic
- * Authentication realm : opendaylight
- * Transport : HTTP and HTTPS
- *
- * HTTPS Authentication is disabled by default. Administrator can enable it in tomcat-server.xml after adding - * a proper keystore / SSL certificate from a trusted authority.
- * More info : http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration - */ -@Path("/") -public class BridgeDomainNorthbound { - private String username; - - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - protected String getUserName() { - return username; - } - - private IBridgeDomainConfigService getConfigurationService() { - return (IBridgeDomainConfigService) ServiceHelper - .getGlobalInstance(IBridgeDomainConfigService.class, this); - } - - private IConnectionManager getConnectionManager() { - return (IConnectionManager) ServiceHelper - .getGlobalInstance(IConnectionManager.class, this); - } - - /** - * Create a Bridge. - *
-     *
-     * Example :
-     *
-     * Request :
-     * http://localhost:8080/controller/nb/v2/networkconfig/bridgedomain/bridge/STUB/mgmt1/bridge1
-     *
-     *
- * @param nodeType Node Type of the node with the management session. - * @param nodeId Node Identifier of the node with the management session. - * @param bridgeName Name / Identifier for a bridge to be created. - * @param bridgeConfigs Additional Bridge Configurations. - * It takes in complex structures under the ConfigConstants.CUSTOM key. - * The use-cases are documented under wiki.opendaylight.org project pages: - * https://wiki.opendaylight.org/view/OVSDB_Integration:Mininet_OVSDB_Tutorial - */ - - @Path("/bridge/{nodeType}/{nodeId}/{bridgeName}") - @POST - @StatusCodes( { @ResponseCode(code = 201, condition = "Bridge created successfully"), - @ResponseCode(code = 404, condition = "Could not create Bridge"), - @ResponseCode(code = 412, condition = "Failed to create Bridge due to an exception"), - @ResponseCode(code = 503, condition = "Bridge Domain Configuration Service not available")} ) - - public Response createBridge( - @PathParam(value = "nodeType") String nodeType, - @PathParam(value = "nodeId") String nodeId, - @PathParam(value = "bridgeName") String name, - Map bridgeConfigs) { - - IBridgeDomainConfigService configurationService = getConfigurationService(); - if (configurationService == null) { - throw new ServiceUnavailableException("IBridgeDomainConfigService not available."); - } - - Node node = Node.fromString(nodeType, nodeId); - Status status = null; - try { - Map configs = this.buildConfig(bridgeConfigs); - status = configurationService.createBridgeDomain(node, name, configs); - if (status.getCode().equals(StatusCode.SUCCESS)) { - return Response.status(Response.Status.CREATED).build(); - } - } catch (BridgeDomainConfigServiceException e) { - return Response.status(Response.Status.PRECONDITION_FAILED).build(); - } - throw new ResourceNotFoundException(status.getDescription()); - } - - - /** - * Remove a Bridge. - *
-    *
-    * Example :
-    *
-    * Request :
-    * DELETE
-    * http://localhost:8080/controller/nb/v2/networkconfig/bridgedomain/bridge/STUB/mgmt1/bridge1
-    *
-    *
- * @param nodeType Node Type of the node with the management session. - * @param nodeId Node Identifier of the node with the management session. - * @param bridgeName Name / Identifier for a bridge to be deleted. - */ - - @Path("/bridge/{nodeType}/{nodeId}/{bridgeName}") - @DELETE - @StatusCodes( { @ResponseCode(code = 200, condition = "Bridge deleted successfully"), - @ResponseCode(code = 404, condition = "Could not delete Bridge"), - @ResponseCode(code = 412, condition = "Failed to delete Bridge due to an exception"), - @ResponseCode(code = 503, condition = "Bridge Domain Configuration Service not available")} ) - - public Response deleteBridge( - @PathParam(value = "nodeType") String nodeType, - @PathParam(value = "nodeId") String nodeId, - @PathParam(value = "bridgeName") String name) { - - IBridgeDomainConfigService configurationService = getConfigurationService(); - if (configurationService == null) { - throw new ServiceUnavailableException("IBridgeDomainConfigService not available."); - } - - Node node = Node.fromString(nodeType, nodeId); - Status status = null; - try { - status = configurationService.deleteBridgeDomain(node, name); - if (status.getCode().equals(StatusCode.SUCCESS)) { - return Response.status(Response.Status.OK).build(); - } - } catch (Exception t) { - return Response.status(Response.Status.PRECONDITION_FAILED).build(); - } - throw new ResourceNotFoundException(status.getDescription()); - } - - /** - * Add a Port to a Bridge - *
-    *
-    * Example :
-    *
-    * Request :
-    * http://localhost:8080/controller/nb/v2/networkconfig/bridgedomain/port/STUB/mgmt1/bridge1/port1
-    *
-    *
- * @param nodeType Node Type of the node with the management session. - * @param nodeId Node Identifier of the node with the management session. - * @param bridgeName Name / Identifier of the bridge to which a Port is being added. - * @param portName Name / Identifier of a Port that is being added to a bridge. - * @param portConfigs Additional Port Configurations. - * It takes in complex structures under the ConfigConstants.CUSTOM key. - * The use-cases are documented under wiki.opendaylight.org project pages : - * https://wiki.opendaylight.org/view/OVSDB_Integration:Mininet_OVSDB_Tutorial - */ - - @Path("/port/{nodeType}/{nodeId}/{bridgeName}/{portName}") - @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @StatusCodes( { @ResponseCode(code = 201, condition = "Port added successfully"), - @ResponseCode(code = 404, condition = "Could not add Port to the Bridge"), - @ResponseCode(code = 412, condition = "Failed to add Port due to an exception"), - @ResponseCode(code = 503, condition = "Bridge Domain Configuration Service not available")} ) - - public Response addPort( - @PathParam(value = "nodeType") String nodeType, - @PathParam(value = "nodeId") String nodeId, - @PathParam(value = "bridgeName") String bridge, - @PathParam(value = "portName") String port, - Map portConfigs) { - - IBridgeDomainConfigService configurationService = getConfigurationService(); - if (configurationService == null) { - throw new ServiceUnavailableException("IBridgeDomainConfigService not available."); - } - - Node node = Node.fromString(nodeType, nodeId); - Status status = null; - try { - Map configs = this.buildConfig(portConfigs); - status = configurationService.addPort(node, bridge, port, configs); - if (status.getCode().equals(StatusCode.SUCCESS)) { - return Response.status(Response.Status.CREATED).build(); - } - } catch (Exception t) { - return Response.status(Response.Status.PRECONDITION_FAILED).build(); - } - throw new ResourceNotFoundException(status.getDescription()); - } - - /** - * Remove a Port from a Bridge - *
-    *
-    * Example :
-    *
-    * Request :
-    * DELETE
-    * http://localhost:8080/controller/nb/v2/networkconfig/bridgedomain/port/STUB/mgmt1/bridge1/port1
-    *
-    *
- * @param nodeType Node Type of the node with the management session. - * @param nodeId Node Identifier of the node with the management session. - * @param bridgeName Name / Identifier of the bridge to which a Port is being added. - * @param portName Name / Identifier of a Port that is being deleted from a bridge. - */ - - @Path("/port/{nodeType}/{nodeId}/{bridgeName}/{portName}") - @DELETE - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @StatusCodes( { @ResponseCode(code = 200, condition = "Port deleted successfully"), - @ResponseCode(code = 404, condition = "Could not delete Port to the Bridge"), - @ResponseCode(code = 412, condition = "Failed to delete Port due to an exception"), - @ResponseCode(code = 503, condition = "Bridge Domain Configuration Service not available")} ) - - public Response deletePort( - @PathParam(value = "nodeType") String nodeType, - @PathParam(value = "nodeId") String nodeId, - @PathParam(value = "bridgeName") String bridge, - @PathParam(value = "portName") String port) { - - IBridgeDomainConfigService configurationService = getConfigurationService(); - if (configurationService == null) { - throw new ServiceUnavailableException("IBridgeDomainConfigService not available."); - } - - Node node = Node.fromString(nodeType, nodeId); - Status status = null; - try { - status = configurationService.deletePort(node, bridge, port); - if (status.getCode().equals(StatusCode.SUCCESS)) { - return Response.status(Response.Status.OK).build(); - } - } catch (Exception t) { - return Response.status(Response.Status.PRECONDITION_FAILED).build(); - } - throw new ResourceNotFoundException(status.getDescription()); - } - - private Map buildConfig(Map rawConfigs) { - if (rawConfigs == null) return null; - Map configs = new HashMap(); - for (String key : rawConfigs.keySet()) { - ConfigConstants cc = ConfigConstants.valueOf(key.toUpperCase()); - configs.put(cc, rawConfigs.get(key)); - } - return configs; - } -/** - * Add a Port,Vlan to a Bridge - *
-    *
-    * Example :
-    * Request :
-    * http://localhost:8080/controller/nb/v2/networkconfig/bridgedomain/port/STUB/mgmt1/bridge1/port2/200
-    *
-    * 
- * @param nodeType Node Type of the node with the management session. - * @param nodeId Node Identifier of the node with the management session. - * @param bridgeName Name / Identifier of the bridge to which a Port is being added. - * @param portName Name / Identifier of a Port that is being added to a bridge. - * @param vlan Vlan Id. - */ - - @Path("/port/{nodeType}/{nodeId}/{bridgeName}/{portName}/{vlan}") - @POST - @StatusCodes( { @ResponseCode(code = 201, condition = "Created Port with Vlan tag successfully"), - @ResponseCode(code = 404, condition = "Could not add Port,Vlan to the Bridge"), - @ResponseCode(code = 406, condition = "Invalid Vlan parameter passed."), - @ResponseCode(code = 412, condition = "Failed to add Port,Vlan due to an exception"), - @ResponseCode(code = 503, condition = "Bridge Domain Configuration Service not available")} ) - - public Response addPort( - @PathParam(value = "nodeType") String nodeType, - @PathParam(value = "nodeId") String nodeId, - @PathParam(value = "bridgeName") String bridge, - @PathParam(value = "portName") String port, - @PathParam(value = "vlan") String vlan) { - - IBridgeDomainConfigService configurationService = getConfigurationService(); - if (configurationService == null) { - throw new ServiceUnavailableException("IBridgeDomainConfigService not available."); - } - try { - Integer.parseInt(vlan); - } catch (Exception e) { - throw new NotAcceptableException("Incorrect Vlan :"+vlan); - } - - Node node = Node.fromString(nodeType, nodeId); - Map configs = new HashMap(); - configs.put(ConfigConstants.TYPE, ConfigConstants.VLAN.name()); - configs.put(ConfigConstants.VLAN, vlan); - - Status status = null; - try { - status = configurationService.addPort(node, bridge, port, configs); - if (status.getCode().equals(StatusCode.SUCCESS)) { - return Response.status(Response.Status.CREATED).build(); - } - } catch (Exception e) { - return Response.status(Response.Status.PRECONDITION_FAILED).build(); - } - throw new ResourceNotFoundException(status.getDescription()); - } -} diff --git a/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 455fbdd1c7..0000000000 --- a/opendaylight/adsal/northbound/networkconfiguration/bridgedomain/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - - BridgeDomainConfiguration - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - BridgeDomainConfiguration - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,DELETE,HEAD,OPTIONS,PUT - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - - \ No newline at end of file diff --git a/opendaylight/adsal/northbound/staticrouting/enunciate.xml b/opendaylight/adsal/northbound/staticrouting/enunciate.xml deleted file mode 100644 index 4d2f1cb611..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/staticrouting/pom.xml b/opendaylight/adsal/northbound/staticrouting/pom.xml deleted file mode 100644 index c65f0369ba..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../adsal-enunciate-parent - - - forwarding.staticrouting.northbound - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - forwarding.staticrouting - - - org.opendaylight.controller - sal - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.forwarding.staticrouting, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.usermanager, - com.sun.jersey.spi.container.servlet, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.northbound.commons.query, - org.opendaylight.controller.sal.authorization, - org.slf4j, - javax.ws.rs, - javax.ws.rs.ext, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - - /controller/nb/v2/staticroute - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoute.java b/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoute.java deleted file mode 100644 index 573a08189f..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoute.java +++ /dev/null @@ -1,77 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting.northbound; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * StaticRoute represents the static route data that is returned as a response to - * the NorthBound GET request. - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class StaticRoute { - /** - * The name of the static route. - */ - @XmlElement - private String name; - - /** - * The prefix for the route. - * Format: A.B.C.D/MM Where A.B.C.D is the Default Gateway IP (L3) or ARP Querier IP (L2) - */ - @XmlElement - private String prefix; - - /** - * NextHop IP-Address (or) datapath ID/port list: xx:xx:xx:xx:xx:xx:xx:xx/a,b,c-m,r-t,y - */ - @XmlElement - private String nextHop; - - public StaticRoute() { - } - - public StaticRoute(String name, String prefix, String nextHop) { - super(); - this.name = name; - this.prefix = prefix; - this.nextHop = nextHop; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getPrefix() { - return prefix; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - public String getNextHop() { - return nextHop; - } - - public void setNextHop(String nextHop) { - this.nextHop = nextHop; - } -} diff --git a/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutes.java b/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutes.java deleted file mode 100644 index d6d0995fa2..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutes.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - - -/** - * This class represents a list of static routes. - */ -@XmlRootElement(name = "list") -@XmlAccessorType(XmlAccessType.NONE) -public class StaticRoutes { - @XmlElement - List staticRoute; - //To satisfy JAXB - private StaticRoutes() { - - } - - public StaticRoutes(List staticRoute) { - this.staticRoute = staticRoute; - } - - public List getFlowConfig() { - return staticRoute; - } - - public void setFlowConfig(List staticRoute) { - this.staticRoute = staticRoute; - } -} diff --git a/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthbound.java b/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthbound.java deleted file mode 100644 index de291d6d96..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthbound.java +++ /dev/null @@ -1,376 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.forwarding.staticrouting.northbound; - -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.ContextResolver; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.forwarding.staticrouting.IForwardingStaticRouting; -import org.opendaylight.controller.forwarding.staticrouting.StaticRouteConfig; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException; -import org.opendaylight.controller.northbound.commons.exception.NotAcceptableException; -import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.query.QueryContext; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; - -/** - *

Static Routing Northbound API allows for the management of the static - * routes.

- *
- * An example request/response for retrieving the static routes may look like this:
- *
- * GET http://localhost:8080/controller/nb/v2/staticroute/default HTTP/1.1
- * Accept: application/json
- *
- * HTTP/1.1 200 OK
- * Content-Type: application/json
- *
- * { "staticRoute":[
- *       "name":"route-1",
- *       "prefix":"10.10.1.0/24",
- *       "nextHop":"1.1.1.1"
- *   ]
- * }
- *
- * 
- * - *

- * Authentication scheme : HTTP Basic
- * Authentication realm : opendaylight
- * Transport : HTTP and HTTPS
- *
- */ -@Path("/") -public class StaticRoutingNorthbound { - - private String username; - private QueryContext queryContext; - - @Context - public void setQueryContext(ContextResolver queryCtxResolver) { - if (queryCtxResolver != null) { - queryContext = queryCtxResolver.getContext(QueryContext.class); - } - } - - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - protected String getUserName() { - return username; - } - - - - private List getStaticRoutesInternal(String containerName) { - - IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper - .getInstance(IForwardingStaticRouting.class, containerName, - this); - - if (staticRouting == null) { - throw new ResourceNotFoundException(RestMessages.NOCONTAINER - .toString()); - } - - List routes = new ArrayList(); - - for (StaticRouteConfig conf : staticRouting.getStaticRouteConfigs() - .values()) { - StaticRoute route = new StaticRoute(conf.getName(), conf - .getStaticRoute(), conf.getNextHop()); - routes.add(route); - } - return routes; - } - - /** - * Get a list of static routes present on the given container. - * - * @param containerName Name of the Container. The Container name for the base controller is "default". - * @return List of configured static routes on the given container - * - *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/staticroute/default/routes
-     *
-     * Response body in XML:
-     *  <list>
-     *   <staticRoute>
-     *     <name>route-1</name>
-     *     <prefix>10.10.1.0/24</prefix>
-     *     <nextHop>1.1.1.1</nextHop>
-     *   </staticRoute>
-     *  </list>
-     *
-     * Response body in JSON:
-     * {
-     *    "staticRoute": [
-     *      {
-     *       "name": "route-1",
-     *       "prefix": "10.10.1.0/24",
-     *       "nextHop": "1.1.1.1"
-     *      }
-     *    ]
-     * }
-     * 
- */ - @Path("/{containerName}/routes") - @GET - @Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(StaticRoutes.class) - @StatusCodes( { - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName passed was not found") }) - public StaticRoutes getStaticRoutes( - @PathParam("containerName") String containerName, - @QueryParam("_q") String queryString) { - - if(!NorthboundUtils.isAuthorized(getUserName(), containerName, - Privilege.WRITE, this)){ - throw new - UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - StaticRoutes result = new StaticRoutes(getStaticRoutesInternal(containerName)); - if (queryString != null) { - queryContext.createQuery(queryString, StaticRoutes.class) - .filter(result, StaticRoute.class); - } - return result; - } - - /** - * Returns the static route for the provided configuration name on a given container - * - * @param containerName Name of the Container. The Container name for the base controller is "default". - * @param route Name of the Static Route configuration - * @return Static route configured with the supplied Name. - * - *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/staticroute/default/route/route-1
-     *
-     * Response body in XML:
-     *
-     *   <staticRoute>
-     *     <name>route-1</name>
-     *     <prefix>10.10.1.0/24</prefix>
-     *     <nextHop>1.1.1.1</nextHop>
-     *   </staticRoute>
-     *
-     * Response body in JSON:
-     * {
-     *    "name":"route-1",
-     *    "prefix":"10.10.1.0/24",
-     *    "nextHop":"1.1.1.1"
-     * }
-     *
-     * 
- */ - @Path("/{containerName}/route/{route}") - @GET - @Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(StaticRoute.class) - @StatusCodes( { - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The Container Name or Static Route Configuration name passed was not found") }) - public StaticRoute getStaticRoute( - @PathParam("containerName") String containerName, - @PathParam("route") String route) { - - if(!NorthboundUtils.isAuthorized(getUserName(), containerName, - Privilege.WRITE, this)){ - throw new - UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - List routes = this.getStaticRoutesInternal(containerName); - for (StaticRoute r : routes) { - if (r.getName().equalsIgnoreCase(route)) { - return r; - } - } - - throw new ResourceNotFoundException(RestMessages.NOSTATICROUTE - .toString()); - } - - /** - * - * Add a new Static Route. If a route by the given name already exists, this - * method will return a non-successful status response. - * - * @param containerName Name of the Container. The Container name for the base controller is "default". - * @param route Name of the Static Route configuration - * @return Response as dictated by the HTTP Response code - * - *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/staticroute/default/route/route-1
-     *
-     * Request body in XML:
-     * <staticRoute>
-     *   <name>route-1</name>
-     *   <prefix>10.10.1.0/24</prefix>
-     *   <nextHop>1.1.1.1</nextHop>
-     *   </staticRoute>
-     * Request body in JSON:
-     * {
-     *    "name":"route-1",
-     *    "prefix":"10.10.1.0/24",
-     *    "nextHop":"1.1.1.1"
-     * }
-     * 
- */ - @Path("/{containerName}/route/{route}") - @PUT - @Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes( { - @ResponseCode(code = 201, condition = "Created Static Route successfully"), - @ResponseCode(code = 404, condition = "The Container Name passed is not found"), - @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active"), - @ResponseCode(code = 409, condition = "Failed to create Static Route entry due to Conflicting Name or Prefix."), }) - public Response addStaticRoute( - @Context UriInfo uriInfo, - @PathParam(value = "containerName") String containerName, - @PathParam(value = "route") String route, - @TypeHint(StaticRoute.class) StaticRoute staticRouteData) { - - - if(!NorthboundUtils.isAuthorized(getUserName(), containerName, - Privilege.WRITE, this)){ - throw new - UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - handleDefaultDisabled(containerName); - - IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper - .getInstance(IForwardingStaticRouting.class, containerName, - this); - - if (staticRouting == null) { - throw new ResourceNotFoundException(RestMessages.NOCONTAINER - .toString()); - } - - StaticRoute sRoute = staticRouteData; - StaticRouteConfig cfgObject = new StaticRouteConfig(sRoute.getName(), - sRoute.getPrefix(), sRoute.getNextHop()); - Status response = staticRouting.addStaticRoute(cfgObject); - if (response.isSuccess()) { - NorthboundUtils.auditlog("Static Route", username, "added", route, containerName); - return Response.created(uriInfo.getRequestUri()).build(); - } - throw new ResourceConflictException(response.getDescription()); - } - - /** - * - * Delete a Static Route - * - * @param containerName Name of the Container. The Container name for the base controller is "default". - * @param route Name of the Static Route configuration to be removed - * - * @return Response as dictated by the HTTP Response code - * - *
-     * Example:
-     *
-     * Request URL:
-     * DELETE http://localhost:8080/controller/nb/v2/staticroute/default/route/route-1
-     *
-     * 
- */ - @Path("/{containerName}/route/{route}") - @DELETE - @StatusCodes( { - @ResponseCode(code = 204, condition = "Static route removed successfully"), - @ResponseCode(code = 404, condition = "Container Name or Configuration Name not found"), - @ResponseCode(code = 406, condition = "Cannot operate on Default Container when other Containers are active") }) - public Response removeStaticRoute( - @PathParam(value = "containerName") String containerName, - @PathParam(value = "route") String route) { - - if(!NorthboundUtils.isAuthorized(getUserName(), containerName, - Privilege.WRITE, this)){ - throw new - UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - handleDefaultDisabled(containerName); - - IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper - .getInstance(IForwardingStaticRouting.class, containerName, - this); - - if (staticRouting == null) { - throw new ResourceNotFoundException(RestMessages.NOCONTAINER - .toString()); - } - - Status status = staticRouting.removeStaticRoute(route); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Static Route", username, "removed", route, containerName); - return Response.noContent().build(); - } - return NorthboundUtils.getResponse(status); - } - - private void handleDefaultDisabled(String containerName) { - IContainerManager containerManager = (IContainerManager) ServiceHelper - .getGlobalInstance(IContainerManager.class, this); - if (containerManager == null) { - throw new InternalServerErrorException(RestMessages.INTERNALERROR - .toString()); - } - if (containerName.equals(GlobalConstants.DEFAULT.toString()) - && containerManager.hasNonDefaultContainer()) { - throw new NotAcceptableException(RestMessages.DEFAULTDISABLED - .toString()); - } - } -} diff --git a/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/northbound/staticrouting/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/staticrouting/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index ef58aab0b5..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - JAXRSStaticRouting - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSStaticRouting - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - \ No newline at end of file diff --git a/opendaylight/adsal/northbound/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthboundTest.java b/opendaylight/adsal/northbound/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthboundTest.java deleted file mode 100644 index 5a5da4ef1f..0000000000 --- a/opendaylight/adsal/northbound/staticrouting/src/test/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthboundTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.forwarding.staticrouting.northbound; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; - -public class StaticRoutingNorthboundTest { - - @Test - public void testStaticRoute() { - StaticRoute sr = new StaticRoute(); - Assert.assertTrue(sr.getName() == null); - Assert.assertTrue(sr.getPrefix() == null); - Assert.assertTrue(sr.getNextHop() == null); - - sr = new StaticRoute("Static Route 1", "192.168.100.0/24", "170.0.0.1"); - Assert.assertTrue(sr.getName().equals("Static Route 1")); - Assert.assertTrue(sr.getPrefix().equals("192.168.100.0/24")); - Assert.assertTrue(sr.getNextHop().equals("170.0.0.1")); - - sr.setName("Static Route 2"); - Assert.assertTrue(sr.getName().equals("Static Route 2")); - sr.setPrefix("192.168.100.0/26"); - Assert.assertTrue(sr.getPrefix().equals("192.168.100.0/26")); - sr.setNextHop("170.0.2.1"); - Assert.assertTrue(sr.getNextHop().equals("170.0.2.1")); - } - - @Test - public void testStaticRoutes() { - StaticRoutes srs = new StaticRoutes(null); - Assert.assertTrue(srs.getFlowConfig() == null); - - List srl = new ArrayList(); - srs.setFlowConfig(srl); - Assert.assertTrue(srs.getFlowConfig().equals(srl)); - } - -} diff --git a/opendaylight/adsal/northbound/statistics/enunciate.xml b/opendaylight/adsal/northbound/statistics/enunciate.xml deleted file mode 100644 index c5f9140c76..0000000000 --- a/opendaylight/adsal/northbound/statistics/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/statistics/pom.xml b/opendaylight/adsal/northbound/statistics/pom.xml deleted file mode 100644 index 8b54a9847c..0000000000 --- a/opendaylight/adsal/northbound/statistics/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../adsal-enunciate-parent - - - statistics.northbound - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - statisticsmanager - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.forwardingrulesmanager, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.reader, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.statisticsmanager, - org.opendaylight.controller.usermanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.sal.authorization, - org.apache.commons.logging, - com.sun.jersey.spi.container.servlet, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.northbound.commons.query, - javax.ws.rs, - javax.ws.rs.ext, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.slf4j, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - - /controller/nb/v2/statistics - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllFlowStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllFlowStatistics.java deleted file mode 100644 index 18627285ea..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllFlowStatistics.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statistics.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "list") -@XmlAccessorType(XmlAccessType.NONE) -public class AllFlowStatistics { - @XmlElement - List flowStatistics; - //To satisfy JAXB - @SuppressWarnings("unused") - private AllFlowStatistics() {} - - public AllFlowStatistics(List flowStatistics) { - this.flowStatistics = flowStatistics; - } - - public List getFlowStatistics() { - return flowStatistics; - } - - public void setFlowStatistics(List flowStatistics) { - this.flowStatistics = flowStatistics; - } - -} diff --git a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllPortStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllPortStatistics.java deleted file mode 100644 index 2117690d97..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllPortStatistics.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statistics.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "list") -@XmlAccessorType(XmlAccessType.NONE) -public class AllPortStatistics { - @XmlElement - List portStatistics; - //To satisfy JAXB - @SuppressWarnings("unused") - private AllPortStatistics() {} - - public AllPortStatistics(List portStatistics) { - this.portStatistics = portStatistics; - } - - public List getPortStatistics() { - return portStatistics; - } - - public void setPortStatistics(List portStatistics) { - this.portStatistics = portStatistics; - } - -} diff --git a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllTableStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllTableStatistics.java deleted file mode 100644 index 4a10eb4fa2..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/AllTableStatistics.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.statistics.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "list") -@XmlAccessorType(XmlAccessType.NONE) -public class AllTableStatistics { - @XmlElement - List tableStatistics; - //To satisfy JAXB - @SuppressWarnings("unused") - private AllTableStatistics() {} - - public AllTableStatistics(List tableStatistics) { - this.tableStatistics = tableStatistics; - } - - public List getTableStatistics() { - return tableStatistics; - } - - public void setTableStatistics(List tableStatistics) { - this.tableStatistics = tableStatistics; - } - -} diff --git a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/FlowStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/FlowStatistics.java deleted file mode 100644 index 9b31b913fe..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/FlowStatistics.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statistics.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.reader.FlowOnNode; - -@XmlRootElement(name = "nodeFlowStatistics") -@XmlAccessorType(XmlAccessType.NONE) -public class FlowStatistics { - @XmlElement - private Node node; - @XmlElement - private List flowStatistic; - - // To satisfy JAXB - @SuppressWarnings("unused") - private FlowStatistics() { - } - - public FlowStatistics(Node node, List flowStat) { - super(); - this.node = node; - this.flowStatistic = flowStat; - } - - public Node getNode() { - return node; - } - - public void setNode(Node node) { - this.node = node; - } - - public List getFlowStats() { - return flowStatistic; - } - - public void setFlowStats(List flowStats) { - this.flowStatistic = flowStats; - } -} diff --git a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/PortStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/PortStatistics.java deleted file mode 100644 index e519472d40..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/PortStatistics.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statistics.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; - -@XmlRootElement(name = "nodePortStatistics") -@XmlAccessorType(XmlAccessType.NONE) -public class PortStatistics { - @XmlElement - private Node node; - @XmlElement - private List portStatistic; - - // To satisfy JAXB - @SuppressWarnings("unused") - private PortStatistics() { - } - - public PortStatistics(Node node, List portStats) { - super(); - this.node = node; - this.portStatistic = portStats; - } - - public Node getNode() { - return node; - } - - public void setNode(Node node) { - this.node = node; - } - - public List getPortStats() { - return portStatistic; - } - - public void setFlowStats(List portStats) { - this.portStatistic = portStats; - } - -} diff --git a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthbound.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthbound.java deleted file mode 100644 index ad9d1269e5..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthbound.java +++ /dev/null @@ -1,1171 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statistics.northbound; - -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.ext.ContextResolver; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException; -import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.query.QueryContext; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.statisticsmanager.IStatisticsManager; -import org.opendaylight.controller.switchmanager.ISwitchManager; - -/** - * Northbound APIs that returns various Statistics exposed by the Southbound - * protocol plugins such as Openflow. - * - *
- *
- * Authentication scheme : HTTP Basic
- * Authentication realm : opendaylight
- * Transport : HTTP and HTTPS
- *
- * HTTPS Authentication is disabled by default. - * - */ -@Path("/") -public class StatisticsNorthbound { - - private String username; - private QueryContext queryContext; - - @Context - public void setQueryContext(ContextResolver queryCtxResolver) { - if (queryCtxResolver != null) { - queryContext = queryCtxResolver.getContext(QueryContext.class); - } - } - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - - protected String getUserName() { - return username; - } - - private IStatisticsManager getStatisticsService(String containerName) { - IContainerManager containerManager = (IContainerManager) ServiceHelper - .getGlobalInstance(IContainerManager.class, this); - if (containerManager == null) { - throw new ServiceUnavailableException("Container " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - boolean found = false; - List containerNames = containerManager.getContainerNames(); - for (String cName : containerNames) { - if (cName.trim().equalsIgnoreCase(containerName.trim())) { - found = true; - } - } - - if (found == false) { - throw new ResourceNotFoundException(containerName + " " - + RestMessages.NOCONTAINER.toString()); - } - - IStatisticsManager statsManager = (IStatisticsManager) ServiceHelper - .getInstance(IStatisticsManager.class, containerName, this); - - if (statsManager == null) { - throw new ServiceUnavailableException("Statistics " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - return statsManager; - } - - /** - * Returns a list of all Flow Statistics from all the Nodes. - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * @return List of FlowStatistics from all the Nodes - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/statistics/default/flow
-     *
-     * Response body in JSON:
-     * {
-     *     "flowStatistics": [
-     *         {
-     *             "node": {
-     *                 "id":"00:00:00:00:00:00:00:02",
-     *                 "type":"OF"
-     *             },
-     *             "flowStatistic": [
-     *                 {
-     *                     "flow": {
-     *                         "match": {
-     *                             "matchField": [
-     *                                 {
-     *                                     "type": "DL_TYPE",
-     *                                     "value": "2048"
-     *                                 },
-     *                                 {
-     *                                     "mask": "255.255.255.255",
-     *                                     "type": "NW_DST",
-     *                                     "value": "1.1.1.1"
-     *                                 }
-     *                             ]
-     *                         },
-     *                         "actions": {
-     *                             "@type": "output",
-     *                             "port": {
-     *                                 "node":{
-     *                                     "id":"00:00:00:00:00:00:00:02",
-     *                                     "type":"OF"
-     *                                 },
-     *                                 "id":"3",
-     *                                 "type":"OF"
-     *                             }
-     *                         },
-     *                         "priority": "1",
-     *                         "idleTimeout": "0",
-     *                         "hardTimeout": "0",
-     *                         "id": "0"
-     *                     },
-     *                     "tableId": "0",
-     *                     "durationSeconds": "1828",
-     *                     "durationNanoseconds": "397000000",
-     *                     "packetCount": "0",
-     *                     "byteCount": "0"
-     *                 }
-     *             ]
-     *         },
-     *         {   flow statistics of another node
-     *             ............
-     *             ................
-     *             ......................
-     *         }
-     *
-     *     ]
-     * }
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <list>
-     *     <flowStatistics>
-     *         <node>
-     *             <id>00:00:00:00:00:00:00:02</id>
-     *             <type>OF</type>
-     *         </node>
-     *         <flowStatistic>
-     *             <flow>
-     *                 <match>
-     *                     <matchField>
-     *                         <type>DL_TYPE</type>
-     *                         <value>2048</value>
-     *                     </matchField>
-     *                     <matchField>
-     *                         <mask>255.255.255.255</mask>
-     *                         <type>NW_DST</type>
-     *                         <value>1.1.1.2</value>
-     *                     </matchField>
-     *                 </match>
-     *                 <actions
-     *                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="output">
-     *                     <port>
-     *                         <node>
-     *                             <id>00:00:00:00:00:00:00:02</id>
-     *                             <type>OF</type>
-     *                         </node>
-     *                         <id>3</id>
-     *                         <type>OF</type>
-     *                     </port>
-     *                 </actions>
-     *                 <priority>1</priority>
-     *                 <idleTimeout>0</idleTimeout>
-     *                 <hardTimeout>0</hardTimeout>
-     *                 <id>0</id>
-     *             </flow>
-     *             <tableId>0</tableId>
-     *             <durationSeconds>337</durationSeconds>
-     *             <durationNanoseconds>149000000</durationNanoseconds>
-     *             <packetCount>0</packetCount>
-     *             <byteCount>0</byteCount>
-     *         </flowStatistic>
-     *     </flowStatistics>
-     *     <flowStatistics>
-     *          flow statistics for another node
-     *          ..........
-     *          ................
-     *          .....................
-     *     </flowStatistics>
-     * </list>
-     * 
- */ - - @Path("/{containerName}/flow") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(AllFlowStatistics.class) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public AllFlowStatistics getFlowStatistics( - @PathParam("containerName") String containerName, - @QueryParam("_q") String queryString) { - if (!NorthboundUtils.isAuthorized( - getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException( - "User is not authorized to perform this operation on container " - + containerName); - } - IStatisticsManager statisticsManager = getStatisticsService(containerName); - if (statisticsManager == null) { - throw new ServiceUnavailableException("Statistics " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, containerName, this); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch manager " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - List statistics = new ArrayList(); - for (Node node : switchManager.getNodes()) { - List flowStats = new ArrayList(); - - List flows = statisticsManager.getFlows(node); - for (FlowOnNode flowOnSwitch : flows) { - flowStats.add(flowOnSwitch); - } - FlowStatistics stat = new FlowStatistics(node, flowStats); - statistics.add(stat); - } - AllFlowStatistics result = new AllFlowStatistics(statistics); - if (queryString != null) { - queryContext.createQuery(queryString, AllFlowStatistics.class) - .filter(result, FlowStatistics.class); - } - return result; - } - - /** - * Returns a list of Flow Statistics for a given Node. - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * @param nodeType - * Node Type as specifid in {@link org.opendaylight.controller.sal.core.Node} class - * @param nodeId - * Node Identifier - * @return List of Flow Statistics for a given Node. * - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/statistics/default/flow/node/OF/00:00:00:00:00:00:00:01
-     *
-     * Response body in JSON:
-     * {
-     *     "node": {
-     *         "id":"00:00:00:00:00:00:00:01",
-     *         "type":"OF"
-     *     },
-     *     "flowStatistic": [
-     *         {
-     *             "flow": {
-     *                 "match": {
-     *                     "matchField": [
-     *                         {
-     *                             "type": "DL_TYPE",
-     *                             "value": "2048"
-     *                         },
-     *                         {
-     *                             "mask": "255.255.255.255",
-     *                             "type": "NW_DST",
-     *                             "value": "1.1.1.2"
-     *                         }
-     *                     ]
-     *                 },
-     *                 "actions": [
-     *                     {
-     *                         "@type": "setDlDst",
-     *                         "address": "52d28b0f76ec"
-     *                     },
-     *                     {
-     *                         "@type": "output",
-     *                         "port":{
-     *                             "node":{
-     *                                 "id":"00:00:00:00:00:00:00:01",
-     *                                 "type":"OF"
-     *                              },
-     *                              "id":"5",
-     *                              "type":"OF"
-     *                         }
-     *                     }
-     *                 ],
-     *                 "priority": "1",
-     *                 "idleTimeout": "0",
-     *                 "hardTimeout": "0",
-     *                 "id": "0"
-     *             },
-     *             "tableId": "0",
-     *             "durationSeconds": "2089",
-     *             "durationNanoseconds": "538000000",
-     *             "packetCount": "0",
-     *             "byteCount": "0"
-     *         }
-     *     ]
-     * }
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     *     <nodeFlowStatistics>
-     *         <node>
-     *             <id>00:00:00:00:00:00:00:02</id>
-     *             <type>OF</type>
-     *         </node>
-     *         <flowStatistic>
-     *             <flow>
-     *                 <match>
-     *                     <matchField>
-     *                         <type>DL_TYPE</type>
-     *                         <value>2048</value>
-     *                     </matchField>
-     *                     <matchField>
-     *                         <mask>255.255.255.255</mask>
-     *                         <type>NW_DST</type>
-     *                         <value>1.1.1.2</value>
-     *                     </matchField>
-     *                 </match>
-     *                 <actions
-     *                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="output">
-     *                     <port>
-     *                         <node>
-     *                             <id>00:00:00:00:00:00:00:02</id>
-     *                             <type>OF</type>
-     *                         </node>
-     *                         <id>3</id>
-     *                         <type>OF</type>
-     *                     </port>
-     *                 </actions>
-     *                 <priority>1</priority>
-     *                 <idleTimeout>0</idleTimeout>
-     *                 <hardTimeout>0</hardTimeout>
-     *                 <id>0</id>
-     *             </flow>
-     *             <tableId>0</tableId>
-     *             <durationSeconds>337</durationSeconds>
-     *             <durationNanoseconds>149000000</durationNanoseconds>
-     *             <packetCount>0</packetCount>
-     *             <byteCount>0</byteCount>
-     *         </flowStatistic>
-     *         <flowStatistic>
-     *             <flow>
-     *                 <match>
-     *                     <matchField>
-     *                         <type>DL_TYPE</type>
-     *                         <value>2048</value>
-     *                     </matchField>
-     *                     <matchField>
-     *                         <mask>255.255.255.255</mask>
-     *                         <type>NW_DST</type>
-     *                         <value>1.1.1.1</value>
-     *                     </matchField>
-     *                 </match>
-     *                 <actions
-     *                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="output">
-     *                     <port>
-     *                         <node>
-     *                             <id>00:00:00:00:00:00:00:02</id>
-     *                             <type>OF</type>
-     *                         </node>
-     *                         <id>3</id>
-     *                         <type>OF</type>
-     *                     </port>
-     *                 </actions>
-     *                 <priority>1</priority>
-     *                 <idleTimeout>0</idleTimeout>
-     *                 <hardTimeout>0</hardTimeout>
-     *                 <id>0</id>
-     *             </flow>
-     *             <tableId>0</tableId>
-     *             <durationSeconds>337</durationSeconds>
-     *             <durationNanoseconds>208000000</durationNanoseconds>
-     *             <packetCount>0</packetCount>
-     *             <byteCount>0</byteCount>
-     *         </flowStatistic>
-     *     </nodeFlowStatistics>
-     * 
- */ - @Path("/{containerName}/flow/node/{nodeType}/{nodeId}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(FlowStatistics.class) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public FlowStatistics getFlowStatistics( - @PathParam("containerName") String containerName, - @PathParam("nodeType") String nodeType, - @PathParam("nodeId") String nodeId) { - if (!NorthboundUtils.isAuthorized( - getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException( - "User is not authorized to perform this operation on container " - + containerName); - } - handleDefaultDisabled(containerName); - - IStatisticsManager statisticsManager = getStatisticsService(containerName); - if (statisticsManager == null) { - throw new ServiceUnavailableException("Statistics " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, containerName, this); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch manager " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - Node node = handleNodeAvailability(containerName, nodeType, nodeId); - return new FlowStatistics(node, statisticsManager.getFlows(node)); - } - - /** - * Returns a list of all the Port Statistics across all the NodeConnectors - * on all the Nodes. - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * @return List of all the Port Statistics across all the NodeConnectors on - * all the Nodes. - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/statistics/default/port
-     *
-     * Response body in JSON:
-     * {
-     *     "portStatistics": [
-     *         {
-     *             "node": {
-     *                  "id":"00:00:00:00:00:00:00:02",
-     *                  "type":"OF"
-     *             },
-     *             "portStatistic": [
-     *                 {
-     *                     "nodeConnector":{
-     *                          "node":{
-     *                                 "id":"00:00:00:00:00:00:00:02",
-     *                                 "type":"OF"
-     *                           },
-     *                           "id":"3",
-     *                           "type":"OF"
-     *                     },
-     *                     "receivePackets": "182",
-     *                     "transmitPackets": "173",
-     *                     "receiveBytes": "12740",
-     *                     "transmitBytes": "12110",
-     *                     "receiveDrops": "0",
-     *                     "transmitDrops": "0",
-     *                     "receiveErrors": "0",
-     *                     "transmitErrors": "0",
-     *                     "receiveFrameError": "0",
-     *                     "receiveOverRunError": "0",
-     *                     "receiveCrcError": "0",
-     *                     "collisionCount": "0"
-     *                 },
-     *                 {
-     *                     "nodeConnector": {
-     *                          "node":{
-     *                                  "id":"00:00:00:00:00:00:00:02",
-     *                                  "type":"OF"
-     *                           },
-     *                           "id":"2",
-     *                           "type":"OF"
-     *                     },
-     *                     "receivePackets": "174",
-     *                     "transmitPackets": "181",
-     *                     "receiveBytes": "12180",
-     *                     "transmitBytes": "12670",
-     *                     "receiveDrops": "0",
-     *                     "transmitDrops": "0",
-     *                     "receiveErrors": "0",
-     *                     "transmitErrors": "0",
-     *                     "receiveFrameError": "0",
-     *                     "receiveOverRunError": "0",
-     *                     "receiveCrcError": "0",
-     *                     "collisionCount": "0"
-     *                 },
-     *
-     *             ]
-     *         },
-     *         {
-     *             "node": {
-     *                  "id":"00:00:00:00:00:00:00:03",
-     *                  "type":"OF"
-     *             },
-     *             "portStatistic": [
-     *                  ..................
-     *                  .......................
-     *                  ..........................
-     *             ]
-     *         }
-     *     ]
-     * }
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <list>
-     *     <portStatistics>
-     *          <node>
-     *             <id>00:00:00:00:00:00:00:02</id>
-     *             <type>OF</type>
-     *          </node>
-     *          <portStatistic>
-     *             <nodeConnector>
-     *                <node>
-     *                   <id>00:00:00:00:00:00:00:02</id>
-     *                   <type>OF</type>
-     *                </node>
-     *                <id>3</id>
-     *                <type>OF</type>
-     *             </nodeConnector>
-     *             <receivePackets>181</receivePackets>
-     *             <transmitPackets>172</transmitPackets>
-     *             <receiveBytes>12670</receiveBytes>
-     *             <transmitBytes>12040</transmitBytes>
-     *             <receiveDrops>0</receiveDrops>
-     *             <transmitDrops>0</transmitDrops>
-     *             <receiveErrors>0</receiveErrors>
-     *             <transmitErrors>0</transmitErrors>
-     *             <receiveFrameError>0</receiveFrameError>
-     *             <receiveOverRunError>0</receiveOverRunError>
-     *             <receiveCrcError>0</receiveCrcError>
-     *             <collisionCount>0</collisionCount>
-     *         </portStatistic>
-     *         <portStatistic>
-     *             <nodeConnector>
-     *                <node>
-     *                   <id>00:00:00:00:00:00:00:02</id>
-     *                   <type>OF</type>
-     *                </node>
-     *                <id>2</id>
-     *                <type>OF</type>
-     *             </nodeConnector>
-     *             <receivePackets>173</receivePackets>
-     *             <transmitPackets>180</transmitPackets>
-     *             <receiveBytes>12110</receiveBytes>
-     *             <transmitBytes>12600</transmitBytes>
-     *             <receiveDrops>0</receiveDrops>
-     *             <transmitDrops>0</transmitDrops>
-     *             <receiveErrors>0</receiveErrors>
-     *             <transmitErrors>0</transmitErrors>
-     *             <receiveFrameError>0</receiveFrameError>
-     *             <receiveOverRunError>0</receiveOverRunError>
-     *             <receiveCrcError>0</receiveCrcError>
-     *             <collisionCount>0</collisionCount>
-     *         </portStatistic>
-     *     </portStatistics>
-     * </list>
-     * 
- */ - - @Path("/{containerName}/port") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(AllPortStatistics.class) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public AllPortStatistics getPortStatistics( - @PathParam("containerName") String containerName, - @QueryParam("_q") String queryString) { - - if (!NorthboundUtils.isAuthorized( - getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException( - "User is not authorized to perform this operation on container " - + containerName); - } - IStatisticsManager statisticsManager = getStatisticsService(containerName); - if (statisticsManager == null) { - throw new ServiceUnavailableException("Statistics " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, containerName, this); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch manager " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - List statistics = new ArrayList(); - for (Node node : switchManager.getNodes()) { - List stat = statisticsManager - .getNodeConnectorStatistics(node); - PortStatistics portStat = new PortStatistics(node, stat); - statistics.add(portStat); - } - - AllPortStatistics result = new AllPortStatistics(statistics); - if (queryString != null) { - queryContext.createQuery(queryString, AllPortStatistics.class) - .filter(result, PortStatistics.class); - } - return result; - } - - /** - * Returns a list of all the Port Statistics across all the NodeConnectors - * in a given Node. - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * @param nodeType - * Node Type as specifid in {@link org.opendaylight.controller.sal.core.Node} class - * @param Node - * Identifier (e.g. MAC address) - * @return Returns a list of all the Port Statistics across all the - * NodeConnectors in a given Node. - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/statistics/default/port/node/OF/00:00:00:00:00:00:00:01
-     *
-     * Response body in JSON:
-     * {
-     *     "node": {
-     *         "id":"00:00:00:00:00:00:00:01",
-     *         "type":"OF"
-     *     },
-     *     "portStatistic": [
-     *         {
-     *             "nodeConnector": {
-     *                 "node":{
-     *                     "id":"00:00:00:00:00:00:00:01",
-     *                     "type":"OF"
-     *                 },
-     *                 "id":"3",
-     *                 "type":"OF"
-     *             },
-     *             "receivePackets": "171",
-     *             "transmitPackets": "2451",
-     *             "receiveBytes": "11970",
-     *             "transmitBytes": "235186",
-     *             "receiveDrops": "0",
-     *             "transmitDrops": "0",
-     *             "receiveErrors": "0",
-     *             "transmitErrors": "0",
-     *             "receiveFrameError": "0",
-     *             "receiveOverRunError": "0",
-     *             "receiveCrcError": "0",
-     *             "collisionCount": "0"
-     *         },
-     *         {
-     *             "nodeConnector": {
-     *                 "node":{
-     *                     "id":"00:00:00:00:00:00:00:01",
-     *                     "type":"OF"
-     *                 },
-     *                 "id":"2",
-     *                 "type":"OF"
-     *             },
-     *             "receivePackets": "179",
-     *             "transmitPackets": "2443",
-     *             "receiveBytes": "12530",
-     *             "transmitBytes": "234626",
-     *             "receiveDrops": "0",
-     *             "transmitDrops": "0",
-     *             "receiveErrors": "0",
-     *             "transmitErrors": "0",
-     *             "receiveFrameError": "0",
-     *             "receiveOverRunError": "0",
-     *             "receiveCrcError": "0",
-     *             "collisionCount": "0"
-     *         }
-     *     ]
-     * }
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <nodePortStatistics>
-     *     <node>
-     *         <id>00:00:00:00:00:00:00:01</id>
-     *         <type>OF</type>
-     *     </node>
-     *     <portStatistic>
-     *         <nodeConnector>
-     *             <node>
-     *                 <id>00:00:00:00:00:00:00:01</id>
-     *                 <type>OF</type>
-     *             </node>
-     *             <id>2</id>
-     *             <type>OF</type>
-     *         </nodeConnector>
-     *         <receivePackets>180</receivePackets>
-     *         <transmitPackets>2594</transmitPackets>
-     *         <receiveBytes>12600</receiveBytes>
-     *         <transmitBytes>249396</transmitBytes>
-     *         <receiveDrops>0</receiveDrops>
-     *         <transmitDrops>0</transmitDrops>
-     *         <receiveErrors>0</receiveErrors>
-     *         <transmitErrors>0</transmitErrors>
-     *         <receiveFrameError>0</receiveFrameError>
-     *         <receiveOverRunError>0</receiveOverRunError>
-     *         <receiveCrcError>0</receiveCrcError>
-     *         <collisionCount>0</collisionCount>
-     *     </portStatistic>
-     *     <portStatistic>
-     *         <nodeConnector>
-     *             <node>
-     *                 <id>00:00:00:00:00:00:00:01</id>
-     *                 <type>OF</type>
-     *             </node>
-     *             <id>5</id>
-     *             <type>OF</type>
-     *         </nodeConnector>
-     *         <receivePackets>2542</receivePackets>
-     *         <transmitPackets>2719</transmitPackets>
-     *         <receiveBytes>243012</receiveBytes>
-     *         <transmitBytes>255374</transmitBytes>
-     *         <receiveDrops>0</receiveDrops>
-     *         <transmitDrops>0</transmitDrops>
-     *         <receiveErrors>0</receiveErrors>
-     *         <transmitErrors>0</transmitErrors>
-     *         <receiveFrameError>0</receiveFrameError>
-     *         <receiveOverRunError>0</receiveOverRunError>
-     *         <receiveCrcError>0</receiveCrcError>
-     *         <collisionCount>0</collisionCount>
-     *     </portStatistic>
-     * </nodePortStatistics>
-     * 
- */ - @Path("/{containerName}/port/node/{nodeType}/{nodeId}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(PortStatistics.class) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public PortStatistics getPortStatistics( - @PathParam("containerName") String containerName, - @PathParam("nodeType") String nodeType, - @PathParam("nodeId") String nodeId) { - - if (!NorthboundUtils.isAuthorized( - getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException( - "User is not authorized to perform this operation on container " - + containerName); - } - handleDefaultDisabled(containerName); - - IStatisticsManager statisticsManager = getStatisticsService(containerName); - if (statisticsManager == null) { - throw new ServiceUnavailableException("Statistics " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, containerName, this); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch manager " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - Node node = handleNodeAvailability(containerName, nodeType, nodeId); - return new PortStatistics(node, - statisticsManager.getNodeConnectorStatistics(node)); - } - - /** - * Returns a list of all the Table Statistics on all Nodes. - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * - * @return Returns a list of all the Table Statistics in a given Node. - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/statistics/default/table
-     *
-     * Response body in JSON:
-     * {
-     *     "tableStatistics": [
-     *         {
-     *             "node": {
-     *                 "id":"00:00:00:00:00:00:00:02",
-     *                 "type":"OF"
-     *             },
-     *             "tableStatistic": [
-     *                 {
-     *                     "nodeTable": {
-     *                        "node":{
-     *                           "id":"00:00:00:00:00:00:00:02",
-     *                           "type":"OF"
-     *                         },
-     *                         "id":"0"
-     *                     },
-     *                     "activeCount": "11",
-     *                     "lookupCount": "816",
-     *                     "matchedCount": "220",
-     *                     "maximumEntries": "1000"
-     *                 },
-     *                 {
-     *                     ...another table
-     *                     .....
-     *                     ........
-     *                 }
-     *
-     *             ]
-     *         }
-     *     ]
-     * }
-     *
-     *  Response body in XML:
-     *  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     *  <list>
-     *  <tableStatistics>
-     *      <node>
-     *          <id>00:00:00:00:00:00:00:01</id>
-     *          <type>OF</type>
-     *      </node>
-     *      <tableStatistic>
-     *          <nodeTable>
-     *              <node>
-     *                  <id>00:00:00:00:00:00:00:01</id>
-     *                  <type>OF</type>
-     *              </node>
-     *              <id>0</id>
-     *          </nodeTable>
-     *          <activeCount>12</activeCount>
-     *          <lookupCount>10935</lookupCount>
-     *          <matchedCount>10084</matchedCount>
-     *          <maximumEntries>1000</maximumEntries>
-     *      </tableStatistic>
-     *      <tableStatistic>
-     *          <nodeTable>
-     *              <node>
-     *                  <id>00:00:00:00:00:00:00:01</id>
-     *                  <type>OF</type>
-     *              </node>
-     *              <id>1</id>
-     *          </nodeTable>
-     *          <activeCount>0</activeCount>
-     *          <lookupCount>0</lookupCount>
-     *          <matchedCount>0</matchedCount>
-     *          <maximumEntries>0</maximumEntries>
-     *      </tableStatistic>
-     *      <tableStatistic>
-     *          <nodeTable>
-     *              <node>
-     *                  <id>00:00:00:00:00:00:00:01</id>
-     *                  <type>OF</type>
-     *              </node>
-     *              <id>2</id>
-     *          </nodeTable>
-     *          <activeCount>0</activeCount>
-     *          <lookupCount>0</lookupCount>
-     *          <matchedCount>0</matchedCount>
-     *          <maximumEntries>0</maximumEntries>
-     *      </tableStatistic>
-     *  </tableStatistics>
-     *  <tableStatistics>
-     *  ...
-     *  ......
-     *  ........
-     *  </tableStatistics>
-     *  </list>
-     *
-     * 
- */ - @Path("/{containerName}/table") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(AllTableStatistics.class) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public AllTableStatistics getTableStatistics( - @PathParam("containerName") String containerName, - @QueryParam("_q") String queryString) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - handleDefaultDisabled(containerName); - - IStatisticsManager statisticsManager = getStatisticsService(containerName); - if (statisticsManager == null) { - throw new ServiceUnavailableException("Statistics manager" - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, containerName, this); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch manager " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - List statistics = new ArrayList(); - for (Node node : switchManager.getNodes()) { - List stat = statisticsManager - .getNodeTableStatistics(node); - TableStatistics tableStat = new TableStatistics(node, stat); - statistics.add(tableStat); - } - AllTableStatistics allstats = new AllTableStatistics(statistics); - if (queryString != null) { - queryContext.createQuery(queryString, AllTableStatistics.class) - .filter(allstats, TableStatistics.class); - } - return allstats; - } - - /** - * Returns a list of all the Table Statistics on a specific node. - * - * @param containerName - * Name of the Container. The Container name for the base - * controller is "default". - * @param nodeType - * Node Type as specified in {@link org.opendaylight.controller.sal.core.Node} class (e.g. OF for Openflow) - * @param Node - * Identifier (e.g. MAC address) - * @return Returns a list of all the Table Statistics in a given Node. - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/statistics/default/table/node/OF/00:00:00:00:00:00:00:01
-     *
-     * Response body in JSON:
-     * {
-     *     "node": {
-     *         "id":"00:00:00:00:00:00:00:01",
-     *         "type":"OF"
-     *     },
-     *     "tableStatistic": [
-     *         {
-     *             "nodeTable": {
-     *                 "node":{
-     *                     "id":"00:00:00:00:00:00:00:01",
-     *                     "type":"OF"
-     *                 },
-     *                 "id":"0"
-     *             },
-     *             "activeCount": "12",
-     *             "lookupCount": "11382",
-     *             "matchedCount": "10524",
-     *             "maximumEntries": "1000"
-     *         },
-     *         {
-     *             "nodeTable": {
-     *                 "node":{
-     *                     "id":"00:00:00:00:00:00:00:01",
-     *                     "type":"OF"
-     *                 },
-     *                 "id":"1"
-     *             },
-     *             "activeCount": "0",
-     *             "lookupCount": "0",
-     *             "matchedCount": "0",
-     *             "maximumEntries": "0"
-     *         }
-     *    ]
-     * }
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <nodeTableStatistics>
-     *     <node>
-     *          <id>00:00:00:00:00:00:00:01</id>
-     *          <type>OF</type>
-     *     </node>
-     *     <tableStatistic>
-     *         <nodeTable>
-     *             <node>
-     *                 <id>00:00:00:00:00:00:00:01</id>
-     *                 <type>OF</type>
-     *             </node>
-     *             <id>0</id>
-     *         </nodeTable>
-     *         <activeCount>12</activeCount>
-     *         <lookupCount>10935</lookupCount>
-     *         <matchedCount>10084</matchedCount>
-     *         <maximumEntries>1000</maximumEntries>
-     *     </tableStatistic>
-     *     <tableStatistic>
-     *         <nodeTable>
-     *             <node>
-     *                 <id>00:00:00:00:00:00:00:01</id>
-     *                 <type>OF</type>
-     *             </node>
-     *             <id>1</id>
-     *         </nodeTable>
-     *         <activeCount>0</activeCount>
-     *         <lookupCount>0</lookupCount>
-     *         <matchedCount>0</matchedCount>
-     *         <maximumEntries>0</maximumEntries>
-     *     </tableStatistic>
-     *     <tableStatistic>
-     *         <nodeTable>
-     *             <node>
-     *                 <id>00:00:00:00:00:00:00:01</id>
-     *                 <type>OF</type>
-     *             </node>
-     *             <id>2</id>
-     *         </nodeTable>
-     *         <activeCount>0</activeCount>
-     *         <lookupCount>0</lookupCount>
-     *         <matchedCount>0</matchedCount>
-     *         <maximumEntries>0</maximumEntries>
-     *     </tableStatistic>
-     * </nodeTableStatistics>
-     *
-     * 
- */ - @Path("/{containerName}/table/node/{nodeType}/{nodeId}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(TableStatistics.class) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public TableStatistics getTableStatistics( - @PathParam("containerName") String containerName, - @PathParam("nodeType") String nodeType, - @PathParam("nodeId") String nodeId) { - - if (!NorthboundUtils.isAuthorized( - getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException( - "User is not authorized to perform this operation on container " - + containerName); - } - handleDefaultDisabled(containerName); - - IStatisticsManager statisticsManager = getStatisticsService(containerName); - if (statisticsManager == null) { - throw new ServiceUnavailableException("Statistics " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, containerName, this); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch manager " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - Node node = handleNodeAvailability(containerName, nodeType, nodeId); - return new TableStatistics(node, - statisticsManager.getNodeTableStatistics(node)); - } - - private void handleDefaultDisabled(String containerName) { - IContainerManager containerManager = (IContainerManager) ServiceHelper - .getGlobalInstance(IContainerManager.class, this); - if (containerManager == null) { - throw new InternalServerErrorException( - RestMessages.INTERNALERROR.toString()); - } - if (containerName.equals(GlobalConstants.DEFAULT.toString()) - && containerManager.hasNonDefaultContainer()) { - throw new ResourceConflictException( - RestMessages.DEFAULTDISABLED.toString()); - } - } - - private Node handleNodeAvailability(String containerName, String nodeType, - String nodeId) { - - Node node = Node.fromString(nodeType, nodeId); - if (node == null) { - throw new ResourceNotFoundException(nodeId + " : " - + RestMessages.NONODE.toString()); - } - - ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance( - ISwitchManager.class, containerName, this); - - if (sm == null) { - throw new ServiceUnavailableException("Switch Manager " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if (!sm.getNodes().contains(node)) { - throw new ResourceNotFoundException(node.toString() + " : " - + RestMessages.NONODE.toString()); - } - return node; - } - -} diff --git a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/TableStatistics.java b/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/TableStatistics.java deleted file mode 100644 index 552e707dae..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/TableStatistics.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statistics.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; - -@XmlRootElement(name = "nodeTableStatistics") -@XmlAccessorType(XmlAccessType.NONE) -public class TableStatistics { - @XmlElement - private Node node; - @XmlElement - private List tableStatistic; - - // To satisfy JAXB - @SuppressWarnings("unused") - private TableStatistics() { - } - - public TableStatistics(Node node, List tableStats) { - super(); - this.node = node; - this.tableStatistic = tableStats; - } - - public Node getNode() { - return node; - } - - public void setNode(Node node) { - this.node = node; - } - - public List getTableStats() { - return tableStatistic; - } - - public void setTableStats(List tableStats) { - this.tableStatistic = tableStats; - } - -} diff --git a/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/northbound/statistics/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/statistics/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 3fa41fee2b..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - JAXRSStatistics - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSStatistics - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - \ No newline at end of file diff --git a/opendaylight/adsal/northbound/statistics/src/test/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthboundTest.java b/opendaylight/adsal/northbound/statistics/src/test/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthboundTest.java deleted file mode 100644 index d09ff04574..0000000000 --- a/opendaylight/adsal/northbound/statistics/src/test/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthboundTest.java +++ /dev/null @@ -1,99 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statistics.northbound; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; -import org.opendaylight.controller.sal.utils.NodeCreator; - -public class StatisticsNorthboundTest { - - @Test - public void testFlowStatistics() { - List fon = new ArrayList(); - Node node = NodeCreator.createOFNode(1L); - FlowStatistics fs = new FlowStatistics(node, fon); - Assert.assertTrue(fs.getNode().equals(node)); - Assert.assertTrue(fs.getFlowStats().equals(fon)); - - Node node2 = NodeCreator.createOFNode(2L); - fs.setNode(node2); - Assert.assertTrue(fs.getNode().equals(node2)); - fs.setNode(node2); - Assert.assertTrue(fs.getNode().equals(node2)); - fs.setFlowStats(null); - Assert.assertTrue(fs.getFlowStats() == null); - } - - @Test - public void testAllFlowStatistics() { - List fs = new ArrayList(); - AllFlowStatistics afs = new AllFlowStatistics(fs); - Assert.assertTrue(afs.getFlowStatistics().equals(fs)); - afs.setFlowStatistics(null); - Assert.assertTrue(afs.getFlowStatistics() == null); - } - - @Test - public void testPortStatistics() { - List ncs = new ArrayList(); - Node node = NodeCreator.createOFNode(1L); - PortStatistics ps = new PortStatistics(node, ncs); - - Assert.assertTrue(ps.getNode().equals(node)); - Assert.assertTrue(ps.getPortStats().equals(ncs)); - Node node2 = NodeCreator.createOFNode(2L); - ps.setNode(node2); - Assert.assertTrue(ps.getNode().equals(node2)); - ps.setFlowStats(null); - Assert.assertTrue(ps.getPortStats() == null); - } - - @Test - public void testAllPortStatistics() { - List ps = new ArrayList(); - AllPortStatistics aps = new AllPortStatistics(ps); - Assert.assertTrue(aps.getPortStatistics().equals(ps)); - aps.setPortStatistics(null); - Assert.assertTrue(aps.getPortStatistics() == null); - } - - @Test - public void testTableStatistics() { - List nts = new ArrayList(); - Node node = NodeCreator.createOFNode(1L); - TableStatistics ts = new TableStatistics(node, nts); - - Assert.assertTrue(ts.getNode().equals(node)); - Assert.assertTrue(ts.getTableStats().equals(nts)); - Node node2 = NodeCreator.createOFNode(2L); - ts.setNode(node2); - Assert.assertTrue(ts.getNode().equals(node2)); - ts.setTableStats(null); - Assert.assertTrue(ts.getTableStats() == null); - } - - @Test - public void testAllTableStatistics() { - List ts = new ArrayList(); - AllTableStatistics ats = new AllTableStatistics(ts); - Assert.assertTrue(ats.getTableStatistics().equals(ts)); - ats.setTableStatistics(null); - Assert.assertTrue(ats.getTableStatistics() == null); - } - -} diff --git a/opendaylight/adsal/northbound/subnets/enunciate.xml b/opendaylight/adsal/northbound/subnets/enunciate.xml deleted file mode 100644 index e75daf94ee..0000000000 --- a/opendaylight/adsal/northbound/subnets/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/subnets/pom.xml b/opendaylight/adsal/northbound/subnets/pom.xml deleted file mode 100644 index 5c3228b51e..0000000000 --- a/opendaylight/adsal/northbound/subnets/pom.xml +++ /dev/null @@ -1,116 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../adsal-enunciate-parent - - - subnets.northbound - 0.6.0-SNAPSHOT - bundle - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - junit - junit - test - - - - - - - org.codehaus.enunciate - maven-enunciate-plugin - - - org.opendaylight.controller - clustering.services - ${clustering.services.version} - - - org.opendaylight.controller - configuration - ${configuration.version} - - - org.opendaylight.controller - sal - ${sal.version} - - - org.opendaylight.controller - switchmanager - ${switchmanager.api.version} - - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.query, - org.opendaylight.controller.northbound.commons.utils, - com.sun.jersey.spi.container.servlet, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.usermanager, - javax.ws.rs, - javax.ws.rs.core, - javax.ws.rs.ext, - javax.xml.bind, - javax.xml.bind.annotation, - org.slf4j, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - - /controller/nb/v2/subnetservice - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetConfigs.java b/opendaylight/adsal/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetConfigs.java deleted file mode 100644 index 31dd76faa5..0000000000 --- a/opendaylight/adsal/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetConfigs.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.subnets.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.switchmanager.SubnetConfig; - -@XmlRootElement (name = "list") -@XmlAccessorType(XmlAccessType.NONE) - -public class SubnetConfigs { - @XmlElement - List subnetConfig; - //To satisfy JAXB - @SuppressWarnings("unused") - private SubnetConfigs() { - - } - - public SubnetConfigs(List subnetConfig) { - this.subnetConfig = subnetConfig; - } - - public List getSubnetConfig() { - return subnetConfig; - } - - public void setSubnetConfig(List subnetConfig) { - this.subnetConfig = subnetConfig; - } -} diff --git a/opendaylight/adsal/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthbound.java b/opendaylight/adsal/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthbound.java deleted file mode 100644 index b6274795df..0000000000 --- a/opendaylight/adsal/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthbound.java +++ /dev/null @@ -1,498 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.subnets.northbound; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.ContextResolver; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.BadRequestException; -import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.query.QueryContext; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.SubnetConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class provides REST APIs to manage subnets. - * - *
- *
- * Authentication scheme : HTTP Basic
- * Authentication realm : opendaylight
- * Transport : HTTP and HTTPS
- *
- * HTTPS Authentication is disabled by default. - * - */ - -@Path("/") -public class SubnetsNorthbound { - protected static final Logger logger = LoggerFactory.getLogger(SubnetsNorthbound.class); - - private String username; - private QueryContext queryContext; - - @Context - public void setQueryContext(ContextResolver queryCtxResolver) { - if (queryCtxResolver != null) { - queryContext = queryCtxResolver.getContext(QueryContext.class); - } - } - - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - - protected String getUserName() { - return username; - } - - private void handleContainerDoesNotExist(String containerName) { - IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance( - IContainerManager.class, this); - if (containerManager == null) { - throw new ServiceUnavailableException("Container " + RestMessages.NOCONTAINER.toString()); - } - - List containerNames = containerManager.getContainerNames(); - for (String cName : containerNames) { - if (cName.trim().equalsIgnoreCase(containerName.trim())) { - return; - } - } - - throw new ResourceNotFoundException(containerName + " " + RestMessages.NOCONTAINER.toString()); - } - - private void handleNameMismatch(String name, String nameinURL) { - if (name == null || nameinURL == null) { - throw new BadRequestException(RestMessages.INVALIDDATA.toString() + " : Name is null"); - } - - if (name.equals(nameinURL)) { - return; - } - throw new ResourceConflictException(RestMessages.INVALIDDATA.toString() - + " : Name in URL does not match the name in request body"); - } - - /** - * List all the subnets in a given container - * - * @param containerName - * container in which we want to query the subnets - * - * @return a List of SubnetConfig - * - *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/subnetservice/default/subnets
-     *
-     * Response body in XML:
-     * <list>
-     * <subnetConfig>
-     *    <name>marketingdepartment</name>
-     *    <subnet>30.31.54.254/24</subnet>
-     * </subnetConfig>
-     * <subnetConfig>
-     *    <name>salesdepartment</name>
-     *    <subnet>20.18.1.254/16</subnet>
-     *    <nodeConnectors>OF|11@OF|00:00:00:aa:bb:cc:dd:ee</nodeConnectors>
-     *    <nodeConnectors>OF|13@OF|00:00:00:aa:bb:cc:dd:ee</nodeConnectors>
-     * </subnetConfig>
-     * </list>
-     * Response body in JSON:
-     * {
-     *   "subnetConfig": [
-     *     {
-     *       "name": "marketingdepartment",
-     *       "subnet": "30.31.54.254/24",
-     *       "nodeConnectors": [
-     *           "OF|04@OF|00:00:00:00:00:00:00:04",
-     *           "OF|07@OF|00:00:00:00:00:00:00:07"
-     *       ]
-     *     },
-     *     {
-     *       "name":"salesdepartment",
-     *       "subnet":"20.18.1.254/16",
-     *       "nodeConnectors": [
-     *            "OF|11@OF|00:00:00:aa:bb:cc:dd:ee",
-     *            "OF|13@OF|00:00:00:aa:bb:cc:dd:ee"
-     *        ]
-     *      }
-     *   ]
-     * }
-     *
-     * 
- */ - @Path("/{containerName}/subnets") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName passed was not found"), - @ResponseCode(code = 503, condition = "Service unavailable"), - @ResponseCode(code = 400, condition = "Incorrect query syntex") }) - @TypeHint(SubnetConfigs.class) - public SubnetConfigs listSubnets(@PathParam("containerName") String containerName, - @QueryParam("_q") String queryString) { - - handleContainerDoesNotExist(containerName); - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - if (switchManager == null) { - throw new ServiceUnavailableException("SwitchManager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - List subnets = switchManager.getSubnetsConfigList(); - if (queryString != null) { - subnets = queryContext.createQuery(queryString, SubnetConfig.class) - .find(subnets); - - } - return new SubnetConfigs(subnets); - } - - /** - * List the configuration of a subnet in a given container - * - * @param containerName - * container in which we want to query the subnet - * @param subnetName - * of the subnet being queried - * - * @return SubnetConfig - * - *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/subnetservice/default/subnet/marketingdepartment
-     *
-     * Response body in XML:
-     * <subnetConfig>
-     *    <name>marketingdepartment</name>
-     *    <subnet>30.0.0.1/24</subnet>
-     *    <nodeConnectors>OF|1@OF|00:00:00:00:00:00:00:01</nodePorts>
-     *    <nodeConnectors>OF|3@OF|00:00:00:00:00:00:00:03</nodePorts>
-     * </subnetConfig>
-     *
-     * Response body in JSON:
-     * {
-     *  "name":"marketingdepartment",
-     *  "subnet":"30.0.0.1/24",
-     *  "nodeConnectors":[
-     *       "OF|1@OF|00:00:00:00:00:00:00:01",
-     *       "OF|3@OF|00:00:00:00:00:00:00:03"
-     *   ]
-     * }
-     * 
- */ - @Path("/{containerName}/subnet/{subnetName}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName or subnetName passed was not found"), - @ResponseCode(code = 503, condition = "Service unavailable") }) - @TypeHint(SubnetConfig.class) - public SubnetConfig listSubnet(@PathParam("containerName") String containerName, - @PathParam("subnetName") String subnetName) { - - handleContainerDoesNotExist(containerName); - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - if (switchManager == null) { - throw new ServiceUnavailableException("SwitchManager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - SubnetConfig res = switchManager.getSubnetConfig(subnetName); - if (res == null) { - throw new ResourceNotFoundException(RestMessages.NOSUBNET.toString()); - } - return res; - } - - /** - * Add a subnet into the specified container context, node connectors are - * optional - * - * @param containerName - * name of the container context in which the subnet needs to be - * added - * @param subnetName - * name of new subnet to be added - * @param subnetConfigData - * the {@link SubnetConfig} structure in request body - * - * @return Response as dictated by the HTTP Response Status code - * - *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/subnetservice/default/subnet/salesdepartment
-     *
-     * Request body in XML:
-     *  <subnetConfig>
-     *      <name>salesdepartment</name>
-     *      <subnet>172.173.174.254/24</subnet>
-     *      <nodeConnectors>OF|22@OF|00:00:11:22:33:44:55:66</nodeConnectors>
-     *      <nodeConnectors>OF|39@OF|00:00:ab:cd:33:44:55:66</nodeConnectors>
-     *  </subnetConfig>
-     *
-     * Request body in JSON:
-     * {
-     *  "name":"salesdepartment",
-     *  "subnet":"172.173.174.254/24",
-     *  "nodeConnectors":[
-     *       "OF|22@OF|00:00:11:22:33:44:55:66",
-     *       "OF|39@OF|00:00:ab:cd:33:44:55:66"
-     *       ]
-     * }
-     * 
- */ - - @Path("/{containerName}/subnet/{subnetName}") - @PUT - @StatusCodes({ @ResponseCode(code = 201, condition = "Subnet created successfully"), - @ResponseCode(code = 400, condition = "Invalid data passed"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 409, condition = "Subnet name in url conflicts with name in request body"), - @ResponseCode(code = 404, condition = "Container name passed was not found or subnet config is null"), - @ResponseCode(code = 500, condition = "Internal Server Error: Addition of subnet failed"), - @ResponseCode(code = 503, condition = "Service unavailable") }) - public Response addSubnet(@PathParam("containerName") String containerName, - @PathParam("subnetName") String subnetName, @TypeHint(SubnetConfig.class) SubnetConfig subnetConfigData) { - - handleContainerDoesNotExist(containerName); - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - SubnetConfig cfgObject = subnetConfigData; - handleNameMismatch(cfgObject.getName(), subnetName); - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - if (switchManager == null) { - throw new ServiceUnavailableException("SwitchManager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - Status status = switchManager.addSubnet(cfgObject); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Subnet Gateway", username, "added", subnetName, containerName); - if (subnetConfigData.getNodeConnectors() != null) { - for (NodeConnector port : subnetConfigData.getNodeConnectors()) { - NorthboundUtils.auditlog("Port", getUserName(), "added", - NorthboundUtils.getPortName(port, switchManager) + " to Subnet Gateway " + subnetName, - containerName); - } - } - return Response.status(Response.Status.CREATED).build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Delete a subnet from the specified container context - * - * @param containerName - * name of the container in which subnet needs to be removed - * @param subnetName - * name of new subnet to be deleted - * @return Response as dictated by the HTTP Response Status code - * - *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/subnetservice/default/subnet/engdepartment
-     *
-     * 
- */ - @Path("/{containerName}/subnet/{subnetName}") - @DELETE - @StatusCodes({ @ResponseCode(code = 204, condition = "No Content"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName passed was not found"), - @ResponseCode(code = 500, condition = "Internal Server Error : Removal of subnet failed"), - @ResponseCode(code = 503, condition = "Service unavailable") }) - public Response removeSubnet(@PathParam("containerName") String containerName, - @PathParam("subnetName") String subnetName) { - - handleContainerDoesNotExist(containerName); - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - if (switchManager == null) { - throw new ServiceUnavailableException("SwitchManager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - Status status = switchManager.removeSubnet(subnetName); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Subnet Gateway", username, "removed", subnetName, containerName); - return Response.status(Response.Status.NO_CONTENT).build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Modify a subnet. Replace the existing subnet with the new specified one. - * For now only port list modification is allowed. If the respective subnet - * configuration does not exist this call is equivalent to a subnet - * creation. - * - * @param containerName - * Name of the Container context - * @param subnetName - * Name of the subnet to be modified - * @param subnetConfigData - * the {@link SubnetConfig} structure in request body parameter - * @return Response as dictated by the HTTP Response Status code - * - *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/subnetservice/default/subnet/salesdepartment
-     *
-     *  Request body in XML:
-     *  <subnetConfig>
-     *      <name>salesdepartment</name>
-     *      <subnet>172.173.174.254/24</subnet>
-     *      <nodeConnectors>OF|22@OF|00:00:11:22:33:44:55:66</nodeConnectors>
-     *      <nodeConnectors>OF|39@OF|00:00:ab:cd:33:44:55:66</nodeConnectors>
-     *  </subnetConfig>
-     *
-     * Request body in JSON:
-     * {
-     *  "name":"salesdepartment",
-     *  "subnet":"172.173.174.254/24",
-     *  "nodeConnectors":[
-     *      "OF|22@OF|00:00:11:22:33:44:55:66",
-     *      "OF|39@OF|00:00:ab:cd:33:44:55:66"
-     *  ]
-     * }
-     * 
- */ - @Path("/{containerName}/subnet/{subnetName}") - @POST - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ @ResponseCode(code = 200, condition = "Configuration replaced successfully"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 409, condition = "Subnet name in url conflicts with name in request body"), - @ResponseCode(code = 404, condition = "The containerName or subnetName is not found"), - @ResponseCode(code = 500, condition = "Internal server error: Modify subnet failed"), - @ResponseCode(code = 503, condition = "Service unavailable") }) - public Response modifySubnet(@Context UriInfo uriInfo, @PathParam("containerName") String containerName, - @PathParam("subnetName") String subnetName, @TypeHint(SubnetConfig.class) SubnetConfig subnetConfigData) { - - handleContainerDoesNotExist(containerName); - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - handleNameMismatch(subnetConfigData.getName(), subnetName); - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - if (switchManager == null) { - throw new ServiceUnavailableException("SwitchManager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - // Need to check this until Status does not return a CREATED status code - SubnetConfig existingConf = switchManager.getSubnetConfig(subnetName); - - Status status = switchManager.modifySubnet(subnetConfigData); - - if (status.isSuccess()) { - if (existingConf == null) { - NorthboundUtils.auditlog("Subnet Gateway", username, "added", subnetName, containerName); - if (subnetConfigData.getNodeConnectors() != null) { - for (NodeConnector port : subnetConfigData.getNodeConnectors()) { - NorthboundUtils.auditlog("Port", getUserName(), "added", - NorthboundUtils.getPortName(port, switchManager) + " to Subnet Gateway" + subnetName, - containerName); - } - } - return Response.created(uriInfo.getRequestUri()).build(); - } else { - Set existingNCList = existingConf.getNodeConnectors(); - - if (existingNCList == null) { - existingNCList = new HashSet(0); - } - if (subnetConfigData.getNodeConnectors() != null) { - for (NodeConnector port : subnetConfigData.getNodeConnectors()) { - if (!existingNCList.contains(port)) { - NorthboundUtils.auditlog("Port", getUserName(), "added", - NorthboundUtils.getPortName(port, switchManager) + " to Subnet Gateway " - + subnetName, containerName); - } - } - } - for (NodeConnector port : existingNCList) { - if (!subnetConfigData.getNodeConnectors().contains(port)) { - NorthboundUtils - .auditlog("Port", getUserName(), "removed", - NorthboundUtils.getPortName(port, switchManager) + " from Subnet Gateway " - + subnetName, containerName); - } - } - } - } - return NorthboundUtils.getResponse(status); - } -} diff --git a/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/northbound/subnets/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/northbound/subnets/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/subnets/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 7e0d465256..0000000000 --- a/opendaylight/adsal/northbound/subnets/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - JAXRSSubnets - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSSubnets - /* - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - diff --git a/opendaylight/adsal/northbound/subnets/src/test/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthboundTest.java b/opendaylight/adsal/northbound/subnets/src/test/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthboundTest.java deleted file mode 100644 index 833b5d4ce7..0000000000 --- a/opendaylight/adsal/northbound/subnets/src/test/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthboundTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.subnets.northbound; - -import java.util.ArrayList; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.switchmanager.SubnetConfig; - -public class SubnetsNorthboundTest { - - @Test - public void testSubnetConfigs() { - SubnetConfigs sc1 = new SubnetConfigs(null); - Assert.assertNull(sc1.getSubnetConfig()); - - ArrayList list = new ArrayList(); - SubnetConfig s1 = new SubnetConfig(); - list.add(s1); - sc1.setSubnetConfig(list); - Assert.assertTrue(sc1.getSubnetConfig().equals(list)); - - sc1.setSubnetConfig(null); - Assert.assertNull(sc1.getSubnetConfig()); - } - -} diff --git a/opendaylight/adsal/northbound/swagger-ui/pom.xml b/opendaylight/adsal/northbound/swagger-ui/pom.xml deleted file mode 100644 index e25a28c0f0..0000000000 --- a/opendaylight/adsal/northbound/swagger-ui/pom.xml +++ /dev/null @@ -1,219 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - swagger-ui - 0.2.0-SNAPSHOT - bundle - - - ${resource.dir}/apis - ${project.build.directory}/classes - - - - - com.google.code.gson - gson - - - equinoxSDK381 - javax.servlet - - - - org.opendaylight.controller - connectionmanager.northbound - - - org.opendaylight.controller - controllermanager.northbound - - - org.opendaylight.controller - flowprogrammer.northbound - - - org.opendaylight.controller - forwarding.staticrouting.northbound - - - org.opendaylight.controller - hosttracker.northbound - - - org.opendaylight.controller - networkconfig.bridgedomain.northbound - - - org.opendaylight.controller - statistics.northbound - - - org.opendaylight.controller - subnets.northbound - - - org.opendaylight.controller - switchmanager.northbound - - - org.opendaylight.controller - topology.northbound - - - org.opendaylight.controller - usermanager.northbound - - - org.slf4j - slf4j-api - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.slf4j, - javax.annotation, - javax.naming, - javax.servlet, - javax.servlet.annotation, - javax.servlet.http, - com.google.gson, - - apis=target/classes/apis, - index.html=target/classes/index.html, - apilist.json=target/classes/apilist.json, - css=target/classes/css, - lib=target/classes/lib, - swagger-ui.min.js=target/classes/swagger-ui.min.js, - swagger-ui.js=target/classes/swagger-ui.js, - images=target/classes/images, - WEB-INF/web.xml=target/classes/WEB-INF/web.xml - /swagger - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.7 - - - ant-contrib - ant-contrib - 1.0b3 - - - ant - ant - - - - - - - - run - - generate-sources - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - { - "swaggerVersion": "1.1", - "basePath": "http://localhost:8080/swagger/apis", - "apis": [ - - - - - - - - - - - - - - - - - - - { } - ] -} - - - - - - - - - - - - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/swagger-ui/src/main/java/org/opendaylight/controller/swaggerui/BasePathModifierServlet.java b/opendaylight/adsal/northbound/swagger-ui/src/main/java/org/opendaylight/controller/swaggerui/BasePathModifierServlet.java deleted file mode 100644 index 083a50c81e..0000000000 --- a/opendaylight/adsal/northbound/swagger-ui/src/main/java/org/opendaylight/controller/swaggerui/BasePathModifierServlet.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.opendaylight.controller.swaggerui; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -/** - * Servlet implementation class BasePathModifierServlet - */ -public class BasePathModifierServlet extends HttpServlet { - private static final long serialVersionUID = 1L; - private static final Logger logger = LoggerFactory - .getLogger(BasePathModifierServlet.class); - - private static final String API_BASE_PATH_SUFFIX = "/swagger/apis"; - private static final String BASE_PATH_KEY = "basePath"; - - /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse - * response) - */ - @Override - protected void doGet(HttpServletRequest request, - HttpServletResponse response) throws ServletException, IOException { - String resourcePath = request.getRequestURI().substring( - request.getContextPath().length()); - logger.debug("Locating resource : {}.", resourcePath); - JsonObject jsonObject = null; - try { - - InputStream stream = this.getServletContext().getResourceAsStream( - resourcePath); - if (stream == null) { - response.sendError(HttpServletResponse.SC_NOT_FOUND, - "API / API Listing not found"); - return; - } - BufferedReader streamReader = new BufferedReader( - new InputStreamReader(stream, "UTF-8")); - StringBuilder responseStrBuilder = new StringBuilder(); - - String inputStr; - while ((inputStr = streamReader.readLine()) != null) - responseStrBuilder.append(inputStr); - - JsonElement jelement = new JsonParser().parse(responseStrBuilder - .toString()); - jsonObject = jelement.getAsJsonObject(); - - String basePath = jsonObject.get(BASE_PATH_KEY).getAsString(); - - // construct base path - StringBuilder requestURL = new StringBuilder(); - - requestURL.append(request.isSecure() ? "https://" : "http://") - .append(request.getServerName()).append(":") - .append(request.getServerPort()); - if (!basePath.contains(requestURL)) { - String endPath = ""; - if (basePath.contains(API_BASE_PATH_SUFFIX)) { - endPath = basePath.substring(basePath - .indexOf(API_BASE_PATH_SUFFIX)); - } - basePath = requestURL + endPath; - logger.debug("Modified Base Path is {}", basePath); - jsonObject.addProperty(BASE_PATH_KEY, basePath); - } - } catch (Exception ex) { - logger.error("Error processing JSON data", ex); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - "Could not read API Listing or APIs"); - return; - } - - try { - response.setContentType("application/json"); - PrintWriter out = response.getWriter(); - out.print(jsonObject); - out.flush(); - } catch (Exception ex) { - logger.error("Error while writing response", ex); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - "Internal Error while writing resposne"); - } - } - -} diff --git a/opendaylight/adsal/northbound/swagger-ui/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/swagger-ui/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 6d0239019c..0000000000 --- a/opendaylight/adsal/northbound/swagger-ui/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - BasePathModifierServlet - org.opendaylight.controller.swaggerui.BasePathModifierServlet - - - - BasePathModifierServlet - /apis/* - - - - BasePathModifierServlet - /apilist.json - - - index.html - - diff --git a/opendaylight/adsal/northbound/swagger-ui/src/main/resources/css/custom.css b/opendaylight/adsal/northbound/swagger-ui/src/main/resources/css/custom.css deleted file mode 100644 index e39394375f..0000000000 --- a/opendaylight/adsal/northbound/swagger-ui/src/main/resources/css/custom.css +++ /dev/null @@ -1,12 +0,0 @@ -body #header a#logo { - font-size: 1.5em; - font-weight: bold; - text-decoration: none; - background: transparent url(../images/logo.png) no-repeat left center; - padding: 20px 0 20px 70px; - color: white; -} - -div.footer { - display: none; -} diff --git a/opendaylight/adsal/northbound/swagger-ui/src/main/resources/images/logo.png b/opendaylight/adsal/northbound/swagger-ui/src/main/resources/images/logo.png deleted file mode 100644 index d49fb86ed5..0000000000 Binary files a/opendaylight/adsal/northbound/swagger-ui/src/main/resources/images/logo.png and /dev/null differ diff --git a/opendaylight/adsal/northbound/swagger-ui/src/main/resources/index.html b/opendaylight/adsal/northbound/swagger-ui/src/main/resources/index.html deleted file mode 100644 index bb5126ce2b..0000000000 --- a/opendaylight/adsal/northbound/swagger-ui/src/main/resources/index.html +++ /dev/null @@ -1,77 +0,0 @@ - - - - Swagger UI - - - - - - - - - - - - - - - - - - - - - -
-   -
- -
- -
- - - - diff --git a/opendaylight/adsal/northbound/switchmanager/enunciate.xml b/opendaylight/adsal/northbound/switchmanager/enunciate.xml deleted file mode 100644 index 3db309d46f..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/switchmanager/pom.xml b/opendaylight/adsal/northbound/switchmanager/pom.xml deleted file mode 100644 index 4710fea1f5..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/pom.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../adsal-enunciate-parent - - switchmanager.northbound - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.usermanager, - org.apache.commons.lang3.tuple, - org.apache.commons.logging, - com.sun.jersey.spi.container.servlet, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.northbound.commons.query, - javax.ws.rs, - javax.ws.rs.ext, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.slf4j, - org.apache.catalina.filters, - com.fasterxml.jackson.annotation, - com.fasterxml.jackson.databind, - !org.codehaus.enunciate.jaxrs - /controller/nb/v2/switchmanager - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectorProperties.java b/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectorProperties.java deleted file mode 100644 index bb3fc0cc03..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectorProperties.java +++ /dev/null @@ -1,83 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.northbound; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * The class describes set of properties attached to a node connector - */ - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class NodeConnectorProperties { - @XmlElement - private NodeConnector nodeconnector; - - @XmlElement(name="property") - @XmlElementWrapper - @JsonIgnore - private Set properties; - - // JAXB required constructor - private NodeConnectorProperties() { - this.nodeconnector = null; - this.properties = null; - } - - public NodeConnectorProperties(NodeConnector nodeconnector, Set properties) { - this.nodeconnector = nodeconnector; - this.properties = properties; - } - - @JsonProperty(value="properties") - public Map getMapProperties() { - Map map = new HashMap(); - for (Property p : properties) { - map.put(p.getName(), p); - } - return map; - } - - public void setMapProperties(Map propertiesMap) { - this.properties = new HashSet(propertiesMap.values()); - } - - public Set getProperties() { - return properties; - } - - public void setProperties(Set properties) { - this.properties = properties; - } - - public NodeConnector getNodeConnector() { - return nodeconnector; - } - - public void setNodeConnector(NodeConnector nodeconnector) { - this.nodeconnector = nodeconnector; - } -} diff --git a/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectors.java b/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectors.java deleted file mode 100644 index 32e1002c94..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeConnectors.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name="list") -@XmlAccessorType(XmlAccessType.NONE) - -public class NodeConnectors { - @XmlElement - List nodeConnectorProperties; - //To satisfy JAXB - private NodeConnectors() { - - } - - public NodeConnectors(List nodeConnectorProperties) { - this.nodeConnectorProperties = nodeConnectorProperties; - } - - public List getNodeConnectorProperties() { - return nodeConnectorProperties; - } - - public void setNodeConnectorProperties(List nodeConnectorProperties) { - this.nodeConnectorProperties = nodeConnectorProperties; - } -} diff --git a/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeProperties.java b/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeProperties.java deleted file mode 100644 index 380d759ab7..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/NodeProperties.java +++ /dev/null @@ -1,83 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.northbound; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.Property; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * The class describes set of properties attached to a node - */ - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class NodeProperties { - @XmlElement - private Node node; - - @XmlElement(name="property") - @XmlElementWrapper - @JsonIgnore - private Set properties; - - // JAXB required constructor - private NodeProperties() { - this.node = null; - this.properties = null; - } - - public NodeProperties(Node node, Set properties) { - this.node = node; - this.properties = properties; - } - - @JsonProperty(value="properties") - public Map getMapProperties() { - Map map = new HashMap(); - for (Property p : properties) { - map.put(p.getName(), p); - } - return map; - } - - public void setMapProperties(Map propertiesMap) { - this.properties = new HashSet(propertiesMap.values()); - } - - public Set getProperties() { - return properties; - } - - public void setProperties(Set properties) { - this.properties = properties; - } - - public Node getNode() { - return node; - } - - public void setNode(Node node) { - this.node = node; - } -} diff --git a/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/Nodes.java b/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/Nodes.java deleted file mode 100644 index 061e51732e..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/Nodes.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name="list") -@XmlAccessorType(XmlAccessType.NONE) - -public class Nodes { - @XmlElement - List nodeProperties; - //To satisfy JAXB - private Nodes() { - - } - - public Nodes(List nodeProperties) { - this.nodeProperties = nodeProperties; - } - - public List getNodeProperties() { - return nodeProperties; - } - - public void setNodeProperties(List nodeProperties) { - this.nodeProperties = nodeProperties; - } -} diff --git a/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java b/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java deleted file mode 100644 index dab5d7d1b2..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java +++ /dev/null @@ -1,896 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.northbound; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; -import javax.ws.rs.ext.ContextResolver; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.query.QueryContext; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.SwitchConfig; - -/** - * The class provides Northbound REST APIs to access the nodes, node connectors - * and their properties. - * - */ - -@Path("/") -public class SwitchNorthbound { - - private String username; - private QueryContext queryContext; - - @Context - public void setQueryContext(ContextResolver queryCtxResolver) { - if (queryCtxResolver != null) { - queryContext = queryCtxResolver.getContext(QueryContext.class); - } - } - - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - - protected String getUserName() { - return username; - } - - private ISwitchManager getIfSwitchManagerService(String containerName) { - IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance( - IContainerManager.class, this); - if (containerManager == null) { - throw new ServiceUnavailableException("Container " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - boolean found = false; - List containerNames = containerManager.getContainerNames(); - for (String cName : containerNames) { - if (cName.trim().equalsIgnoreCase(containerName.trim())) { - found = true; - break; - } - } - - if (found == false) { - throw new ResourceNotFoundException(containerName + " " + RestMessages.NOCONTAINER.toString()); - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - - if (switchManager == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - return switchManager; - } - - /** - * - * Retrieve a list of all the nodes and their properties in the network - * - * @param containerName - * Name of the Container (Eg. 'default') - * @return A list of Pair each pair represents a - * {@link org.opendaylight.controller.sal.core.Node} and Set of - * {@link org.opendaylight.controller.sal.core.Property} attached to - * it. - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/switchmanager/default/nodes
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <list>
-     *        <nodeProperties>
-     *               <node>
-     *                      <id>00:00:00:00:00:00:00:02</id>
-     *                      <type>OF</type>
-     *               </node>
-     *               <properties>
-     *                      <tables>
-     *                             <value>-1</value>
-     *                      </tables>
-     *                      <description>
-     *                             <value>Switch2</value>
-     *                      </description>
-     *                      <actions>
-     *                             <value>4095</value>
-     *                      </actions>
-     *                      <macAddress>
-     *                             <value>00:00:00:00:00:02</value>
-     *                      </macAddress>
-     *                      <capabilities>
-     *                             <value>199</value>
-     *                      </capabilities>
-     *                      <timeStamp>
-     *                             <value>1377291227877</value>
-     *                             <name>connectedSince</name>
-     *                      </timeStamp>
-     *                      <buffers>
-     *                             <value>256</value>
-     *                      </buffers>
-     *               </properties>
-     *        </nodeProperties>
-     * </list>
-     *
-     * Response body in JSON:
-     * {
-     *    "nodeProperties":[
-     *       {
-     *          "node":{
-     *             "id":"00:00:00:00:00:00:00:02",
-     *             "type":"OF"
-     *          },
-     *          "properties":{
-     *             "tables":{
-     *                "value":"-1"
-     *             },
-     *             "description":{
-     *                "value":"None"
-     *             },
-     *             "actions":{
-     *                "value":"4095"
-     *             },
-     *             "macAddress":{
-     *                "value":"00:00:00:00:00:02"
-     *             },
-     *             "capabilities":{
-     *                "value":"199"
-     *             },
-     *             "timeStamp":{
-     *                "value":"1377291227877",
-     *                "name":"connectedSince"
-     *             },
-     *             "buffers":{
-     *                "value":"256"
-     *             }
-     *          }
-     *       }
-     *    ]
-     * }
-     *
-     * 
- */ - @Path("/{containerName}/nodes") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Nodes.class) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable"), - @ResponseCode(code = 400, condition = "Incorrect query syntex") }) - public Nodes getNodes(@PathParam("containerName") String containerName, @QueryParam("_q") String queryString) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - ISwitchManager switchManager = getIfSwitchManagerService(containerName); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - List res = new ArrayList(); - Set nodes = switchManager.getNodes(); - if (nodes == null) { - return new Nodes(res); - } - - for (Node node : nodes) { - Map propMap = switchManager.getNodeProps(node); - if (propMap == null) { - continue; - } - Set props = new HashSet(propMap.values()); - - NodeProperties nodeProps = new NodeProperties(node, props); - res.add(nodeProps); - } - Nodes result = new Nodes(res); - if (queryString != null) { - queryContext.createQuery(queryString, Nodes.class) - .filter(result, NodeProperties.class); - } - return result; - } - - /** - * Add a Description, Tier and Forwarding mode property to a node. This - * method returns a non-successful response if a node by that name already - * exists. - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier as specified by - * {@link org.opendaylight.controller.sal.core.Node} (Eg. - * '00:00:00:00:00:00:00:03') - * @param propertyName - * Name of the Property. Properties that can be configured are: - * description, forwarding(only for default container) and tier - * @param propertyValue - * Value of the Property. Description can be any string (Eg. - * 'Node1'), valid values for tier are non negative numbers, and - * valid values for forwarding are 0 for reactive and 1 for - * proactive forwarding. - * @return Response as dictated by the HTTP Response Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/switchmanager/default/node/OF/00:00:00:00:00:00:00:03/property/description/Switch3
-     *
-     * 
- */ - - @Path("/{containerName}/node/{nodeType}/{nodeId}/property/{propertyName}/{propertyValue}") - @PUT - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Response.class) - @StatusCodes({ - @ResponseCode(code = 201, condition = "Operation successful"), - @ResponseCode(code = 400, condition = "The nodeId or configuration is invalid"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The Container Name or node or configuration name is not found"), - @ResponseCode(code = 406, condition = "The property cannot be configured in non-default container"), - @ResponseCode(code = 409, condition = "Unable to update configuration due to cluster conflict or conflicting description property"), - @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") }) - public Response addNodeProperty(@Context UriInfo uriInfo, @PathParam("containerName") String containerName, - @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId, - @PathParam("propertyName") String propertyName, @PathParam("propertyValue") String propertyValue) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - ISwitchManager switchManager = getIfSwitchManagerService(containerName); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - handleNodeAvailability(containerName, nodeType, nodeId); - Node node = Node.fromString(nodeType, nodeId); - Property prop = switchManager.createProperty(propertyName, propertyValue); - if (prop == null) { - throw new ResourceNotFoundException("Property with name " + propertyName + " does not exist."); - } - SwitchConfig switchConfig = switchManager.getSwitchConfig(node.toString()); - Map nodeProperties = (switchConfig == null) ? new HashMap() - : new HashMap(switchConfig.getNodeProperties()); - nodeProperties.put(prop.getName(), prop); - SwitchConfig newSwitchConfig = new SwitchConfig(node.toString(), nodeProperties); - Status status = switchManager.updateNodeConfig(newSwitchConfig); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Property " + propertyName, username, "updated", - "of Node " + NorthboundUtils.getNodeDesc(node, switchManager), containerName); - - return Response.created(uriInfo.getRequestUri()).build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Delete a property of a node - * - * @param containerName - * Name of the Container (Eg. 'SliceRed') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier as specified by - * {@link org.opendaylight.controller.sal.core.Node} (Eg. - * '00:00:00:00:00:03:01:02') - * @param propertyName - * Name of the Property. Properties that can be deleted are - * description, forwarding(only in default container) and tier. - * @return Response as dictated by the HTTP Response Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/switchmanager/default/node/OF/00:00:00:00:00:00:00:03/property/forwarding
-     *
-     * 
- */ - - @Path("/{containerName}/node/{nodeType}/{nodeId}/property/{propertyName}") - @DELETE - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ @ResponseCode(code = 204, condition = "Property removed successfully"), - @ResponseCode(code = 400, condition = "The nodeId or configuration is invalid"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"), - @ResponseCode(code = 409, condition = "Unable to delete property due to cluster conflict"), - @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") }) - public Response deleteNodeProperty(@PathParam("containerName") String containerName, - @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId, - @PathParam("propertyName") String propertyName) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - ISwitchManager switchManager = getIfSwitchManagerService(containerName); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - handleNodeAvailability(containerName, nodeType, nodeId); - Node node = Node.fromString(nodeType, nodeId); - - SwitchConfig switchConfig = switchManager.getSwitchConfig(node.toString()); - Status status; - if (switchConfig == null) { - status = new Status(StatusCode.NOTFOUND, "Switch Configuration does not exist"); - } else { - Map nodeProperties = new HashMap(switchConfig.getNodeProperties()); - if (!nodeProperties.containsKey(propertyName.toLowerCase())) { - String msg = "Property " + propertyName + " does not exist or not configured for switch " + nodeId; - status = new Status(StatusCode.NOTFOUND, msg); - } else { - nodeProperties.remove(propertyName.toLowerCase()); - SwitchConfig newSwitchConfig = new SwitchConfig(node.toString(), nodeProperties); - status = switchManager.updateNodeConfig(newSwitchConfig); - if (status.isSuccess()) { - NorthboundUtils.auditlog("Property " + propertyName, username, "removed", "of Node " - + NorthboundUtils.getNodeDesc(node, switchManager), containerName); - return Response.noContent().build(); - } - } - } - return NorthboundUtils.getResponse(status); - } - - /** - * Get a property of a node - * - * @param containerName - * Name of the Container (Eg. 'SliceRed') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier as specified by - * {@link org.opendaylight.controller.sal.core.Node} (Eg. - * '00:00:00:00:00:03:01:02') - * @param propertyName - * Name of the Property. Properties that can be deleted are - * description, forwarding(only in default container) and tier. - * @return Property value of the property - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/switchmanager/default/node/OF/00:00:00:00:00:00:00:01/property/description
-     *
-     * Response body in XML
-     * <description>
-     *       <value>switch1</value>
-     * </description>
-     *
-     * Response body in JSON
-     * {
-     *       "value": "switch1"
-     * }
-     * 
- */ - - @Path("/{containerName}/node/{nodeType}/{nodeId}/property/{propertyName}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(String.class) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public Property getNodeProperty(@PathParam("containerName") String containerName, - @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId, - @PathParam("propertyName") String propertyName) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - ISwitchManager switchManager = getIfSwitchManagerService(containerName); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - handleNodeAvailability(containerName, nodeType, nodeId); - Node node = Node.fromString(nodeType, nodeId); - if (node == null) { - throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString()); - } - SwitchConfig switchConfig = switchManager.getSwitchConfig(node.toString()); - if (switchConfig == null) { - throw new ResourceNotFoundException(nodeId + " : " + "Config Not Found" ); - } else { - Map nodeProperties = new HashMap(switchConfig.getNodeProperties()); - if (!nodeProperties.containsKey(propertyName.toLowerCase())) { - String msg = "Property " + propertyName + " does not exist or not " - + "configured for switch " + nodeId; - throw new ResourceNotFoundException(msg); - } else { - return nodeProperties.get(propertyName.toLowerCase()); - } - } - } - - /** - * - * Retrieve a list of all the nodeconnectors and their properties in a given - * node - * - * @param containerName - * The container for which we want to retrieve the list (Eg. - * 'default') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier as specified by - * {@link org.opendaylight.controller.sal.core.Node} (Eg. - * '00:00:00:00:00:00:00:03') - * @return A List of Pair each pair represents a - * {@link org.opendaylight.controller.sal.core.NodeConnector} and - * its corresponding - * {@link org.opendaylight.controller.sal.core.Property} attached to - * it. - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/switchmanager/default/node/OF/00:00:00:00:00:00:00:01
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <list>
-     *        <nodeConnectorProperties>
-     *               <nodeconnector>
-     *                      <node>
-     *                             <id>00:00:00:00:00:00:00:01</id>
-     *                             <type>OF</type>
-     *                      </node>
-     *                      <id>2</id>
-     *                      <type>OF</type>
-     *               </nodeconnector>
-     *               <properties>
-     *                      <state>
-     *                             <value>1</value>
-     *                      </state>
-     *                      <config>
-     *                             <value>1</value>
-     *                      </config>
-     *                      <name>
-     *                             <value>L1_2-C2_1</value>
-     *                      </name>
-     *               </properties>
-     *        </nodeConnectorProperties>
-     * </list>
-     *
-     * Response body in JSON:
-     * {
-     *    "nodeConnectorProperties":[
-     *       {
-     *          "nodeconnector":{
-     *             "node":{
-     *                "id":"00:00:00:00:00:00:00:01",
-     *                "type":"OF"
-     *             },
-     *             "id":"2",
-     *             "type":"OF"
-     *          },
-     *          "properties":{
-     *             "state":{
-     *                "value":"1"
-     *             },
-     *             "config":{
-     *                "value":"1"
-     *             },
-     *             "name":{
-     *                "value":"L1_2-C2_1"
-     *             }
-     *          }
-     *       }
-     *    ]
-     * }
-     *
-     * 
- */ - @Path("/{containerName}/node/{nodeType}/{nodeId}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(NodeConnectors.class) - @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable"), - @ResponseCode(code = 400, condition = "Incorrect query syntex") }) - public NodeConnectors getNodeConnectors(@PathParam("containerName") String containerName, - @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId, - @QueryParam("_q") String queryString) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - ISwitchManager switchManager = getIfSwitchManagerService(containerName); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - handleNodeAvailability(containerName, nodeType, nodeId); - Node node = Node.fromString(nodeType, nodeId); - List res = new ArrayList(); - Set ncs = switchManager.getNodeConnectors(node); - if (ncs == null) { - return null; - } - - for (NodeConnector nc : ncs) { - Map propMap = switchManager.getNodeConnectorProps(nc); - if (propMap == null) { - continue; - } - Set props = new HashSet(propMap.values()); - NodeConnectorProperties ncProps = new NodeConnectorProperties(nc, props); - res.add(ncProps); - } - NodeConnectors result = new NodeConnectors(res); - if (queryString != null) { - queryContext.createQuery(queryString, NodeConnectors.class) - .filter(result, NodeConnectorProperties.class); - } - return result; - } - - /** - * Add node-connector property to a node connector. This method returns a - * non-successful response if a node connector by the given name already - * exists. - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier as specified by - * {@link org.opendaylight.controller.sal.core.Node} (Eg. - * '00:00:00:00:00:00:00:03') - * @param nodeConnectorType - * Type of the node connector being programmed (Eg. 'OF') - * @param nodeConnectorId - * NodeConnector Identifier as specified by - * {@link org.opendaylight.controller.sal.core.NodeConnector}. - * (Eg. '2'). If nodeConnecterId contains forward slash(/), - * replace forward slash with underscore(_) in the URL. (Eg. for - * Ethernet1/2, use Ethernet1_2) - * @param propertyName - * Name of the Property specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes Property that can be configured is bandwidth - * @param propertyValue - * Value of the Property specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * @return Response as dictated by the HTTP Response Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/switchmanager/default/nodeconnector/OF/00:00:00:00:00:00:00:01/OF/2/property/bandwidth/1
-     *
-     * 
- */ - - @Path("/{containerName}/nodeconnector/{nodeType}/{nodeId}/{nodeConnectorType}/{nodeConnectorId}/property/{propertyName}/{propertyValue}") - @PUT - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ @ResponseCode(code = 201, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"), - @ResponseCode(code = 409, condition = "Unable to add property due to cluster conflict"), - @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") }) - public Response addNodeConnectorProperty(@Context UriInfo uriInfo, - @PathParam("containerName") String containerName, @PathParam("nodeType") String nodeType, - @PathParam("nodeId") String nodeId, @PathParam("nodeConnectorType") String nodeConnectorType, - @PathParam("nodeConnectorId") String nodeConnectorId, @PathParam("propertyName") String propertyName, - @PathParam("propertyValue") String propertyValue) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - ISwitchManager switchManager = getIfSwitchManagerService(containerName); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - handleNodeAvailability(containerName, nodeType, nodeId); - Node node = Node.fromString(nodeType, nodeId); - - if (nodeConnectorId.contains("_")) { - nodeConnectorId = nodeConnectorId.replace("_", "/"); - } - - handleNodeConnectorAvailability(containerName, node, nodeConnectorType, nodeConnectorId); - NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node); - - Property prop = switchManager.createProperty(propertyName, propertyValue); - if (prop == null) { - throw new ResourceNotFoundException(RestMessages.INVALIDDATA.toString()); - } - - Status ret = switchManager.addNodeConnectorProp(nc, prop); - if (ret.isSuccess()) { - NorthboundUtils.auditlog("Property " + propertyName, username, "updated", "of Node Connector " - + NorthboundUtils.getPortName(nc, switchManager), containerName); - return Response.created(uriInfo.getRequestUri()).build(); - } - throw new InternalServerErrorException(ret.getDescription()); - } - - /** - * Delete a property of a node connector - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param nodeType - * Type of the node being programmed (Eg. 'OF') - * @param nodeId - * Node Identifier as specified by - * {@link org.opendaylight.controller.sal.core.Node} (Eg. - * '00:00:00:00:00:00:00:01') - * @param nodeConnectorType - * Type of the node connector being programmed (Eg. 'OF') - * @param nodeConnectorId - * NodeConnector Identifier as specified by - * {@link org.opendaylight.controller.sal.core.NodeConnector} - * (Eg. '1'). If nodeConnecterId contains forward slash(/), - * replace forward slash with underscore(_) in the URL. (Eg. for - * Ethernet1/2, use Ethernet1_2) - * @param propertyName - * Name of the Property specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes. Property that can be deleted is bandwidth - * @return Response as dictated by the HTTP Response Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/switchmanager/default/nodeconnector/OF/00:00:00:00:00:00:00:01/OF/2/property/bandwidth
-     *
-     * 
- */ - - @Path("/{containerName}/nodeconnector/{nodeType}/{nodeId}/{nodeConnectorType}/{nodeConnectorId}/property/{propertyName}") - @DELETE - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ @ResponseCode(code = 204, condition = "Property removed successfully"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The Container Name or nodeId or configuration name is not found"), - @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") }) - public Response deleteNodeConnectorProperty(@PathParam("containerName") String containerName, - @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId, - @PathParam("nodeConnectorType") String nodeConnectorType, - @PathParam("nodeConnectorId") String nodeConnectorId, @PathParam("propertyName") String propertyName) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - - ISwitchManager switchManager = getIfSwitchManagerService(containerName); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - handleNodeAvailability(containerName, nodeType, nodeId); - Node node = Node.fromString(nodeType, nodeId); - - if (nodeConnectorId.contains("_")) { - nodeConnectorId = nodeConnectorId.replace("_", "/"); - } - - handleNodeConnectorAvailability(containerName, node, nodeConnectorType, nodeConnectorId); - NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node); - Status ret = switchManager.removeNodeConnectorProp(nc, propertyName); - if (ret.isSuccess()) { - NorthboundUtils.auditlog("Property " + propertyName, username, "removed", "of Node Connector " - + NorthboundUtils.getPortName(nc, switchManager), containerName); - return Response.noContent().build(); - } - throw new ResourceNotFoundException(ret.getDescription()); - } - - /** - * Save the current switch configurations - * - * @param containerName - * Name of the Container (Eg. 'default') - * @return Response as dictated by the HTTP Response Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/switchmanager/default/save
-     *
-     * 
- */ - @Path("/{containerName}/save") - @POST - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 500, condition = "Failed to save switch configuration. Failure Reason included in HTTP Error response"), - @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") }) - public Response saveSwitchConfig(@PathParam("containerName") String containerName) { - - if (!isValidContainer(containerName)) { - throw new ResourceNotFoundException("Container " + containerName + " does not exist."); - } - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - ISwitchManager switchManager = getIfSwitchManagerService(containerName); - if (switchManager == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - Status ret = switchManager.saveSwitchConfig(); - if (ret.isSuccess()) { - return Response.ok().build(); - } - throw new InternalServerErrorException(ret.getDescription()); - } - - private Node handleNodeAvailability(String containerName, String nodeType, String nodeId) { - - Node node = Node.fromString(nodeType, nodeId); - if (node == null) { - throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString()); - } - - ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this); - - if (sm == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if (!sm.getNodes().contains(node)) { - throw new ResourceNotFoundException(node.toString() + " : " + RestMessages.NONODE.toString()); - } - return node; - } - - private void handleNodeConnectorAvailability(String containerName, Node node, String nodeConnectorType, - String nodeConnectorId) { - - NodeConnector nc = NodeConnector.fromStringNoNode(nodeConnectorType, nodeConnectorId, node); - if (nc == null) { - throw new ResourceNotFoundException(nc + " : " + RestMessages.NORESOURCE.toString()); - } - - ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this); - - if (sm == null) { - throw new ServiceUnavailableException("Switch Manager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if (!sm.getNodeConnectors(node).contains(nc)) { - throw new ResourceNotFoundException(nc.toString() + " : " + RestMessages.NORESOURCE.toString()); - } - } - - private boolean isValidContainer(String containerName) { - if (containerName.equals(GlobalConstants.DEFAULT.toString())) { - return true; - } - IContainerManager containerManager = (IContainerManager) ServiceHelper.getGlobalInstance( - IContainerManager.class, this); - if (containerManager == null) { - throw new InternalServerErrorException(RestMessages.INTERNALERROR.toString()); - } - if (containerManager.getContainerNames().contains(containerName)) { - return true; - } - return false; - } - -} diff --git a/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/northbound/switchmanager/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/switchmanager/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 2efd81c44e..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - JAXRSSwitchManager - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSSwitchManager - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - \ No newline at end of file diff --git a/opendaylight/adsal/northbound/switchmanager/src/test/java/org/opendaylight/controller/switchmanager/northbound/SwitchManagerNorthboundTest.java b/opendaylight/adsal/northbound/switchmanager/src/test/java/org/opendaylight/controller/switchmanager/northbound/SwitchManagerNorthboundTest.java deleted file mode 100644 index 89a5c96a29..0000000000 --- a/opendaylight/adsal/northbound/switchmanager/src/test/java/org/opendaylight/controller/switchmanager/northbound/SwitchManagerNorthboundTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.switchmanager.northbound; - - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -public class SwitchManagerNorthboundTest { - - @Test - public void testNodes() { - List nodeProperties = new ArrayList(); - Nodes nodes = new Nodes(nodeProperties); - Assert.assertTrue(nodes.getNodeProperties().equals(nodeProperties)); - nodes.setNodeProperties(null); - Assert.assertTrue(nodes.getNodeProperties() == null); - } - - @Test - public void testNodeProperties() { - Node node = NodeCreator.createOFNode(1L); - NodeProperties np= new NodeProperties(node, null); - Assert.assertTrue(np.getNode().equals(node)); - Assert.assertTrue(np.getProperties() == null); - - Node node2 = NodeCreator.createOFNode(2L); - np.setNode(node2); - Assert.assertTrue(np.getNode().equals(node2)); - - Set props = new HashSet(); - np.setProperties(props); - Assert.assertTrue(np.getProperties().equals(props)); - } - - @Test - public void testNodeConnectors() { - List nodeConnectorProperties = new ArrayList(); - NodeConnectors ncs = new NodeConnectors(nodeConnectorProperties); - Assert.assertTrue(ncs.getNodeConnectorProperties().equals(nodeConnectorProperties)); - ncs.setNodeConnectorProperties(null); - Assert.assertTrue(ncs.getNodeConnectorProperties() == null); - } - - @Test - public void testNodeConnectorProperties() { - Node node = NodeCreator.createOFNode(1L); - NodeConnector port = NodeConnectorCreator.createOFNodeConnector( - (short) 24, node); - - NodeConnectorProperties ncp= new NodeConnectorProperties(port, null); - Assert.assertTrue(ncp.getProperties() == null); - Assert.assertTrue(ncp.getNodeConnector().equals(port)); - - NodeConnector port2 = NodeConnectorCreator.createOFNodeConnector( - (short) 33, node); - ncp.setNodeConnector(port2); - Assert.assertTrue(ncp.getNodeConnector().equals(port2)); - - Set props = new HashSet(); - ncp.setProperties(props); - Assert.assertTrue(ncp.getProperties().equals(props)); - } - -} diff --git a/opendaylight/adsal/northbound/topology/enunciate.xml b/opendaylight/adsal/northbound/topology/enunciate.xml deleted file mode 100644 index b70ea74071..0000000000 --- a/opendaylight/adsal/northbound/topology/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/topology/pom.xml b/opendaylight/adsal/northbound/topology/pom.xml deleted file mode 100644 index 21f73d53fb..0000000000 --- a/opendaylight/adsal/northbound/topology/pom.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../adsal-enunciate-parent - - - topology.northbound - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - topologymanager - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.containermanager, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.utils, - org.opendaylight.controller.northbound.commons.query, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.packet.address, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.usermanager, - org.opendaylight.controller.topologymanager, - com.sun.jersey.spi.container.servlet, - com.fasterxml.jackson.annotation, - javax.ws.rs, - javax.ws.rs.ext, - javax.ws.rs.core, - javax.xml.bind, - javax.xml.bind.annotation, - org.slf4j, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - /controller/nb/v2/topology - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/EdgeProperties.java b/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/EdgeProperties.java deleted file mode 100644 index d43b9bc893..0000000000 --- a/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/EdgeProperties.java +++ /dev/null @@ -1,78 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topology.northbound; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Property; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class EdgeProperties { - @XmlElement - private Edge edge; - - @XmlElement(name="property") - @XmlElementWrapper - @JsonIgnore - private Set properties; - - // JAXB required constructor - private EdgeProperties() { - this.edge = null; - this.properties = null; - } - - public EdgeProperties(Edge e, Set properties) { - this.edge = e; - this.properties = properties; - } - - @JsonProperty(value="properties") - public Map getMapProperties() { - Map map = new HashMap(); - for (Property p : properties) { - map.put(p.getName(), p); - } - return map; - } - - public void setMapProperties(Map propertiesMap) { - this.properties = new HashSet(propertiesMap.values()); - } - - public Set getProperties() { - return properties; - } - public void setProperties(Set properties) { - this.properties = properties; - } - - public Edge getEdge() { - return edge; - } - - public void setEdge(Edge edge) { - this.edge = edge; - } -} diff --git a/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/Topology.java b/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/Topology.java deleted file mode 100644 index 15548d9428..0000000000 --- a/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/Topology.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topology.northbound; - -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) - -public class Topology { - @XmlElement - List edgeProperties; - //To satisfy JAXB - private Topology() { - - } - - public Topology(List edgeProperties) { - this.edgeProperties = edgeProperties; - } - - public List getEdgeProperties() { - return edgeProperties; - } - - public void setEdgeProperties(List edgeProperties) { - this.edgeProperties = edgeProperties; - } -} diff --git a/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyNorthboundJAXRS.java b/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyNorthboundJAXRS.java deleted file mode 100644 index 3773070504..0000000000 --- a/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyNorthboundJAXRS.java +++ /dev/null @@ -1,475 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topology.northbound; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.ext.ContextResolver; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.query.QueryContext; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig; - -/** - * Topology Northbound REST API - * - *
- *
- * Authentication scheme : HTTP Basic
- * Authentication realm : opendaylight
- * Transport : HTTP and HTTPS
- *
- * HTTPS Authentication is disabled by default. - */ - -@Path("/") -public class TopologyNorthboundJAXRS { - - private String username; - private QueryContext queryContext; - - @Context - public void setQueryContext(ContextResolver queryCtxResolver) { - if (queryCtxResolver != null) { - queryContext = queryCtxResolver.getContext(QueryContext.class); - } - } - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - - protected String getUserName() { - return username; - } - - /** - * - * Retrieve the Topology - * - * @param containerName - * The container for which we want to retrieve the topology (Eg. - * 'default') - * - * @return A List of EdgeProps each EdgeProp represent an Edge of the graph - * with the corresponding properties attached to it. - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/topology/default
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <topology>
-     *     <edgeProperties>
-     *         <edge>
-     *             <tailNodeConnector>
-     *                 <node>
-     *                     <id>00:00:00:00:00:00:00:02</id>
-     *                     <type>OF</type>
-     *                 </node>
-     *                 <id>2</id>
-     *                 <type>OF</type>
-     *             </tailNodeConnector>
-     *             <headNodeConnector>
-     *                 <node>
-     *                     <id>00:00:00:00:00:00:00:51</id>
-     *                     <type>OF</type>
-     *                 </node>
-     *                 <id>2</id>
-     *                 <type>OF</type>
-     *             </headNodeConnector>
-     *         </edge>
-     *         <properties>
-     *             <state>
-     *                 <value>1</value>
-     *             </state>
-     *             <config>
-     *                 <value>1</value>
-     *             </config>
-     *             <name>
-     *                 <value>C1_2-L2_2</value>
-     *             </name>
-     *             <timeStamp>
-     *                 <value>1377279422032</value>
-     *                 <name>creation</name>
-     *             </timeStamp>
-     *         </properties>
-     *     </edgeProperties>
-     *     <edgeProperties>
-     *         <edge>
-     *             <tailNodeConnector>
-     *                 <node>
-     *                     <id>00:00:00:00:00:00:00:51</id>
-     *                     <type>OF</type>
-     *                 </node>
-     *                 <id>2</id>
-     *                 <type>OF</type>
-     *             </tailNodeConnector>
-     *             <headNodeConnector>
-     *                 <node>
-     *                     <id>00:00:00:00:00:00:00:02</id>
-     *                     <type>OF</type>
-     *                 </node>
-     *                 <id>2</id>
-     *                 <type>OF</type>
-     *             </headNodeConnector>
-     *         </edge>
-     *         <properties>
-     *             <state>
-     *                 <value>1</value>
-     *             </state>
-     *             <name>
-     *                 <value>L2_2-C1_2</value>
-     *             </name>
-     *             <config>
-     *                 <value>1</value>
-     *             </config>
-     *             <timeStamp>
-     *                 <value>1377279423564</value>
-     *                 <name>creation</name>
-     *             </timeStamp>
-     *         </properties>
-     *     </edgeProperties>
-     * </topology>
-     *
-     * Response body in JSON:
-     * {
-     *    "edgeProperties":[
-     *       {
-     *          "edge":{
-     *             "tailNodeConnector":{
-     *                "node":{
-     *                   "id":"00:00:00:00:00:00:00:02",
-     *                   "type":"OF"
-     *                },
-     *                "id":"2",
-     *                "type":"OF"
-     *             },
-     *             "headNodeConnector":{
-     *                "node":{
-     *                   "id":"00:00:00:00:00:00:00:51",
-     *                   "type":"OF"
-     *                },
-     *                "id":"2",
-     *                "type":"OF"
-     *             }
-     *          },
-     *          "properties":{
-     *             "timeStamp": {
-     *                "value": 1379527162648,
-     *                "name": "creation",
-     *             },
-     *             "name": {
-     *                "value": "s2-eth3"
-     *             },
-     *             "state": {
-     *                "value": 1
-     *             },
-     *             "config": {
-     *                "value": 1
-     *             },
-     *             "bandwidth": {
-     *                "value": 10000000000
-     *             }
-     *          }
-     *       },
-     *       {
-     *          "edge":{
-     *             "tailNodeConnector":{
-     *                "node":{
-     *                   "id":"00:00:00:00:00:00:00:51",
-     *                   "type":"OF"
-     *                },
-     *                "id":"2",
-     *                "type":"OF"
-     *             },
-     *             "headNodeConnector":{
-     *                "node":{
-     *                   "id":"00:00:00:00:00:00:00:02",
-     *                   "type":"OF"
-     *                },
-     *                "id":"2",
-     *                "type":"OF"
-     *             }
-     *           },
-     *           "properties":{
-     *             "timeStamp": {
-     *                "value": 1379527162648,
-     *                "name": "creation",
-     *             }
-     *          }
-     *        }
-     *     ]
-     *  }
-     * 
- */ - @Path("/{containerName}") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Topology.class) - @StatusCodes({ @ResponseCode(code = 404, condition = "The Container Name was not found") }) - public Topology getTopology(@PathParam("containerName") String containerName, - @QueryParam("_q") String queryString) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(ITopologyManager.class, - containerName, this); - if (topologyManager == null) { - throw new ResourceNotFoundException(RestMessages.NOCONTAINER.toString()); - } - - Map> topo = topologyManager.getEdges(); - if (topo == null) { - return null; - } - List res = new ArrayList(); - for (Map.Entry> entry : topo.entrySet()) { - EdgeProperties el = new EdgeProperties(entry.getKey(), entry.getValue()); - res.add(el); - } - Topology result = new Topology(res); - - if (queryString != null) { - queryContext.createQuery(queryString, Topology.class) - .filter(result, EdgeProperties.class); - } - return result; - } - - /** - * Retrieve the user configured links - * - * @param containerName - * The container for which we want to retrieve the user links - * (Eg. 'default') - * - * @return A List of user configured links - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/topology/default/userLinks
-     *
-     * Response body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <list>
-     * <userLinks>
-     * <status>Success</status>
-     * <name>link1</name>
-     * <srcNodeConnector>OF|2@OF|00:00:00:00:00:00:00:02</srcNodeConnector>
-     * <dstNodeConnector>OF|2@OF|00:00:00:00:00:00:00:51</dstNodeConnector>
-     * </userLinks>
-     * </list>
-     *
-     * Response body in JSON:
-    * {
-     *   "userLinks": [
-     *    {
-     *      "status": "Success",
-     *      "name": "link1",
-     *      "srcNodeConnector": "OF|2@OF|00:00:00:00:00:00:00:02",
-     *      "dstNodeConnector": "OF|5@OF|00:00:00:00:00:00:00:05"
-     *    }
-     *  ]
-     * }
-     *
-     * 
- */ - @Path("/{containerName}/userLinks") - @GET - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(TopologyUserLinks.class) - @StatusCodes({ @ResponseCode(code = 404, condition = "The Container Name was not found") }) - public TopologyUserLinks getUserLinks(@PathParam("containerName") String containerName, - @QueryParam("_q") String queryString) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(ITopologyManager.class, - containerName, this); - if (topologyManager == null) { - throw new ResourceNotFoundException(RestMessages.NOCONTAINER.toString()); - } - - ConcurrentMap userLinks = topologyManager.getUserLinks(); - if ((userLinks == null) || (userLinks.values() == null)) { - return null; - } - TopologyUserLinks result = new TopologyUserLinks( - new ArrayList(userLinks.values())); - if (queryString != null) { - queryContext.createQuery(queryString, TopologyUserLinks.class) - .filter(result, TopologyUserLinkConfig.class); - } - return result; - } - - /** - * Add an User Link - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param name - * Name of the user link - * @param TopologyUserLinkConfig - * in JSON or XML format - * @return Response as dictated by the HTTP Response Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/topology/default/userLink/link1
-     *
-     * Request body in XML:
-     * <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-     * <topologyUserLinkConfig>
-     * <status>Success</status>
-     * <name>link1</name>
-     * <srcNodeConnector>OF|2@OF|00:00:00:00:00:00:00:02</srcNodeConnector>
-     * <dstNodeConnector>OF|2@OF|00:00:00:00:00:00:00:51</dstNodeConnector>
-     * </topologyUserLinkConfig>
-     *
-     * Request body in JSON:
-     * {
-     *    "status":"Success",
-     *    "name":"link1",
-     *    "srcNodeConnector":"OF|2@OF|00:00:00:00:00:00:00:02",
-     *    "dstNodeConnector":"OF|2@OF|00:00:00:00:00:00:00:51"
-     * }
-     *
-     * 
- */ - @Path("/{containerName}/userLink/{name}") - @PUT - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ - @ResponseCode(code = 201, condition = "User Link added successfully"), - @ResponseCode(code = 404, condition = "The Container Name was not found"), - @ResponseCode(code = 409, condition = "Failed to add User Link due to Conflicting Name"), - @ResponseCode(code = 500, condition = "Failed to add User Link. Failure Reason included in HTTP Error response"), - @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") }) - public Response addUserLink(@PathParam(value = "containerName") String containerName, - @PathParam(value = "name") String name, - @TypeHint(TopologyUserLinkConfig.class) TopologyUserLinkConfig userLinkConfig) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(ITopologyManager.class, - containerName, this); - if (topologyManager == null) { - throw new ResourceNotFoundException(RestMessages.NOCONTAINER.toString()); - } - - Status status = topologyManager.addUserLink(userLinkConfig); - if (status.isSuccess()) { - NorthboundUtils - .auditlog( - "User Link",username,"added", userLinkConfig.getName() + " from " + NorthboundUtils.getPortName( - NodeConnector.fromString(userLinkConfig.getSrcNodeConnector()), - containerName, this) + " to " - + NorthboundUtils.getPortName(NodeConnector.fromString - (userLinkConfig.getDstNodeConnector()),containerName, this), containerName); - return Response.status(Response.Status.CREATED).build(); - } - throw new InternalServerErrorException(status.getDescription()); - } - - /** - * Delete an User Link - * - * @param containerName - * Name of the Container (Eg. 'default') - * @param name - * Name of the Link Configuration (Eg. 'config1') - * @return Response as dictated by the HTTP Response Status code - * - *
-     *
-     * Example:
-     *
-     * Request URL:
-     * http://localhost:8080/controller/nb/v2/topology/default/userLink/config1
-     *
-     * 
- */ - @Path("/{containerName}/userLink/{name}") - @DELETE - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes({ @ResponseCode(code = 204, condition = "User link removed successfully"), - @ResponseCode(code = 404, condition = "The Container Name or Link Configuration Name was not found"), - @ResponseCode(code = 503, condition = "One or more of Controller services are unavailable") }) - public Response deleteUserLink(@PathParam("containerName") String containerName, @PathParam("name") String name) { - - if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.WRITE, this)) { - throw new UnauthorizedException("User is not authorized to perform this operation on container " - + containerName); - } - ITopologyManager topologyManager = (ITopologyManager) ServiceHelper.getInstance(ITopologyManager.class, - containerName, this); - if (topologyManager == null) { - throw new ResourceNotFoundException(RestMessages.NOCONTAINER.toString()); - } - - Status ret = topologyManager.deleteUserLink(name); - if (ret.isSuccess()) { - NorthboundUtils.auditlog("User Link", username, "removed", name, containerName); - return Response.noContent().build(); - } - return NorthboundUtils.getResponse(ret); - } -} diff --git a/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyUserLinks.java b/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyUserLinks.java deleted file mode 100644 index dee2e243d4..0000000000 --- a/opendaylight/adsal/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyUserLinks.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topology.northbound; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig; - -@XmlRootElement (name = "list") -@XmlAccessorType(XmlAccessType.NONE) - -public class TopologyUserLinks { - @XmlElement - List userLinks; - - //To satisfy JAXB - private TopologyUserLinks() { - - } - - public List getUserLinks() { - return userLinks; - } - - public void setUserLinks(List userLinks) { - this.userLinks = userLinks; - } - - public TopologyUserLinks(List userLinks) { - this.userLinks = new ArrayList(userLinks); - } -} diff --git a/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/northbound/topology/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/northbound/topology/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/topology/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index dac8cf622c..0000000000 --- a/opendaylight/adsal/northbound/topology/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - JAXRSTopology - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSTopology - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - diff --git a/opendaylight/adsal/northbound/topology/src/test/java/org/opendaylight/controller/topology/northbound/TopologyTest.java b/opendaylight/adsal/northbound/topology/src/test/java/org/opendaylight/controller/topology/northbound/TopologyTest.java deleted file mode 100644 index bcfa2a9ee9..0000000000 --- a/opendaylight/adsal/northbound/topology/src/test/java/org/opendaylight/controller/topology/northbound/TopologyTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.topology.northbound; - -import org.junit.Test; -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Latency; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -public class TopologyTest { - protected static final Logger logger = LoggerFactory - .getLogger(TopologyTest.class); - - @Test - public void edgePropertiesTopologyTest() { - - //Create 3 nodes and edges between them - Node n1 = NodeCreator.createOFNode((long)1); - Node n2 = NodeCreator.createOFNode((long)2); - Node n3 = NodeCreator.createOFNode((long)3); - - NodeConnector nc11 = NodeConnectorCreator.createOFNodeConnector((short) 1, n1); - NodeConnector nc12 = NodeConnectorCreator.createOFNodeConnector((short) 2, n1); - NodeConnector nc21 = NodeConnectorCreator.createOFNodeConnector((short) 1, n2); - NodeConnector nc22 = NodeConnectorCreator.createOFNodeConnector((short) 2, n2); - NodeConnector nc23 = NodeConnectorCreator.createOFNodeConnector((short) 2, n3); - NodeConnector nc32 = NodeConnectorCreator.createOFNodeConnector((short) 3, n2); - NodeConnector nc33 = NodeConnectorCreator.createOFNodeConnector((short) 3, n3); - - Edge e12 = null; - Edge e23 = null; - - try { - e12 = new Edge(nc12, nc21); - } catch (ConstructionException e) { - fail("Failed to construct edge " + e.getMessage()); - } - try { - e23 = new Edge(nc23, nc32); - } catch (ConstructionException e) { - fail("Failed to construct edge " + e.getMessage()); - } - - Set props = new HashSet(); - State state = new State(State.EDGE_UP); - Bandwidth bw = new Bandwidth(Bandwidth.BW100Gbps); - Latency l = new Latency(Latency.LATENCY100ns); - props.add(state); - props.add(bw); - props.add(l); - - //Check get methods for edge and properties - EdgeProperties edgeProp = new EdgeProperties(e12, props); - - Edge getEdge = edgeProp.getEdge(); - assertEquals(e12, getEdge); - assertEquals(nc12, getEdge.getTailNodeConnector()); - assertEquals(n1, getEdge.getTailNodeConnector().getNode()); - assertEquals((long)1, getEdge.getTailNodeConnector().getNode().getID()); - assertEquals(nc21, getEdge.getHeadNodeConnector()); - assertEquals(n2, getEdge.getHeadNodeConnector().getNode()); - assertEquals((long)2, getEdge.getHeadNodeConnector().getNode().getID()); - - Set getProp = edgeProp.getProperties(); - assertEquals(props, getProp); - assertEquals(props.size(), getProp.size()); - - //Use set methods - edgeProp.setEdge(e23); - getEdge = edgeProp.getEdge(); - assertEquals(e23, getEdge); - assertEquals(nc23, getEdge.getTailNodeConnector()); - assertEquals(nc32, getEdge.getHeadNodeConnector()); - - props.remove(state); - edgeProp.setProperties(props); - assertEquals(props, getProp); - assertEquals(props.size(), getProp.size()); - - - //Create and check topology - List edgePropList= new ArrayList(); - edgePropList.add(edgeProp); - - Topology t = new Topology(edgePropList); - - List getEdgePropList = t.getEdgeProperties(); - assertEquals(edgePropList, getEdgePropList); - assertEquals(1, getEdgePropList.size()); - - EdgeProperties edgeProp2 = new EdgeProperties(e23, props); - edgePropList.add(edgeProp2); - t.setEdgeProperties(edgePropList); - - getEdgePropList = t.getEdgeProperties(); - assertEquals(edgePropList, getEdgePropList); - assertEquals(2, getEdgePropList.size()); - - } - - -} diff --git a/opendaylight/adsal/northbound/usermanager/enunciate.xml b/opendaylight/adsal/northbound/usermanager/enunciate.xml deleted file mode 100644 index 0386c759b2..0000000000 --- a/opendaylight/adsal/northbound/usermanager/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/northbound/usermanager/pom.xml b/opendaylight/adsal/northbound/usermanager/pom.xml deleted file mode 100644 index b13b746148..0000000000 --- a/opendaylight/adsal/northbound/usermanager/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - enunciate-parent - 1.6.0-SNAPSHOT - ../../../commons/enunciate-parent - - - usermanager.northbound - 0.2.0-SNAPSHOT - bundle - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - usermanager - - - junit - junit - test - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - org.opendaylight.controller.northbound.commons.utils, - com.sun.jersey.spi.container.servlet, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.usermanager, - javax.ws.rs, - javax.ws.rs.core, - javax.xml.bind, - javax.xml.bind.annotation, - org.slf4j, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - - /controller/nb/v2/usermanager - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/northbound/usermanager/src/main/java/org/opendaylight/controller/usermanager/northbound/UserManagerNorthbound.java b/opendaylight/adsal/northbound/usermanager/src/main/java/org/opendaylight/controller/usermanager/northbound/UserManagerNorthbound.java deleted file mode 100644 index 3f384f4772..0000000000 --- a/opendaylight/adsal/northbound/usermanager/src/main/java/org/opendaylight/controller/usermanager/northbound/UserManagerNorthbound.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.usermanager.northbound; - -import java.net.URI; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.core.UriInfo; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.BadRequestException; -import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException; -import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; -import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; -import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.usermanager.IUserManager; -import org.opendaylight.controller.usermanager.UserConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class provides REST APIs to manage users. - * This API will only be availalbe via HTTPS. - *
- *
- * Authentication scheme : HTTP Basic
- * Authentication realm : opendaylight
- * Transport : HTTPS
- *
- * HTTPS Authentication is disabled by default so to - * use UserManager APIs turn on HTTPS on Web Server - */ - -@Path("/") -public class UserManagerNorthbound { - - protected static final Logger logger = LoggerFactory.getLogger(UserManagerNorthbound.class); - - private String username; - @Context - UriInfo uriInfo; - - @Context - public void setSecurityContext(SecurityContext context) { - if (context != null && context.getUserPrincipal() != null) { - username = context.getUserPrincipal().getName(); - } - } - - protected String getUserName() { - return username; - } - - private void handleNameMismatch(String name, String nameinURL) { - if (name == null || nameinURL == null) { - throw new BadRequestException(RestMessages.INVALIDDATA.toString() + " : Name is null"); - } - - if (name.equals(nameinURL)) { - return; - } - throw new ResourceConflictException(RestMessages.INVALIDDATA.toString() - + " : Name in URL does not match the name in request body"); - } - - /** - * Add a user - * - * @param userConfigData - * the {@link UserConfig} user config structure in request body - * - * @return Response as dictated by the HTTP Response Status code - * - *
-     * Example:
-     *
-     * Request URL:
-     * https://localhost/controller/nb/v2/usermanager/users
-     *
-     * Request body in XML:
-     *  <userConfig>
-     *      <user>testuser</user>
-     *      <roles>Network-Admin</roles>
-     *      <password>pass!23</password>
-     *  </userConfig>
-     *
-     * Request body in JSON:
-     * {
-     *  "user":"testuser",
-     *  "password":"pass!23",
-     *  "roles":[
-     *       "Network-Admin"
-     *       ]
-     * }
-     * 
- */ - - @Path("/users") - @POST - @StatusCodes({ @ResponseCode(code = 201, condition = "User created successfully"), - @ResponseCode(code = 400, condition = "Invalid data passed"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 409, condition = "User name in url conflicts with name in request body"), - @ResponseCode(code = 404, condition = "User config is null"), - @ResponseCode(code = 500, condition = "Internal Server Error: Addition of user failed"), - @ResponseCode(code = 503, condition = "Service unavailable") }) - @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - public Response addLocalUser(@TypeHint(UserConfig.class) UserConfig userConfigData) { - - if (!isAdminUser()) { - throw new UnauthorizedException("User is not authorized to perform user management operations "); - } - - // Reconstructing the object so password can be hashed in userConfig - UserConfig userCfgObject = new UserConfig(userConfigData.getUser(),userConfigData.getPassword(), - userConfigData.getRoles()); - - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - throw new ServiceUnavailableException("UserManager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - Status status = userManager.addLocalUser(userCfgObject); - if (status.isSuccess()) { - - NorthboundUtils.auditlog("User", username, "added", userCfgObject.getUser()); - URI uri = uriInfo.getAbsolutePathBuilder().path("/"+userCfgObject.getUser()).build(); - return Response.created(uri).build(); - } - return NorthboundUtils.getResponse(status); - } - - /** - * Delete a user - * - * @param userName - * name of user to be deleted - * @return Response as dictated by the HTTP Response Status code - * - *
-     * Example:
-     *
-     * Request URL:
-     * https://localhost/controller/nb/v2/usermanager/users/testuser
-     *
-     * 
- */ - @Path("/users/{userName}") - @DELETE - @StatusCodes({ @ResponseCode(code = 204, condition = "User Deleted Successfully"), - @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), - @ResponseCode(code = 404, condition = "The userName passed was not found"), - @ResponseCode(code = 500, condition = "Internal Server Error : Removal of user failed"), - @ResponseCode(code = 503, condition = "Service unavailable") }) - public Response removeLocalUser(@PathParam("userName") String userToBeRemoved) { - - if (!isAdminUser()) { - throw new UnauthorizedException("User is not authorized to perform user management operations "); - } - - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - throw new ServiceUnavailableException("UserManager " + RestMessages.SERVICEUNAVAILABLE.toString()); - } - Status status = userManager.removeLocalUser(userToBeRemoved); - if (status.isSuccess()) { - NorthboundUtils.auditlog("User", username, "removed", userToBeRemoved); - return Response.noContent().build(); - } - return NorthboundUtils.getResponse(status); - } - - private boolean isAdminUser(){ - // get UserManager's instance - IUserManager auth = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - // check if logged in user has privileges of NETWORK_ADMIN or SYSTEM_ADMIN, if so return true - return auth.getUserLevel(getUserName()).ordinal() <= UserLevel.NETWORKADMIN.ordinal(); - } - -} diff --git a/opendaylight/adsal/northbound/usermanager/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/northbound/usermanager/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 9a191acf63..0000000000 --- a/opendaylight/adsal/northbound/usermanager/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - JAXRSUserManager - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSUserManager - /* - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - - - - CONFIDENTIAL - - - - - System-Admin - - - Network-Admin - - - - BASIC - opendaylight - - diff --git a/opendaylight/adsal/northbound/usermanager/src/test/java/org/opendaylight/controller/subnets/northbound/UserManagerNorthboundTest.java b/opendaylight/adsal/northbound/usermanager/src/test/java/org/opendaylight/controller/subnets/northbound/UserManagerNorthboundTest.java deleted file mode 100644 index ac0307a721..0000000000 --- a/opendaylight/adsal/northbound/usermanager/src/test/java/org/opendaylight/controller/subnets/northbound/UserManagerNorthboundTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.subnets.northbound; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.authorization.AuthResultEnum; -import org.opendaylight.controller.usermanager.AuthResponse; -import org.opendaylight.controller.usermanager.UserConfig; - -public class UserManagerNorthboundTest { - - @Test - public void testUserConfigs() { - List roles = new ArrayList(); - roles.add("Network-Admin"); - - UserConfig userConfig = new UserConfig("test","testPass",roles); - - Assert.assertNotNull(userConfig); - Assert.assertNotNull(userConfig.getUser()); - Assert.assertNotNull(userConfig.getPassword()); - Assert.assertTrue(userConfig.getRoles().equals(roles)); - - - AuthResponse authResponse = userConfig.authenticate("testPass"); - Assert.assertNotNull(authResponse); - - Assert.assertEquals(AuthResultEnum.AUTH_ACCEPT_LOC,authResponse.getStatus()); - } - -} diff --git a/opendaylight/adsal/northboundtest/unit_test_suite/pom.xml b/opendaylight/adsal/northboundtest/unit_test_suite/pom.xml deleted file mode 100644 index 3047bdd072..0000000000 --- a/opendaylight/adsal/northboundtest/unit_test_suite/pom.xml +++ /dev/null @@ -1,55 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../opendaylight/commons/opendaylight - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - - - org.opendaylight.controller - northboundtest - 0.6.0-SNAPSHOT - bundle - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - - org.opendaylight.controller.sal.core, - org.eclipse.osgi.framework.console, - org.osgi.framework, - org.apache.felix.dm - - - - - org.opendaylight.controller.northboundtest.unittestsuite.internal.Activator - - - - - - - - - - - org.opendaylight.controller - sal - - - diff --git a/opendaylight/adsal/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/API3UnitTest.java b/opendaylight/adsal/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/API3UnitTest.java deleted file mode 100644 index aef2540f93..0000000000 --- a/opendaylight/adsal/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/API3UnitTest.java +++ /dev/null @@ -1,210 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northboundtest.unittestsuite.internal; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This java class provides the osgi console with the commands for running the unit test scripts for the API3 - * - * - * - */ -public class API3UnitTest implements CommandProvider { - private static Logger log = LoggerFactory - .getLogger(API3UnitTest.class); - - private static final String python = "/usr/bin/python"; - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, - null); - } - - /** - * Function called by the dependency manager when at least one - * dependency become unsatisfied or when the component is shutting - * down because for example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called - * and after the services provided by the class are registered in - * the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services - * exported by the component are unregistered, this will be - * followed by a "destroy ()" calls - * - */ - void stop() { - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---API3 Unit Test---\n"); - help - .append("\t api3ut - run the python script for the specified northbound module\n"); - help.append("\t GET "); - help.append("\t PUT data1==x1 data2==x2 ..."); - help.append("\t POST data1==x1 data2==x2 ..."); - help.append("\t DELETE "); - return help.toString(); - } - - public void _api3ut(CommandInterpreter ci) { - boolean custom = false; - String target = null; - String module = null; - - module = ci.nextArgument(); - if (module == null) { - printUsage(ci); - return; - } - - if (module.equals("custom")) { - target = ci.nextArgument(); - custom = true; - } else if (module.equals("flows")) { - target = "flowsUnitTest.py"; - } else if (module.equals("subnets")) { - target = "subnetsUnitTest.py"; - } else if (module.equals("hosts")) { - target = "hostsUnitTest.py"; - } else if (module.equals("slices")) { - target = "slicesUnitTest.py"; - } else if (module.equals("tif")) { - target = "tifUnitTest.py"; - } else { - ci.println("ERROR: Coming soon"); - } - - if (target != null) { - executeScript(target, custom); - } - } - - private void printUsage(CommandInterpreter ci) { - ci.println("Usage: api3ut [ | custom ]"); - ci - .println(": [flows, hosts, subnets, slices, tif] (You need python-httplib2 installed)"); - ci.println(": your linux script (w/ absolute path)"); - } - - private void printStream(InputStream stream) throws IOException { - String line; - BufferedReader reader = new BufferedReader( - new InputStreamReader(stream)); - - while ((line = reader.readLine()) != null) { - System.out.println(line); - } - } - - public void executeScript(String target, boolean custom) - throws RuntimeException { - String script = (custom) ? target : "SCRIPTS/python/" + target; - try { - Runtime runTime = Runtime.getRuntime(); - Process process = runTime.exec(python + " " + script); - printStream(process.getInputStream()); - printStream(process.getErrorStream()); - } catch (Exception e) { - System.out.println("Exception!"); - log.error("",e); - } - } - - public void _GET(CommandInterpreter ci) { - parseRestRequest("GET", ci); - } - - public void _PUT(CommandInterpreter ci) { - parseRestRequest("PUT", ci); - } - - public void _DELETE(CommandInterpreter ci) { - parseRestRequest("DELETE", ci); - } - - public void _POST(CommandInterpreter ci) { - parseRestRequest("POST", ci); - } - - private void parseRestRequest(String action, CommandInterpreter ci) { - String uri, resource; - StringBuffer resources = new StringBuffer(" "); - - uri = ci.nextArgument(); - if (uri == null) { - printRestUsage(ci); - return; - } - - resource = ci.nextArgument(); - while (resource != null) { - resources.append(resource); - resources.append(" "); - resource = ci.nextArgument(); - } - - executeRestCall(action, uri, resources.toString()); - - } - - private void executeRestCall(String action, String uri, String resources) { - String script = "SCRIPTS/python/rest_call.py"; - - try { - Runtime runTime = Runtime.getRuntime(); - Process process = runTime.exec(python + " " + script + " " + action - + " " + uri + " " + resources); - printStream(process.getInputStream()); - printStream(process.getErrorStream()); - } catch (Exception e) { - System.out.println("Exception!"); - log.error("",e); - } - } - - private void printRestUsage(CommandInterpreter ci) { - ci.println("Usage: GET/PUT/POST/DELETE []"); - ci.println(": ex: slices/red or slices/red/flowspecs"); - ci - .println(": resource==,... ex: switchId==2 port==3-7"); - } -} diff --git a/opendaylight/adsal/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/Activator.java b/opendaylight/adsal/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/Activator.java deleted file mode 100644 index 471a440c38..0000000000 --- a/opendaylight/adsal/northboundtest/unit_test_suite/src/main/java/org/opendaylight/controller/northboundtest/unittestsuite/internal/Activator.java +++ /dev/null @@ -1,79 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.northboundtest.unittestsuite.internal; - -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; - -import org.apache.felix.dm.Component; - -public class Activator extends ComponentActivatorAbstractBase { - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - public Object[] getImplementations() { - return null; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - public void configureInstance(Component c, Object imp, String containerName) { - } - - /** - * Method which tells how many Global implementations are - * supported by the bundle. This way we can tune the number of - * components created. This components will be created ONLY at the - * time of bundle startup and will be destroyed only at time of - * bundle destruction, this is the major difference with the - * implementation retrieved via getImplementations where all of - * them are assumed to be in a Container! - * - * - * @return The list of implementations the bundle will support, - * in Global version - */ - protected Object[] getGlobalImplementations() { - Object[] res = { API3UnitTest.class }; - return res; - } - - /** - * Configure the dependency for a given instance Global - * - * @param c Component assigned for this instance, this will be - * what will be used for configuration - * @param imp implementation to be configured - * @param containerName container on which the configuration happens - */ - protected void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(API3UnitTest.class)) { - // Nothing to initialize - } - } -} diff --git a/opendaylight/adsal/pom.xml b/opendaylight/adsal/pom.xml deleted file mode 100644 index 91f4ddd36c..0000000000 --- a/opendaylight/adsal/pom.xml +++ /dev/null @@ -1,141 +0,0 @@ - - - 4.0.0 - - - org.opendaylight.controller - commons.parent - 1.2.0-SNAPSHOT - ../commons/parent - - - adsal-parent - pom - - forwarding/staticrouting - clustering/services - clustering/services_implementation - clustering/stub - clustering/test - configuration/api - configuration/implementation - routing/dijkstra_implementation - arphandler - forwardingrulesmanager/api - forwardingrulesmanager/implementation - hosttracker/api - hosttracker/implementation - hosttracker/shell - hosttracker_new/api - hosttracker_new/implementation - containermanager/api - containermanager/implementation - containermanager/shell - appauth - switchmanager/api - switchmanager/implementation - statisticsmanager/api - statisticsmanager/implementation - topologymanager/implementation - topologymanager/shell - usermanager/api - usermanager/implementation - connectionmanager/api - connectionmanager/implementation - security - karaf-tomcat-security - - - sal/api - sal/implementation - - - sal/connection/api - sal/connection/implementation - sal/networkconfiguration/api - sal/networkconfiguration/implementation - - - web/root - web/flows - web/devices - web/troubleshoot - web/topology - web/osgi-brandfragment - - - northbound/commons - northbound/bundlescanner/api - northbound/bundlescanner/implementation - northbound/topology - northbound/staticrouting - northbound/statistics - northbound/flowprogrammer - northbound/hosttracker - northbound/subnets - northbound/switchmanager - northbound/containermanager - northbound/networkconfiguration/bridgedomain - northbound/httpservice-bridge - northbound/jolokia - northbound/connectionmanager - northbound/usermanager - northbound/controllermanager - - - logging/bridge - - - protocol_plugins/openflow - protocol_plugins/stub - - - samples/simpleforwarding - samples/loadbalancer - samples/northbound/loadbalancer - - dummy-console - adsal-enunciate-parent - - - features/base - features/controller - features/adsal - features/nsf - features/extras - - - - integrationtests - - false - - - clustering/integrationtest - configuration/integrationtest - forwardingrulesmanager/integrationtest - hosttracker/integrationtest - switchmanager/integrationtest - topologymanager/integrationtest - - northbound/integrationtest - statisticsmanager/integrationtest - containermanager/it.implementation - commons/integrationtest - - commons/httpclient - - - - docs-java7 - - false - 1.7 - - - northbound/java-client - northbound/swagger-ui - - - - diff --git a/opendaylight/adsal/protocol_plugins/openflow/pom.xml b/opendaylight/adsal/protocol_plugins/openflow/pom.xml deleted file mode 100644 index 91cf49a873..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - protocol_plugins.openflow - 0.6.0-SNAPSHOT - bundle - - - equinoxSDK381 - org.eclipse.osgi - - - junit - junit - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller.thirdparty - org.openflow.openflowj - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.discovery, - org.opendaylight.controller.sal.topology, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.reader, - org.opendaylight.controller.sal.inventory, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.connection, - org.apache.commons.lang3.builder, - org.apache.commons.lang3.tuple, - org.apache.felix.dm, - org.slf4j, - org.eclipse.osgi.framework.console, - org.osgi.framework, - javax.net.ssl - org.opendaylight.controller.protocol_plugin.openflow.internal - org.openflow.openflowj - false - org.opendaylight.controller.protocol_plugin.openflow.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketListen.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketListen.java deleted file mode 100644 index 300967e87c..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketListen.java +++ /dev/null @@ -1,39 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IDataPacketListen.java - * - * @brief Interface to dispatch locally in the protocol plugin the - * data packets, intended especially for Discovery, main difference - * here with the analogous of SAL is that this is Global - * inherently - * - */ -package org.opendaylight.controller.protocol_plugin.openflow; - -import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.packet.PacketResult; - -/** - * Interface to dispatch locally in the protocol plugin the - * data packets, intended especially for Discovery, main difference - * here with the analogous of SAL is that this is Global - * inherently. - */ -public interface IDataPacketListen { - /** - * Dispatch received data packet - * - * @param inPkt - * The incoming raw packet - * @return Possible results for Data packet processing handler - */ - public PacketResult receiveDataPacket(RawPacket inPkt); -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketMux.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketMux.java deleted file mode 100644 index 747a8fbec5..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDataPacketMux.java +++ /dev/null @@ -1,31 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow; - -/** - * @file IDataPacketMux.java - * - * @brief Simple wrapped interface for the IPluginInDataPacketService - * which will be only exported by DataPacketServices mux/demux - * component and will be only accessible by the openflow protocol - * plugin - */ - -import org.opendaylight.controller.sal.packet.IPluginInDataPacketService; - -/** - * Simple wrapped interface for the IPluginInDataPacketService - * which will be only exported by DataPacketServices mux/demux - * component and will be only accessible by the openflow protocol - * plugin - */ -public interface IDataPacketMux extends IPluginInDataPacketService { - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDiscoveryListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDiscoveryListener.java deleted file mode 100644 index ecc5d6ef0f..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IDiscoveryListener.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow; - -import org.opendaylight.controller.sal.discovery.IDiscoveryService; - -/** - * The interface provides method to notify the local plugin listener when an - * edge is discovered or removed. - */ -public interface IDiscoveryListener extends IDiscoveryService { - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IFlowProgrammerNotifier.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IFlowProgrammerNotifier.java deleted file mode 100644 index 307176590f..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IFlowProgrammerNotifier.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow; - -import org.opendaylight.controller.sal.flowprogrammer.IPluginOutFlowProgrammerService; - -/** - * Interface which defines the methods exposed by the Flow Programmer Notifier. - * Their implementation relays the asynchronous messages received from the - * network nodes to the the SAL Flow Programmer Notifier Service on the proper - * container. - */ -public interface IFlowProgrammerNotifier extends - IPluginOutFlowProgrammerService { - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryProvider.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryProvider.java deleted file mode 100644 index 6b2ea3016e..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow; - -import org.opendaylight.controller.sal.inventory.IPluginInInventoryService; - -/** - * The Interface provides inventory service to the local plugin modules - */ -public interface IInventoryProvider extends IPluginInInventoryService { - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimExternalListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimExternalListener.java deleted file mode 100644 index df03a04384..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimExternalListener.java +++ /dev/null @@ -1,18 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow; - -/** - * Wrapper of Interface that provides inventory updates locally in the protocol - * plugin. - */ -public interface IInventoryShimExternalListener extends - IInventoryShimInternalListener { -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimInternalListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimInternalListener.java deleted file mode 100644 index 3c698b6ce3..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IInventoryShimInternalListener.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow; - -import java.util.Set; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; - -/** - * The Interface provides inventory updates to inventory listeners within the - * protocol plugin - */ -public interface IInventoryShimInternalListener { - /** - * Updates node and its properties - * - * @param node - * {@link org.opendaylight.controller.sal.core.Node} being - * updated - * @param type - * update type {@link org.opendaylight.controller.sal.core.UpdateType} - * @param props - * set of {@link org.opendaylight.controller.sal.core.Property} - * such as - * {@link org.opendaylight.controller.sal.core.Description} - * and/or {@link org.opendaylight.controller.sal.core.Tier} etc. - */ - public void updateNode(Node node, UpdateType type, Set props); - - /** - * Updates node connector and its properties - * - * @param nodeConnector - * {@link org.opendaylight.controller.sal.core.NodeConnector} - * being updated - * @param type - * update type {@link org.opendaylight.controller.sal.core.UpdateType} - * @param props - * set of {@link org.opendaylight.controller.sal.core.Property} - * such as - * {@link org.opendaylight.controller.sal.core.Description} - * and/or {@link org.opendaylight.controller.sal.core.State} etc. - */ - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props); - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsListener.java deleted file mode 100644 index 9a2d4ffbc4..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsListener.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.protocol_plugin.openflow; - -import java.util.List; - -import org.openflow.protocol.statistics.OFStatistics; - -/** - * Interface which defines the notification functions which will get called when - * the information contained in the OF statistics reply message received from a - * network node is different from the cached one. - */ -public interface IOFStatisticsListener { - /** - * Notifies that a new list of description statistics objects for the given - * switch is available - * - * @param switchId - * The datapath id of the openflow switch - * @param description - * The new list of description statistics objects - */ - public void descriptionStatisticsRefreshed(Long switchId, List description); - - /** - * Notifies that a new list of flows statistics objects for the given switch - * is available - * - * @param switchId - * The datapath id of the openflow switch - * @param flows - * The new list of flow statistics objects - */ - public void flowStatisticsRefreshed(Long switchId, List flows); - - /** - * Notifies that a new list of port statistics objects for the given switch - * is available - * - * @param switchId - * The datapath id of the openflow switch - * @param flows - * The new list of port statistics objects - */ - public void portStatisticsRefreshed(Long switchId, List ports); - - /** - * Notifies that a new list of table statistics objects for the given switch - * is available - * - * @param switchId - * The datapath id of the openflow switch - * @param flows - * The new list of table statistics objects - */ - public void tableStatisticsRefreshed(Long switchId, List tables); -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsManager.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsManager.java deleted file mode 100644 index fa225a8d3e..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IOFStatisticsManager.java +++ /dev/null @@ -1,118 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow; - -import java.util.List; - -import org.openflow.protocol.OFMatch; -import org.openflow.protocol.statistics.OFStatistics; -import org.openflow.protocol.statistics.OFStatisticsType; - -/** - * Interface to expose the openflow statistics collected on the switches - */ -public interface IOFStatisticsManager { - /** - * Return all the statistics for all the flows present on the specified switch - * - * @param switchId the openflow datapath id - * @return the list of openflow statistics - */ - List getOFFlowStatistics(Long switchId); - - /** - * Return all the statistics for all the flows present on the specified switch - * - * @param switchId the openflow datapath id - * @param ofMatch the openflow match to query. If null, the query is intended for all the flows - * @param priority Priority of the wanted flow - * @return the list of openflow statistics - */ - List getOFFlowStatistics(Long switchId, OFMatch ofMatch, short priority); - - /** - * Return the description statistics for the specified switch. - * - * @param switchId the openflow datapath id - * @return the list of openflow statistics - */ - List getOFDescStatistics(Long switchId); - - /** - * Returns the statistics for all the ports on the specified switch - * - * @param switchId the openflow datapath id - * @return the list of openflow statistics - */ - List getOFPortStatistics(Long switchId); - - /** - * Returns the statistics for the specified switch port - * - * @param switchId the openflow datapath id - * @param portId the openflow switch port id - * @return the list of openflow statistics - */ - List getOFPortStatistics(Long switchId, short portId); - - /** - * Returns the number of flows installed on the switch - * - * @param switchId the openflow datapath id - * @return the number of flows installed on the switch - */ - int getFlowsNumber(long switchId); - - /** - * Send a statistics request message to the specified switch and returns - * the switch response. It blocks the caller until the response has arrived - * from the switch or the request has timed out - * - * @param switchId the openflow datapath id of the target switch - * @param statType the openflow statistics type - * @param target the target object. For flow statistics it is the OFMatch. - * For port statistics, it is the port id. If null the query - * will be performed for all the targets for the specified - * statistics type. - * - * @param timeout the timeout in milliseconds the system will wait for a response - * from the switch, before declaring failure - * @return the list of openflow statistics - */ - List queryStatistics(Long switchId, - OFStatisticsType statType, Object target); - - /** - * Returns the averaged transmit rate for the passed switch port - * - * @param switchId the openflow datapath id of the target switch - * @param portId the openflow switch port id - * @return the median transmit rate in bits per second - */ - long getTransmitRate(Long switchId, Short port); - - /** - * Returns the statistics for the specified switch table - * - * @param switchId the openflow datapath id - * @param tableId the openflow switch table id - * @return the list of openflow statistics - */ - List getOFTableStatistics(Long switchId, Byte tableId); - - /** - * Returns all the table statistics for the node specified - * - * @param switchId the openflow datapath id - * @return the list of openflow statistics - */ - List getOFTableStatistics(Long switchId); - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadFilterInternalListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadFilterInternalListener.java deleted file mode 100644 index eb46c60466..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadFilterInternalListener.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.protocol_plugin.openflow; - -import java.util.List; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; - -/** - * The Interface provides notification of statistics (hardware view) updates to - * ReaderFilter listeners within the protocol plugin - */ -public interface IReadFilterInternalListener { - - /** - * Notifies the hardware view of all the flow installed on the specified - * network node was updated - * - * @param node - * the network node - * @param flowStatsList - */ - public void nodeFlowStatisticsUpdated(Node node, List flowStatsList); - - /** - * Notifies the hardware view of the specified network node connectors was - * updated - * - * @param node - * the network node - */ - public void nodeConnectorStatisticsUpdated(Node node, List ncStatsList); - - /** - * Notifies the hardware view of the specified network node tables was - * updated - * - * @param node - * the network node - */ - public void nodeTableStatisticsUpdated(Node node, List tableStatsList); - - /** - * Notifies the hardware view of all the flow installed on the specified - * network node was updated - * - * @param node - * the network node - */ - public void nodeDescriptionStatisticsUpdated(Node node, NodeDescription nodeDescription); -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadServiceFilter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadServiceFilter.java deleted file mode 100644 index 9ba67e382f..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IReadServiceFilter.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow; - -import java.util.List; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; - -/** - * Interface to serve the hardware information requests coming from SAL It is - * implemented by the respective OF1.0 plugin component - * - */ -public interface IReadServiceFilter { - /** - * Returns the hardware image for the specified flow on the specified - * network node for the passed container - * - * @param container - * the container for which the request is originated - * @param node - * the network node - * @param flow - * the target flow - * @param cached - * specify if entry has to be queried from the cached hardware - * information maintained in the protocol plugin or directly from - * the network node. - * @return The FlowOnNode object containing the information present in - * hardware for the passed flow on the specified network node - */ - public FlowOnNode readFlow(String container, Node node, Flow flow, boolean cached); - - /** - * Returns the hardware view of all the flow installed on the specified - * network node for the passed container - * - * @param container - * the container for which the request is originated - * @param node - * the network node - * @param cached - * specify if entries have to be queried from the cached hardware - * information maintained in the protocol plugin or directly from - * the network node. - * @return The list of FlowOnNode objects containing the information present - * in hardware on the specified network node for all its flows - */ - public List readAllFlow(String container, Node node, boolean cached); - - /** - * Returns the description of the network node as provided by the node - * itself - * - * @param node - * the network node - * @param cached - * specify if entry has to be queried from the cached hardware - * information maintained in the protocol plugin or directly from - * the network node. - * @return The NodeDescription object containing the description information - * for the specified network node - */ - public NodeDescription readDescription(Node node, boolean cached); - - /** - * Returns the hardware view of the specified network node connector for the - * given container - * - * @param container - * the container for which the request is originated - * @param nodeConnector - * the target nodeConnector - * @param cached - * specify if entry has to be queried from the cached hardware - * information maintained in the protocol plugin or directly from - * the corresponding network node. - * @return The NodeConnectorStatistics object containing the statistics - * present in hardware for the corresponding network node port - */ - public NodeConnectorStatistics readNodeConnector(String container, NodeConnector nodeConnector, boolean cached); - - /** - * Returns the hardware info for all the node connectors on the specified - * network node for the given container - * - * @param container - * the container for which the request is originated - * @param node - * the target node - * @param cached - * specify if entries have to be queried from the cached hardware - * information maintained in the protocol plugin or directly from - * the corresponding network node. - * @return The list of NodeConnectorStatistics objects containing the - * statistics present in hardware for all the network node ports - */ - public List readAllNodeConnector(String container, Node node, boolean cached); - - /** - * Returns the table statistics of the node as specified by the given - * container - * - * @param container - * the container for which the request is originated - * @param nodeTable - * the target network node table - * @param cached - * specify if entry has to be queried from the cached hardware - * information maintained in the protocol plugin or directly from - * the corresponding network node. - * @return The NodeTableStatistics object containing the statistics present - * in hardware for the corresponding network node table - */ - public NodeTableStatistics readNodeTable(String container, NodeTable nodeTable, boolean cached); - - /** - * Returns the table statistics of all the tables for the specified node - * - * @param container - * the container for which the request is originated - * @param node - * the target node - * @param cached - * specify if entries have to be queried from the cached hardware - * information maintained in the protocol plugin or directly from - * the corresponding network node. - * @return The list of NodeTableStatistics objects containing the statistics - * present in hardware for all the network node tables - */ - public List readAllNodeTable(String containerName, Node node, boolean cached); - - /** - * Returns the average transmit rate for the specified node connector on the - * given container. If the node connector does not belong to the passed - * container a zero value is returned - * - * @param container - * the container for which the request is originated - * @param nodeConnector - * the target node connector - * @return The average tx rate in bps - */ - public long getTransmitRate(String container, NodeConnector nodeConnector); -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IRefreshInternalProvider.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IRefreshInternalProvider.java deleted file mode 100644 index 506d1702af..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/IRefreshInternalProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow; - -/** - * @file IRefreshInternalProvider.java - * - * @brief Topology refresh notifications requested by application - * to be fetched from the plugin - * - * For example, an application that has been started late, will want to - * be up to date with the latest topology. Hence, it requests for a - * topology refresh from the plugin. - */ - -/** - * Topology refresh requested by the application from the plugin - * - */ - -public interface IRefreshInternalProvider { - - /** - * @param containerName - * Name of the container for the topology - */ - public void requestRefresh(String containerName); -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/ITopologyServiceShimListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/ITopologyServiceShimListener.java deleted file mode 100644 index 35ed2e6ad3..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/ITopologyServiceShimListener.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow; - -import java.util.List; - -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; - -/** - * The Interface provides Edge updates to the topology listeners - */ -public interface ITopologyServiceShimListener { - /** - * Called to update on Edge in the topology graph - * - * @param topoedgeupdateList - * List of topoedgeupdates Each topoedgeupdate includes edge, its - * Properties ( BandWidth and/or Latency etc) and update type. - */ - public void edgeUpdate(List topoedgeupdateList); - - /** - * Called when an Edge utilization is above the safe threshold configured on - * the controller - * - * @param {@link org.opendaylight.controller.sal.core.Edge} - */ - public void edgeOverUtilized(Edge edge); - - /** - * Called when the Edge utilization is back to normal, below the safety - * threshold level configured on the controller - * - * @param {@link org.opendaylight.controller.sal.core.Edge} - */ - public void edgeUtilBackToNormal(Edge edge); -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IController.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IController.java deleted file mode 100644 index 9e3c21c65e..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IController.java +++ /dev/null @@ -1,62 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core; - -import java.util.Map; - -import org.openflow.protocol.OFType; - -/** - * This interface defines an abstraction of the Open Flow Controller that allows applications to control and manage the Open Flow switches. - * - */ -public interface IController { - - /** - * Allows application to start receiving OF messages received from switches. - * @param type the type of OF message that applications want to receive - * @param listener: Object that implements the IMessageListener - */ - public void addMessageListener(OFType type, IMessageListener listener); - - /** - * Allows application to stop receiving OF message received from switches. - * @param type The type of OF message that applications want to stop receiving - * @param listener The object that implements the IMessageListener - */ - public void removeMessageListener(OFType type, IMessageListener listener); - - /** - * Allows application to start receiving switch state change events. - * @param listener The object that implements the ISwitchStateListener - */ - public void addSwitchStateListener(ISwitchStateListener listener); - - /** - * Allows application to stop receiving switch state change events. - * @param listener The object that implements the ISwitchStateListener - */ - public void removeSwitchStateListener(ISwitchStateListener listener); - - /** - * Returns a map containing all the OF switches that are currently connected to the Controller. - * @return Map of ISwitch - */ - public Map getSwitches(); - - /** - * Returns the ISwitch of the given switchId. - * - * @param switchId The switch ID - * @return ISwitch if present, null otherwise - */ - public ISwitch getSwitch(Long switchId); - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageListener.java deleted file mode 100644 index aed19db04c..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageListener.java +++ /dev/null @@ -1,26 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core; - -import org.openflow.protocol.OFMessage; - -/** - * Interface to be implemented by applications that want to receive OF messages. - * - */ -public interface IMessageListener { - /** - * This method is called by the Controller when a message is received from a switch. - * Application who is interested in receiving OF Messages needs to implement this method. - * @param sw The ISwitch which sent the OF message - * @param msg The OF message - */ - public void receive(ISwitch sw, OFMessage msg); -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageReadWrite.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageReadWrite.java deleted file mode 100644 index ce91e1f275..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/IMessageReadWrite.java +++ /dev/null @@ -1,53 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core; - -import java.util.List; - -import org.openflow.protocol.OFMessage; - -/** - * This interface defines low level routines to read/write messages on an open - * socket channel. If secure communication is desired, these methods also perform - * encryption and decryption of the network data. - */ -public interface IMessageReadWrite { - /** - * Sends the OF message out over the socket channel. For secure - * communication, the data will be encrypted. - * - * @param msg OF message to be sent - * @throws Exception - */ - public void asyncSend(OFMessage msg) throws Exception; - - /** - * Resumes sending the remaining messages in the outgoing buffer - * @throws Exception - */ - public void resumeSend() throws Exception; - - /** - * Reads the incoming network data from the socket and retrieves the OF - * messages. For secure communication, the data will be decrypted first. - * - * @return list of OF messages - * @throws Exception - */ - public List readMessages() throws Exception; - - /** - * Proper clean up when the switch connection is closed - * - * @return - * @throws Exception - */ - public void stop() throws Exception; -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitch.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitch.java deleted file mode 100644 index d924b66a09..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitch.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core; - -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.openflow.protocol.OFMessage; -import org.openflow.protocol.OFPhysicalPort; -import org.openflow.protocol.OFStatisticsRequest; - -/** - * This interface defines an abstraction of an Open Flow Switch. - * - */ -public interface ISwitch { - /** - * Gets a unique XID. - * - * @return XID - */ - public int getNextXid(); - - /** - * Returns the Switch's ID. - * - * @return the Switch's ID - */ - public Long getId(); - - /** - * Returns the Switch's table numbers supported by datapath - * - * @return the tables - */ - public Byte getTables(); - - /** - * Returns the Switch's bitmap of supported ofp_action_type - * - * @return the actions - */ - public Integer getActions(); - - /** - * Returns the Switch's bitmap of supported ofp_capabilities - * - * @return the capabilities - */ - public Integer getCapabilities(); - - /** - * Returns the Switch's buffering capacity in Number of Pkts - * - * @return the buffers - */ - public Integer getBuffers(); - - /** - * Returns the Date when the switch was connected. - * - * @return Date The date when the switch was connected - */ - public Date getConnectedDate(); - - /** - * This method puts the message in an outgoing priority queue with normal - * priority. It will be served after high priority messages. The method - * should be used for non-critical messages such as statistics request, - * discovery packets, etc. An unique XID is generated automatically and - * inserted into the message. - * - * @param msg - * The OF message to be sent - * @return The XID used - */ - public Integer asyncSend(OFMessage msg); - - /** - * This method puts the message in an outgoing priority queue with normal - * priority. It will be served after high priority messages. The method - * should be used for non-critical messages such as statistics request, - * discovery packets, etc. The specified XID is inserted into the message. - * - * @param msg - * The OF message to be Sent - * @param xid - * The XID to be used in the message - * @return The XID used - */ - public Integer asyncSend(OFMessage msg, int xid); - - /** - * This method puts the message in an outgoing priority queue with high - * priority. It will be served first before normal priority messages. The - * method should be used for critical messages such as hello, echo reply - * etc. An unique XID is generated automatically and inserted into the - * message. - * - * @param msg - * The OF message to be sent - * @return The XID used - */ - public Integer asyncFastSend(OFMessage msg); - - /** - * This method puts the message in an outgoing priority queue with high - * priority. It will be served first before normal priority messages. The - * method should be used for critical messages such as hello, echo reply - * etc. The specified XID is inserted into the message. - * - * @param msg - * The OF message to be sent - * @param xid - * The XID to be used in the message - * @return The XID used - */ - public Integer asyncFastSend(OFMessage msg, int xid); - - /** - * Sends the OF message followed by a Barrier Request with a unique XID - * which is automatically generated, and waits for a result from the switch. - * - * @param msg - * The message to be sent - * @return An Object which has one of the followings instances/values: - * Boolean with value true to indicate the message has been - * successfully processed and acknowledged by the switch; Boolean - * with value false to indicate the message has failed to be - * processed by the switch within a period of time or OFError to - * indicate that the message has been denied by the switch which - * responded with OFError. - */ - public Object syncSend(OFMessage msg); - - /** - * Returns a map containing all OFPhysicalPorts of this switch. - * - * @return The Map of OFPhysicalPort - */ - public Map getPhysicalPorts(); - - /** - * Returns a Set containing all port IDs of this switch. - * - * @return The Set of port ID - */ - public Set getPorts(); - - /** - * Returns OFPhysicalPort of the specified portNumber of this switch. - * - * @param portNumber - * The port ID - * @return OFPhysicalPort for the specified PortNumber - */ - public OFPhysicalPort getPhysicalPort(Short portNumber); - - /** - * Returns the bandwidth of the specified portNumber of this switch. - * - * @param portNumber - * the port ID - * @return bandwidth - */ - public Integer getPortBandwidth(Short portNumber); - - /** - * Returns True if the port is enabled, - * - * @param portNumber - * the port ID - * @return True if the port is enabled - */ - public boolean isPortEnabled(short portNumber); - - /** - * Returns True if the port is enabled. - * - * @param port - * the OpenFlow port - * @return True if the port is enabled - */ - public boolean isPortEnabled(OFPhysicalPort port); - - /** - * Returns a list containing all enabled ports of this switch. - * - * @return: List containing all enabled ports of this switch - */ - public List getEnabledPorts(); - - /** - * Sends OFStatisticsRequest with a unique XID generated automatically and - * waits for a result from the switch. - * - * @param req - * the OF Statistic Request to be sent - * @return Object has one of the following instances/values:: - * List, a list of statistics records received from - * the switch as response from the request; OFError if the switch - * failed handle the request or NULL if timeout has occurred while - * waiting for the response. - */ - public Object getStatistics(OFStatisticsRequest req); - - /** - * Returns true if the switch has reached the operational state (has sent - * FEATURE_REPLY to the controller). - * - * @return true if the switch is operational - */ - public boolean isOperational(); - - /** - * Send Barrier message synchronously. The caller will be blocked until the - * Barrier reply arrives. - */ - public Object syncSendBarrierMessage(); - - /** - * Send Barrier message asynchronously. The caller is not blocked. The - * Barrier message will be sent in a transmit thread which will be blocked - * until the Barrier reply arrives. - */ - public Object asyncSendBarrierMessage(); - - /** - * Send a FLOW_MOD message with a wildcard match and action=DELETE. - */ - public void deleteAllFlows(); -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitchStateListener.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitchStateListener.java deleted file mode 100644 index 608b6f583b..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitchStateListener.java +++ /dev/null @@ -1,31 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core; - -/** - * Interface to be implemented by applications that want to receive switch state event changes. - * - */ -public interface ISwitchStateListener { - /** - * This method is invoked by Controller when a switch has been connected to the Controller. - * Application who wants to receive this event needs to implement this method. - * @param sw The switch that has just connected. - */ - public void switchAdded(ISwitch sw); - - /** - * This method is invoked by Controller when a switch has been disconnected from the Controller. - * Application who wants to receive this event needs to implement this method. - * @param sw The switch that has just disconnected. - */ - public void switchDeleted(ISwitch sw); - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/Controller.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/Controller.java deleted file mode 100644 index 63dd0bc29a..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/Controller.java +++ /dev/null @@ -1,430 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core.internal; - -import java.io.IOException; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.Comparator; -import java.util.Date; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.PriorityBlockingQueue; -import java.util.concurrent.atomic.AtomicInteger; - -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitchStateListener; -import org.opendaylight.controller.sal.connection.ConnectionConstants; -import org.opendaylight.controller.sal.connection.IPluginInConnectionService; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.openflow.protocol.OFMessage; -import org.openflow.protocol.OFType; -import org.openflow.util.HexString; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Controller implements IController, CommandProvider, IPluginInConnectionService { - private static final Logger logger = LoggerFactory - .getLogger(Controller.class); - private ControllerIO controllerIO; - private Thread switchEventThread; - private volatile boolean shutdownSwitchEventThread;// default to false - private ConcurrentHashMap switches; - private PriorityBlockingQueue switchEvents; - // only 1 message listener per OFType - private ConcurrentMap messageListeners; - // only 1 switch state listener - private ISwitchStateListener switchStateListener; - private AtomicInteger switchInstanceNumber; - private int MAXQUEUESIZE = 50000; - - private static enum SwitchEventPriority { LOW, NORMAL, HIGH } - - /* - * this thread monitors the switchEvents queue for new incoming events from - * switch - */ - private class EventHandler implements Runnable { - @Override - public void run() { - - while (true) { - try { - if(shutdownSwitchEventThread) { - // break out of the infinite loop - // if you are shutting down - logger.info("Switch Event Thread is shutting down"); - break; - } - SwitchEvent ev = switchEvents.take(); - SwitchEvent.SwitchEventType eType = ev.getEventType(); - ISwitch sw = ev.getSwitch(); - switch (eType) { - case SWITCH_ADD: - Long sid = sw.getId(); - ISwitch existingSwitch = switches.get(sid); - if (existingSwitch != null) { - logger.info("Replacing existing {} with New {}", - existingSwitch, sw); - disconnectSwitch(existingSwitch); - } - switches.put(sid, sw); - notifySwitchAdded(sw); - break; - case SWITCH_DELETE: - disconnectSwitch(sw); - break; - case SWITCH_ERROR: - disconnectSwitch(sw); - break; - case SWITCH_MESSAGE: - OFMessage msg = ev.getMsg(); - if (msg != null) { - IMessageListener listener = messageListeners - .get(msg.getType()); - if (listener != null) { - listener.receive(sw, msg); - } - } - break; - default: - logger.error("Unknown switch event {}", eType.ordinal()); - } - } catch (InterruptedException e) { - // nothing to do except retry - } catch (Exception e) { - // log the exception and retry - logger.warn("Exception in Switch Event Thread is {}" ,e); - } - } - switchEvents.clear(); - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - public void init() { - logger.debug("Initializing!"); - this.switches = new ConcurrentHashMap(); - this.switchEvents = new PriorityBlockingQueue(MAXQUEUESIZE, new Comparator() { - @Override - public int compare(SwitchEvent p1, SwitchEvent p2) { - return p2.getPriority() - p1.getPriority(); - } - }); - this.messageListeners = new ConcurrentHashMap(); - this.switchStateListener = null; - this.switchInstanceNumber = new AtomicInteger(0); - registerWithOSGIConsole(); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - public void start() { - logger.debug("Starting!"); - /* - * start a thread to handle event coming from the switch - */ - switchEventThread = new Thread(new EventHandler(), "SwitchEvent Thread"); - switchEventThread.start(); - - // spawn a thread to start to listen on the open flow port - controllerIO = new ControllerIO(this); - try { - controllerIO.start(); - } catch (IOException ex) { - logger.error("Caught exception while starting:", ex); - } - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - public void stop() { - for (Iterator> it = switches.entrySet().iterator(); it - .hasNext();) { - Entry entry = it.next(); - ((SwitchHandler) entry.getValue()).stop(); - it.remove(); - } - shutdownSwitchEventThread = true; - switchEventThread.interrupt(); - try { - controllerIO.shutDown(); - } catch (IOException ex) { - logger.error("Caught exception while stopping:", ex); - } - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - public void destroy() { - } - - @Override - public void addMessageListener(OFType type, IMessageListener listener) { - IMessageListener currentListener = this.messageListeners.get(type); - if (currentListener != null) { - logger.warn("{} is already listened by {}", type, - currentListener); - } - this.messageListeners.put(type, listener); - logger.debug("{} is now listened by {}", type, listener); - } - - @Override - public void removeMessageListener(OFType type, IMessageListener listener) { - IMessageListener currentListener = this.messageListeners.get(type); - if ((currentListener != null) && (currentListener == listener)) { - logger.debug("{} listener {} is Removed", type, listener); - this.messageListeners.remove(type); - } - } - - @Override - public void addSwitchStateListener(ISwitchStateListener listener) { - if (this.switchStateListener != null) { - logger.warn("Switch events are already listened by {}", - this.switchStateListener); - } - this.switchStateListener = listener; - logger.debug("Switch events are now listened by {}", listener); - } - - @Override - public void removeSwitchStateListener(ISwitchStateListener listener) { - if ((this.switchStateListener != null) - && (this.switchStateListener == listener)) { - logger.debug("SwitchStateListener {} is Removed", listener); - this.switchStateListener = null; - } - } - - public void handleNewConnection(Selector selector, - SelectionKey serverSelectionKey) { - ServerSocketChannel ssc = (ServerSocketChannel) serverSelectionKey - .channel(); - SocketChannel sc = null; - try { - sc = ssc.accept(); - // create new switch - int i = this.switchInstanceNumber.addAndGet(1); - String instanceName = "SwitchHandler-" + i; - SwitchHandler switchHandler = new SwitchHandler(this, sc, instanceName); - switchHandler.start(); - if (sc.isConnected()) { - logger.info("Switch:{} is connected to the Controller", - sc.socket().getRemoteSocketAddress() - .toString().split("/")[1]); - } - - } catch (IOException e) { - return; - } - } - - private void disconnectSwitch(ISwitch sw) { - if (((SwitchHandler) sw).isOperational()) { - Long sid = sw.getId(); - if (this.switches.remove(sid, sw)) { - logger.info("{} is removed", sw); - notifySwitchDeleted(sw); - } - } - ((SwitchHandler) sw).stop(); - sw = null; - } - - private void notifySwitchAdded(ISwitch sw) { - if (switchStateListener != null) { - switchStateListener.switchAdded(sw); - } - } - - private void notifySwitchDeleted(ISwitch sw) { - if (switchStateListener != null) { - switchStateListener.switchDeleted(sw); - } - } - - private synchronized void addSwitchEvent(SwitchEvent event) { - this.switchEvents.put(event); - } - - public void takeSwitchEventAdd(ISwitch sw) { - SwitchEvent ev = new SwitchEvent(SwitchEvent.SwitchEventType.SWITCH_ADD, sw, null, - SwitchEventPriority.HIGH.ordinal()); - addSwitchEvent(ev); - } - - public void takeSwitchEventDelete(ISwitch sw) { - SwitchEvent ev = new SwitchEvent(SwitchEvent.SwitchEventType.SWITCH_DELETE, sw, null, - SwitchEventPriority.HIGH.ordinal()); - addSwitchEvent(ev); - } - - public void takeSwitchEventError(ISwitch sw) { - SwitchEvent ev = new SwitchEvent(SwitchEvent.SwitchEventType.SWITCH_ERROR, sw, null, - SwitchEventPriority.NORMAL.ordinal()); - addSwitchEvent(ev); - } - - public void takeSwitchEventMsg(ISwitch sw, OFMessage msg) { - if (messageListeners.get(msg.getType()) != null) { - SwitchEvent ev = new SwitchEvent(SwitchEvent.SwitchEventType.SWITCH_MESSAGE, sw, msg, - SwitchEventPriority.LOW.ordinal()); - addSwitchEvent(ev); - } - } - - @Override - public Map getSwitches() { - return this.switches; - } - - @Override - public ISwitch getSwitch(Long switchId) { - return this.switches.get(switchId); - } - - public void _controllerShowQueueSize(CommandInterpreter ci) { - ci.print("switchEvents queue size: " + switchEvents.size() + "\n"); - } - - public void _controllerShowSwitches(CommandInterpreter ci) { - Set sids = switches.keySet(); - StringBuffer s = new StringBuffer(); - int size = sids.size(); - if (size == 0) { - ci.print("switches: empty"); - return; - } - Iterator iter = sids.iterator(); - s.append("Total: " + size + " switches\n"); - while (iter.hasNext()) { - Long sid = iter.next(); - Date date = switches.get(sid).getConnectedDate(); - String switchInstanceName = ((SwitchHandler) switches.get(sid)) - .getInstanceName(); - s.append(switchInstanceName + "/" + HexString.toHexString(sid) - + " connected since " + date.toString() + "\n"); - } - ci.print(s.toString()); - return; - } - - public void _controllerReset(CommandInterpreter ci) { - ci.print("...Disconnecting the communication to all switches...\n"); - stop(); - try { - Thread.sleep(1000); - } catch (InterruptedException ie) { - } finally { - ci.print("...start to accept connections from switches...\n"); - start(); - } - } - - public void _controllerShowConnConfig(CommandInterpreter ci) { - String str = System.getProperty("secureChannelEnabled"); - if ((str != null) && (str.trim().equalsIgnoreCase("true"))) { - ci.print("The Controller and Switch should communicate through TLS connetion.\n"); - - String keyStoreFile = System.getProperty("controllerKeyStore"); - String trustStoreFile = System.getProperty("controllerTrustStore"); - if ((keyStoreFile == null) || keyStoreFile.trim().isEmpty()) { - ci.print("controllerKeyStore not specified\n"); - } else { - ci.print("controllerKeyStore=" + keyStoreFile + "\n"); - } - if ((trustStoreFile == null) || trustStoreFile.trim().isEmpty()) { - ci.print("controllerTrustStore not specified\n"); - } else { - ci.print("controllerTrustStore=" + trustStoreFile + "\n"); - } - } else { - ci.print("The Controller and Switch should communicate through TCP connetion.\n"); - } - } - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, - null); - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---Open Flow Controller---\n"); - help.append("\t controllerShowSwitches\n"); - help.append("\t controllerReset\n"); - help.append("\t controllerShowConnConfig\n"); - help.append("\t controllerShowQueueSize\n"); - return help.toString(); - } - - @Override - public Status disconnect(Node node) { - ISwitch sw = getSwitch((Long) node.getID()); - if (sw != null) disconnectSwitch(sw); - return new Status(StatusCode.SUCCESS); - } - - @Override - public Node connect(String connectionIdentifier, Map params) { - return null; - } - - /** - * View Change notification - */ - public void notifyClusterViewChanged() { - for (ISwitch sw : switches.values()) { - notifySwitchAdded(sw); - } - } - - /** - * Node Disconnected from the node's master controller. - */ - @Override - public void notifyNodeDisconnectFromMaster(Node node) { - ISwitch sw = switches.get((Long)node.getID()); - if (sw != null) notifySwitchAdded(sw); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/ControllerIO.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/ControllerIO.java deleted file mode 100644 index 47461f4722..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/ControllerIO.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core.internal; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.spi.SelectorProvider; -import java.util.Iterator; - -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ControllerIO { - private static final Logger logger = LoggerFactory - .getLogger(ControllerIO.class); - private static Short defaultOpenFlowPort = 6633; - private Short openFlowPort; - private InetAddress controllerIP; - private NetworkInterface netInt; - private SelectionKey serverSelectionKey; - private IController listener; - private ServerSocketChannel serverSocket; - private Selector selector; - private boolean running; - private Thread controllerIOThread; - - public ControllerIO(IController l) { - this.listener = l; - this.openFlowPort = defaultOpenFlowPort; - String portString = System.getProperty("of.listenPort"); - if (portString != null) { - try { - openFlowPort = Short.decode(portString).shortValue(); - } catch (NumberFormatException e) { - logger.warn("Invalid port:{}, use default({})", portString, - openFlowPort); - } - } - String addressString = System.getProperty("of.address"); - if (addressString != null) { - try { - controllerIP = InetAddress.getByName(addressString); - } catch (Exception e) { - controllerIP = null; - logger.warn("Invalid IP: {}, use wildcard *", addressString); - } - } else { - controllerIP = null; - } - } - - public void start() throws IOException { - this.running = true; - this.netInt = null; - controllerIOThread = new Thread(new Runnable() { - @Override - public void run() { - waitUntilInterfaceUp(); - if (!startAcceptConnections()) { - return; - } - logger.info("Controller is now listening on {}:{}", - (controllerIP == null) ? "any" : controllerIP.getHostAddress(), - openFlowPort); - boolean netInterfaceUp = true; - while (running) { - try { - // wait for an incoming connection - // check interface state every 5sec - selector.select(5000); - Iterator selectedKeys = selector - .selectedKeys().iterator(); - netInterfaceUp = isNetInterfaceUp(netInterfaceUp); - while (selectedKeys.hasNext()) { - SelectionKey skey = selectedKeys.next(); - selectedKeys.remove(); - if (skey.isValid() && skey.isAcceptable()) { - ((Controller) listener).handleNewConnection( - selector, serverSelectionKey); - } - } - } catch (Exception e) { - continue; - } - } - } - }, "ControllerI/O Thread"); - controllerIOThread.start(); - } - - private boolean startAcceptConnections() { - if (running) { - try { - // obtain a selector - selector = SelectorProvider.provider().openSelector(); - // create the listening socket - serverSocket = ServerSocketChannel.open(); - serverSocket.configureBlocking(false); - serverSocket.socket().bind( - new java.net.InetSocketAddress(controllerIP, - openFlowPort)); - serverSocket.socket().setReuseAddress(true); - // register this socket for accepting incoming - // connections - serverSelectionKey = serverSocket.register(selector, - SelectionKey.OP_ACCEPT); - } catch (IOException e) { - logger.error( - "Failed to listen on {}:{}, exit", - (controllerIP == null) ? "" : controllerIP - .getHostAddress(), openFlowPort); - return false; - } - return true; - } - return false; - } - - private boolean isNetInterfaceUp(boolean currentlyUp) { - if (controllerIP == null) { - // for wildcard address, return since there is always an "up" - // interface (such as loopback) - return true; - } - boolean up; - try { - if (netInt == null) { - logger.warn("Can't find any operational interface for address {}", - controllerIP.getHostAddress()); - return false; - } - up = netInt.isUp(); - if (!up) { - // always generate log if the interface is down - logger.warn("Interface {} with address {} is DOWN!", - netInt.getDisplayName(), - controllerIP.getHostAddress()); - } else { - if (!currentlyUp) { - // only generate log if the interface changes from down to up - logger.trace("Interface {} with address {} is UP!", - netInt.getDisplayName(), - controllerIP.getHostAddress()); - } - } - } catch (SocketException e) { - logger.warn("Interface {} with address {} is DOWN!", - netInt.getDisplayName(), - controllerIP.getHostAddress()); - up = false; - } - return up; - } - - private void waitUntilInterfaceUp() { - if (controllerIP == null) { - // for wildcard address, return since there is always an "up" - // interface (such as loopback) - return; - } - boolean isUp = false; - do { - try { - // get the network interface from the address - netInt = NetworkInterface.getByInetAddress(controllerIP); - isUp = isNetInterfaceUp(isUp); - if (!isUp) { - Thread.sleep(5000); - } - } catch (Exception e) { - } - } while ((!isUp) && (running)); - } - public void shutDown() throws IOException { - this.running = false; - this.selector.wakeup(); - this.serverSocket.close(); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/MessageReadWriteService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/MessageReadWriteService.java deleted file mode 100644 index 9041004605..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/MessageReadWriteService.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core.internal; - -import java.nio.ByteBuffer; -import java.nio.channels.AsynchronousCloseException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.SocketChannel; -import java.util.List; - -import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageReadWrite; -import org.openflow.protocol.OFMessage; -import org.openflow.protocol.factory.BasicFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class implements methods to read/write messages over an established - * socket channel. The data exchange is in clear text format. - */ -public class MessageReadWriteService implements IMessageReadWrite { - private static final Logger logger = LoggerFactory - .getLogger(MessageReadWriteService.class); - private static final int bufferSize = 1024 * 1024; - - private Selector selector; - private SelectionKey clientSelectionKey; - private SocketChannel socket; - private ByteBuffer inBuffer; - private ByteBuffer outBuffer; - private BasicFactory factory; - - public MessageReadWriteService(SocketChannel socket, Selector selector) - throws ClosedChannelException { - this.socket = socket; - this.selector = selector; - this.factory = new BasicFactory(); - this.inBuffer = ByteBuffer.allocateDirect(bufferSize); - this.outBuffer = ByteBuffer.allocateDirect(bufferSize); - this.clientSelectionKey = this.socket.register(this.selector, - SelectionKey.OP_READ); - } - - /** - * Sends the OF message out over the socket channel. - * - * @param msg - * OF message to be sent - * @throws Exception - */ - @Override - public void asyncSend(OFMessage msg) throws Exception { - synchronized (outBuffer) { - int msgLen = msg.getLengthU(); - if (outBuffer.remaining() < msgLen) { - // increase the buffer size so that it can contain this message - ByteBuffer newBuffer = ByteBuffer.allocateDirect(outBuffer - .capacity() + msgLen); - outBuffer.flip(); - newBuffer.put(outBuffer); - outBuffer = newBuffer; - } - } - synchronized (outBuffer) { - msg.writeTo(outBuffer); - - if (!socket.isOpen()) { - return; - } - - outBuffer.flip(); - socket.write(outBuffer); - outBuffer.compact(); - if (outBuffer.position() > 0) { - this.clientSelectionKey = this.socket.register(this.selector, - SelectionKey.OP_WRITE, this); - } - logger.trace("Message sent: {}", msg); - } - } - - /** - * Resumes sending the remaining messages in the outgoing buffer - * - * @throws Exception - */ - @Override - public void resumeSend() throws Exception { - synchronized (outBuffer) { - if (!socket.isOpen()) { - return; - } - - outBuffer.flip(); - socket.write(outBuffer); - outBuffer.compact(); - if (outBuffer.position() > 0) { - this.clientSelectionKey = this.socket.register(this.selector, - SelectionKey.OP_WRITE, this); - } else { - this.clientSelectionKey = this.socket.register(this.selector, - SelectionKey.OP_READ, this); - } - } - } - - /** - * Reads the incoming network data from the socket and retrieves the OF - * messages. - * - * @return list of OF messages - * @throws Exception - */ - @Override - public List readMessages() throws Exception { - if (!socket.isOpen()) { - return null; - } - - List msgs = null; - int bytesRead = -1; - bytesRead = socket.read(inBuffer); - if (bytesRead < 0) { - throw new AsynchronousCloseException(); - } - - try { - inBuffer.flip(); - msgs = factory.parseMessages(inBuffer); - if (inBuffer.hasRemaining()) { - inBuffer.compact(); - } else { - inBuffer.clear(); - } - } catch (Exception e) { - inBuffer.clear(); - logger.debug("Caught exception: ", e); - } - return msgs; - } - - @Override - public void stop() { - inBuffer = null; - outBuffer = null; - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/PriorityMessage.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/PriorityMessage.java deleted file mode 100644 index 7893ae0acc..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/PriorityMessage.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core.internal; - -import java.util.concurrent.atomic.AtomicLong; - -import org.openflow.protocol.OFMessage; - -/** - * This class describes an OpenFlow message with priority - */ -class PriorityMessage { - OFMessage msg; - int priority; - final static AtomicLong seq = new AtomicLong(); - final long seqNum; - boolean syncReply; // set to true if we want to be blocked until the response arrives - - public PriorityMessage(OFMessage msg, int priority) { - this.msg = msg; - this.priority = priority; - this.seqNum = seq.getAndIncrement(); - this.syncReply = false; - } - - public PriorityMessage(OFMessage msg, int priority, boolean syncReply) { - this(msg, priority); - this.syncReply = syncReply; - } - - public OFMessage getMsg() { - return msg; - } - - public void setMsg(OFMessage msg) { - this.msg = msg; - } - - public int getPriority() { - return priority; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((msg == null) ? 0 : msg.hashCode()); - result = prime * result + priority; - result = prime * result + (int) (seqNum ^ (seqNum >>> 32)); - result = prime * result + (syncReply ? 1231 : 1237); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - PriorityMessage other = (PriorityMessage) obj; - if (msg == null) { - if (other.msg != null) - return false; - } else if (!msg.equals(other.msg)) - return false; - if (priority != other.priority) - return false; - if (seqNum != other.seqNum) - return false; - if (syncReply != other.syncReply) - return false; - return true; - } - - @Override - public String toString() { - return "PriorityMessage [msg=" + msg + ", priority=" + priority - + ", seqNum=" + seqNum + ", syncReply=" + syncReply + "]"; - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SecureMessageReadWriteService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SecureMessageReadWriteService.java deleted file mode 100644 index f27d30eaae..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SecureMessageReadWriteService.java +++ /dev/null @@ -1,451 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core.internal; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.AsynchronousCloseException; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.SocketChannel; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.util.List; - -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLEngineResult; -import javax.net.ssl.SSLEngineResult.HandshakeStatus; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManagerFactory; - -import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageReadWrite; -import org.openflow.protocol.OFMessage; -import org.openflow.protocol.factory.BasicFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class implements methods to read/write messages over an established - * socket channel. The data exchange is encrypted/decrypted by SSLEngine. - */ -public class SecureMessageReadWriteService implements IMessageReadWrite { - private static final Logger logger = LoggerFactory - .getLogger(SecureMessageReadWriteService.class); - - private Selector selector; - private SocketChannel socket; - private BasicFactory factory; - - private SSLEngine sslEngine; - private SSLEngineResult sslEngineResult; // results from sslEngine last operation - private ByteBuffer myAppData; // clear text message to be sent - private ByteBuffer myNetData; // encrypted message to be sent - private ByteBuffer peerAppData; // clear text message received from the - // switch - private ByteBuffer peerNetData; // encrypted message from the switch - private FileInputStream kfd = null, tfd = null; - private final String keyStoreFileDefault = "./configuration/tlsKeyStore"; - private final String trustStoreFileDefault = "./configuration/tlsTrustStore"; - private final String keyStorePasswordPropName = "controllerKeyStorePassword"; - private final String trustStorePasswordPropName = "controllerTrustStorePassword"; - private static String keyStorePassword = null; - private static String trustStorePassword = null; - - public SecureMessageReadWriteService(SocketChannel socket, Selector selector) - throws Exception { - this.socket = socket; - this.selector = selector; - this.factory = new BasicFactory(); - - try { - createSecureChannel(socket); - createBuffers(sslEngine); - } catch (Exception e) { - logger.warn("Failed to setup TLS connection {} {}", socket, e); - stop(); - throw e; - } - } - - /** - * Bring up secure channel using SSL Engine - * - * @param socket - * TCP socket channel - * @throws Exception - */ - private void createSecureChannel(SocketChannel socket) throws Exception { - String keyStoreFile = System.getProperty("controllerKeyStore"); - String trustStoreFile = System.getProperty("controllerTrustStore"); - String keyStorePasswordProp = System.getProperty(keyStorePasswordPropName); - String trustStorePasswordProp = System.getProperty(trustStorePasswordPropName); - - if (keyStoreFile != null) { - keyStoreFile = keyStoreFile.trim(); - } else { - keyStoreFile = keyStoreFileDefault; - } - if ((keyStoreFile == null) || keyStoreFile.isEmpty()) { - throw new FileNotFoundException("TLS KeyStore file not found."); - } - - if ((keyStorePassword == null) || ((keyStorePasswordProp != null) && !keyStorePasswordProp.isEmpty())) { - keyStorePassword = keyStorePasswordProp; - } - if (keyStorePassword != null) { - keyStorePassword = keyStorePassword.trim(); - System.setProperty(keyStorePasswordPropName, ""); - } - if ((keyStorePassword == null) || keyStorePassword.isEmpty()) { - throw new FileNotFoundException("TLS KeyStore Password not provided."); - } - if (trustStoreFile != null) { - trustStoreFile = trustStoreFile.trim(); - } else { - trustStoreFile = trustStoreFileDefault; - } - if ((trustStoreFile == null) || trustStoreFile.isEmpty()) { - throw new FileNotFoundException("TLS TrustStore file not found"); - } - - if ((trustStorePassword == null) || ((trustStorePasswordProp != null) && !trustStorePasswordProp.isEmpty())) { - trustStorePassword = trustStorePasswordProp; - } - if (trustStorePassword != null) { - trustStorePassword = trustStorePassword.trim(); - System.setProperty(trustStorePasswordPropName, ""); - } - if ((trustStorePassword == null) || trustStorePassword.isEmpty()) { - throw new FileNotFoundException("TLS TrustStore Password not provided."); - } - - KeyStore ks = KeyStore.getInstance("JKS"); - KeyStore ts = KeyStore.getInstance("JKS"); - KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - kfd = new FileInputStream(keyStoreFile); - tfd = new FileInputStream(trustStoreFile); - ks.load(kfd, keyStorePassword.toCharArray()); - ts.load(tfd, trustStorePassword.toCharArray()); - kmf.init(ks, keyStorePassword.toCharArray()); - tmf.init(ts); - - SecureRandom random = new SecureRandom(); - random.nextInt(); - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), random); - sslEngine = sslContext.createSSLEngine(); - sslEngine.setUseClientMode(false); - sslEngine.setNeedClientAuth(true); - sslEngine.setEnabledCipherSuites(new String[] { - "SSL_RSA_WITH_RC4_128_MD5", - "SSL_RSA_WITH_RC4_128_SHA", - "TLS_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_RSA_WITH_AES_128_CBC_SHA", - "TLS_DHE_DSS_WITH_AES_128_CBC_SHA", - "SSL_RSA_WITH_3DES_EDE_CBC_SHA", - "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", - "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA", - "SSL_RSA_WITH_DES_CBC_SHA", - "SSL_DHE_RSA_WITH_DES_CBC_SHA", - "SSL_DHE_DSS_WITH_DES_CBC_SHA", - "SSL_RSA_EXPORT_WITH_RC4_40_MD5", - "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", - "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"}); - - // Do initial handshake - doHandshake(socket, sslEngine); - - this.socket.register(this.selector, SelectionKey.OP_READ); - } - - /** - * Sends the OF message out over the socket channel. The message is - * encrypted by SSL Engine. - * - * @param msg - * OF message to be sent - * @throws Exception - */ - @Override - public void asyncSend(OFMessage msg) throws Exception { - synchronized (myAppData) { - int msgLen = msg.getLengthU(); - if (myAppData.remaining() < msgLen) { - // increase the buffer size so that it can contain this message - ByteBuffer newBuffer = ByteBuffer.allocateDirect(myAppData - .capacity() + msgLen); - myAppData.flip(); - newBuffer.put(myAppData); - myAppData = newBuffer; - } - } - synchronized (myAppData) { - msg.writeTo(myAppData); - myAppData.flip(); - sslEngineResult = sslEngine.wrap(myAppData, myNetData); - logger.trace("asyncSend sslEngine wrap: {}", sslEngineResult); - runDelegatedTasks(sslEngineResult, sslEngine); - - if (!socket.isOpen()) { - return; - } - - myNetData.flip(); - socket.write(myNetData); - if (myNetData.hasRemaining()) { - myNetData.compact(); - } else { - myNetData.clear(); - } - - if (myAppData.hasRemaining()) { - myAppData.compact(); - this.socket.register(this.selector, SelectionKey.OP_WRITE, this); - } else { - myAppData.clear(); - this.socket.register(this.selector, SelectionKey.OP_READ, this); - } - - logger.trace("Message sent: {}", msg); - } - } - - /** - * Resumes sending the remaining messages in the outgoing buffer - * - * @throws Exception - */ - @Override - public void resumeSend() throws Exception { - synchronized (myAppData) { - myAppData.flip(); - sslEngineResult = sslEngine.wrap(myAppData, myNetData); - logger.trace("resumeSend sslEngine wrap: {}", sslEngineResult); - runDelegatedTasks(sslEngineResult, sslEngine); - - if (!socket.isOpen()) { - return; - } - - myNetData.flip(); - socket.write(myNetData); - if (myNetData.hasRemaining()) { - myNetData.compact(); - } else { - myNetData.clear(); - } - - if (myAppData.hasRemaining()) { - myAppData.compact(); - this.socket.register(this.selector, SelectionKey.OP_WRITE, this); - } else { - myAppData.clear(); - this.socket.register(this.selector, SelectionKey.OP_READ, this); - } - } - } - - /** - * Reads the incoming network data from the socket, decryptes them and then - * retrieves the OF messages. - * - * @return list of OF messages - * @throws Exception - */ - @Override - public List readMessages() throws Exception { - if (!socket.isOpen()) { - return null; - } - - List msgs = null; - int bytesRead = -1; - int countDown = 50; - - bytesRead = socket.read(peerNetData); - if (bytesRead < 0) { - logger.debug("Message read operation failed"); - throw new AsynchronousCloseException(); - } - - do { - peerNetData.flip(); - sslEngineResult = sslEngine.unwrap(peerNetData, peerAppData); - if (peerNetData.hasRemaining()) { - peerNetData.compact(); - } else { - peerNetData.clear(); - } - logger.trace("sslEngine unwrap result: {}", sslEngineResult); - runDelegatedTasks(sslEngineResult, sslEngine); - } while ((sslEngineResult.getStatus() == SSLEngineResult.Status.OK) - && peerNetData.hasRemaining() && (--countDown > 0)); - - if (countDown == 0) { - logger.trace("countDown reaches 0. peerNetData pos {} lim {}", - peerNetData.position(), peerNetData.limit()); - } - - try { - peerAppData.flip(); - msgs = factory.parseMessages(peerAppData); - if (peerAppData.hasRemaining()) { - peerAppData.compact(); - } else { - peerAppData.clear(); - } - } catch (Exception e) { - peerAppData.clear(); - logger.debug("Caught exception: ", e); - } - - this.socket.register(this.selector, SelectionKey.OP_READ, this); - - return msgs; - } - - /** - * If the result indicates that we have outstanding tasks to do, go ahead - * and run them in this thread. - */ - private void runDelegatedTasks(SSLEngineResult result, SSLEngine engine) - throws Exception { - - if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - logger.debug("\trunning delegated task..."); - runnable.run(); - } - HandshakeStatus hsStatus = engine.getHandshakeStatus(); - if (hsStatus == HandshakeStatus.NEED_TASK) { - throw new Exception("handshake shouldn't need additional tasks"); - } - logger.debug("\tnew HandshakeStatus: {}", hsStatus); - } - } - - private void doHandshake(SocketChannel socket, SSLEngine engine) - throws Exception { - SSLSession session = engine.getSession(); - ByteBuffer myAppData = ByteBuffer.allocate(session - .getApplicationBufferSize()); - ByteBuffer peerAppData = ByteBuffer.allocate(session - .getApplicationBufferSize()); - ByteBuffer myNetData = ByteBuffer.allocate(session - .getPacketBufferSize()); - ByteBuffer peerNetData = ByteBuffer.allocate(session - .getPacketBufferSize()); - - // Begin handshake - engine.beginHandshake(); - SSLEngineResult.HandshakeStatus hs = engine.getHandshakeStatus(); - - // Process handshaking message - while (hs != SSLEngineResult.HandshakeStatus.FINISHED - && hs != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { - switch (hs) { - case NEED_UNWRAP: - // Receive handshaking data from peer - if (socket.read(peerNetData) < 0) { - throw new AsynchronousCloseException(); - } - - // Process incoming handshaking data - peerNetData.flip(); - SSLEngineResult res = engine.unwrap(peerNetData, peerAppData); - peerNetData.compact(); - hs = res.getHandshakeStatus(); - - // Check status - switch (res.getStatus()) { - case OK: - // Handle OK status - break; - } - break; - - case NEED_WRAP: - // Empty the local network packet buffer. - myNetData.clear(); - - // Generate handshaking data - res = engine.wrap(myAppData, myNetData); - hs = res.getHandshakeStatus(); - - // Check status - switch (res.getStatus()) { - case OK: - myNetData.flip(); - - // Send the handshaking data to peer - while (myNetData.hasRemaining()) { - if (socket.write(myNetData) < 0) { - throw new AsynchronousCloseException(); - } - } - break; - } - break; - - case NEED_TASK: - // Handle blocking tasks - Runnable runnable; - while ((runnable = engine.getDelegatedTask()) != null) { - logger.debug("\trunning delegated task..."); - runnable.run(); - } - hs = engine.getHandshakeStatus(); - if (hs == HandshakeStatus.NEED_TASK) { - throw new Exception( - "handshake shouldn't need additional tasks"); - } - logger.debug("\tnew HandshakeStatus: {}", hs); - break; - } - } - } - - private void createBuffers(SSLEngine engine) { - SSLSession session = engine.getSession(); - this.myAppData = ByteBuffer - .allocate(session.getApplicationBufferSize()); - this.peerAppData = ByteBuffer.allocate(session - .getApplicationBufferSize() * 20); - this.myNetData = ByteBuffer.allocate(session.getPacketBufferSize()); - this.peerNetData = ByteBuffer.allocate(session.getPacketBufferSize() * 20); - } - - @Override - public void stop() throws IOException { - this.sslEngine = null; - this.sslEngineResult = null; - this.myAppData = null; - this.myNetData = null; - this.peerAppData = null; - this.peerNetData = null; - - if (this.kfd != null) { - this.kfd.close(); - this.kfd = null; - } - if (this.tfd != null) { - this.tfd.close(); - this.tfd = null; - } - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/StatisticsCollector.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/StatisticsCollector.java deleted file mode 100644 index 0eaecc5c56..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/StatisticsCollector.java +++ /dev/null @@ -1,82 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core.internal; - -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CountDownLatch; - -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.openflow.protocol.OFError; -import org.openflow.protocol.OFStatisticsReply; -import org.openflow.protocol.OFStatisticsRequest; -import org.openflow.protocol.statistics.OFStatistics; - -public class StatisticsCollector implements Callable { - - private ISwitch sw; - private Integer xid; - private OFStatisticsRequest request; - private CountDownLatch latch; - private Object result; - private List stats; - - public StatisticsCollector(ISwitch sw, int xid, OFStatisticsRequest request) { - this.sw = sw; - this.xid = xid; - this.request = request; - latch = new CountDownLatch(1); - result = new Object(); - stats = new CopyOnWriteArrayList(); - } - - /* - * accumulate the stats records in result - * Returns: true: if this is the last record - * false: more to come - */ - public boolean collect(OFStatisticsReply reply) { - synchronized (result) { - stats.addAll(reply.getStatistics()); - if ((reply.getFlags() & 0x01) == 0) { - // all stats are collected, done - result = stats; - return true; - } else { - // still waiting for more to come - return false; - } - } - } - - @Override - public Object call() throws Exception { - sw.asyncSend(request, xid); - // free up the request as it is no longer needed - request = null; - // wait until all stats replies are received or timeout - latch.await(); - return result; - } - - public Integer getXid() { - return this.xid; - } - - public void wakeup() { - this.latch.countDown(); - } - - public void wakeup(OFError errorMsg) { - result = errorMsg; - wakeup(); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchEvent.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchEvent.java deleted file mode 100644 index 785be9be09..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchEvent.java +++ /dev/null @@ -1,74 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core.internal; - -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.openflow.protocol.OFMessage; - -public class SwitchEvent { - - public static enum SwitchEventType { - SWITCH_ADD, SWITCH_DELETE, SWITCH_ERROR, SWITCH_MESSAGE, - } - - private SwitchEventType eventType; - private ISwitch sw; - private OFMessage msg; - private int priority; - - public SwitchEvent(SwitchEventType type, ISwitch sw, OFMessage msg, int priority) { - this.eventType = type; - this.sw = sw; - this.msg = msg; - this.priority = priority; - } - - public SwitchEventType getEventType() { - return this.eventType; - } - - public ISwitch getSwitch() { - return this.sw; - } - - public OFMessage getMsg() { - return this.msg; - } - - public int getPriority() { - return priority; - } - - public void setPriority(int priority) { - this.priority = priority; - } - - @Override - public String toString() { - String s; - switch (this.eventType) { - case SWITCH_ADD: - s = "SWITCH_ADD"; - break; - case SWITCH_DELETE: - s = "SWITCH_DELETE"; - break; - case SWITCH_ERROR: - s = "SWITCH_ERROR"; - break; - case SWITCH_MESSAGE: - s = "SWITCH_MESSAGE"; - break; - default: - s = "?" + this.eventType.ordinal() + "?"; - } - return "Switch Event: " + s; - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchHandler.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchHandler.java deleted file mode 100644 index 7a177fa078..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SwitchHandler.java +++ /dev/null @@ -1,949 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core.internal; - -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.SocketChannel; -import java.nio.channels.spi.SelectorProvider; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -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 java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.PriorityBlockingQueue; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageReadWrite; -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.openflow.protocol.OFBarrierReply; -import org.openflow.protocol.OFBarrierRequest; -import org.openflow.protocol.OFEchoReply; -import org.openflow.protocol.OFEchoRequest; -import org.openflow.protocol.OFError; -import org.openflow.protocol.OFFeaturesReply; -import org.openflow.protocol.OFFlowMod; -import org.openflow.protocol.OFGetConfigReply; -import org.openflow.protocol.OFMatch; -import org.openflow.protocol.OFMessage; -import org.openflow.protocol.OFPhysicalPort; -import org.openflow.protocol.OFPhysicalPort.OFPortConfig; -import org.openflow.protocol.OFPhysicalPort.OFPortFeatures; -import org.openflow.protocol.OFPhysicalPort.OFPortState; -import org.openflow.protocol.OFPort; -import org.openflow.protocol.OFPortStatus; -import org.openflow.protocol.OFPortStatus.OFPortReason; -import org.openflow.protocol.OFSetConfig; -import org.openflow.protocol.OFStatisticsReply; -import org.openflow.protocol.OFStatisticsRequest; -import org.openflow.protocol.OFType; -import org.openflow.protocol.factory.BasicFactory; -import org.openflow.util.HexString; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class SwitchHandler implements ISwitch { - private static final Logger logger = LoggerFactory.getLogger(SwitchHandler.class); - private static final int SWITCH_LIVENESS_TIMER = 5000; - private static final int switchLivenessTimeout = getSwitchLivenessTimeout(); - private final int MESSAGE_RESPONSE_TIMER = 2000; - - private final String instanceName; - private final ISwitch thisISwitch; - private final IController core; - private Long sid; - private Integer buffers; - private Integer capabilities; - private Byte tables; - private Integer actions; - private Selector selector; - private final SocketChannel socket; - private final BasicFactory factory; - private final AtomicInteger xid; - private SwitchState state; - private Timer periodicTimer; - private final Map physicalPorts; - private final Map portBandwidth; - private final Date connectedDate; - private Long lastMsgReceivedTimeStamp; - private Boolean probeSent; - private final ExecutorService executor; - private final ConcurrentHashMap> messageWaitingDone; - private boolean running; - private IMessageReadWrite msgReadWriteService; - private Thread switchHandlerThread; - private Integer responseTimerValue; - private PriorityBlockingQueue transmitQ; - private Thread transmitThread; - - private enum SwitchState { - NON_OPERATIONAL(0), WAIT_FEATURES_REPLY(1), WAIT_CONFIG_REPLY(2), OPERATIONAL(3); - - private int value; - - private SwitchState(int value) { - this.value = value; - } - - @SuppressWarnings("unused") - public int value() { - return this.value; - } - } - - public SwitchHandler(Controller core, SocketChannel sc, String name) { - this.instanceName = name; - this.thisISwitch = this; - this.sid = (long) 0; - this.buffers = (int) 0; - this.capabilities = (int) 0; - this.tables = (byte) 0; - this.actions = (int) 0; - this.core = core; - this.socket = sc; - this.factory = new BasicFactory(); - this.connectedDate = new Date(); - this.lastMsgReceivedTimeStamp = connectedDate.getTime(); - this.physicalPorts = new HashMap(); - this.portBandwidth = new HashMap(); - this.state = SwitchState.NON_OPERATIONAL; - this.probeSent = false; - this.xid = new AtomicInteger(this.socket.hashCode()); - this.periodicTimer = null; - this.executor = Executors.newFixedThreadPool(4); - this.messageWaitingDone = new ConcurrentHashMap>(); - this.responseTimerValue = MESSAGE_RESPONSE_TIMER; - String rTimer = System.getProperty("of.messageResponseTimer"); - if (rTimer != null) { - try { - responseTimerValue = Integer.decode(rTimer); - } catch (NumberFormatException e) { - logger.warn("Invalid of.messageResponseTimer: {} use default({})", rTimer, MESSAGE_RESPONSE_TIMER); - } - } - } - - public void start() { - try { - startTransmitThread(); - setupCommChannel(); - sendFirstHello(); - startHandlerThread(); - } catch (Exception e) { - reportError(e); - } - } - - private void startHandlerThread() { - switchHandlerThread = new Thread(new Runnable() { - @Override - public void run() { - running = true; - while (running) { - try { - // wait for an incoming connection - selector.select(0); - Iterator selectedKeys = selector.selectedKeys().iterator(); - while (selectedKeys.hasNext()) { - SelectionKey skey = selectedKeys.next(); - selectedKeys.remove(); - if (skey.isValid() && skey.isWritable()) { - resumeSend(); - } - if (skey.isValid() && skey.isReadable()) { - handleMessages(); - } - } - } catch (Exception e) { - reportError(e); - } - } - } - }, instanceName); - switchHandlerThread.start(); - } - - private void stopInternal() { - logger.debug("{} receives stop signal", - (isOperational() ? HexString.toHexString(sid) : "unknown")); - running = false; - cancelSwitchTimer(); - try { - selector.wakeup(); - selector.close(); - } catch (Exception e) { - } - try { - socket.close(); - } catch (Exception e) { - } - try { - msgReadWriteService.stop(); - } catch (Exception e) { - } - logger.debug("executor shutdown now"); - executor.shutdownNow(); - - msgReadWriteService = null; - } - - public void stop() { - stopInternal(); - - if (switchHandlerThread != null) { - switchHandlerThread.interrupt(); - } - if (transmitThread != null) { - transmitThread.interrupt(); - } - } - - @Override - public int getNextXid() { - return this.xid.incrementAndGet(); - } - - /** - * This method puts the message in an outgoing priority queue with normal - * priority. It will be served after high priority messages. The method - * should be used for non-critical messages such as statistics request, - * discovery packets, etc. An unique XID is generated automatically and - * inserted into the message. - * - * @param msg - * The OF message to be sent - * @return The XID used - */ - @Override - public Integer asyncSend(OFMessage msg) { - return asyncSend(msg, getNextXid()); - } - - private Object syncSend(OFMessage msg, int xid) { - return syncMessageInternal(msg, xid, true); - } - - /** - * This method puts the message in an outgoing priority queue with normal - * priority. It will be served after high priority messages. The method - * should be used for non-critical messages such as statistics request, - * discovery packets, etc. The specified XID is inserted into the message. - * - * @param msg - * The OF message to be Sent - * @param xid - * The XID to be used in the message - * @return The XID used - */ - @Override - public Integer asyncSend(OFMessage msg, int xid) { - msg.setXid(xid); - if (transmitQ != null) { - transmitQ.add(new PriorityMessage(msg, 0)); - } - return xid; - } - - /** - * This method puts the message in an outgoing priority queue with high - * priority. It will be served first before normal priority messages. The - * method should be used for critical messages such as hello, echo reply - * etc. An unique XID is generated automatically and inserted into the - * message. - * - * @param msg - * The OF message to be sent - * @return The XID used - */ - @Override - public Integer asyncFastSend(OFMessage msg) { - return asyncFastSend(msg, getNextXid()); - } - - /** - * This method puts the message in an outgoing priority queue with high - * priority. It will be served first before normal priority messages. The - * method should be used for critical messages such as hello, echo reply - * etc. The specified XID is inserted into the message. - * - * @param msg - * The OF message to be sent - * @return The XID used - */ - @Override - public Integer asyncFastSend(OFMessage msg, int xid) { - msg.setXid(xid); - if (transmitQ != null) { - transmitQ.add(new PriorityMessage(msg, 1)); - } - return xid; - } - - public void resumeSend() { - try { - if (msgReadWriteService != null) { - msgReadWriteService.resumeSend(); - } - } catch (Exception e) { - reportError(e); - } - } - - /** - * This method bypasses the transmit queue and sends the message over the - * socket directly. If the input xid is not null, the specified xid is - * inserted into the message. Otherwise, an unique xid is generated - * automatically and inserted into the message. - * - * @param msg - * Message to be sent - * @param xid - * Message xid - */ - private void asyncSendNow(OFMessage msg, Integer xid) { - if (xid == null) { - xid = getNextXid(); - } - msg.setXid(xid); - - asyncSendNow(msg); - } - - /** - * This method bypasses the transmit queue and sends the message over the - * socket directly. - * - * @param msg - * Message to be sent - */ - private void asyncSendNow(OFMessage msg) { - if (msgReadWriteService == null) { - logger.warn("asyncSendNow: {} is not sent because Message ReadWrite Service is not available.", msg); - return; - } - - try { - msgReadWriteService.asyncSend(msg); - } catch (Exception e) { - reportError(e); - } - } - - public void handleMessages() { - List msgs = null; - - try { - if (msgReadWriteService != null) { - msgs = msgReadWriteService.readMessages(); - } - } catch (Exception e) { - reportError(e); - } - - if (msgs == null) { - return; - } - for (OFMessage msg : msgs) { - logger.trace("Message received: {}", msg); - this.lastMsgReceivedTimeStamp = System.currentTimeMillis(); - OFType type = msg.getType(); - switch (type) { - case HELLO: - sendFeaturesRequest(); - break; - case ECHO_REQUEST: - OFEchoReply echoReply = (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY); - - byte []payload = ((OFEchoRequest)msg).getPayload(); - if (payload != null && payload.length != 0 ) { - // the response must have the same payload as the request - echoReply.setPayload(payload); - echoReply.setLength( (short)(echoReply.getLength() + payload.length) ); - } - - // respond immediately - asyncSendNow(echoReply, msg.getXid()); - - // send features request if not sent yet - sendFeaturesRequest(); - break; - case ECHO_REPLY: - this.probeSent = false; - break; - case FEATURES_REPLY: - processFeaturesReply((OFFeaturesReply) msg); - break; - case GET_CONFIG_REPLY: - // make sure that the switch can send the whole packet to the - // controller - if (((OFGetConfigReply) msg).getMissSendLength() == (short) 0xffff) { - this.state = SwitchState.OPERATIONAL; - } - break; - case BARRIER_REPLY: - processBarrierReply((OFBarrierReply) msg); - break; - case ERROR: - processErrorReply((OFError) msg); - break; - case PORT_STATUS: - processPortStatusMsg((OFPortStatus) msg); - break; - case STATS_REPLY: - processStatsReply((OFStatisticsReply) msg); - break; - case PACKET_IN: - break; - default: - break; - } // end of switch - if (isOperational()) { - ((Controller) core).takeSwitchEventMsg(thisISwitch, msg); - } - } // end of for - } - - private void processPortStatusMsg(OFPortStatus msg) { - OFPhysicalPort port = msg.getDesc(); - if (msg.getReason() == (byte) OFPortReason.OFPPR_MODIFY.ordinal()) { - updatePhysicalPort(port); - } else if (msg.getReason() == (byte) OFPortReason.OFPPR_ADD.ordinal()) { - updatePhysicalPort(port); - } else if (msg.getReason() == (byte) OFPortReason.OFPPR_DELETE.ordinal()) { - deletePhysicalPort(port); - } - - } - - private void startSwitchTimer() { - this.periodicTimer = new Timer(); - this.periodicTimer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - try { - Long now = System.currentTimeMillis(); - if ((now - lastMsgReceivedTimeStamp) > switchLivenessTimeout) { - if (probeSent) { - // switch failed to respond to our probe, consider - // it down - logger.warn("{} sid {} is idle for too long, disconnect", socket.socket() - .getRemoteSocketAddress().toString().split("/")[1], (sid == 0) ? "unknown" - : HexString.toHexString(sid)); - reportSwitchStateChange(false); - } else { - // send a probe to see if the switch is still alive - logger.debug("Send idle probe (Echo Request) to {}", this); - probeSent = true; - OFMessage echo = factory.getMessage(OFType.ECHO_REQUEST); - asyncFastSend(echo); - } - } else { - if (state == SwitchState.WAIT_FEATURES_REPLY) { - // send another features request - OFMessage request = factory.getMessage(OFType.FEATURES_REQUEST); - asyncFastSend(request); - } else { - if (state == SwitchState.WAIT_CONFIG_REPLY) { - // send another config request - OFSetConfig config = (OFSetConfig) factory.getMessage(OFType.SET_CONFIG); - config.setMissSendLength((short) 0xffff).setLengthU(OFSetConfig.MINIMUM_LENGTH); - asyncFastSend(config); - OFMessage getConfig = factory.getMessage(OFType.GET_CONFIG_REQUEST); - asyncFastSend(getConfig); - } - } - } - } catch (Exception e) { - reportError(e); - } - } - }, SWITCH_LIVENESS_TIMER, SWITCH_LIVENESS_TIMER); - } - - private void cancelSwitchTimer() { - if (this.periodicTimer != null) { - this.periodicTimer.cancel(); - } - } - - private void reportError(Exception e) { - if (!running) { - logger.debug("Caught exception {} while switch {} is shutting down. Skip", e.getMessage(), - (isOperational() ? HexString.toHexString(sid) : "unknown")); - return; - } - logger.debug("Caught exception: ", e); - - // notify core of this error event and disconnect the switch - ((Controller) core).takeSwitchEventError(this); - - // clean up some internal states immediately - stopInternal(); - } - - private void reportSwitchStateChange(boolean added) { - if (added) { - ((Controller) core).takeSwitchEventAdd(this); - } else { - ((Controller) core).takeSwitchEventDelete(this); - } - } - - @Override - public Long getId() { - return this.sid; - } - - private void sendFeaturesRequest() { - if (!isOperational() && (this.state != SwitchState.WAIT_FEATURES_REPLY)) { - // send feature request - OFMessage featureRequest = factory.getMessage(OFType.FEATURES_REQUEST); - asyncFastSend(featureRequest); - this.state = SwitchState.WAIT_FEATURES_REPLY; - startSwitchTimer(); - } - } - - private void processFeaturesReply(OFFeaturesReply reply) { - if (this.state == SwitchState.WAIT_FEATURES_REPLY) { - this.sid = reply.getDatapathId(); - this.buffers = reply.getBuffers(); - this.capabilities = reply.getCapabilities(); - this.tables = reply.getTables(); - this.actions = reply.getActions(); - // notify core of this error event - for (OFPhysicalPort port : reply.getPorts()) { - updatePhysicalPort(port); - } - // config the switch to send full data packet - OFSetConfig config = (OFSetConfig) factory.getMessage(OFType.SET_CONFIG); - config.setMissSendLength((short) 0xffff).setLengthU(OFSetConfig.MINIMUM_LENGTH); - asyncFastSend(config); - // send config request to make sure the switch can handle the set - // config - OFMessage getConfig = factory.getMessage(OFType.GET_CONFIG_REQUEST); - asyncFastSend(getConfig); - this.state = SwitchState.WAIT_CONFIG_REPLY; - // inform core that a new switch is now operational - reportSwitchStateChange(true); - } - } - - private void updatePhysicalPort(OFPhysicalPort port) { - Short portNumber = port.getPortNumber(); - physicalPorts.put(portNumber, port); - portBandwidth - .put(portNumber, - port.getCurrentFeatures() - & (OFPortFeatures.OFPPF_10MB_FD.getValue() | OFPortFeatures.OFPPF_10MB_HD.getValue() - | OFPortFeatures.OFPPF_100MB_FD.getValue() - | OFPortFeatures.OFPPF_100MB_HD.getValue() - | OFPortFeatures.OFPPF_1GB_FD.getValue() - | OFPortFeatures.OFPPF_1GB_HD.getValue() | OFPortFeatures.OFPPF_10GB_FD - .getValue())); - } - - private void deletePhysicalPort(OFPhysicalPort port) { - Short portNumber = port.getPortNumber(); - physicalPorts.remove(portNumber); - portBandwidth.remove(portNumber); - } - - @Override - public boolean isOperational() { - return ((this.state == SwitchState.WAIT_CONFIG_REPLY) || (this.state == SwitchState.OPERATIONAL)); - } - - @Override - public String toString() { - try { - return ("Switch:" + socket.socket().getRemoteSocketAddress().toString().split("/")[1] + " SWID:" + (isOperational() ? HexString - .toHexString(this.sid) : "unknown")); - } catch (Exception e) { - return (isOperational() ? HexString.toHexString(this.sid) : "unknown"); - } - - } - - @Override - public Date getConnectedDate() { - return this.connectedDate; - } - - public String getInstanceName() { - return instanceName; - } - - @Override - public Object getStatistics(OFStatisticsRequest req) { - int xid = getNextXid(); - StatisticsCollector worker = new StatisticsCollector(this, xid, req); - messageWaitingDone.put(xid, worker); - Future submit; - Object result = null; - try { - submit = executor.submit(worker); - } catch (RejectedExecutionException re) { - messageWaitingDone.remove(xid); - return result; - } - try { - result = submit.get(responseTimerValue, TimeUnit.MILLISECONDS); - return result; - } catch (Exception e) { - logger.warn("Timeout while waiting for {} replies from {}", - req.getType(), (isOperational() ? HexString.toHexString(sid) : "unknown")); - result = null; // to indicate timeout has occurred - worker.wakeup(); - return result; - } - } - - @Override - public Object syncSend(OFMessage msg) { - if (!running) { - logger.debug("Switch is going down, ignore syncSend"); - return null; - } - int xid = getNextXid(); - return syncSend(msg, xid); - } - - /* - * Either a BarrierReply or a OFError is received. If this is a reply for an - * outstanding sync message, wake up associated task so that it can continue - */ - private void processBarrierReply(OFBarrierReply msg) { - Integer xid = msg.getXid(); - SynchronousMessage worker = (SynchronousMessage) messageWaitingDone.remove(xid); - if (worker == null) { - return; - } - worker.wakeup(); - } - - private void processErrorReply(OFError errorMsg) { - OFMessage offendingMsg = errorMsg.getOffendingMsg(); - Integer xid; - if (offendingMsg != null) { - xid = offendingMsg.getXid(); - } else { - xid = errorMsg.getXid(); - } - /* - * the error can be a reply to a synchronous message or to a statistic - * request message - */ - Callable worker = messageWaitingDone.remove(xid); - if (worker == null) { - return; - } - if (worker instanceof SynchronousMessage) { - ((SynchronousMessage) worker).wakeup(errorMsg); - } else { - ((StatisticsCollector) worker).wakeup(errorMsg); - } - } - - private void processStatsReply(OFStatisticsReply reply) { - Integer xid = reply.getXid(); - StatisticsCollector worker = (StatisticsCollector) messageWaitingDone.get(xid); - if (worker == null) { - return; - } - if (worker.collect(reply)) { - // if all the stats records are received (collect() returns true) - // then we are done. - messageWaitingDone.remove(xid); - worker.wakeup(); - } - } - - @Override - public Map getPhysicalPorts() { - return this.physicalPorts; - } - - @Override - public OFPhysicalPort getPhysicalPort(Short portNumber) { - return this.physicalPorts.get(portNumber); - } - - @Override - public Integer getPortBandwidth(Short portNumber) { - return this.portBandwidth.get(portNumber); - } - - @Override - public Set getPorts() { - return this.physicalPorts.keySet(); - } - - @Override - public Byte getTables() { - return this.tables; - } - - @Override - public Integer getActions() { - return this.actions; - } - - @Override - public Integer getCapabilities() { - return this.capabilities; - } - - @Override - public Integer getBuffers() { - return this.buffers; - } - - @Override - public boolean isPortEnabled(short portNumber) { - return isPortEnabled(physicalPorts.get(portNumber)); - } - - @Override - public boolean isPortEnabled(OFPhysicalPort port) { - if (port == null) { - return false; - } - int portConfig = port.getConfig(); - int portState = port.getState(); - if ((portConfig & OFPortConfig.OFPPC_PORT_DOWN.getValue()) > 0) { - return false; - } - if ((portState & OFPortState.OFPPS_LINK_DOWN.getValue()) > 0) { - return false; - } - if ((portState & OFPortState.OFPPS_STP_MASK.getValue()) == OFPortState.OFPPS_STP_BLOCK.getValue()) { - return false; - } - return true; - } - - @Override - public List getEnabledPorts() { - List result = new ArrayList(); - synchronized (this.physicalPorts) { - for (OFPhysicalPort port : physicalPorts.values()) { - if (isPortEnabled(port)) { - result.add(port); - } - } - } - return result; - } - - /* - * Transmit thread polls the message out of the priority queue and invokes - * messaging service to transmit it over the socket channel - */ - class PriorityMessageTransmit implements Runnable { - @Override - public void run() { - running = true; - while (running) { - try { - PriorityMessage pmsg = transmitQ.take(); - msgReadWriteService.asyncSend(pmsg.msg); - /* - * If syncReply is set to true, wait for the response back. - */ - if (pmsg.syncReply) { - syncMessageInternal(pmsg.msg, pmsg.msg.getXid(), false); - } - } catch (InterruptedException ie) { - reportError(new InterruptedException("PriorityMessageTransmit thread interrupted")); - } catch (Exception e) { - reportError(e); - } - } - transmitQ = null; - } - } - - /* - * Setup and start the transmit thread - */ - private void startTransmitThread() { - this.transmitQ = new PriorityBlockingQueue(11, new Comparator() { - @Override - public int compare(PriorityMessage p1, PriorityMessage p2) { - if (p2.priority != p1.priority) { - return p2.priority - p1.priority; - } else { - return (p2.seqNum < p1.seqNum) ? 1 : -1; - } - } - }); - this.transmitThread = new Thread(new PriorityMessageTransmit()); - this.transmitThread.start(); - } - - /* - * Setup communication services - */ - private void setupCommChannel() throws Exception { - this.selector = SelectorProvider.provider().openSelector(); - this.socket.configureBlocking(false); - this.socket.socket().setTcpNoDelay(true); - this.msgReadWriteService = getMessageReadWriteService(); - } - - private void sendFirstHello() { - try { - OFMessage msg = factory.getMessage(OFType.HELLO); - asyncFastSend(msg); - } catch (Exception e) { - reportError(e); - } - } - - private IMessageReadWrite getMessageReadWriteService() throws Exception { - String str = System.getProperty("secureChannelEnabled"); - return ((str != null) && (str.trim().equalsIgnoreCase("true"))) ? new SecureMessageReadWriteService(socket, - selector) : new MessageReadWriteService(socket, selector); - } - - /** - * Send Barrier message synchronously. The caller will be blocked until the - * Barrier reply is received. - */ - @Override - public Object syncSendBarrierMessage() { - OFBarrierRequest barrierMsg = new OFBarrierRequest(); - return syncSend(barrierMsg); - } - - /** - * Send Barrier message asynchronously. The caller is not blocked. The - * Barrier message will be sent in a transmit thread which will be blocked - * until the Barrier reply is received. - */ - @Override - public Object asyncSendBarrierMessage() { - if (transmitQ == null) { - return Boolean.FALSE; - } - - OFBarrierRequest barrierMsg = new OFBarrierRequest(); - int xid = getNextXid(); - - barrierMsg.setXid(xid); - transmitQ.add(new PriorityMessage(barrierMsg, 0, true)); - - return Boolean.TRUE; - } - - /** - * This method returns the switch liveness timeout value. If controller did - * not receive any message from the switch for such a long period, - * controller will tear down the connection to the switch. - * - * @return The timeout value - */ - private static int getSwitchLivenessTimeout() { - String timeout = System.getProperty("of.switchLivenessTimeout"); - int rv = 60500; - - try { - if (timeout != null) { - rv = Integer.parseInt(timeout); - } - } catch (Exception e) { - } - - return rv; - } - - /** - * This method performs synchronous operations for a given message. If - * syncRequest is set to true, the message will be sent out followed by a - * Barrier request message. Then it's blocked until the Barrier rely arrives - * or timeout. If syncRequest is false, it simply skips the message send and - * just waits for the response back. - * - * @param msg - * Message to be sent - * @param xid - * Message XID - * @param request - * If set to true, the message the message will be sent out - * followed by a Barrier request message. If set to false, it - * simply skips the sending and just waits for the Barrier reply. - * @return the result - */ - private Object syncMessageInternal(OFMessage msg, int xid, boolean syncRequest) { - SynchronousMessage worker = new SynchronousMessage(this, xid, msg, syncRequest); - messageWaitingDone.put(xid, worker); - Object result = null; - Boolean status = false; - Future submit; - try { - submit = executor.submit(worker); - } catch (RejectedExecutionException re) { - messageWaitingDone.remove(xid); - return result; - } - try { - result = submit.get(responseTimerValue, TimeUnit.MILLISECONDS); - messageWaitingDone.remove(xid); - if (result == null) { - // if result is null, then it means the switch can handle this - // message successfully - // convert the result into a Boolean with value true - status = true; - // logger.debug("Successfully send " + - // msg.getType().toString()); - result = status; - } else { - // if result is not null, this means the switch can't handle - // this message - // the result if OFError already - if (logger.isDebugEnabled()) { - logger.debug("Send {} failed --> {}", msg.getType(), (result)); - } - } - return result; - } catch (Exception e) { - logger.warn("Timeout while waiting for {} reply", msg.getType().toString()); - // convert the result into a Boolean with value false - status = false; - result = status; - worker.wakeup(); - return result; - } - } - - @Override - public void deleteAllFlows() { - logger.trace("deleteAllFlows on switch {}", HexString.toHexString(this.sid)); - OFMatch match = new OFMatch().setWildcards(OFMatch.OFPFW_ALL); - OFFlowMod flowMod = (OFFlowMod) factory.getMessage(OFType.FLOW_MOD); - flowMod.setMatch(match).setCommand(OFFlowMod.OFPFC_DELETE).setOutPort(OFPort.OFPP_NONE) - .setLength((short) OFFlowMod.MINIMUM_LENGTH); - asyncFastSend(flowMod); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SynchronousMessage.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SynchronousMessage.java deleted file mode 100644 index bb94d4b318..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/internal/SynchronousMessage.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.core.internal; - -import java.util.concurrent.Callable; -import java.util.concurrent.CountDownLatch; - -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.openflow.protocol.OFBarrierRequest; -import org.openflow.protocol.OFError; -import org.openflow.protocol.OFMessage; - -/** - * This class implements synchronous operations on message send to a switch. If - * syncRequest is set to true, it sends the requested message to the switch - * followed by a Barrier request message. It returns the result once it gets the - * reply from the switch or after a timeout. If the protocol does not dictate - * the switch to reply the processing status for a particular message, the - * Barrier request forces the switch to reply saying whether or not the message - * processing was successful for messages sent to the switch up to this point. - * If syncRequest is false, it simply skips the message send and just waits for - * the response back. - */ -public class SynchronousMessage implements Callable { - private ISwitch sw; - private Integer xid; - private OFMessage syncMsg; - protected CountDownLatch latch; - private Object result; - private boolean syncRequest; - - public SynchronousMessage(ISwitch sw, Integer xid, OFMessage msg, - boolean syncRequest) { - this.sw = sw; - this.xid = xid; - syncMsg = msg; - latch = new CountDownLatch(1); - result = null; - this.syncRequest = syncRequest; - } - - @Override - public Object call() throws Exception { - /* - * Send out message only if syncRequest is set to true. Otherwise, just - * wait for the Barrier response back. - */ - if (syncRequest) { - sw.asyncSend(syncMsg, xid); - if (!(syncMsg instanceof OFBarrierRequest)) { - OFBarrierRequest barrierMsg = new OFBarrierRequest(); - sw.asyncSend(barrierMsg, xid); - } - } - latch.await(); - return result; - } - - public Integer getXid() { - return this.xid; - } - - public void wakeup() { - this.latch.countDown(); - } - - public void wakeup(OFError e) { - result = e; - wakeup(); - } - -} \ No newline at end of file diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Activator.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Activator.java deleted file mode 100644 index d92c57bd8a..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Activator.java +++ /dev/null @@ -1,451 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.Dictionary; -import java.util.Hashtable; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.protocol_plugin.openflow.IDataPacketListen; -import org.opendaylight.controller.protocol_plugin.openflow.IDataPacketMux; -import org.opendaylight.controller.protocol_plugin.openflow.IDiscoveryListener; -import org.opendaylight.controller.protocol_plugin.openflow.IFlowProgrammerNotifier; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryProvider; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimInternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsListener; -import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsManager; -import org.opendaylight.controller.protocol_plugin.openflow.IReadFilterInternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.IReadServiceFilter; -import org.opendaylight.controller.protocol_plugin.openflow.IRefreshInternalProvider; -import org.opendaylight.controller.protocol_plugin.openflow.ITopologyServiceShimListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.internal.Controller; -import org.opendaylight.controller.sal.connection.IPluginInConnectionService; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.core.IContainerAware; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.flowprogrammer.IPluginInFlowProgrammerService; -import org.opendaylight.controller.sal.flowprogrammer.IPluginOutFlowProgrammerService; -import org.opendaylight.controller.sal.inventory.IPluginInInventoryService; -import org.opendaylight.controller.sal.inventory.IPluginOutInventoryService; -import org.opendaylight.controller.sal.packet.IPluginInDataPacketService; -import org.opendaylight.controller.sal.packet.IPluginOutDataPacketService; -import org.opendaylight.controller.sal.reader.IPluginInReadService; -import org.opendaylight.controller.sal.reader.IPluginOutReadService; -import org.opendaylight.controller.sal.topology.IPluginInTopologyService; -import org.opendaylight.controller.sal.topology.IPluginOutTopologyService; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Openflow protocol plugin Activator - * - * - */ -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - /** - * Priority to determine whether to override existing protocol service. - */ - private static final int PLUGIN_PRIORITY = 10; - - /** - * Function that is used to communicate to dependency manager the list of - * known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { TopologyServices.class, DataPacketServices.class, - InventoryService.class, ReadService.class, - FlowProgrammerNotifier.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies is - * required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - * @param containerName - * The containerName being configured, this allow also optional - * per-container different behavior if needed, usually should not - * be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(TopologyServices.class)) { - // export the service to be used by SAL - c.setInterface( - new String[] { IPluginInTopologyService.class.getName(), - ITopologyServiceShimListener.class.getName() }, null); - // Hook the services coming in from SAL, as optional in - // case SAL is not yet there, could happen - c.add(createContainerServiceDependency(containerName) - .setService(IPluginOutTopologyService.class) - .setCallbacks("setPluginOutTopologyService", - "unsetPluginOutTopologyService").setRequired(false)); - c.add(createServiceDependency() - .setService(IRefreshInternalProvider.class) - .setCallbacks("setRefreshInternalProvider", - "unsetRefreshInternalProvider").setRequired(false)); - } - - if (imp.equals(InventoryService.class)) { - // export the service - c.setInterface( - new String[] { - IPluginInInventoryService.class.getName(), - IInventoryShimInternalListener.class.getName(), - IInventoryProvider.class.getName() }, null); - - // Now lets add a service dependency to make sure the - // provider of service exists - c.add(createServiceDependency() - .setService(IController.class, "(name=Controller)") - .setCallbacks("setController", "unsetController") - .setRequired(true)); - c.add(createContainerServiceDependency(containerName) - .setService(IPluginOutInventoryService.class) - .setCallbacks("setPluginOutInventoryServices", - "unsetPluginOutInventoryServices") - .setRequired(false)); - } - - if (imp.equals(DataPacketServices.class)) { - // export the service to be used by SAL - Dictionary props = new Hashtable(); - // Set the protocolPluginType property which will be used - // by SAL - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), Node.NodeIDType.OPENFLOW); - props.put(GlobalConstants.PROTOCOLPLUGINPRIORITY.toString(), - Integer.valueOf(PLUGIN_PRIORITY)); - c.setInterface(IPluginInDataPacketService.class.getName(), props); - // Hook the services coming in from SAL, as optional in - // case SAL is not yet there, could happen - c.add(createServiceDependency() - .setService(IController.class, "(name=Controller)") - .setCallbacks("setController", "unsetController") - .setRequired(true)); - // This is required for the transmission to happen properly - c.add(createServiceDependency().setService(IDataPacketMux.class) - .setCallbacks("setIDataPacketMux", "unsetIDataPacketMux") - .setRequired(true)); - c.add(createContainerServiceDependency(containerName) - .setService(IPluginOutDataPacketService.class) - .setCallbacks("setPluginOutDataPacketService", - "unsetPluginOutDataPacketService") - .setRequired(false)); - c.add(createServiceDependency() - .setService(IPluginOutConnectionService.class) - .setCallbacks("setIPluginOutConnectionService", - "unsetIPluginOutConnectionService") - .setRequired(true)); - } - - if (imp.equals(ReadService.class)) { - // export the service to be used by SAL - Dictionary props = new Hashtable(); - // Set the protocolPluginType property which will be used - // by SAL - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), Node.NodeIDType.OPENFLOW); - props.put(GlobalConstants.PROTOCOLPLUGINPRIORITY.toString(), - Integer.valueOf(PLUGIN_PRIORITY)); - c.setInterface(new String[] { - IReadFilterInternalListener.class.getName(), - IPluginInReadService.class.getName() }, props); - - c.add(createServiceDependency() - .setService(IReadServiceFilter.class) - .setCallbacks("setService", "unsetService") - .setRequired(true)); - - c.add(createContainerServiceDependency(containerName) - .setService(IPluginOutReadService.class) - .setCallbacks("setPluginOutReadServices", - "unsetPluginOutReadServices") - .setRequired(false)); - - c.add(createServiceDependency() - .setService(IPluginOutConnectionService.class) - .setCallbacks("setIPluginOutConnectionService", - "unsetIPluginOutConnectionService") - .setRequired(true)); - } - - if (imp.equals(FlowProgrammerNotifier.class)) { - // export the service to be used by SAL - Dictionary props = new Hashtable(); - // Set the protocolPluginType property which will be used - // by SAL - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), Node.NodeIDType.OPENFLOW); - c.setInterface(IFlowProgrammerNotifier.class.getName(), props); - - c.add(createContainerServiceDependency(containerName) - .setService(IPluginOutFlowProgrammerService.class) - .setCallbacks("setPluginOutFlowProgrammerService", - "unsetPluginOutFlowProgrammerService") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IPluginOutConnectionService.class) - .setCallbacks("setIPluginOutConnectionService", - "unsetIPluginOutConnectionService") - .setRequired(true)); - } - } - - /** - * Function that is used to communicate to dependency manager the list of - * known implementations for services that are container independent. - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getGlobalImplementations() { - Object[] res = { Controller.class, OFStatisticsManager.class, - FlowProgrammerService.class, ReadServiceFilter.class, - DiscoveryService.class, DataPacketMuxDemux.class, InventoryService.class, - InventoryServiceShim.class, TopologyServiceShim.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies is - * required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - */ - @Override - public void configureGlobalInstance(Component c, Object imp) { - - if (imp.equals(Controller.class)) { - logger.debug("Activator configureGlobalInstance( ) is called"); - Dictionary props = new Hashtable(); - props.put("name", "Controller"); - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), Node.NodeIDType.OPENFLOW); - c.setInterface(new String[] { IController.class.getName(), - IPluginInConnectionService.class.getName()}, - props); - } - - if (imp.equals(FlowProgrammerService.class)) { - // export the service to be used by SAL - Dictionary props = new Hashtable(); - // Set the protocolPluginType property which will be used - // by SAL - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), Node.NodeIDType.OPENFLOW); - props.put(GlobalConstants.PROTOCOLPLUGINPRIORITY.toString(), - Integer.valueOf(PLUGIN_PRIORITY)); - c.setInterface( - new String[] { IPluginInFlowProgrammerService.class.getName(), IMessageListener.class.getName(), - IContainerListener.class.getName(), IInventoryShimExternalListener.class.getName(), - IContainerAware.class.getName() }, props); - - c.add(createServiceDependency() - .setService(IController.class, "(name=Controller)") - .setCallbacks("setController", "unsetController") - .setRequired(true)); - - c.add(createServiceDependency() - .setService(IFlowProgrammerNotifier.class) - .setCallbacks("setFlowProgrammerNotifier", - "unsetFlowProgrammerNotifier") - .setRequired(false)); - - c.add(createServiceDependency() - .setService(IPluginOutConnectionService.class) - .setCallbacks("setIPluginOutConnectionService", - "unsetIPluginOutConnectionService") - .setRequired(true)); - } - - if (imp.equals(ReadServiceFilter.class)) { - - c.setInterface(new String[] { IReadServiceFilter.class.getName(), IContainerListener.class.getName(), - IOFStatisticsListener.class.getName(), IContainerAware.class.getName() }, null); - - c.add(createServiceDependency() - .setService(IController.class, "(name=Controller)") - .setCallbacks("setController", "unsetController") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IOFStatisticsManager.class) - .setCallbacks("setService", "unsetService") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IReadFilterInternalListener.class) - .setCallbacks("setReadFilterInternalListener", - "unsetReadFilterInternalListener") - .setRequired(false)); - } - - if (imp.equals(OFStatisticsManager.class)) { - - c.setInterface(new String[] { IOFStatisticsManager.class.getName(), - IInventoryShimExternalListener.class.getName() }, null); - - c.add(createServiceDependency() - .setService(IController.class, "(name=Controller)") - .setCallbacks("setController", "unsetController") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IOFStatisticsListener.class) - .setCallbacks("setStatisticsListener", - "unsetStatisticsListener").setRequired(false)); - } - - if (imp.equals(DiscoveryService.class)) { - // export the service - c.setInterface( - new String[] { IInventoryShimExternalListener.class.getName(), IDataPacketListen.class.getName(), - IContainerListener.class.getName() }, null); - - c.add(createServiceDependency() - .setService(IController.class, "(name=Controller)") - .setCallbacks("setController", "unsetController") - .setRequired(true)); - c.add(createContainerServiceDependency( - GlobalConstants.DEFAULT.toString()) - .setService(IInventoryProvider.class) - .setCallbacks("setInventoryProvider", - "unsetInventoryProvider").setRequired(true)); - c.add(createServiceDependency().setService(IDataPacketMux.class) - .setCallbacks("setIDataPacketMux", "unsetIDataPacketMux") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IDiscoveryListener.class) - .setCallbacks("setDiscoveryListener", - "unsetDiscoveryListener").setRequired(true)); - c.add(createServiceDependency() - .setService(IPluginOutConnectionService.class) - .setCallbacks("setIPluginOutConnectionService", - "unsetIPluginOutConnectionService") - .setRequired(true)); - } - - // DataPacket mux/demux services, which is teh actual engine - // doing the packet switching - if (imp.equals(DataPacketMuxDemux.class)) { - c.setInterface(new String[] { IDataPacketMux.class.getName(), IContainerListener.class.getName(), - IInventoryShimExternalListener.class.getName(), IContainerAware.class.getName() }, null); - - c.add(createServiceDependency() - .setService(IController.class, "(name=Controller)") - .setCallbacks("setController", "unsetController") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IPluginOutDataPacketService.class) - .setCallbacks("setPluginOutDataPacketService", - "unsetPluginOutDataPacketService") - .setRequired(false)); - // See if there is any local packet dispatcher - c.add(createServiceDependency() - .setService(IDataPacketListen.class) - .setCallbacks("setIDataPacketListen", - "unsetIDataPacketListen").setRequired(false)); - c.add(createServiceDependency() - .setService(IPluginOutConnectionService.class) - .setCallbacks("setIPluginOutConnectionService", - "unsetIPluginOutConnectionService") - .setRequired(true)); - } - - if (imp.equals(InventoryService.class)) { - // export the service - Dictionary props = new Hashtable(); - props.put("scope", "Global"); - - c.setInterface( - new String[] { IPluginInInventoryService.class.getName(), - IInventoryShimInternalListener.class.getName(), - IInventoryProvider.class.getName() }, props); - - // Now lets add a service dependency to make sure the - // provider of service exists - c.add(createServiceDependency() - .setService(IController.class, "(name=Controller)") - .setCallbacks("setController", "unsetController") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IPluginOutInventoryService.class, "(scope=Global)") - .setCallbacks("setPluginOutInventoryServices", - "unsetPluginOutInventoryServices") - .setRequired(true)); - } - - if (imp.equals(InventoryServiceShim.class)) { - c.setInterface(new String[] { IContainerListener.class.getName(), - IOFStatisticsListener.class.getName(), IContainerAware.class.getName() }, null); - - c.add(createServiceDependency() - .setService(IController.class, "(name=Controller)") - .setCallbacks("setController", "unsetController") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IInventoryShimInternalListener.class, "(!(scope=Global))") - .setCallbacks("setInventoryShimInternalListener", - "unsetInventoryShimInternalListener") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IInventoryShimInternalListener.class, "(scope=Global)") - .setCallbacks("setInventoryShimGlobalInternalListener", - "unsetInventoryShimGlobalInternalListener") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IInventoryShimExternalListener.class) - .setCallbacks("setInventoryShimExternalListener", - "unsetInventoryShimExternalListener") - .setRequired(false)); - c.add(createServiceDependency() - .setService(IPluginOutConnectionService.class) - .setCallbacks("setIPluginOutConnectionService", - "unsetIPluginOutConnectionService") - .setRequired(true)); - } - - if (imp.equals(TopologyServiceShim.class)) { - c.setInterface(new String[] { IDiscoveryListener.class.getName(), IContainerListener.class.getName(), - IRefreshInternalProvider.class.getName(), IInventoryShimExternalListener.class.getName(), - IContainerAware.class.getName() }, null); - c.add(createServiceDependency() - .setService(ITopologyServiceShimListener.class) - .setCallbacks("setTopologyServiceShimListener", - "unsetTopologyServiceShimListener") - .setRequired(true)); - c.add(createServiceDependency() - .setService(IOFStatisticsManager.class) - .setCallbacks("setStatisticsManager", - "unsetStatisticsManager").setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java deleted file mode 100644 index 932ac4e20b..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java +++ /dev/null @@ -1,494 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.opendaylight.controller.protocol_plugin.openflow.IDataPacketListen; -import org.opendaylight.controller.protocol_plugin.openflow.IDataPacketMux; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.IContainerAware; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.packet.Ethernet; -import org.opendaylight.controller.sal.packet.IPluginOutDataPacketService; -import org.opendaylight.controller.sal.packet.PacketException; -import org.opendaylight.controller.sal.packet.PacketResult; -import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.openflow.protocol.OFMessage; -import org.openflow.protocol.OFPacketIn; -import org.openflow.protocol.OFPacketOut; -import org.openflow.protocol.OFPort; -import org.openflow.protocol.OFType; -import org.openflow.protocol.action.OFAction; -import org.openflow.protocol.action.OFActionOutput; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DataPacketMuxDemux implements IContainerListener, - IMessageListener, IDataPacketMux, IInventoryShimExternalListener, IContainerAware { - protected static final Logger logger = LoggerFactory - .getLogger(DataPacketMuxDemux.class); - private IController controller = null; - private ConcurrentMap swID2ISwitch = new ConcurrentHashMap(); - // Gives a map between a Container and all the DataPacket listeners on SAL - private ConcurrentMap pluginOutDataPacketServices = new ConcurrentHashMap(); - // Gives a map between a NodeConnector and the containers to which it - // belongs - private ConcurrentMap> nc2Container = new ConcurrentHashMap>(); - // Gives a map between a Container and the FlowSpecs on it - private ConcurrentMap> container2FlowSpecs = new ConcurrentHashMap>(); - // Track local data packet listener - private List iDataPacketListen = new CopyOnWriteArrayList(); - private IPluginOutConnectionService connectionOutService; - - void setIDataPacketListen(IDataPacketListen s) { - if (this.iDataPacketListen != null) { - if (!this.iDataPacketListen.contains(s)) { - logger.debug("Added new IDataPacketListen"); - this.iDataPacketListen.add(s); - } - } - } - - void unsetIDataPacketListen(IDataPacketListen s) { - if (this.iDataPacketListen != null) { - if (this.iDataPacketListen.contains(s)) { - logger.debug("Removed IDataPacketListen"); - this.iDataPacketListen.remove(s); - } - } - } - - void setPluginOutDataPacketService(Map props, - IPluginOutDataPacketService s) { - if (props == null) { - logger.error("Didn't receive the service properties"); - return; - } - String containerName = (String) props.get("containerName"); - if (containerName == null) { - logger.error("containerName not supplied"); - return; - } - if (this.pluginOutDataPacketServices != null) { - // It's expected only one SAL per container as long as the - // replication is done in the SAL implementation toward - // the different APPS - this.pluginOutDataPacketServices.put(containerName, s); - logger.debug("New outService for container: {}", containerName); - } - } - - void unsetPluginOutDataPacketService(Map props, - IPluginOutDataPacketService s) { - if (props == null) { - logger.error("Didn't receive the service properties"); - return; - } - String containerName = (String) props.get("containerName"); - if (containerName == null) { - logger.error("containerName not supplied"); - return; - } - if (this.pluginOutDataPacketServices != null) { - this.pluginOutDataPacketServices.remove(containerName); - logger.debug("Removed outService for container: {}", containerName); - } - } - - void setController(IController s) { - logger.debug("Controller provider set in DATAPACKET SERVICES"); - this.controller = s; - } - - void unsetController(IController s) { - if (this.controller == s) { - logger.debug("Controller provider UNset in DATAPACKET SERVICES"); - this.controller = null; - } - } - - void setIPluginOutConnectionService(IPluginOutConnectionService s) { - connectionOutService = s; - } - - void unsetIPluginOutConnectionService(IPluginOutConnectionService s) { - if (connectionOutService == s) { - connectionOutService = null; - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - this.controller.addMessageListener(OFType.PACKET_IN, this); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - this.controller.removeMessageListener(OFType.PACKET_IN, this); - - // Clear state that may need to be reused on component restart - this.pluginOutDataPacketServices.clear(); - this.nc2Container.clear(); - this.container2FlowSpecs.clear(); - this.controller = null; - this.swID2ISwitch.clear(); - } - - @Override - public void receive(ISwitch sw, OFMessage msg) { - if (sw == null || msg == null || this.pluginOutDataPacketServices == null) { - // Something fishy, we cannot do anything - logger.debug("sw: {} and/or msg: {} and/or pluginOutDataPacketServices: {} is null!", new Object[] { sw, - msg, this.pluginOutDataPacketServices }); - return; - } - - Long ofSwitchID = Long.valueOf(sw.getId()); - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, ofSwitchID); - if (!connectionOutService.isLocal(n)) { - logger.debug("Connection service refused DataPacketMuxDemux receive {} {}", sw, msg); - return; - } - } catch (Exception e) { - return; - } - - if (msg instanceof OFPacketIn) { - OFPacketIn ofPacket = (OFPacketIn) msg; - Short ofPortID = Short.valueOf(ofPacket.getInPort()); - - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, ofSwitchID); - NodeConnector p = PortConverter.toNodeConnector(ofPortID, n); - RawPacket dataPacket = new RawPacket(ofPacket.getPacketData()); - dataPacket.setIncomingNodeConnector(p); - - // Try to dispatch the packet locally, in here we will - // pass the parsed packet simply because once the - // packet infra is settled all the packets will passed - // around as parsed and read-only - for (IDataPacketListen s : this.iDataPacketListen) { - if (s.receiveDataPacket(dataPacket).equals(PacketResult.CONSUME)) { - logger.trace("Consumed locally data packet"); - return; - } - } - - boolean dispatched_to_container = false; - - // Now check the mapping between nodeConnector and - // Container and later on optimally filter based on - // flowSpec - List containersRX = this.nc2Container.get(p); - if (containersRX != null) { - Ethernet frame = new Ethernet(); - byte data[] = dataPacket.getPacketData(); - frame.deserialize(data, 0, data.length * NetUtils.NumBitsInAByte); - Match packetMatch = frame.getMatch(); - for (String container : containersRX) { - boolean notify = true; - List containerFlows = this.container2FlowSpecs.get(container); - if (containerFlows != null) { - notify = false; - for (ContainerFlow cFlow : containerFlows) { - if (cFlow.allowsMatch(packetMatch)) { - notify = true; - break; - } - } - if (notify) { - IPluginOutDataPacketService s = this.pluginOutDataPacketServices.get(container); - if (s != null) { - s.receiveDataPacket(dataPacket); - if (logger.isTraceEnabled()) { - logger.trace( - "Dispatched to apps a frame of size: {}" + " on container: {}: {}", - new Object[] { ofPacket.getPacketData().length, container, - HexEncode.bytesToHexString(dataPacket.getPacketData()) }); - } - } - dispatched_to_container = true; - } - } - } - } - if (!dispatched_to_container) { - // Now dispatch the packet toward SAL for default container - IPluginOutDataPacketService defaultOutService = this.pluginOutDataPacketServices - .get(GlobalConstants.DEFAULT.toString()); - if (defaultOutService != null) { - defaultOutService.receiveDataPacket(dataPacket); - if (logger.isTraceEnabled()) { - logger.trace("Dispatched to apps a frame of size: {} on " + "container: {}: {}", - new Object[] { ofPacket.getPacketData().length, - GlobalConstants.DEFAULT.toString(), - HexEncode.bytesToHexString(dataPacket.getPacketData()) }); - } - } - } - // This is supposed to be the catch all for all the - // DataPacket hence we will assume it has been handled - return; - } catch (ConstructionException cex) { - } catch (PacketException e) { - logger.debug("Failed to deserialize raw packet: ", e.getMessage()); - } - // If we reach this point something went wrong. - return; - } else { - // We don't care about non-data packets - return; - } - } - - @Override - public void transmitDataPacket(RawPacket outPkt) { - // Sanity check area - if (outPkt == null) { - logger.debug("outPkt is null!"); - return; - } - - NodeConnector outPort = outPkt.getOutgoingNodeConnector(); - if (outPort == null) { - logger.debug("outPort is null! outPkt: {}", outPkt); - return; - } - - if (!connectionOutService.isLocal(outPort.getNode())) { - logger.debug("data packets will not be sent to {} in a non-master controller", outPort.toString()); - return; - } - - - if (!outPort.getType().equals( - NodeConnector.NodeConnectorIDType.OPENFLOW)) { - // The output Port is not of type OpenFlow - logger.debug("outPort is not OF Type! outPort: {}", outPort); - return; - } - - Short port = (Short) outPort.getID(); - Long swID = (Long) outPort.getNode().getID(); - ISwitch sw = this.swID2ISwitch.get(swID); - - if (sw == null) { - // If we cannot get the controller descriptor we cannot even - // send out the frame - logger.debug("swID: {} - sw is null!", swID); - return; - } - - byte[] data = outPkt.getPacketData(); - // build action - OFActionOutput action = new OFActionOutput().setPort(port); - // build packet out - OFPacketOut po = new OFPacketOut() - .setBufferId(OFPacketOut.BUFFER_ID_NONE) - .setActions(Collections.singletonList((OFAction) action)) - .setActionsLength((short) OFActionOutput.MINIMUM_LENGTH); - if(outPkt.getIncomingNodeConnector() != null) { - po.setInPort((Short)outPkt.getIncomingNodeConnector().getID()); - } else { - po.setInPort(OFPort.OFPP_NONE); - } - - po.setLengthU(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength() - + data.length); - po.setPacketData(data); - - // send PACKET_OUT at high priority - sw.asyncFastSend(po); - logger.trace("Transmitted a frame of size: {}", data.length); - } - - public void addNode(Node node, Set props) { - if (node == null) { - logger.debug("node is null!"); - return; - } - - long sid = (Long) node.getID(); - ISwitch sw = controller.getSwitches().get(sid); - if (sw == null) { - logger.debug("sid: {} - sw is null!", sid); - return; - } - this.swID2ISwitch.put(sw.getId(), sw); - } - - public void removeNode(Node node) { - if (node == null) { - logger.debug("node is null!"); - return; - } - - long sid = (Long) node.getID(); - ISwitch sw = controller.getSwitches().get(sid); - if (sw == null) { - logger.debug("sid: {} - sw is null!", sid); - return; - } - this.swID2ISwitch.remove(sw.getId()); - } - - @Override - public void tagUpdated(String containerName, Node n, short oldTag, - short newTag, UpdateType t) { - // Do nothing - } - - @Override - public void containerFlowUpdated(String containerName, - ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) { - if (this.container2FlowSpecs == null) { - logger.error("container2FlowSpecs is NULL"); - return; - } - List fSpecs = this.container2FlowSpecs - .get(containerName); - if (fSpecs == null) { - fSpecs = new CopyOnWriteArrayList(); - } - switch (t) { - case ADDED: - if (!fSpecs.contains(currentFlow)) { - fSpecs.add(currentFlow); - } - container2FlowSpecs.put(containerName, fSpecs); - break; - case REMOVED: - fSpecs.remove(currentFlow); - break; - case CHANGED: - break; - } - } - - @Override - public void nodeConnectorUpdated(String containerName, NodeConnector p, - UpdateType t) { - if (this.nc2Container == null) { - logger.error("nc2Container is NULL"); - return; - } - List containers = this.nc2Container.get(p); - if (containers == null) { - containers = new CopyOnWriteArrayList(); - } - boolean updateMap = false; - switch (t) { - case ADDED: - if (!containers.contains(containerName)) { - containers.add(containerName); - updateMap = true; - } - break; - case REMOVED: - if (containers.contains(containerName)) { - containers.remove(containerName); - updateMap = true; - } - break; - case CHANGED: - break; - } - if (updateMap) { - if (containers.isEmpty()) { - // Do cleanup to reduce memory footprint if no - // elements to be tracked - this.nc2Container.remove(p); - } else { - this.nc2Container.put(p, containers); - } - } - } - - @Override - public void containerModeUpdated(UpdateType t) { - // do nothing - } - - @Override - public void updateNode(Node node, UpdateType type, Set props) { - switch (type) { - case ADDED: - addNode(node, props); - break; - case REMOVED: - removeNode(node); - break; - default: - break; - } - } - - @Override - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props) { - // do nothing - } - - @Override - public void containerCreate(String containerName) { - // do nothing - } - - @Override - public void containerDestroy(String containerName) { - Set removeNodeConnectorSet = new HashSet(); - for (Map.Entry> entry : nc2Container.entrySet()) { - List ncContainers = entry.getValue(); - if (ncContainers.contains(containerName)) { - NodeConnector nodeConnector = entry.getKey(); - removeNodeConnectorSet.add(nodeConnector); - } - } - for (NodeConnector nodeConnector : removeNodeConnectorSet) { - List ncContainers = nc2Container.get(nodeConnector); - ncContainers.remove(containerName); - if (ncContainers.isEmpty()) { - nc2Container.remove(nodeConnector); - } - } - container2FlowSpecs.remove(containerName); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketServices.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketServices.java deleted file mode 100644 index 4c65645bfe..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketServices.java +++ /dev/null @@ -1,55 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import org.opendaylight.controller.protocol_plugin.openflow.IDataPacketMux; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.packet.IPluginInDataPacketService; -import org.opendaylight.controller.sal.packet.RawPacket; - -public class DataPacketServices implements IPluginInDataPacketService { - protected static final Logger logger = LoggerFactory - .getLogger(DataPacketServices.class); - private IDataPacketMux iDataPacketMux = null; - private IPluginOutConnectionService connectionOutService; - - void setIDataPacketMux(IDataPacketMux s) { - this.iDataPacketMux = s; - } - - void unsetIDataPacketMux(IDataPacketMux s) { - if (this.iDataPacketMux == s) { - this.iDataPacketMux = null; - } - } - - void setIPluginOutConnectionService(IPluginOutConnectionService s) { - connectionOutService = s; - } - - void unsetIPluginOutConnectionService(IPluginOutConnectionService s) { - if (connectionOutService == s) { - connectionOutService = null; - } - } - - @Override - public void transmitDataPacket(RawPacket outPkt) { - NodeConnector nc = outPkt.getOutgoingNodeConnector(); - if (connectionOutService != null && connectionOutService.isLocal(nc.getNode())) { - this.iDataPacketMux.transmitDataPacket(outPkt); - } else { - logger.debug("{} is dropped in the controller "+outPkt); - } - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DescStatisticsConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DescStatisticsConverter.java deleted file mode 100644 index 28c3dd6b4f..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DescStatisticsConverter.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.List; - -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.openflow.protocol.statistics.OFDescriptionStatistics; -import org.openflow.protocol.statistics.OFStatistics; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Utility class for converting openflow description statistics into SAL - * NodeDescription object - */ -public class DescStatisticsConverter { - private static final Logger log = LoggerFactory - .getLogger(DescStatisticsConverter.class); - NodeDescription hwDesc; - OFDescriptionStatistics ofDesc; - - public DescStatisticsConverter(List statsList) { - this.hwDesc = null; - this.ofDesc = (statsList == null || statsList.isEmpty())? - null : (OFDescriptionStatistics) statsList.get(0); - } - public DescStatisticsConverter(OFDescriptionStatistics desc) { - this.hwDesc = null; - this.ofDesc = desc; - } - - public NodeDescription getHwDescription() { - if (hwDesc == null && ofDesc != null) { - hwDesc = new NodeDescription(); - hwDesc.setManufacturer(ofDesc.getManufacturerDescription()); - hwDesc.setHardware(ofDesc.getHardwareDescription()); - hwDesc.setSoftware(ofDesc.getSoftwareDescription()); - hwDesc.setDescription(ofDesc.getDatapathDescription()); - hwDesc.setSerialNumber(ofDesc.getSerialNumber()); - } - log.trace("OFDescriptionStatistics: {}", ofDesc); - log.trace("NodeDescription: {}", hwDesc); - return hwDesc; - } - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DiscoveryService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DiscoveryService.java deleted file mode 100644 index 1a59a325ad..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DiscoveryService.java +++ /dev/null @@ -1,1715 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.LinkedBlockingQueue; - -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.protocol_plugin.openflow.IDataPacketListen; -import org.opendaylight.controller.protocol_plugin.openflow.IDataPacketMux; -import org.opendaylight.controller.protocol_plugin.openflow.IDiscoveryListener; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryProvider; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.Config; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.packet.Ethernet; -import org.opendaylight.controller.sal.packet.LLDP; -import org.opendaylight.controller.sal.packet.LLDPTLV; -import org.opendaylight.controller.sal.packet.LinkEncap; -import org.opendaylight.controller.sal.packet.PacketResult; -import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.openflow.protocol.OFPhysicalPort; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class describes neighbor discovery service for an OpenFlow network. - */ -public class DiscoveryService implements IInventoryShimExternalListener, IDataPacketListen, IContainerListener, - CommandProvider { - private static Logger logger = LoggerFactory.getLogger(DiscoveryService.class); - private IController controller = null; - private IDiscoveryListener discoveryListener = null; - private IInventoryProvider inventoryProvider = null; - private IDataPacketMux iDataPacketMux = null; - // High priority list containing newly added ports which will be served first - private List readyListHi = null; - // List containing all the ports which will be served periodically - private List readyListLo = null; - // Staging area during quiet period - private List stagingList = null; - // Wait for next discovery packet. The map contains the time elapsed since - // the last received LLDP frame on each node connector - private ConcurrentMap holdTime = null; - // Allow one more retry for newly added ports. This map contains the time - // period elapsed since last discovery pkt transmission on the port. - private ConcurrentMap elapsedTime = null; - // OpenFlow edges keyed by head connector - private ConcurrentMap edgeMap = null; - // The map contains aging entry keyed by head connector of Production edge - private ConcurrentMap agingMap = null; - // Production edges keyed by head connector - private ConcurrentMap prodMap = null; - - private Timer discoveryTimer; - private DiscoveryTimerTask discoveryTimerTask; - private final static long discoveryTimerTick = 2L * 1000; // per tick in msec - private int discoveryTimerTickCount = 0; // main tick counter - // Max # of ports handled in one batch - private int discoveryBatchMaxPorts; - // Periodically restart batching process - private int discoveryBatchRestartTicks; - private int discoveryBatchPausePeriod = 2; - // Pause after this point - private int discoveryBatchPauseTicks; - private int discoveryTimeoutTicks; - private int discoveryThresholdTicks; - private int discoveryAgeoutTicks; - // multiple of discoveryBatchRestartTicks - private int discoveryConsistencyCheckMultiple = 2; - // CC tick counter - private int discoveryConsistencyCheckTickCount; - // # of times CC gets called - private int discoveryConsistencyCheckCallingTimes = 0; - // # of cases CC corrected - private int discoveryConsistencyCheckCorrected = 0; - // Enable or disable CC - private boolean discoveryConsistencyCheckEnabled = true; - // Enable or disable aging - private boolean discoveryAgingEnabled = true; - // Global flag to enable or disable LLDP snooping - private boolean discoverySnoopingEnabled = true; - // The list of ports that will not do LLDP snooping - private List discoverySnoopingDisableList; - private BlockingQueue transmitQ; - private Thread transmitThread; - private Boolean throttling = false; // if true, no more batching. - private volatile Boolean shuttingDown = false; - - private LLDPTLV chassisIdTlv, systemNameTlv, portIdTlv, ttlTlv, customTlv; - private IPluginOutConnectionService connectionOutService; - - class DiscoveryTransmit implements Runnable { - private final BlockingQueue transmitQ; - private int count = 0; - - DiscoveryTransmit(BlockingQueue transmitQ) { - this.transmitQ = transmitQ; - } - - @Override - public void run() { - while (true) { - try { - NodeConnector nodeConnector = transmitQ.take(); - RawPacket outPkt = createDiscoveryPacket(nodeConnector); - sendDiscoveryPacket(nodeConnector, outPkt); - nodeConnector = null; - if ((++count & 0x7f) == 0) { - Thread.sleep(10); - } - } catch (InterruptedException e1) { - logger.trace("DiscoveryTransmit interupted", e1.getMessage()); - if (shuttingDown) { - return; - } - } catch (Exception e2) { - logger.error("", e2); - } - } - } - } - - class DiscoveryTimerTask extends TimerTask { - @Override - public void run() { - checkTimeout(); - checkAging(); - doConsistencyCheck(); - doDiscovery(); - } - } - - public enum DiscoveryPeriod { - INTERVAL (300), - AGEOUT (120), - THRESHOLD (30); - - private int time; // sec - private int tick; // tick - - DiscoveryPeriod(int time) { - this.time = time; - this.tick = time2Tick(time); - } - - public int getTime() { - return time; - } - - public void setTime(int time) { - this.time = time; - this.tick = time2Tick(time); - } - - public int getTick() { - return tick; - } - - public void setTick(int tick) { - this.time = tick2Time(tick); - this.tick = tick; - } - - private int time2Tick(int time) { - return (int) (time / (discoveryTimerTick / 1000)); - } - - private int tick2Time(int tick) { - return (int) (tick * (discoveryTimerTick / 1000)); - } - } - - private RawPacket createDiscoveryPacket(NodeConnector nodeConnector) { - String nodeId = HexEncode.longToHexString((Long) nodeConnector.getNode().getID()); - - // Create LLDP ChassisID TLV - byte[] cidValue = LLDPTLV.createChassisIDTLVValue(nodeId); - chassisIdTlv.setType(LLDPTLV.TLVType.ChassisID.getValue()).setLength((short) cidValue.length) - .setValue(cidValue); - - // Create LLDP SystemName TLV - byte[] snValue = LLDPTLV.createSystemNameTLVValue(nodeConnector.getNode().toString()); - systemNameTlv.setType(LLDPTLV.TLVType.SystemName.getValue()).setLength((short) snValue.length) - .setValue(snValue); - - // Create LLDP PortID TLV - String portId = nodeConnector.getNodeConnectorIDString(); - byte[] pidValue = LLDPTLV.createPortIDTLVValue(portId); - portIdTlv.setType(LLDPTLV.TLVType.PortID.getValue()).setLength((short) pidValue.length).setValue(pidValue); - - // Create LLDP Custom TLV - byte[] customValue = LLDPTLV.createCustomTLVValue(nodeConnector.toString()); - customTlv.setType(LLDPTLV.TLVType.Custom.getValue()).setLength((short) customValue.length) - .setValue(customValue); - - // Create LLDP Custom Option list - List customList = new ArrayList(); - customList.add(customTlv); - - // Create discovery pkt - LLDP discoveryPkt = new LLDP(); - discoveryPkt.setChassisId(chassisIdTlv).setPortId(portIdTlv).setTtl(ttlTlv).setSystemNameId(systemNameTlv) - .setOptionalTLVList(customList); - - RawPacket rawPkt = null; - try { - // Create ethernet pkt - byte[] sourceMac = getSourceMACFromNodeID(nodeId); - Ethernet ethPkt = new Ethernet(); - ethPkt.setSourceMACAddress(sourceMac).setDestinationMACAddress(LLDP.LLDPMulticastMac) - .setEtherType(EtherTypes.LLDP.shortValue()).setPayload(discoveryPkt); - - byte[] data = ethPkt.serialize(); - rawPkt = new RawPacket(data); - rawPkt.setOutgoingNodeConnector(nodeConnector); - } catch (ConstructionException cex) { - logger.warn("RawPacket creation caught exception {}", cex.getMessage()); - } catch (Exception e) { - logger.error("Failed to serialize the LLDP packet: " + e); - } - - return rawPkt; - } - - private void sendDiscoveryPacket(NodeConnector nodeConnector, RawPacket outPkt) { - if (nodeConnector == null) { - logger.debug("Can not send discovery packet out since nodeConnector is null"); - return; - } - - if (!connectionOutService.isLocal(nodeConnector.getNode())) { - logger.debug("Discoery packets will not be sent to {} in a non-master controller", nodeConnector.toString()); - return; - } - - if (outPkt == null) { - logger.debug("Can not send discovery packet out since outPkt is null"); - return; - } - - long sid = (Long) nodeConnector.getNode().getID(); - ISwitch sw = controller.getSwitches().get(sid); - - if (sw == null) { - logger.debug("Can not send discovery packet out since switch {} is null", sid); - return; - } - - if (!sw.isOperational()) { - logger.debug("Can not send discovery packet out since switch {} is not operational", sw); - return; - } - - if (this.iDataPacketMux == null) { - logger.debug("Can not send discovery packet out since DataPacket service is not available"); - return; - } - - logger.trace("Sending topology discovery pkt thru {}", nodeConnector); - this.iDataPacketMux.transmitDataPacket(outPkt); - } - - @Override - public PacketResult receiveDataPacket(RawPacket inPkt) { - if (inPkt == null) { - logger.debug("Ignoring null packet"); - return PacketResult.IGNORED; - } - - byte[] data = inPkt.getPacketData(); - if (data.length <= 0) { - logger.trace("Ignoring zero length packet"); - return PacketResult.IGNORED; - } - - if (!inPkt.getEncap().equals(LinkEncap.ETHERNET)) { - logger.trace("Ignoring non ethernet packet"); - return PacketResult.IGNORED; - } - - NodeConnector nodeConnector = inPkt.getIncomingNodeConnector(); - if (((Short) nodeConnector.getID()).equals(NodeConnector.SPECIALNODECONNECTORID)) { - logger.trace("Ignoring ethernet packet received on special port: " - + inPkt.getIncomingNodeConnector().toString()); - return PacketResult.IGNORED; - } - - if (!connectionOutService.isLocal(nodeConnector.getNode())) { - logger.debug("Discoery packets will not be processed from {} in a non-master controller", nodeConnector.toString()); - return PacketResult.IGNORED; - } - - Ethernet ethPkt = new Ethernet(); - try { - ethPkt.deserialize(data, 0, data.length * NetUtils.NumBitsInAByte); - } catch (Exception e) { - logger.warn("Failed to decode LLDP packet from {}: {}", inPkt.getIncomingNodeConnector(), e); - return PacketResult.IGNORED; - } - - if (ethPkt.getPayload() instanceof LLDP) { - NodeConnector dst = inPkt.getIncomingNodeConnector(); - if (isEnabled(dst)) { - if (!processDiscoveryPacket(dst, ethPkt)) { - // Snoop the discovery pkt if not generated from us - snoopDiscoveryPacket(dst, ethPkt); - } - return PacketResult.CONSUME; - } - } - return PacketResult.IGNORED; - } - - /* - * Snoop incoming discovery frames generated by the production network - * neighbor switch - */ - private void snoopDiscoveryPacket(NodeConnector dstNodeConnector, Ethernet ethPkt) { - if (!this.discoverySnoopingEnabled || discoverySnoopingDisableList.contains(dstNodeConnector)) { - logger.trace("Discarded received discovery packet on {} since snooping is turned off", dstNodeConnector); - return; - } - - if ((dstNodeConnector == null) || (ethPkt == null)) { - logger.trace("Quit snooping discovery packet: Null node connector or packet"); - return; - } - - LLDP lldp = (LLDP) ethPkt.getPayload(); - - try { - String nodeId = LLDPTLV.getHexStringValue(lldp.getChassisId().getValue(), lldp.getChassisId().getLength()); - String portId = LLDPTLV.getStringValue(lldp.getPortId().getValue(), lldp.getPortId().getLength()); - byte[] systemNameBytes = null; - // get system name if present in the LLDP pkt - for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) { - if (lldptlv.getType() == LLDPTLV.TLVType.SystemName.getValue()) { - systemNameBytes = lldptlv.getValue(); - break; - } - } - String nodeName = (systemNameBytes == null) ? nodeId - : new String(systemNameBytes, Charset.defaultCharset()); - Node srcNode = new Node(Node.NodeIDType.PRODUCTION, nodeName); - NodeConnector srcNodeConnector = NodeConnectorCreator.createNodeConnector( - NodeConnector.NodeConnectorIDType.PRODUCTION, portId, srcNode); - - Edge edge = null; - Set props = null; - edge = new Edge(srcNodeConnector, dstNodeConnector); - props = getProps(dstNodeConnector); - - updateProdEdge(edge, props); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug( - "Caught exception while attempting to snoop non controller generated or malformed LLDP frame sent by {} and received on {}: {}", - HexEncode.bytesToHexStringFormat(ethPkt.getSourceMACAddress()), dstNodeConnector, - e.getMessage()); - } - } - } - - /* - * Handle discovery frames generated by our controller - * - * @return true if it's a success - */ - private boolean processDiscoveryPacket(NodeConnector dstNodeConnector, Ethernet ethPkt) { - if ((dstNodeConnector == null) || (ethPkt == null)) { - logger.trace("Ignoring processing of discovery packet: Null node connector or packet"); - return false; - } - - logger.trace("Handle discovery packet {} from {}", ethPkt, dstNodeConnector); - - LLDP lldp = (LLDP) ethPkt.getPayload(); - - List optionalTLVList = lldp.getOptionalTLVList(); - if (optionalTLVList == null) { - logger.warn("The discovery packet with null custom option from {}", dstNodeConnector); - return false; - } - - Node srcNode = null; - NodeConnector srcNodeConnector = null; - for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) { - if (lldptlv.getType() == LLDPTLV.TLVType.Custom.getValue()) { - String ncString = LLDPTLV.getCustomString(lldptlv.getValue(), lldptlv.getLength()); - srcNodeConnector = NodeConnector.fromString(ncString); - if (srcNodeConnector != null) { - srcNode = srcNodeConnector.getNode(); - } - } - } - - if ((srcNode == null) || (srcNodeConnector == null)) { - logger.trace("Received non-controller generated discovery packet from {}", dstNodeConnector); - return false; - } - - // push it out to Topology - Edge edge = null; - Set props = null; - try { - edge = new Edge(srcNodeConnector, dstNodeConnector); - props = getProps(dstNodeConnector); - } catch (ConstructionException e) { - logger.error("Caught exception ", e); - } - addEdge(edge, props); - - logger.trace("Received discovery packet for Edge {}", edge); - - return true; - } - - public Map getPropMap(NodeConnector nodeConnector) { - if (nodeConnector == null) { - return null; - } - - if (inventoryProvider == null) { - return null; - } - - Map> props = inventoryProvider.getNodeConnectorProps(false); - if (props == null) { - return null; - } - - return props.get(nodeConnector); - } - - public Property getProp(NodeConnector nodeConnector, String propName) { - Map propMap = getPropMap(nodeConnector); - if (propMap == null) { - return null; - } - - Property prop = propMap.get(propName); - return prop; - } - - public Set getProps(NodeConnector nodeConnector) { - Map propMap = getPropMap(nodeConnector); - if (propMap == null) { - return null; - } - - Set props = new HashSet(propMap.values()); - return props; - } - - private boolean isEnabled(NodeConnector nodeConnector) { - if (nodeConnector == null) { - return false; - } - - Config config = (Config) getProp(nodeConnector, Config.ConfigPropName); - State state = (State) getProp(nodeConnector, State.StatePropName); - return ((config != null) && (config.getValue() == Config.ADMIN_UP) && (state != null) && (state.getValue() == State.EDGE_UP)); - } - - private boolean isTracked(NodeConnector nodeConnector) { - if (readyListHi.contains(nodeConnector)) { - return true; - } - - if (readyListLo.contains(nodeConnector)) { - return true; - } - - if (holdTime.keySet().contains(nodeConnector)) { - return true; - } - - if (stagingList.contains(nodeConnector)) { - return true; - } - - return false; - } - - private Set getWorkingSet() { - Set workingSet = new HashSet(); - Set removeSet = new HashSet(); - - for (NodeConnector nodeConnector : readyListHi) { - if (isOverLimit(workingSet.size())) { - break; - } - - workingSet.add(nodeConnector); - removeSet.add(nodeConnector); - - // Put it in the map and start the timer. It may need retry. - elapsedTime.put(nodeConnector, 0); - } - readyListHi.removeAll(removeSet); - - removeSet.clear(); - for (NodeConnector nodeConnector : readyListLo) { - if (isOverLimit(workingSet.size())) { - break; - } - - workingSet.add(nodeConnector); - removeSet.add(nodeConnector); - } - readyListLo.removeAll(removeSet); - - return workingSet; - } - - private Boolean isOverLimit(int size) { - return ((size >= discoveryBatchMaxPorts) && !throttling); - } - - private void addDiscovery() { - Map switches = controller.getSwitches(); - Set sidSet = switches.keySet(); - if (sidSet == null) { - return; - } - for (Long sid : sidSet) { - Node node = NodeCreator.createOFNode(sid); - addDiscovery(node); - } - } - - private void addDiscovery(Node node) { - Map switches = controller.getSwitches(); - ISwitch sw = switches.get(node.getID()); - if (sw == null) { - //switch could be removed by now, stop propagation - return; - } - List ports = sw.getEnabledPorts(); - for (OFPhysicalPort port : ports) { - NodeConnector nodeConnector = NodeConnectorCreator.createOFNodeConnector(port.getPortNumber(), node); - if (!readyListHi.contains(nodeConnector)) { - readyListHi.add(nodeConnector); - } - } - } - - private void addDiscovery(NodeConnector nodeConnector) { - if (isTracked(nodeConnector)) { - return; - } - - readyListHi.add(nodeConnector); - } - - private void removeNodeConnector(NodeConnector nodeConnector) { - readyListLo.remove(nodeConnector); - readyListHi.remove(nodeConnector); - stagingList.remove(nodeConnector); - holdTime.remove(nodeConnector); - elapsedTime.remove(nodeConnector); - } - - private Set getRemoveSet(Collection c, Node node) { - Set removeSet = new HashSet(); - if (c == null) { - return removeSet; - } - for (NodeConnector nodeConnector : c) { - if (node.equals(nodeConnector.getNode())) { - removeSet.add(nodeConnector); - } - } - return removeSet; - } - - private void removeDiscovery(Node node) { - Set removeSet; - - removeSet = getRemoveSet(edgeMap.keySet(), node); - NodeConnector peerConnector; - Edge edge1, edge2; - for (NodeConnector nodeConnector : removeSet) { - // get the peer for fast removal of the edge in reverse direction - peerConnector = null; - edge1 = edgeMap.get(nodeConnector); - if (edge1 != null) { - edge2 = edgeMap.get(edge1.getTailNodeConnector()); - if ((edge2 != null) && node.equals(edge2.getTailNodeConnector().getNode())) { - peerConnector = edge2.getHeadNodeConnector(); - } - } - - removeEdge(nodeConnector, false); - removeEdge(peerConnector, isEnabled(peerConnector)); - } - - removeSet = getRemoveSet(prodMap.keySet(), node); - for (NodeConnector nodeConnector : removeSet) { - removeProdEdge(nodeConnector); - } - - removeSet = getRemoveSet(readyListHi, node); - readyListHi.removeAll(removeSet); - - removeSet = getRemoveSet(readyListLo, node); - readyListLo.removeAll(removeSet); - - removeSet = getRemoveSet(stagingList, node); - stagingList.removeAll(removeSet); - - removeSet = getRemoveSet(holdTime.keySet(), node); - for (NodeConnector nodeConnector : removeSet) { - holdTime.remove(nodeConnector); - } - - removeSet = getRemoveSet(elapsedTime.keySet(), node); - for (NodeConnector nodeConnector : removeSet) { - elapsedTime.remove(nodeConnector); - } - } - - private void removeDiscovery(NodeConnector nodeConnector) { - removeNodeConnector(nodeConnector); - removeEdge(nodeConnector, false); - removeProdEdge(nodeConnector); - } - - private void checkTimeout() { - Set removeSet = new HashSet(); - int ticks; - - Set monitorSet = holdTime.keySet(); - if (monitorSet != null) { - for (NodeConnector nodeConnector : monitorSet) { - ticks = holdTime.get(nodeConnector); - holdTime.put(nodeConnector, ++ticks); - if (ticks >= discoveryTimeoutTicks) { - // timeout the edge - removeSet.add(nodeConnector); - logger.trace("Discovery timeout {}", nodeConnector); - } - } - } - - for (NodeConnector nodeConnector : removeSet) { - removeEdge(nodeConnector); - } - - Set retrySet = new HashSet(); - Set ncSet = elapsedTime.keySet(); - if ((ncSet != null) && (ncSet.size() > 0)) { - for (NodeConnector nodeConnector : ncSet) { - ticks = elapsedTime.get(nodeConnector); - elapsedTime.put(nodeConnector, ++ticks); - if (ticks >= discoveryThresholdTicks) { - retrySet.add(nodeConnector); - } - } - - for (NodeConnector nodeConnector : retrySet) { - // Allow one more retry - elapsedTime.remove(nodeConnector); - if (connectionOutService.isLocal(nodeConnector.getNode())) { - transmitQ.add(nodeConnector); - } - } - } - } - - private void checkAging() { - if (!discoveryAgingEnabled) { - return; - } - - Set removeSet = new HashSet(); - int ticks; - - Set agingSet = agingMap.keySet(); - if (agingSet != null) { - for (NodeConnector nodeConnector : agingSet) { - ticks = agingMap.get(nodeConnector); - agingMap.put(nodeConnector, ++ticks); - if (ticks > discoveryAgeoutTicks) { - // age out the edge - removeSet.add(nodeConnector); - logger.trace("Discovery age out {}", nodeConnector); - } - } - } - - for (NodeConnector nodeConnector : removeSet) { - removeProdEdge(nodeConnector); - } - } - - private void doDiscovery() { - if (++discoveryTimerTickCount <= discoveryBatchPauseTicks) { - for (NodeConnector nodeConnector : getWorkingSet()) { - if (connectionOutService.isLocal(nodeConnector.getNode())) { - transmitQ.add(nodeConnector); - // Move to staging area after it's served - if (!stagingList.contains(nodeConnector)) { - stagingList.add(nodeConnector); - } - } - } - } else if (discoveryTimerTickCount >= discoveryBatchRestartTicks) { - discoveryTimerTickCount = 0; - for (NodeConnector nodeConnector : stagingList) { - if (!readyListLo.contains(nodeConnector)) { - readyListLo.add(nodeConnector); - } - } - stagingList.removeAll(readyListLo); - } - } - - private void doConsistencyCheck() { - if (!discoveryConsistencyCheckEnabled) { - return; - } - - if (++discoveryConsistencyCheckTickCount % getDiscoveryConsistencyCheckInterval() != 0) { - return; - } - - discoveryConsistencyCheckCallingTimes++; - - Set removeSet = new HashSet(); - Set ncSet = edgeMap.keySet(); - if (ncSet == null) { - return; - } - for (NodeConnector nodeConnector : ncSet) { - if (!isEnabled(nodeConnector)) { - removeSet.add(nodeConnector); - discoveryConsistencyCheckCorrected++; - logger.debug("ConsistencyChecker: remove disabled {}", nodeConnector); - continue; - } - - if (!isTracked(nodeConnector)) { - stagingList.add(nodeConnector); - discoveryConsistencyCheckCorrected++; - logger.debug("ConsistencyChecker: add back untracked {}", nodeConnector); - continue; - } - } - - for (NodeConnector nodeConnector : removeSet) { - removeEdge(nodeConnector, false); - } - - // remove stale entries - removeSet.clear(); - for (NodeConnector nodeConnector : stagingList) { - if (!isEnabled(nodeConnector)) { - removeSet.add(nodeConnector); - discoveryConsistencyCheckCorrected++; - logger.debug("ConsistencyChecker: remove disabled {}", nodeConnector); - } - } - stagingList.removeAll(removeSet); - - // Get a snapshot of all the existing switches - Map switches = this.controller.getSwitches(); - for (ISwitch sw : switches.values()) { - for (OFPhysicalPort port : sw.getEnabledPorts()) { - Node node = NodeCreator.createOFNode(sw.getId()); - NodeConnector nodeConnector = NodeConnectorCreator.createOFNodeConnector(port.getPortNumber(), node); - if (!isTracked(nodeConnector)) { - stagingList.add(nodeConnector); - discoveryConsistencyCheckCorrected++; - logger.debug("ConsistencyChecker: add back untracked {}", nodeConnector); - } - } - } - } - - private void addEdge(Edge edge, Set props) { - if (edge == null) { - return; - } - - NodeConnector src = edge.getTailNodeConnector(); - NodeConnector dst = edge.getHeadNodeConnector(); - if (!src.getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) { - holdTime.put(dst, 0); - } else { - agingMap.put(dst, 0); - } - elapsedTime.remove(src); - - // fast discovery of the edge in reverse direction - if (!edgeMap.containsKey(dst) && !readyListHi.contains(dst) && !elapsedTime.keySet().contains(dst)) { - moveToReadyListHi(dst); - } - - //checking only OF map, since production edge discovery always overwrites any existing edge - UpdateType ut = edgeMap.containsKey(dst) ? UpdateType.CHANGED : UpdateType.ADDED; - // notify - updateEdge(edge, ut, props); - logger.trace("Add edge {}", edge); - } - - /** - * Update Production Edge - * - * @param edge - * The Production Edge - * @param props - * Properties associated with the edge - */ - private void updateProdEdge(Edge edge, Set props) { - NodeConnector edgePort = edge.getHeadNodeConnector(); - - /* Do not update in case there is an existing OpenFlow link */ - if (edgeMap.get(edgePort) != null) { - logger.trace("Discarded edge {} since there is an existing OF link {}", edge, edgeMap.get(edgePort)); - return; - } - - /* Look for any existing Production Edge */ - Edge oldEdge = prodMap.get(edgePort); - if (oldEdge == null) { - /* Let's add a new one */ - addEdge(edge, props); - } else if (!edge.equals(oldEdge)) { - /* Remove the old one first */ - removeProdEdge(oldEdge.getHeadNodeConnector()); - /* Then add the new one */ - addEdge(edge, props); - } else { - /* o/w, just reset the aging timer */ - NodeConnector dst = edge.getHeadNodeConnector(); - agingMap.put(dst, 0); - } - } - - /** - * Remove Production Edge for a given edge port - * - * @param edgePort - * The OF edge port - */ - private void removeProdEdge(NodeConnector edgePort) { - agingMap.remove(edgePort); - - Edge edge = null; - Set prodKeySet = prodMap.keySet(); - if ((prodKeySet != null) && (prodKeySet.contains(edgePort))) { - edge = prodMap.get(edgePort); - prodMap.remove(edgePort); - } - - // notify Topology - if (this.discoveryListener != null) { - this.discoveryListener.notifyEdge(edge, UpdateType.REMOVED, null); - } - logger.trace("Remove edge {}", edge); - } - - /* - * Remove OpenFlow edge - */ - private void removeEdge(NodeConnector nodeConnector, boolean stillEnabled) { - if (nodeConnector == null) { - return; - } - - removeNodeConnector(nodeConnector); - - if (stillEnabled) { - // keep discovering - stagingList.add(nodeConnector); - } - - Edge edge = null; - Set edgeKeySet = edgeMap.keySet(); - if ((edgeKeySet != null) && (edgeKeySet.contains(nodeConnector))) { - edge = edgeMap.get(nodeConnector); - edgeMap.remove(nodeConnector); - } - - // notify Topology - if (this.discoveryListener != null) { - this.discoveryListener.notifyEdge(edge, UpdateType.REMOVED, null); - } - logger.trace("Remove {}", nodeConnector); - } - - private void removeEdge(NodeConnector nodeConnector) { - removeEdge(nodeConnector, isEnabled(nodeConnector)); - } - - private void updateEdge(Edge edge, UpdateType type, Set props) { - if (discoveryListener == null) { - return; - } - - - this.discoveryListener.notifyEdge(edge, type, props); - - NodeConnector src = edge.getTailNodeConnector(), dst = edge.getHeadNodeConnector(); - if (!src.getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) { - if (type == UpdateType.ADDED) { - edgeMap.put(dst, edge); - } else if (type == UpdateType.REMOVED) { - edgeMap.remove(dst); - } - } else { - /* - * Save Production edge into different DB keyed by the Edge port - */ - if (type == UpdateType.ADDED) { - prodMap.put(dst, edge); - } else if (type == UpdateType.REMOVED) { - prodMap.remove(dst); - } - } - } - - private void moveToReadyListHi(NodeConnector nodeConnector) { - if (readyListLo.contains(nodeConnector)) { - readyListLo.remove(nodeConnector); - } else if (stagingList.contains(nodeConnector)) { - stagingList.remove(nodeConnector); - } - readyListHi.add(nodeConnector); - } - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, null); - } - - private int getDiscoveryConsistencyCheckInterval() { - return discoveryConsistencyCheckMultiple * discoveryBatchRestartTicks; - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---Topology Discovery---\n"); - help.append("\t prlh - Print readyListHi entries\n"); - help.append("\t prll - Print readyListLo entries\n"); - help.append("\t psl - Print stagingList entries\n"); - help.append("\t pht - Print hold time\n"); - help.append("\t pet - Print elapsed time\n"); - help.append("\t ptick - Print tick time in msec\n"); - help.append("\t pcc - Print CC info\n"); - help.append("\t psize - Print sizes of all the lists\n"); - help.append("\t ptm - Print timeout info\n"); - help.append("\t ecc - Enable CC\n"); - help.append("\t dcc - Disable CC\n"); - help.append("\t scc [multiple] - Set/show CC multiple and interval\n"); - help.append("\t sports [ports] - Set/show max ports per batch\n"); - help.append("\t spause [ticks] - Set/show pause period\n"); - help.append("\t sdi [ticks] - Set/show discovery interval in ticks\n"); - help.append("\t addsw - Add a switch\n"); - help.append("\t remsw - Remove a switch\n"); - help.append("\t page - Print aging info\n"); - help.append("\t sage - Set/Show aging time limit\n"); - help.append("\t eage - Enable aging\n"); - help.append("\t dage - Disable aging\n"); - help.append("\t pthrot - Print throttling\n"); - help.append("\t ethrot - Enable throttling\n"); - help.append("\t dthrot - Disable throttling\n"); - help.append("\t psnp - Print LLDP snooping\n"); - help.append("\t esnp - Enable LLDP snooping\n"); - help.append("\t dsnp - Disable LLDP snooping\n"); - return help.toString(); - } - - private List sortList(Collection ncs) { - List ncStrArray = new ArrayList(); - for (NodeConnector nc : ncs) { - ncStrArray.add(nc.toString()); - } - Collections.sort(ncStrArray); - - List sortedNodeConnectors = new ArrayList(); - for (String ncStr : ncStrArray) { - sortedNodeConnectors.add(NodeConnector.fromString(ncStr)); - } - - return sortedNodeConnectors; - } - - public void _prlh(CommandInterpreter ci) { - ci.println("readyListHi\n"); - for (NodeConnector nodeConnector : sortList(readyListHi)) { - if (nodeConnector == null) { - continue; - } - ci.println(nodeConnector); - } - ci.println("Total number of Node Connectors: " + readyListHi.size()); - } - - public void _prll(CommandInterpreter ci) { - ci.println("readyListLo\n"); - for (NodeConnector nodeConnector : sortList(readyListLo)) { - if (nodeConnector == null) { - continue; - } - ci.println(nodeConnector); - } - ci.println("Total number of Node Connectors: " + readyListLo.size()); - } - - public void _psl(CommandInterpreter ci) { - ci.println("stagingList\n"); - for (NodeConnector nodeConnector : sortList(stagingList)) { - if (nodeConnector == null) { - continue; - } - ci.println(nodeConnector); - } - ci.println("Total number of Node Connectors: " + stagingList.size()); - } - - public void _pht(CommandInterpreter ci) { - ci.println(" NodeConnector Last rx LLDP (sec)"); - for (ConcurrentMap.Entry entry: holdTime.entrySet()) { - ci.println(entry.getKey() + "\t\t" + entry.getValue() * (discoveryTimerTick / 1000)); - } - ci.println("\nSize: " + holdTime.size() + "\tTimeout: " + discoveryTimeoutTicks * (discoveryTimerTick / 1000) - + " sec"); - } - - public void _pet(CommandInterpreter ci) { - ci.println(" NodeConnector Elapsed Time (sec)"); - for (ConcurrentMap.Entry entry: elapsedTime.entrySet()) { - ci.println(entry.getKey() + "\t\t" + entry.getValue() * (discoveryTimerTick / 1000)); - } - ci.println("\nSize: " + elapsedTime.size() + "\tThreshold: " + DiscoveryPeriod.THRESHOLD.getTime() + " sec"); - } - - public void _ptick(CommandInterpreter ci) { - ci.println("Current timer is " + discoveryTimerTick + " msec per tick"); - } - - public void _pcc(CommandInterpreter ci) { - if (discoveryConsistencyCheckEnabled) { - ci.println("ConsistencyChecker is currently enabled"); - } else { - ci.println("ConsistencyChecker is currently disabled"); - } - ci.println("Interval " + getDiscoveryConsistencyCheckInterval()); - ci.println("Multiple " + discoveryConsistencyCheckMultiple); - ci.println("Number of times called " + discoveryConsistencyCheckCallingTimes); - ci.println("Corrected count " + discoveryConsistencyCheckCorrected); - } - - public void _ptm(CommandInterpreter ci) { - ci.println("Timeout " + discoveryTimeoutTicks + " ticks, " + discoveryTimerTick / 1000 + " sec per tick."); - } - - public void _psize(CommandInterpreter ci) { - ci.println("readyListLo size " + readyListLo.size() + "\n" + "readyListHi size " + readyListHi.size() + "\n" - + "stagingList size " + stagingList.size() + "\n" + "holdTime size " + holdTime.size() + "\n" - + "edgeMap size " + edgeMap.size() + "\n" + "prodMap size " + prodMap.size() + "\n" + "agingMap size " - + agingMap.size() + "\n" + "elapsedTime size " + elapsedTime.size()); - } - - public void _page(CommandInterpreter ci) { - if (this.discoveryAgingEnabled) { - ci.println("Aging is enabled"); - } else { - ci.println("Aging is disabled"); - } - ci.println("Current aging time limit " + this.discoveryAgeoutTicks); - ci.println("\n"); - ci.println(" Edge Aging "); - Collection prodSet = prodMap.values(); - if (prodSet == null) { - return; - } - for (Edge edge : prodSet) { - Integer aging = agingMap.get(edge.getHeadNodeConnector()); - if (aging != null) { - ci.println(edge + " " + aging); - } - } - ci.println("\n"); - ci.println(" NodeConnector Edge "); - Set keySet = prodMap.keySet(); - if (keySet == null) { - return; - } - for (NodeConnector nc : keySet) { - ci.println(nc + " " + prodMap.get(nc)); - } - return; - } - - public void _sage(CommandInterpreter ci) { - String val = ci.nextArgument(); - if (val == null) { - ci.println("Please enter aging time limit. Current value " + this.discoveryAgeoutTicks); - return; - } - try { - this.discoveryAgeoutTicks = Integer.parseInt(val); - } catch (Exception e) { - ci.println("Please enter a valid number"); - } - return; - } - - public void _eage(CommandInterpreter ci) { - this.discoveryAgingEnabled = true; - ci.println("Aging is enabled"); - return; - } - - public void _dage(CommandInterpreter ci) { - this.discoveryAgingEnabled = false; - ci.println("Aging is disabled"); - return; - } - - public void _scc(CommandInterpreter ci) { - String val = ci.nextArgument(); - if (val == null) { - ci.println("Please enter CC multiple. Current multiple " + discoveryConsistencyCheckMultiple - + " (interval " + getDiscoveryConsistencyCheckInterval() + ") calling times " - + discoveryConsistencyCheckCallingTimes); - return; - } - try { - discoveryConsistencyCheckMultiple = Integer.parseInt(val); - } catch (Exception e) { - ci.println("Please enter a valid number"); - } - return; - } - - public void _ecc(CommandInterpreter ci) { - this.discoveryConsistencyCheckEnabled = true; - ci.println("ConsistencyChecker is enabled"); - return; - } - - public void _dcc(CommandInterpreter ci) { - this.discoveryConsistencyCheckEnabled = false; - ci.println("ConsistencyChecker is disabled"); - return; - } - - public void _psnp(CommandInterpreter ci) { - if (this.discoverySnoopingEnabled) { - ci.println("Discovery snooping is globally enabled"); - } else { - ci.println("Discovery snooping is globally disabled"); - } - - ci.println("\nDiscovery snooping is locally disabled on these ports"); - for (NodeConnector nodeConnector : discoverySnoopingDisableList) { - ci.println(nodeConnector); - } - return; - } - - public void _esnp(CommandInterpreter ci) { - String val = ci.nextArgument(); - - if (val == null) { - ci.println("Usage: esnp "); - } else if (val.equalsIgnoreCase("all")) { - this.discoverySnoopingEnabled = true; - ci.println("Discovery snooping is globally enabled"); - } else { - NodeConnector nodeConnector = NodeConnector.fromString(val); - if (nodeConnector != null) { - discoverySnoopingDisableList.remove(nodeConnector); - ci.println("Discovery snooping is locally enabled on port " + nodeConnector); - } else { - ci.println("Entered invalid NodeConnector " + val); - } - } - return; - } - - public void _dsnp(CommandInterpreter ci) { - String val = ci.nextArgument(); - - if (val == null) { - ci.println("Usage: dsnp "); - } else if (val.equalsIgnoreCase("all")) { - this.discoverySnoopingEnabled = false; - ci.println("Discovery snooping is globally disabled"); - } else { - NodeConnector nodeConnector = NodeConnector.fromString(val); - if (nodeConnector != null) { - discoverySnoopingDisableList.add(nodeConnector); - ci.println("Discovery snooping is locally disabled on port " + nodeConnector); - } else { - ci.println("Entered invalid NodeConnector " + val); - } - } - return; - } - - public void _spause(CommandInterpreter ci) { - String val = ci.nextArgument(); - String out = "Please enter pause period less than " + discoveryBatchRestartTicks + ". Current pause period is " - + discoveryBatchPausePeriod + " ticks, pause at " + discoveryBatchPauseTicks + " ticks, " - + discoveryTimerTick / 1000 + " sec per tick."; - - if (val != null) { - try { - int pause = Integer.parseInt(val); - if (pause < discoveryBatchRestartTicks) { - discoveryBatchPausePeriod = pause; - discoveryBatchPauseTicks = getDiscoveryPauseInterval(); - return; - } - } catch (Exception e) { - } - } - - ci.println(out); - } - - public void _sdi(CommandInterpreter ci) { - String val = ci.nextArgument(); - String out = "Please enter discovery interval in ticks. Current value is " + discoveryBatchRestartTicks + " ticks, " - + discoveryTimerTick / 1000 + " sec per tick."; - - if (val != null) { - try { - int ticks; - Set monitorSet = holdTime.keySet(); - if (monitorSet != null) { - for (NodeConnector nodeConnector : monitorSet) { - holdTime.put(nodeConnector, 0); - } - } - - ticks = Integer.parseInt(val); - DiscoveryPeriod.INTERVAL.setTick(ticks); - discoveryBatchRestartTicks = getDiscoveryInterval(); - discoveryBatchPauseTicks = getDiscoveryPauseInterval(); - discoveryTimeoutTicks = getDiscoveryTimeout(); - return; - } catch (Exception e) { - } - } - ci.println(out); - } - - public void _sports(CommandInterpreter ci) { - String val = ci.nextArgument(); - if (val == null) { - ci.println("Please enter max ports per batch. Current value is " + discoveryBatchMaxPorts); - return; - } - try { - discoveryBatchMaxPorts = Integer.parseInt(val); - } catch (Exception e) { - ci.println("Please enter a valid number"); - } - return; - } - - public void _addsw(CommandInterpreter ci) { - String val = ci.nextArgument(); - Long sid; - try { - sid = Long.parseLong(val); - Node node = NodeCreator.createOFNode(sid); - addDiscovery(node); - } catch (Exception e) { - ci.println("Please enter a valid number"); - } - return; - } - - public void _remsw(CommandInterpreter ci) { - String val = ci.nextArgument(); - Long sid; - try { - sid = Long.parseLong(val); - Node node = NodeCreator.createOFNode(sid); - removeDiscovery(node); - } catch (Exception e) { - ci.println("Please enter a valid number"); - } - return; - } - - public void _pthrot(CommandInterpreter ci) { - if (this.throttling) { - ci.println("Throttling is enabled"); - } else { - ci.println("Throttling is disabled"); - } - } - - public void _ethrot(CommandInterpreter ci) { - this.throttling = true; - ci.println("Throttling is enabled"); - return; - } - - public void _dthrot(CommandInterpreter ci) { - this.throttling = false; - ci.println("Throttling is disabled"); - return; - } - - @Override - public void updateNode(Node node, UpdateType type, Set props) { - switch (type) { - case ADDED: - addNode(node, props); - break; - case REMOVED: - removeNode(node); - break; - default: - break; - } - } - - @Override - public void updateNodeConnector(NodeConnector nodeConnector, UpdateType type, Set props) { - Config config = null; - State state = null; - boolean enabled = false; - - for (Property prop : props) { - if (prop.getName().equals(Config.ConfigPropName)) { - config = (Config) prop; - } else if (prop.getName().equals(State.StatePropName)) { - state = (State) prop; - } - } - enabled = ((config != null) && (config.getValue() == Config.ADMIN_UP) && (state != null) && (state.getValue() == State.EDGE_UP)); - - switch (type) { - case ADDED: - if (enabled) { - addDiscovery(nodeConnector); - logger.trace("ADDED enabled {}", nodeConnector); - } else { - logger.trace("ADDED disabled {}", nodeConnector); - } - break; - case CHANGED: - if (enabled) { - addDiscovery(nodeConnector); - logger.trace("CHANGED enabled {}", nodeConnector); - } else { - removeDiscovery(nodeConnector); - logger.trace("CHANGED disabled {}", nodeConnector); - } - break; - case REMOVED: - removeDiscovery(nodeConnector); - logger.trace("REMOVED enabled {}", nodeConnector); - break; - default: - return; - } - } - - public void addNode(Node node, Set props) { - if (node == null) { - return; - } - - addDiscovery(node); - } - - public void removeNode(Node node) { - if (node == null) { - return; - } - - removeDiscovery(node); - } - - void setController(IController s) { - this.controller = s; - } - - void unsetController(IController s) { - if (this.controller == s) { - this.controller = null; - } - } - - public void setInventoryProvider(IInventoryProvider service) { - this.inventoryProvider = service; - } - - public void unsetInventoryProvider(IInventoryProvider service) { - this.inventoryProvider = null; - } - - public void setIDataPacketMux(IDataPacketMux service) { - this.iDataPacketMux = service; - } - - public void unsetIDataPacketMux(IDataPacketMux service) { - if (this.iDataPacketMux == service) { - this.iDataPacketMux = null; - } - } - - void setDiscoveryListener(IDiscoveryListener s) { - this.discoveryListener = s; - } - - void unsetDiscoveryListener(IDiscoveryListener s) { - if (this.discoveryListener == s) { - this.discoveryListener = null; - } - } - - void setIPluginOutConnectionService(IPluginOutConnectionService s) { - connectionOutService = s; - } - - void unsetIPluginOutConnectionService(IPluginOutConnectionService s) { - if (connectionOutService == s) { - connectionOutService = null; - } - } - - private void initDiscoveryPacket() { - // Create LLDP ChassisID TLV - chassisIdTlv = new LLDPTLV(); - chassisIdTlv.setType(LLDPTLV.TLVType.ChassisID.getValue()); - - // Create LLDP SystemName TLV - systemNameTlv = new LLDPTLV(); - systemNameTlv.setType(LLDPTLV.TLVType.SystemName.getValue()); - - // Create LLDP PortID TLV - portIdTlv = new LLDPTLV(); - portIdTlv.setType(LLDPTLV.TLVType.PortID.getValue()); - - // Create LLDP TTL TLV - byte[] ttl = new byte[] { (byte) 0, (byte) 120 }; - ttlTlv = new LLDPTLV(); - ttlTlv.setType(LLDPTLV.TLVType.TTL.getValue()).setLength((short) ttl.length).setValue(ttl); - - customTlv = new LLDPTLV(); - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - logger.trace("Init called"); - - transmitQ = new LinkedBlockingQueue(); - - readyListHi = new CopyOnWriteArrayList(); - readyListLo = new CopyOnWriteArrayList(); - stagingList = new CopyOnWriteArrayList(); - holdTime = new ConcurrentHashMap(); - elapsedTime = new ConcurrentHashMap(); - edgeMap = new ConcurrentHashMap(); - agingMap = new ConcurrentHashMap(); - prodMap = new ConcurrentHashMap(); - discoverySnoopingDisableList = new CopyOnWriteArrayList(); - - discoveryBatchRestartTicks = getDiscoveryInterval(); - discoveryBatchPauseTicks = getDiscoveryPauseInterval(); - discoveryTimeoutTicks = getDiscoveryTimeout(); - discoveryThresholdTicks = getDiscoveryThreshold(); - discoveryAgeoutTicks = getDiscoveryAgeout(); - discoveryConsistencyCheckTickCount = discoveryBatchPauseTicks; - discoveryBatchMaxPorts = getDiscoveryBatchMaxPorts(); - - discoveryTimer = new Timer("DiscoveryService"); - discoveryTimerTask = new DiscoveryTimerTask(); - - transmitThread = new Thread(new DiscoveryTransmit(transmitQ)); - - initDiscoveryPacket(); - - registerWithOSGIConsole(); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - transmitQ = null; - readyListHi = null; - readyListLo = null; - stagingList = null; - holdTime = null; - edgeMap = null; - agingMap = null; - prodMap = null; - discoveryTimer = null; - discoveryTimerTask = null; - transmitThread = null; - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - discoveryTimer.schedule(discoveryTimerTask, discoveryTimerTick, discoveryTimerTick); - transmitThread.start(); - } - - /** - * Function called after registering the service in OSGi service registry. - */ - void started() { - /* get a snapshot of all the existing switches */ - addDiscovery(); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - shuttingDown = true; - discoveryTimer.cancel(); - transmitThread.interrupt(); - } - - @Override - public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) { - } - - @Override - public void containerFlowUpdated(String containerName, ContainerFlow previousFlow, ContainerFlow currentFlow, - UpdateType t) { - } - - @Override - public void nodeConnectorUpdated(String containerName, NodeConnector p, UpdateType t) { - switch (t) { - case ADDED: - moveToReadyListHi(p); - break; - default: - break; - } - } - - @Override - public void containerModeUpdated(UpdateType t) { - // do nothing - } - - private byte[] getSourceMACFromNodeID(String nodeId) { - byte[] cid = HexEncode.bytesFromHexString(nodeId); - byte[] sourceMac = new byte[6]; - int pos = cid.length - sourceMac.length; - - if (pos >= 0) { - System.arraycopy(cid, pos, sourceMac, 0, sourceMac.length); - } - - return sourceMac; - } - - private int getDiscoveryTicks(DiscoveryPeriod dp, String val) { - if (dp == null) { - return 0; - } - - if (val != null) { - try { - dp.setTime(Integer.parseInt(val)); - } catch (Exception e) { - } - } - - return dp.getTick(); - } - - /** - * This method returns the interval which determines how often the discovery - * packets will be sent. - * - * @return The discovery interval in ticks - */ - private int getDiscoveryInterval() { - String intvl = System.getProperty("of.discoveryInterval"); - return getDiscoveryTicks(DiscoveryPeriod.INTERVAL, intvl); - } - - /** - * This method returns the timeout value in receiving subsequent discovery packets on a port. - * - * @return The discovery timeout in ticks - */ - private int getDiscoveryTimeout() { - String val = System.getProperty("of.discoveryTimeoutMultiple"); - int multiple = 2; - - if (val != null) { - try { - multiple = Integer.parseInt(val); - } catch (Exception e) { - } - } - return getDiscoveryInterval() * multiple + 3; - } - - /** - * This method returns the user configurable threshold value - * - * @return The discovery threshold value in ticks - */ - private int getDiscoveryThreshold() { - String val = System.getProperty("of.discoveryThreshold"); - return getDiscoveryTicks(DiscoveryPeriod.THRESHOLD, val); - } - - /** - * This method returns the discovery entry aging time in ticks. - * - * @return The aging time in ticks - */ - private int getDiscoveryAgeout() { - return getDiscoveryTicks(DiscoveryPeriod.AGEOUT, null); - } - - /** - * This method returns the pause interval - * - * @return The pause interval in ticks - */ - private int getDiscoveryPauseInterval() { - if (discoveryBatchRestartTicks > discoveryBatchPausePeriod) { - return discoveryBatchRestartTicks - discoveryBatchPausePeriod; - } else { - return discoveryBatchRestartTicks - 1; - } - } - - /** - * This method returns the user configurable maximum number of ports handled - * in one discovery batch. - * - * @return The maximum number of ports - */ - private int getDiscoveryBatchMaxPorts() { - String val = System.getProperty("of.discoveryBatchMaxPorts"); - int ports = 512; - - if (val != null) { - try { - ports = Integer.parseInt(val); - } catch (Exception e) { - } - } - return ports; - } - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowConverter.java deleted file mode 100644 index 8893762c3c..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowConverter.java +++ /dev/null @@ -1,815 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.math.BigInteger; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6FlowMod; -import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6Match; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.ActionType; -import org.opendaylight.controller.sal.action.Controller; -import org.opendaylight.controller.sal.action.Drop; -import org.opendaylight.controller.sal.action.Enqueue; -import org.opendaylight.controller.sal.action.Flood; -import org.opendaylight.controller.sal.action.FloodAll; -import org.opendaylight.controller.sal.action.HwPath; -import org.opendaylight.controller.sal.action.Loopback; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.action.PopVlan; -import org.opendaylight.controller.sal.action.SetDlDst; -import org.opendaylight.controller.sal.action.SetDlSrc; -import org.opendaylight.controller.sal.action.SetNwDst; -import org.opendaylight.controller.sal.action.SetNwSrc; -import org.opendaylight.controller.sal.action.SetNwTos; -import org.opendaylight.controller.sal.action.SetTpDst; -import org.opendaylight.controller.sal.action.SetTpSrc; -import org.opendaylight.controller.sal.action.SetVlanId; -import org.opendaylight.controller.sal.action.SetVlanPcp; -import org.opendaylight.controller.sal.action.SwPath; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchField; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.openflow.protocol.OFFlowMod; -import org.openflow.protocol.OFMatch; -import org.openflow.protocol.OFMessage; -import org.openflow.protocol.OFPacketOut; -import org.openflow.protocol.OFPort; -import org.openflow.protocol.OFVendor; -import org.openflow.protocol.action.OFAction; -import org.openflow.protocol.action.OFActionDataLayer; -import org.openflow.protocol.action.OFActionDataLayerDestination; -import org.openflow.protocol.action.OFActionDataLayerSource; -import org.openflow.protocol.action.OFActionEnqueue; -import org.openflow.protocol.action.OFActionNetworkLayerAddress; -import org.openflow.protocol.action.OFActionNetworkLayerDestination; -import org.openflow.protocol.action.OFActionNetworkLayerSource; -import org.openflow.protocol.action.OFActionNetworkTypeOfService; -import org.openflow.protocol.action.OFActionOutput; -import org.openflow.protocol.action.OFActionStripVirtualLan; -import org.openflow.protocol.action.OFActionTransportLayer; -import org.openflow.protocol.action.OFActionTransportLayerDestination; -import org.openflow.protocol.action.OFActionTransportLayerSource; -import org.openflow.protocol.action.OFActionVirtualLanIdentifier; -import org.openflow.protocol.action.OFActionVirtualLanPriorityCodePoint; -import org.openflow.util.U16; -import org.openflow.util.U32; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Utility class for converting a SAL Flow into the OF flow and vice-versa - */ -public class FlowConverter { - protected static final Logger logger = LoggerFactory - .getLogger(FlowConverter.class); - - /* - * The value 0xffff (OFP_VLAN_NONE) is used to indicate - * that no VLAN ID is set for OF Flow. - */ - private static final short OFP_VLAN_NONE = (short) 0xffff; - - private Flow flow; // SAL Flow - private OFMatch ofMatch; // OF 1.0 match or OF 1.0 + IPv6 extension match - private List actionsList; // OF 1.0 actions - private int actionsLength; - private boolean isIPv6; - - public FlowConverter(OFMatch ofMatch, List actionsList) { - this.ofMatch = ofMatch; - this.actionsList = actionsList; - this.actionsLength = 0; - this.flow = null; - this.isIPv6 = ofMatch instanceof V6Match; - } - - public FlowConverter(Flow flow) { - this.ofMatch = null; - this.actionsList = null; - this.actionsLength = 0; - this.flow = flow; - this.isIPv6 = flow.isIPv6(); - } - - /** - * Returns the match in OF 1.0 (OFMatch) form or OF 1.0 + IPv6 extensions - * form (V6Match) - * - * @return - */ - public OFMatch getOFMatch() { - if (ofMatch == null) { - Match match = flow.getMatch(); - ofMatch = (isIPv6) ? new V6Match() : new OFMatch(); - - int wildcards = OFMatch.OFPFW_ALL; - if (match.isPresent(MatchType.IN_PORT)) { - short port = (Short) ((NodeConnector) match.getField( - MatchType.IN_PORT).getValue()).getID(); - if (!isIPv6) { - ofMatch.setInputPort(port); - wildcards &= ~OFMatch.OFPFW_IN_PORT; - } else { - ((V6Match) ofMatch).setInputPort(port, (short) 0); - } - } - if (match.isPresent(MatchType.DL_SRC)) { - byte[] srcMac = (byte[]) match.getField(MatchType.DL_SRC) - .getValue(); - if (!isIPv6) { - ofMatch.setDataLayerSource(srcMac.clone()); - wildcards &= ~OFMatch.OFPFW_DL_SRC; - } else { - ((V6Match) ofMatch).setDataLayerSource(srcMac, null); - } - } - if (match.isPresent(MatchType.DL_DST)) { - byte[] dstMac = (byte[]) match.getField(MatchType.DL_DST) - .getValue(); - if (!isIPv6) { - ofMatch.setDataLayerDestination(dstMac.clone()); - wildcards &= ~OFMatch.OFPFW_DL_DST; - } else { - ((V6Match) ofMatch).setDataLayerDestination(dstMac, null); - } - } - if (match.isPresent(MatchType.DL_VLAN)) { - short vlan = (Short) match.getField(MatchType.DL_VLAN) - .getValue(); - if (vlan == MatchType.DL_VLAN_NONE) { - vlan = OFP_VLAN_NONE; - } - if (!isIPv6) { - ofMatch.setDataLayerVirtualLan(vlan); - wildcards &= ~OFMatch.OFPFW_DL_VLAN; - } else { - ((V6Match) ofMatch).setDataLayerVirtualLan(vlan, (short) 0); - } - } - if (match.isPresent(MatchType.DL_VLAN_PR)) { - byte vlanPr = (Byte) match.getField(MatchType.DL_VLAN_PR) - .getValue(); - if (!isIPv6) { - ofMatch.setDataLayerVirtualLanPriorityCodePoint(vlanPr); - wildcards &= ~OFMatch.OFPFW_DL_VLAN_PCP; - } else { - ((V6Match) ofMatch) - .setDataLayerVirtualLanPriorityCodePoint(vlanPr, - (byte) 0); - } - } - if (match.isPresent(MatchType.DL_TYPE)) { - short ethType = (Short) match.getField(MatchType.DL_TYPE) - .getValue(); - if (!isIPv6) { - ofMatch.setDataLayerType(ethType); - wildcards &= ~OFMatch.OFPFW_DL_TYPE; - } else { - ((V6Match) ofMatch).setDataLayerType(ethType, (short) 0); - } - } - if (match.isPresent(MatchType.NW_TOS)) { - /* - * OF 1.0 switch expects the TOS as the 6 msb in the byte. it is - * actually the DSCP field followed by a zero ECN - */ - byte tos = (Byte) match.getField(MatchType.NW_TOS).getValue(); - byte dscp = (byte) (tos << 2); - if (!isIPv6) { - ofMatch.setNetworkTypeOfService(dscp); - wildcards &= ~OFMatch.OFPFW_NW_TOS; - } else { - ((V6Match) ofMatch).setNetworkTypeOfService(dscp, (byte) 0); - } - } - if (match.isPresent(MatchType.NW_PROTO)) { - byte proto = (Byte) match.getField(MatchType.NW_PROTO) - .getValue(); - if (!isIPv6) { - ofMatch.setNetworkProtocol(proto); - wildcards &= ~OFMatch.OFPFW_NW_PROTO; - } else { - ((V6Match) ofMatch).setNetworkProtocol(proto, (byte) 0); - } - } - if (match.isPresent(MatchType.NW_SRC)) { - InetAddress address = (InetAddress) match.getField(MatchType.NW_SRC).getValue(); - InetAddress mask = (InetAddress) match.getField(MatchType.NW_SRC).getMask(); - if (!isIPv6) { - ofMatch.setNetworkSource(NetUtils.byteArray4ToInt(address.getAddress())); - int maskLength = (mask == null) ? 32 : NetUtils.getSubnetMaskLength(mask); - wildcards = (wildcards & ~OFMatch.OFPFW_NW_SRC_MASK) | ((32 - maskLength) << OFMatch.OFPFW_NW_SRC_SHIFT); - } else { - ((V6Match) ofMatch).setNetworkSource(address, mask); - } - } - if (match.isPresent(MatchType.NW_DST)) { - InetAddress address = (InetAddress) match.getField(MatchType.NW_DST).getValue(); - InetAddress mask = (InetAddress) match.getField(MatchType.NW_DST).getMask(); - if (!isIPv6) { - ofMatch.setNetworkDestination(NetUtils.byteArray4ToInt(address.getAddress())); - int maskLength = (mask == null) ? 32 : NetUtils.getSubnetMaskLength(mask); - wildcards = (wildcards & ~OFMatch.OFPFW_NW_DST_MASK) | ((32 - maskLength) << OFMatch.OFPFW_NW_DST_SHIFT); - } else { - ((V6Match) ofMatch).setNetworkDestination(address, mask); - } - } - if (match.isPresent(MatchType.TP_SRC)) { - short port = (Short) match.getField(MatchType.TP_SRC) - .getValue(); - if (!isIPv6) { - ofMatch.setTransportSource(port); - wildcards &= ~OFMatch.OFPFW_TP_SRC; - } else { - ((V6Match) ofMatch).setTransportSource(port, (short) 0); - } - } - if (match.isPresent(MatchType.TP_DST)) { - short port = (Short) match.getField(MatchType.TP_DST) - .getValue(); - if (!isIPv6) { - ofMatch.setTransportDestination(port); - wildcards &= ~OFMatch.OFPFW_TP_DST; - } else { - ((V6Match) ofMatch) - .setTransportDestination(port, (short) 0); - } - } - - if (!isIPv6) { - ofMatch.setWildcards(U32.t(Long.valueOf(wildcards))); - } - } - logger.trace("SAL Match: {} Openflow Match: {}", flow.getMatch(), - ofMatch); - return ofMatch; - } - - /** - * Returns the list of actions in OF 1.0 form - * - * @return - */ - public List getOFActions() { - if (this.actionsList == null) { - actionsList = new ArrayList(); - for (Action action : flow.getActions()) { - if (action.getType() == ActionType.OUTPUT) { - Output a = (Output) action; - OFActionOutput ofAction = new OFActionOutput(); - ofAction.setMaxLength((short) 0xffff); - ofAction.setPort(PortConverter.toOFPort(a.getPort())); - actionsList.add(ofAction); - actionsLength += OFActionOutput.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.ENQUEUE) { - Enqueue a = (Enqueue) action; - OFActionEnqueue ofAction = new OFActionEnqueue(); - ofAction.setPort(PortConverter.toOFPort(a.getPort())); - ofAction.setQueueId(a.getQueue()); - actionsList.add(ofAction); - actionsLength += OFActionEnqueue.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.DROP) { - continue; - } - if (action.getType() == ActionType.LOOPBACK) { - OFActionOutput ofAction = new OFActionOutput(); - ofAction.setPort(OFPort.OFPP_IN_PORT.getValue()); - actionsList.add(ofAction); - actionsLength += OFActionOutput.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.FLOOD) { - OFActionOutput ofAction = new OFActionOutput(); - ofAction.setPort(OFPort.OFPP_FLOOD.getValue()); - actionsList.add(ofAction); - actionsLength += OFActionOutput.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.FLOOD_ALL) { - OFActionOutput ofAction = new OFActionOutput(); - ofAction.setPort(OFPort.OFPP_ALL.getValue()); - actionsList.add(ofAction); - actionsLength += OFActionOutput.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.CONTROLLER) { - OFActionOutput ofAction = new OFActionOutput(); - ofAction.setPort(OFPort.OFPP_CONTROLLER.getValue()); - // We want the whole frame hitting the match be sent to the - // controller - ofAction.setMaxLength((short) 0xffff); - actionsList.add(ofAction); - actionsLength += OFActionOutput.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SW_PATH) { - OFActionOutput ofAction = new OFActionOutput(); - ofAction.setPort(OFPort.OFPP_LOCAL.getValue()); - actionsList.add(ofAction); - actionsLength += OFActionOutput.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.HW_PATH) { - OFActionOutput ofAction = new OFActionOutput(); - ofAction.setPort(OFPort.OFPP_NORMAL.getValue()); - actionsList.add(ofAction); - actionsLength += OFActionOutput.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SET_VLAN_ID) { - SetVlanId a = (SetVlanId) action; - OFActionVirtualLanIdentifier ofAction = new OFActionVirtualLanIdentifier(); - ofAction.setVirtualLanIdentifier((short) a.getVlanId()); - actionsList.add(ofAction); - actionsLength += OFActionVirtualLanIdentifier.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SET_VLAN_PCP) { - SetVlanPcp a = (SetVlanPcp) action; - OFActionVirtualLanPriorityCodePoint ofAction = new OFActionVirtualLanPriorityCodePoint(); - ofAction.setVirtualLanPriorityCodePoint(Integer.valueOf( - a.getPcp()).byteValue()); - actionsList.add(ofAction); - actionsLength += OFActionVirtualLanPriorityCodePoint.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.POP_VLAN) { - OFActionStripVirtualLan ofAction = new OFActionStripVirtualLan(); - actionsList.add(ofAction); - actionsLength += OFActionStripVirtualLan.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SET_DL_SRC) { - SetDlSrc a = (SetDlSrc) action; - OFActionDataLayerSource ofAction = new OFActionDataLayerSource(); - ofAction.setDataLayerAddress(a.getDlAddress()); - actionsList.add(ofAction); - actionsLength += OFActionDataLayer.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SET_DL_DST) { - SetDlDst a = (SetDlDst) action; - OFActionDataLayerDestination ofAction = new OFActionDataLayerDestination(); - ofAction.setDataLayerAddress(a.getDlAddress()); - actionsList.add(ofAction); - actionsLength += OFActionDataLayer.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SET_NW_SRC) { - SetNwSrc a = (SetNwSrc) action; - OFActionNetworkLayerSource ofAction = new OFActionNetworkLayerSource(); - ofAction.setNetworkAddress(NetUtils.byteArray4ToInt(a - .getAddress().getAddress())); - actionsList.add(ofAction); - actionsLength += OFActionNetworkLayerAddress.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SET_NW_DST) { - SetNwDst a = (SetNwDst) action; - OFActionNetworkLayerDestination ofAction = new OFActionNetworkLayerDestination(); - ofAction.setNetworkAddress(NetUtils.byteArray4ToInt(a - .getAddress().getAddress())); - actionsList.add(ofAction); - actionsLength += OFActionNetworkLayerAddress.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SET_NW_TOS) { - SetNwTos a = (SetNwTos) action; - OFActionNetworkTypeOfService ofAction = new OFActionNetworkTypeOfService(); - ofAction.setNetworkTypeOfService(Integer.valueOf( - a.getNwTos()).byteValue()); - actionsList.add(ofAction); - actionsLength += OFActionNetworkTypeOfService.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SET_TP_SRC) { - SetTpSrc a = (SetTpSrc) action; - OFActionTransportLayerSource ofAction = new OFActionTransportLayerSource(); - ofAction.setTransportPort(Integer.valueOf(a.getPort()) - .shortValue()); - actionsList.add(ofAction); - actionsLength += OFActionTransportLayer.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SET_TP_DST) { - SetTpDst a = (SetTpDst) action; - OFActionTransportLayerDestination ofAction = new OFActionTransportLayerDestination(); - ofAction.setTransportPort(Integer.valueOf(a.getPort()) - .shortValue()); - actionsList.add(ofAction); - actionsLength += OFActionTransportLayer.MINIMUM_LENGTH; - continue; - } - if (action.getType() == ActionType.SET_NEXT_HOP) { - logger.warn("Unsupported action: {}", action); - continue; - } - } - } - logger.trace("SAL Actions: {} Openflow Actions: {}", flow.getActions(), - actionsList); - return actionsList; - } - - /** - * Utility to convert a SAL flow to an OF 1.0 (OFFlowMod) or to an OF 1.0 + - * IPv6 extension (V6FlowMod) Flow modifier Message - * - * @param sw - * @param command - * @param port - * @return - */ - public OFMessage getOFFlowMod(short command, OFPort port) { - OFMessage fm = (isIPv6) ? new V6FlowMod() : new OFFlowMod(); - if (this.ofMatch == null) { - getOFMatch(); - } - if (this.actionsList == null) { - getOFActions(); - } - if (!isIPv6) { - ((OFFlowMod) fm).setMatch(this.ofMatch); - ((OFFlowMod) fm).setActions(this.actionsList); - ((OFFlowMod) fm).setPriority(flow.getPriority()); - ((OFFlowMod) fm).setCookie(flow.getId()); - ((OFFlowMod) fm).setBufferId(OFPacketOut.BUFFER_ID_NONE); - ((OFFlowMod) fm).setLength(U16.t(OFFlowMod.MINIMUM_LENGTH - + actionsLength)); - ((OFFlowMod) fm).setIdleTimeout(flow.getIdleTimeout()); - ((OFFlowMod) fm).setHardTimeout(flow.getHardTimeout()); - ((OFFlowMod) fm).setCommand(command); - if (port != null) { - ((OFFlowMod) fm).setOutPort(port); - } - if (command == OFFlowMod.OFPFC_ADD || command == OFFlowMod.OFPFC_MODIFY - || command == OFFlowMod.OFPFC_MODIFY_STRICT) { - // Instruct switch to let controller know when flow is removed - ((OFFlowMod) fm).setFlags((short) 1); - } - } else { - ((V6FlowMod) fm).setVendor(); - ((V6FlowMod) fm).setMatch((V6Match) ofMatch); - ((V6FlowMod) fm).setActions(this.actionsList); - ((V6FlowMod) fm).setPriority(flow.getPriority()); - ((V6FlowMod) fm).setCookie(flow.getId()); - ((V6FlowMod) fm).setLength(U16.t(OFVendor.MINIMUM_LENGTH - + ((V6Match) ofMatch).getIPv6ExtMinHdrLen() - + ((V6Match) ofMatch).getIPv6MatchLen() - + ((V6Match) ofMatch).getPadSize() + actionsLength)); - ((V6FlowMod) fm).setIdleTimeout(flow.getIdleTimeout()); - ((V6FlowMod) fm).setHardTimeout(flow.getHardTimeout()); - ((V6FlowMod) fm).setCommand(command); - if (port != null) { - ((V6FlowMod) fm).setOutPort(port); - } - if (command == OFFlowMod.OFPFC_ADD || command == OFFlowMod.OFPFC_MODIFY - || command == OFFlowMod.OFPFC_MODIFY_STRICT) { - // Instruct switch to let controller know when flow is removed - ((V6FlowMod) fm).setFlags((short) 1); - } - } - logger.trace("Openflow Match: {} Openflow Actions: {}", ofMatch, - actionsList); - logger.trace("Openflow Mod Message: {}", fm); - return fm; - } - - public Flow getFlow(Node node) { - if (this.flow == null) { - Match salMatch = new Match(); - - /* - * Installed flow may not have a Match defined like in case of a - * drop all flow - */ - if (ofMatch != null) { - if (!isIPv6) { - // Compute OF1.0 Match - if (ofMatch.getInputPort() != 0 && ofMatch.getInputPort() != OFPort.OFPP_LOCAL.getValue()) { - salMatch.setField(new MatchField(MatchType.IN_PORT, - NodeConnectorCreator.createNodeConnector( - ofMatch.getInputPort(), node))); - } - if (ofMatch.getDataLayerSource() != null - && !NetUtils - .isZeroMAC(ofMatch.getDataLayerSource())) { - byte srcMac[] = ofMatch.getDataLayerSource(); - salMatch.setField(new MatchField(MatchType.DL_SRC, - srcMac.clone())); - } - if (ofMatch.getDataLayerDestination() != null - && !NetUtils.isZeroMAC(ofMatch - .getDataLayerDestination())) { - byte dstMac[] = ofMatch.getDataLayerDestination(); - salMatch.setField(new MatchField(MatchType.DL_DST, - dstMac.clone())); - } - if (ofMatch.getDataLayerType() != 0) { - salMatch.setField(new MatchField(MatchType.DL_TYPE, - ofMatch.getDataLayerType())); - } - short vlan = ofMatch.getDataLayerVirtualLan(); - if (vlan != 0) { - if (vlan == OFP_VLAN_NONE) { - vlan = MatchType.DL_VLAN_NONE; - } - salMatch.setField(new MatchField(MatchType.DL_VLAN, - vlan)); - } - if ((ofMatch.getWildcards() & OFMatch.OFPFW_DL_VLAN_PCP) == 0) { - salMatch.setField(MatchType.DL_VLAN_PR, ofMatch - .getDataLayerVirtualLanPriorityCodePoint()); - } - if (ofMatch.getNetworkSource() != 0) { - salMatch.setField(MatchType.NW_SRC, NetUtils - .getInetAddress(ofMatch.getNetworkSource()), - NetUtils.getInetNetworkMask( - ofMatch.getNetworkSourceMaskLen(), - false)); - } - if (ofMatch.getNetworkDestination() != 0) { - salMatch.setField(MatchType.NW_DST, - NetUtils.getInetAddress(ofMatch - .getNetworkDestination()), - NetUtils.getInetNetworkMask( - ofMatch.getNetworkDestinationMaskLen(), - false)); - } - if (ofMatch.getNetworkTypeOfService() != 0) { - int dscp = NetUtils.getUnsignedByte(ofMatch - .getNetworkTypeOfService()); - byte tos = (byte) (dscp >> 2); - salMatch.setField(MatchType.NW_TOS, tos); - } - //TODO: NW protocol 0 is a valid protocol - if (ofMatch.getNetworkProtocol() != 0) { - salMatch.setField(MatchType.NW_PROTO, - ofMatch.getNetworkProtocol()); - } - if (ofMatch.getTransportSource() != 0) { - salMatch.setField(MatchType.TP_SRC, - ofMatch.getTransportSource()); - } - if (ofMatch.getTransportDestination() != 0) { - salMatch.setField(MatchType.TP_DST, - ofMatch.getTransportDestination()); - } - } else { - // Compute OF1.0 + IPv6 extensions Match - V6Match v6Match = (V6Match) ofMatch; - if (v6Match.getInputPort() != 0 && v6Match.getInputPort() != OFPort.OFPP_LOCAL.getValue()) { - // Mask on input port is not defined - salMatch.setField(new MatchField(MatchType.IN_PORT, - NodeConnectorCreator.createOFNodeConnector( - v6Match.getInputPort(), node))); - } - if (v6Match.getDataLayerSource() != null - && !NetUtils - .isZeroMAC(ofMatch.getDataLayerSource())) { - byte srcMac[] = v6Match.getDataLayerSource(); - salMatch.setField(new MatchField(MatchType.DL_SRC, - srcMac.clone())); - } - if (v6Match.getDataLayerDestination() != null - && !NetUtils.isZeroMAC(ofMatch - .getDataLayerDestination())) { - byte dstMac[] = v6Match.getDataLayerDestination(); - salMatch.setField(new MatchField(MatchType.DL_DST, - dstMac.clone())); - } - if (v6Match.getDataLayerType() != 0) { - salMatch.setField(new MatchField(MatchType.DL_TYPE, - v6Match.getDataLayerType())); - } - short vlan = v6Match.getDataLayerVirtualLan(); - if (vlan != 0) { - if (vlan == OFP_VLAN_NONE) { - vlan = MatchType.DL_VLAN_NONE; - } - salMatch.setField(new MatchField(MatchType.DL_VLAN, - vlan)); - } - if ((v6Match.getWildcards() & OFMatch.OFPFW_DL_VLAN_PCP) == 0) { - salMatch.setField(MatchType.DL_VLAN_PR, v6Match - .getDataLayerVirtualLanPriorityCodePoint()); - } - // V6Match may carry IPv4 address - if (v6Match.getNetworkSrc() != null) { - salMatch.setField(MatchType.NW_SRC, - v6Match.getNetworkSrc(), - v6Match.getNetworkSourceMask()); - } else if (v6Match.getNetworkSource() != 0) { - salMatch.setField(MatchType.NW_SRC, NetUtils - .getInetAddress(v6Match.getNetworkSource()), - NetUtils.getInetNetworkMask( - v6Match.getNetworkSourceMaskLen(), - false)); - } - // V6Match may carry IPv4 address - if (v6Match.getNetworkDest() != null) { - salMatch.setField(MatchType.NW_DST, - v6Match.getNetworkDest(), - v6Match.getNetworkDestinationMask()); - } else if (v6Match.getNetworkDestination() != 0) { - salMatch.setField(MatchType.NW_DST, - NetUtils.getInetAddress(v6Match - .getNetworkDestination()), - NetUtils.getInetNetworkMask( - v6Match.getNetworkDestinationMaskLen(), - false)); - } - if (v6Match.getNetworkTypeOfService() != 0) { - int dscp = NetUtils.getUnsignedByte(v6Match - .getNetworkTypeOfService()); - byte tos = (byte) (dscp >> 2); - salMatch.setField(MatchType.NW_TOS, tos); - } - if (v6Match.getNetworkProtocol() != 0) { - salMatch.setField(MatchType.NW_PROTO, - v6Match.getNetworkProtocol()); - } - if (v6Match.getTransportSource() != 0) { - salMatch.setField(MatchType.TP_SRC, - (v6Match.getTransportSource())); - } - if (v6Match.getTransportDestination() != 0) { - salMatch.setField(MatchType.TP_DST, - (v6Match.getTransportDestination())); - } - } - } - - // Convert actions - Action salAction = null; - List salActionList = new ArrayList(); - if (actionsList == null) { - salActionList.add(new Drop()); - } else { - for (OFAction ofAction : actionsList) { - if (ofAction instanceof OFActionOutput) { - short ofPort = ((OFActionOutput) ofAction).getPort(); - if (ofPort == OFPort.OFPP_CONTROLLER.getValue()) { - salAction = new Controller(); - } else if (ofPort == OFPort.OFPP_NONE.getValue()) { - salAction = new Drop(); - } else if (ofPort == OFPort.OFPP_IN_PORT.getValue()) { - salAction = new Loopback(); - } else if (ofPort == OFPort.OFPP_FLOOD.getValue()) { - salAction = new Flood(); - } else if (ofPort == OFPort.OFPP_ALL.getValue()) { - salAction = new FloodAll(); - } else if (ofPort == OFPort.OFPP_LOCAL.getValue()) { - salAction = new SwPath(); - } else if (ofPort == OFPort.OFPP_NORMAL.getValue()) { - salAction = new HwPath(); - } else if (ofPort == OFPort.OFPP_TABLE.getValue()) { - salAction = new HwPath(); // TODO: we do not handle - // table in sal for now - } else { - salAction = new Output( - NodeConnectorCreator.createOFNodeConnector( - ofPort, node)); - } - } else if (ofAction instanceof OFActionEnqueue) { - salAction = new Enqueue(NodeConnectorCreator.createOFNodeConnector( - ((OFActionEnqueue) ofAction).getPort(), node), - ((OFActionEnqueue) ofAction).getQueueId()); - } else if (ofAction instanceof OFActionVirtualLanIdentifier) { - salAction = new SetVlanId( - ((OFActionVirtualLanIdentifier) ofAction) - .getVirtualLanIdentifier()); - } else if (ofAction instanceof OFActionStripVirtualLan) { - salAction = new PopVlan(); - } else if (ofAction instanceof OFActionVirtualLanPriorityCodePoint) { - salAction = new SetVlanPcp( - ((OFActionVirtualLanPriorityCodePoint) ofAction) - .getVirtualLanPriorityCodePoint()); - } else if (ofAction instanceof OFActionDataLayerSource) { - salAction = new SetDlSrc( - ((OFActionDataLayerSource) ofAction) - .getDataLayerAddress().clone()); - } else if (ofAction instanceof OFActionDataLayerDestination) { - salAction = new SetDlDst( - ((OFActionDataLayerDestination) ofAction) - .getDataLayerAddress().clone()); - } else if (ofAction instanceof OFActionNetworkLayerSource) { - byte addr[] = BigInteger.valueOf( - ((OFActionNetworkLayerSource) ofAction) - .getNetworkAddress()).toByteArray(); - InetAddress ip = null; - try { - ip = InetAddress.getByAddress(addr); - } catch (UnknownHostException e) { - logger.error("", e); - } - salAction = new SetNwSrc(ip); - } else if (ofAction instanceof OFActionNetworkLayerDestination) { - byte addr[] = BigInteger.valueOf( - ((OFActionNetworkLayerDestination) ofAction) - .getNetworkAddress()).toByteArray(); - InetAddress ip = null; - try { - ip = InetAddress.getByAddress(addr); - } catch (UnknownHostException e) { - logger.error("", e); - } - salAction = new SetNwDst(ip); - } else if (ofAction instanceof OFActionNetworkTypeOfService) { - salAction = new SetNwTos( - ((OFActionNetworkTypeOfService) ofAction) - .getNetworkTypeOfService()); - } else if (ofAction instanceof OFActionTransportLayerSource) { - Short port = ((OFActionTransportLayerSource) ofAction) - .getTransportPort(); - int intPort = NetUtils.getUnsignedShort(port); - salAction = new SetTpSrc(intPort); - } else if (ofAction instanceof OFActionTransportLayerDestination) { - Short port = ((OFActionTransportLayerDestination) ofAction) - .getTransportPort(); - int intPort = NetUtils.getUnsignedShort(port); - salAction = new SetTpDst(intPort); - } - salActionList.add(salAction); - } - } - // Create Flow - flow = new Flow(salMatch, salActionList); - } - logger.trace("Openflow Match: {} Openflow Actions: {}", ofMatch, - actionsList); - logger.trace("SAL Flow: {}", flow); - return flow; - } - - private static final Map> actionMap = new HashMap>() { - private static final long serialVersionUID = 1L; - { - put(1 << 0, Output.class); - put(1 << 1, SetVlanId.class); - put(1 << 2, SetVlanPcp.class); - put(1 << 3, PopVlan.class); - put(1 << 4, SetDlSrc.class); - put(1 << 5, SetDlDst.class); - put(1 << 6, SetNwSrc.class); - put(1 << 7, SetNwDst.class); - put(1 << 8, SetNwTos.class); - put(1 << 9, SetTpSrc.class); - put(1 << 10, SetTpDst.class); - put(1 << 11, Enqueue.class); - } - }; - - /** - * Returns the supported flow actions for the netwrok node given the bitmask - * representing the actions the Openflow 1.0 switch supports - * - * @param ofActionBitmask - * OF 1.0 action bitmask - * @return The correspondent list of SAL Action classes - */ - public static List> getFlowActions(int ofActionBitmask) { - List> list = new ArrayList>(); - - for (int i = 0; i < Integer.SIZE; i++) { - int index = 1 << i; - if ((index & ofActionBitmask) > 0) { - if (actionMap.containsKey(index)) { - list.add(actionMap.get(index)); - } - } - } - // Add implicit SAL actions - list.add(Controller.class); - list.add(SwPath.class); - list.add(HwPath.class); - list.add(Drop.class); - list.add(Flood.class); - list.add(FloodAll.class); - - return list; - } - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerNotifier.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerNotifier.java deleted file mode 100644 index dfa2026cdd..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerNotifier.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.protocol_plugin.openflow.IFlowProgrammerNotifier; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.flowprogrammer.IPluginOutFlowProgrammerService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Flow Programmer Notifier class for relaying asynchronous messages received - * from the network node to the listeners on the proper container - */ -public class FlowProgrammerNotifier implements IFlowProgrammerNotifier { - protected static final Logger logger = LoggerFactory - .getLogger(FlowProgrammerNotifier.class); - private IPluginOutFlowProgrammerService salNotifier; - private IPluginOutConnectionService connectionOutService; - - public FlowProgrammerNotifier() { - salNotifier = null; - } - - void init(Component c) { - logger.debug("INIT called!"); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - logger.debug("DESTROY called!"); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - logger.debug("START called!"); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - logger.debug("STOP called!"); - } - - public void setPluginOutFlowProgrammerService( - IPluginOutFlowProgrammerService s) { - this.salNotifier = s; - } - - public void unsetPluginOutFlowProgrammerService( - IPluginOutFlowProgrammerService s) { - if (this.salNotifier == s) { - this.salNotifier = null; - } - } - - @Override - public void flowRemoved(Node node, Flow flow) { - if (!connectionOutService.isLocal(node)) { - logger.debug("flow removed will not be notified in a non-master controller for node "+node); - return; - } - - if (salNotifier != null) { - salNotifier.flowRemoved(node, flow); - } else { - logger.warn("Unable to relay switch message to upper layer"); - } - } - - @Override - public void flowErrorReported(Node node, long rid, Object err) { - if (!connectionOutService.isLocal(node)) { - logger.debug("flow error will not be notified in a non-master controller for node "+node); - return; - } - - if (salNotifier != null) { - salNotifier.flowErrorReported(node, rid, err); - } else { - logger.warn("Unable to relay switch error message to upper layer"); - } - } - - void setIPluginOutConnectionService(IPluginOutConnectionService s) { - connectionOutService = s; - } - - void unsetIPluginOutConnectionService(IPluginOutConnectionService s) { - if (connectionOutService == s) { - connectionOutService = null; - } - } - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerService.java deleted file mode 100644 index e2fa8d5f1e..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerService.java +++ /dev/null @@ -1,858 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.protocol_plugin.openflow.IFlowProgrammerNotifier; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.IContainerAware; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.Node.NodeIDType; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.flowprogrammer.IPluginInFlowProgrammerService; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.openflow.protocol.OFError; -import org.openflow.protocol.OFFlowMod; -import org.openflow.protocol.OFFlowRemoved; -import org.openflow.protocol.OFMessage; -import org.openflow.protocol.OFPort; -import org.openflow.protocol.OFType; -import org.openflow.protocol.action.OFAction; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Represents the openflow plugin component in charge of programming the flows - * the flow programming and relay them to functional modules above SAL. - */ -public class FlowProgrammerService implements IPluginInFlowProgrammerService, - IMessageListener, IContainerListener, IInventoryShimExternalListener, - CommandProvider, IContainerAware { - private static final Logger log = LoggerFactory - .getLogger(FlowProgrammerService.class); - private IController controller; - private ConcurrentMap flowProgrammerNotifiers; - private Map> containerToNc; - private ConcurrentMap> xid2rid; - private int barrierMessagePriorCount = getBarrierMessagePriorCount(); - private IPluginOutConnectionService connectionOutService; - - public FlowProgrammerService() { - controller = null; - flowProgrammerNotifiers = new ConcurrentHashMap(); - containerToNc = new HashMap>(); - xid2rid = new ConcurrentHashMap>(); - } - - public void setController(IController core) { - this.controller = core; - } - - public void unsetController(IController core) { - if (this.controller == core) { - this.controller = null; - } - } - - void setIPluginOutConnectionService(IPluginOutConnectionService s) { - connectionOutService = s; - } - - void unsetIPluginOutConnectionService(IPluginOutConnectionService s) { - if (connectionOutService == s) { - connectionOutService = null; - } - } - - public void setFlowProgrammerNotifier(Map props, - IFlowProgrammerNotifier s) { - if (props == null || props.get("containerName") == null) { - log.error("Didn't receive the service correct properties"); - return; - } - String containerName = (String) props.get("containerName"); - this.flowProgrammerNotifiers.put(containerName, s); - } - - public void unsetFlowProgrammerNotifier(Map props, - IFlowProgrammerNotifier s) { - if (props == null || props.get("containerName") == null) { - log.error("Didn't receive the service correct properties"); - return; - } - String containerName = (String) props.get("containerName"); - if (this.flowProgrammerNotifiers != null - && this.flowProgrammerNotifiers.containsKey(containerName) - && this.flowProgrammerNotifiers.get(containerName) == s) { - this.flowProgrammerNotifiers.remove(containerName); - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - this.controller.addMessageListener(OFType.FLOW_REMOVED, this); - this.controller.addMessageListener(OFType.ERROR, this); - registerWithOSGIConsole(); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - } - - @Override - public Status addFlow(Node node, Flow flow) { - if (!connectionOutService.isLocal(node)) { - log.debug("Add flow will not be processed in a non-master controller for node " + node); - return new Status(StatusCode.NOTALLOWED, "This is not the master controller for " + node); - } - - return addFlowInternal(node, flow, 0); - } - - @Override - public Status modifyFlow(Node node, Flow oldFlow, Flow newFlow) { - if (!connectionOutService.isLocal(node)) { - log.debug("Modify flow will not be processed in a non-master controller for node " + node); - return new Status(StatusCode.NOTALLOWED, "This is not the master controller for " + node); - } - - return modifyFlowInternal(node, oldFlow, newFlow, 0); - } - - @Override - public Status removeFlow(Node node, Flow flow) { - if (!connectionOutService.isLocal(node)) { - log.debug("Remove flow will not be processed in a non-master controller for node " + node); - return new Status(StatusCode.NOTALLOWED, "This is not the master controller for " + node); - } - - return removeFlowInternal(node, flow, 0); - } - - @Override - public Status addFlowAsync(Node node, Flow flow, long rid) { - if (!connectionOutService.isLocal(node)) { - log.debug("Add flow Async will not be processed in a non-master controller for node " + node); - return new Status(StatusCode.NOTALLOWED, "This is not the master controller for " + node); - } - - return addFlowInternal(node, flow, rid); - } - - @Override - public Status modifyFlowAsync(Node node, Flow oldFlow, Flow newFlow, - long rid) { - if (!connectionOutService.isLocal(node)) { - log.debug("Modify flow async will not be processed in a non-master controller for node " + node); - return new Status(StatusCode.NOTALLOWED, "This is not the master controller for " + node); - } - - return modifyFlowInternal(node, oldFlow, newFlow, rid); - } - - @Override - public Status removeFlowAsync(Node node, Flow flow, long rid) { - if (!connectionOutService.isLocal(node)) { - log.debug("Remove flow async will not be processed in a non-master controller for node " + node); - return new Status(StatusCode.NOTALLOWED, "This is not the master controller for " + node); - } - - return removeFlowInternal(node, flow, rid); - } - - private Status addFlowInternal(Node node, Flow flow, long rid) { - String action = "add"; - if (!node.getType().equals(NodeIDType.OPENFLOW)) { - return new Status(StatusCode.NOTACCEPTABLE, errorString("send", - action, "Invalid node type")); - } - - Status status = validateFlow(flow); - if (!status.isSuccess()) { - return status; - } - - if (controller != null) { - ISwitch sw = controller.getSwitch((Long) node.getID()); - if (sw != null) { - FlowConverter x = new FlowConverter(flow); - OFMessage msg = x.getOFFlowMod(OFFlowMod.OFPFC_ADD, null); - - Object result; - if (rid == 0) { - /* - * Synchronous message send. Each message is followed by a - * Barrier message. - */ - result = sw.syncSend(msg); - } else { - /* - * Message will be sent asynchronously. A Barrier message - * will be inserted automatically to synchronize the - * progression. - */ - result = asyncMsgSend(node, sw, msg, rid); - } - return getStatusInternal(result, action, rid); - } else { - return new Status(StatusCode.GONE, errorString("send", action, - "Switch is not available")); - } - } - return new Status(StatusCode.INTERNALERROR, errorString("send", action, - "Internal plugin error")); - } - - /* - * Method which runs openflow 1.0 specific validation on the requested flow - * This validation is needed because the openflow switch will silently accept - * the request and install only the applicable match fields - */ - private Status validateFlow(Flow flow) { - Match m = flow.getMatch(); - boolean isIPEthertypeSet = m.isPresent(MatchType.DL_TYPE) - && (m.getField(MatchType.DL_TYPE).getValue().equals(EtherTypes.IPv4.shortValue()) || m - .getField(MatchType.DL_TYPE).getValue().equals(EtherTypes.IPv6.shortValue())); - - // network address check - if ((m.isPresent(MatchType.NW_SRC) || m.isPresent(MatchType.NW_DST)) && !isIPEthertypeSet) { - return new Status(StatusCode.NOTACCEPTABLE, - "The match on network source or destination address cannot be accepted if the match " - + "on proper ethertype is missing"); - } - - // transport protocol check - if (m.isPresent(MatchType.NW_PROTO) && !isIPEthertypeSet) { - return new Status(StatusCode.NOTACCEPTABLE, - "The match on network protocol cannot be accepted if the match on proper ethertype is missing"); - } - - // transport ports check - if ((m.isPresent(MatchType.TP_SRC) || m.isPresent(MatchType.TP_DST)) - && (!isIPEthertypeSet || m.isAny(MatchType.NW_PROTO))) { - return new Status( - StatusCode.NOTACCEPTABLE, - "The match on transport source or destination port cannot be accepted if the match on network protocol and match on IP ethertype are missing"); - } - return new Status(StatusCode.SUCCESS); - } - - private Status modifyFlowInternal(Node node, Flow oldFlow, Flow newFlow, long rid) { - String action = "modify"; - if (!node.getType().equals(NodeIDType.OPENFLOW)) { - return new Status(StatusCode.NOTACCEPTABLE, errorString("send", - action, "Invalid node type")); - } - - Status status = validateFlow(newFlow); - if (!status.isSuccess()) { - return status; - } - - if (controller != null) { - ISwitch sw = controller.getSwitch((Long) node.getID()); - if (sw != null) { - OFMessage msg1 = null, msg2 = null; - - // If priority and match portion are the same, send a - // modification message - if (oldFlow.getPriority() != newFlow.getPriority() - || !oldFlow.getMatch().equals(newFlow.getMatch())) { - msg1 = new FlowConverter(oldFlow).getOFFlowMod( - OFFlowMod.OFPFC_DELETE_STRICT, OFPort.OFPP_NONE); - msg2 = new FlowConverter(newFlow).getOFFlowMod( - OFFlowMod.OFPFC_ADD, null); - } else { - msg1 = new FlowConverter(newFlow).getOFFlowMod( - OFFlowMod.OFPFC_MODIFY_STRICT, null); - } - /* - * Synchronous message send - */ - action = (msg2 == null) ? "modify" : "delete"; - Object result; - if (rid == 0) { - /* - * Synchronous message send. Each message is followed by a - * Barrier message. - */ - result = sw.syncSend(msg1); - } else { - /* - * Message will be sent asynchronously. A Barrier message - * will be inserted automatically to synchronize the - * progression. - */ - result = asyncMsgSend(node, sw, msg1, rid); - } - - Status rv = getStatusInternal(result, action, rid); - if ((msg2 == null) || !rv.isSuccess()) { - return rv; - } - - action = "add"; - if (rid == 0) { - /* - * Synchronous message send. Each message is followed by a - * Barrier message. - */ - result = sw.syncSend(msg2); - } else { - /* - * Message will be sent asynchronously. A Barrier message - * will be inserted automatically to synchronize the - * progression. - */ - result = asyncMsgSend(node, sw, msg2, rid); - } - return getStatusInternal(result, action, rid); - } else { - return new Status(StatusCode.GONE, errorString("send", action, - "Switch is not available")); - } - } - return new Status(StatusCode.INTERNALERROR, errorString("send", action, - "Internal plugin error")); - } - - private Status removeFlowInternal(Node node, Flow flow, long rid) { - String action = "remove"; - if (!node.getType().equals(NodeIDType.OPENFLOW)) { - return new Status(StatusCode.NOTACCEPTABLE, errorString("send", - action, "Invalid node type")); - } - if (controller != null) { - ISwitch sw = controller.getSwitch((Long) node.getID()); - if (sw != null) { - OFMessage msg = new FlowConverter(flow).getOFFlowMod( - OFFlowMod.OFPFC_DELETE_STRICT, OFPort.OFPP_NONE); - Object result; - if (rid == 0) { - /* - * Synchronous message send. Each message is followed by a - * Barrier message. - */ - result = sw.syncSend(msg); - } else { - /* - * Message will be sent asynchronously. A Barrier message - * will be inserted automatically to synchronize the - * progression. - */ - result = asyncMsgSend(node, sw, msg, rid); - } - return getStatusInternal(result, action, rid); - } else { - return new Status(StatusCode.GONE, errorString("send", action, - "Switch is not available")); - } - } - return new Status(StatusCode.INTERNALERROR, errorString("send", action, - "Internal plugin error")); - } - - @Override - public Status removeAllFlows(Node node) { - if (!connectionOutService.isLocal(node)) { - log.debug("Remove all flows will not be processed in a non-master controller for node " + node); - return new Status(StatusCode.NOTALLOWED, "This is not the master controller for " + node); - } - - return new Status(StatusCode.SUCCESS); - } - - private String errorString(String phase, String action, String cause) { - return "Failed to " - + ((phase != null) ? phase + " the " + action - + " flow message: " : action + " the flow: ") + cause; - } - - @Override - public void receive(ISwitch sw, OFMessage msg) { - if (msg instanceof OFFlowRemoved) { - handleFlowRemovedMessage(sw, (OFFlowRemoved) msg); - } else if (msg instanceof OFError) { - handleErrorMessage(sw, (OFError) msg); - } - } - - private void handleFlowRemovedMessage(ISwitch sw, OFFlowRemoved msg) { - Node node = NodeCreator.createOFNode(sw.getId()); - Flow flow = new FlowConverter(msg.getMatch(), - new ArrayList(0)).getFlow(node); - flow.setPriority(msg.getPriority()); - flow.setIdleTimeout(msg.getIdleTimeout()); - flow.setId(msg.getCookie()); - - Match match = flow.getMatch(); - NodeConnector inPort = match.isPresent(MatchType.IN_PORT) ? (NodeConnector) match - .getField(MatchType.IN_PORT).getValue() : null; - - for (Map.Entry containerNotifier : flowProgrammerNotifiers - .entrySet()) { - String container = containerNotifier.getKey(); - IFlowProgrammerNotifier notifier = containerNotifier.getValue(); - /* - * Switch only provide us with the match information. For now let's - * try to identify the container membership only from the input port - * match field. In any case, upper layer consumers can derive - * whether the notification was not for them. More sophisticated - * filtering can be added later on. - */ - if (inPort == null - || container.equals(GlobalConstants.DEFAULT.toString()) - || (containerToNc.containsKey(container) && containerToNc.get(container).contains(inPort))) { - notifier.flowRemoved(node, flow); - } - } - } - - private void handleErrorMessage(ISwitch sw, OFError errorMsg) { - Node node = NodeCreator.createOFNode(sw.getId()); - OFMessage offendingMsg = errorMsg.getOffendingMsg(); - Integer xid; - if (offendingMsg != null) { - xid = offendingMsg.getXid(); - } else { - xid = errorMsg.getXid(); - } - - Long rid = getMessageRid(sw.getId(), xid); - /* - * Null or zero requestId indicates that the error message is meant for - * a sync message. It will be handled by the sync message worker thread. - * Hence we are done here. - */ - if ((rid == null) || (rid == 0)) { - return; - } - - /* - * Notifies the caller that error has been reported for a previous flow - * programming request - */ - for (Map.Entry containerNotifier : flowProgrammerNotifiers - .entrySet()) { - IFlowProgrammerNotifier notifier = containerNotifier.getValue(); - notifier.flowErrorReported(node, rid, Utils.getOFErrorString(errorMsg)); - } - } - - @Override - public void tagUpdated(String containerName, Node n, short oldTag, - short newTag, UpdateType t) { - - } - - @Override - public void containerFlowUpdated(String containerName, - ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) { - } - - @Override - public void nodeConnectorUpdated(String containerName, NodeConnector p, - UpdateType type) { - switch (type) { - case ADDED: - if (!containerToNc.containsKey(containerName)) { - containerToNc.put(containerName, new HashSet()); - } - containerToNc.get(containerName).add(p); - break; - case CHANGED: - break; - case REMOVED: - Set target = containerToNc.get(containerName); - if (target != null) { - target.remove(p); - } - break; - default: - } - } - - @Override - public void containerModeUpdated(UpdateType t) { - - } - - @Override - public Status syncSendBarrierMessage(Node node) { - if (!connectionOutService.isLocal(node)) { - log.debug("Sync Send Barrier will not be processed in a non-master controller for node " + node); - return new Status(StatusCode.NOTALLOWED, "This is not the master controller for " + node); - } - - if (!node.getType().equals(NodeIDType.OPENFLOW)) { - return new Status(StatusCode.NOTACCEPTABLE, - "The node does not support Barrier message."); - } - - if (controller != null) { - long swid = (Long) node.getID(); - ISwitch sw = controller.getSwitch(swid); - if (sw != null) { - sw.syncSendBarrierMessage(); - clearXid2Rid(swid); - return (new Status(StatusCode.SUCCESS)); - } else { - return new Status(StatusCode.GONE, - "The node does not have a valid Switch reference."); - } - } - return new Status(StatusCode.INTERNALERROR, - "Failed to send Barrier message."); - } - - @Override - public Status asyncSendBarrierMessage(Node node) { - if (!connectionOutService.isLocal(node)) { - log.debug("ASync Send Barrier will not be processed in a non-master controller for node " + node); - return new Status(StatusCode.NOTALLOWED, "This is not the master controller for " + node); - } - - if (!node.getType().equals(NodeIDType.OPENFLOW)) { - return new Status(StatusCode.NOTACCEPTABLE, - "The node does not support Barrier message."); - } - - if (controller != null) { - long swid = (Long) node.getID(); - ISwitch sw = controller.getSwitch(swid); - if (sw != null) { - sw.asyncSendBarrierMessage(); - clearXid2Rid(swid); - return (new Status(StatusCode.SUCCESS)); - } else { - return new Status(StatusCode.GONE, - "The node does not have a valid Switch reference."); - } - } - return new Status(StatusCode.INTERNALERROR, - "Failed to send Barrier message."); - } - - /** - * This method sends the message asynchronously until the number of messages - * sent reaches a threshold. Then a Barrier message is sent automatically - * for sync purpose. An unique Request ID associated with the message is - * passed down by the caller. The Request ID will be returned to the caller - * when an error message is received from the switch. - * - * @param node - * The node - * @param msg - * The switch - * @param msg - * The OF message to be sent - * @param rid - * The Request Id - * @return result - */ - private Object asyncMsgSend(Node node, ISwitch sw, OFMessage msg, long rid) { - Object result = Boolean.TRUE; - long swid = (Long) node.getID(); - int xid; - - xid = sw.asyncSend(msg); - addXid2Rid(swid, xid, rid); - - Map swxid2rid = this.xid2rid.get(swid); - if (swxid2rid == null) { - return result; - } - - int size = swxid2rid.size(); - if (size % barrierMessagePriorCount == 0) { - result = asyncSendBarrierMessage(node); - } - - return result; - } - - /** - * A number of async messages are sent followed by a synchronous Barrier - * message. This method returns the maximum async messages that can be sent - * before the Barrier message. - * - * @return The max count of async messages sent prior to Barrier message - */ - private int getBarrierMessagePriorCount() { - String count = System.getProperty("of.barrierMessagePriorCount"); - int rv = 100; - - if (count != null) { - try { - rv = Integer.parseInt(count); - } catch (Exception e) { - } - } - - return rv; - } - - /** - * This method returns the message Request ID previously assigned by the - * caller for a given OF message xid - * - * @param swid - * The switch id - * @param xid - * The OF message xid - * @return The Request ID - */ - private Long getMessageRid(long swid, Integer xid) { - Long rid = null; - - if (xid == null) { - return rid; - } - - Map swxid2rid = this.xid2rid.get(swid); - if (swxid2rid != null) { - rid = swxid2rid.get(xid); - } - return rid; - } - - /** - * This method returns a copy of outstanding xid to rid mappings.for a given - * switch - * - * @param swid - * The switch id - * @return a copy of xid2rid mappings - */ - public Map getSwXid2Rid(long swid) { - Map swxid2rid = this.xid2rid.get(swid); - - if (swxid2rid != null) { - return new HashMap(swxid2rid); - } else { - return new HashMap(); - } - } - - /** - * Adds xid to rid mapping to the local DB - * - * @param swid - * The switch id - * @param xid - * The OF message xid - * @param rid - * The message Request ID - */ - private void addXid2Rid(long swid, int xid, long rid) { - Map swxid2rid = this.xid2rid.get(swid); - if (swxid2rid != null) { - swxid2rid.put(xid, rid); - } - } - - /** - * When an Error message is received, this method will be invoked to remove - * the offending xid from the local DB. - * - * @param swid - * The switch id - * @param xid - * The OF message xid - */ - private void removeXid2Rid(long swid, int xid) { - Map swxid2rid = this.xid2rid.get(swid); - if (swxid2rid != null) { - swxid2rid.remove(xid); - } - } - - /** - * Convert various result into Status - * - * @param result - * The returned result from previous action - * @param action - * add/modify/delete flow action - * @param rid - * The Request ID associated with the flow message - * @return Status - */ - private Status getStatusInternal(Object result, String action, long rid) { - if (result instanceof Boolean) { - return ((Boolean) result == Boolean.TRUE) ? new Status( - StatusCode.SUCCESS, rid) : new Status( - StatusCode.TIMEOUT, errorString(null, action, - "Request Timed Out")); - } else if (result instanceof Status) { - return (Status) result; - } else if (result instanceof OFError) { - OFError res = (OFError) result; - return new Status(StatusCode.INTERNALERROR, errorString( - "program", action, Utils.getOFErrorString(res))); - } else { - return new Status(StatusCode.INTERNALERROR, errorString( - "send", action, "Internal Error")); - } - } - - /** - * When a Barrier reply is received, this method will be invoked to clear - * the local DB - * - * @param swid - * The switch id - */ - private void clearXid2Rid(long swid) { - Map swxid2rid = this.xid2rid.get(swid); - if (swxid2rid != null) { - swxid2rid.clear(); - } - } - - @Override - public void updateNode(Node node, UpdateType type, Set props) { - long swid = (Long)node.getID(); - - switch (type) { - case ADDED: - Map swxid2rid = new HashMap(); - this.xid2rid.put(swid, swxid2rid); - break; - case CHANGED: - break; - case REMOVED: - this.xid2rid.remove(swid); - break; - default: - } - } - - @Override - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props) { - } - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, - null); - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("-- Flow Programmer Service --\n"); - help.append("\t px2r - Print outstanding xid2rid mappings for a given node id\n"); - help.append("\t px2rc - Print max num of async msgs prior to the Barrier\n"); - return help.toString(); - } - - public void _px2r(CommandInterpreter ci) { - String st = ci.nextArgument(); - if (st == null) { - ci.println("Please enter a valid node id"); - return; - } - - long sid; - try { - sid = HexEncode.stringToLong(st); - } catch (NumberFormatException e) { - ci.println("Please enter a valid node id"); - return; - } - - Map swxid2rid = this.xid2rid.get(sid); - if (swxid2rid == null) { - ci.println("The node id entered does not exist"); - return; - } - - ci.println("xid rid"); - - Set xidSet = swxid2rid.keySet(); - if (xidSet == null) { - return; - } - - for (Integer xid : xidSet) { - ci.println(xid + " " + swxid2rid.get(xid)); - } - } - - public void _px2rc(CommandInterpreter ci) { - ci.println("Max num of async messages sent prior to the Barrier message is " - + barrierMessagePriorCount); - } - - @Override - public void containerCreate(String containerName) { - // do nothing - } - - @Override - public void containerDestroy(String containerName) { - containerToNc.remove(containerName); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowStatisticsConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowStatisticsConverter.java deleted file mode 100644 index 74af3db5ef..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowStatisticsConverter.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6StatsReply; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.openflow.protocol.statistics.OFFlowStatisticsReply; -import org.openflow.protocol.statistics.OFStatistics; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Converts an openflow list of flow statistics in a SAL list of FlowOnNode - * objects - * - * - * - */ -public class FlowStatisticsConverter { - private static final Logger log = LoggerFactory - .getLogger(FlowStatisticsConverter.class); - private List ofStatsList; - private List flowOnNodeList; - - public FlowStatisticsConverter(List statsList) { - if (statsList == null) { - this.ofStatsList = Collections.emptyList(); - } else { - this.ofStatsList = statsList; - } - this.flowOnNodeList = null; - } - - public List getFlowOnNodeList(Node node) { - if (ofStatsList != null && flowOnNodeList == null) { - flowOnNodeList = new ArrayList(); - FlowConverter flowConverter = null; - OFFlowStatisticsReply ofFlowStat; - V6StatsReply v6StatsReply; - for (OFStatistics ofStat : ofStatsList) { - FlowOnNode flowOnNode = null; - if (ofStat instanceof OFFlowStatisticsReply) { - ofFlowStat = (OFFlowStatisticsReply) ofStat; - flowConverter = new FlowConverter(ofFlowStat.getMatch(), - ofFlowStat.getActions()); - Flow flow = flowConverter.getFlow(node); - flow.setPriority(ofFlowStat.getPriority()); - flow.setIdleTimeout(ofFlowStat.getIdleTimeout()); - flow.setHardTimeout(ofFlowStat.getHardTimeout()); - flow.setId(ofFlowStat.getCookie()); - flowOnNode = new FlowOnNode(flow); - flowOnNode.setByteCount(ofFlowStat.getByteCount()); - flowOnNode.setPacketCount(ofFlowStat.getPacketCount()); - flowOnNode.setDurationSeconds(ofFlowStat - .getDurationSeconds()); - flowOnNode.setDurationNanoseconds(ofFlowStat - .getDurationNanoseconds()); - } else if (ofStat instanceof V6StatsReply) { - v6StatsReply = (V6StatsReply) ofStat; - flowConverter = new FlowConverter(v6StatsReply.getMatch(), - v6StatsReply.getActions()); - Flow flow = flowConverter.getFlow(node); - flow.setPriority(v6StatsReply.getPriority()); - flow.setIdleTimeout(v6StatsReply.getIdleTimeout()); - flow.setHardTimeout(v6StatsReply.getHardTimeout()); - flow.setId(v6StatsReply.getCookie()); - flowOnNode = new FlowOnNode(flow); - flowOnNode.setByteCount(v6StatsReply.getByteCount()); - flowOnNode.setPacketCount(v6StatsReply.getPacketCount()); - flowOnNode.setDurationSeconds(v6StatsReply - .getDurationSeconds()); - flowOnNode.setDurationNanoseconds(v6StatsReply - .getDurationNanoseconds()); - } else { - continue; - } - flowOnNodeList.add(flowOnNode); - } - } - log.trace("OFStatistics: {} FlowOnNode: {}", ofStatsList, - flowOnNodeList); - return flowOnNodeList; - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryService.java deleted file mode 100644 index 39bbecf021..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryService.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.Collections; -import java.util.Dictionary; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArraySet; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryProvider; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimInternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.inventory.IPluginInInventoryService; -import org.opendaylight.controller.sal.inventory.IPluginOutInventoryService; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class describes inventory service protocol plugin. One instance per - * container of the network. Each instance gets container specific inventory - * events from InventoryServiceShim. It interacts with SAL to pass inventory - * data to the upper application. - * - * - */ -public class InventoryService implements IInventoryShimInternalListener, - IPluginInInventoryService, IInventoryProvider { - protected static final Logger logger = LoggerFactory - .getLogger(InventoryService.class); - private final Set pluginOutInventoryServices = - new CopyOnWriteArraySet(); - private IController controller = null; - private ConcurrentMap> nodeProps; - private ConcurrentMap> nodeConnectorProps; - private boolean isDefaultContainer = false; - private String containerName = null; - - void setController(IController s) { - this.controller = s; - } - - void unsetController(IController s) { - if (this.controller == s) { - this.controller = null; - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - @SuppressWarnings("rawtypes") - void init(Component c) { - logger.trace("INIT called!"); - - Dictionary props = c.getServiceProperties(); - if (props != null) { - containerName = (String) props.get("containerName"); - if (containerName != null) { - isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT - .toString()); - } - } - - nodeProps = new ConcurrentHashMap>(); - nodeConnectorProps = new ConcurrentHashMap>(); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - logger.trace("DESTROY called!"); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - logger.trace("START called!"); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - logger.trace("STOP called!"); - pluginOutInventoryServices.clear(); - } - - public void setPluginOutInventoryServices(IPluginOutInventoryService service) { - logger.trace("Got a service set request {}", service); - if (this.pluginOutInventoryServices != null) { - this.pluginOutInventoryServices.add(service); - } - } - - public void unsetPluginOutInventoryServices( - IPluginOutInventoryService service) { - logger.trace("Got a service UNset request"); - if (this.pluginOutInventoryServices != null) { - this.pluginOutInventoryServices.remove(service); - } - } - - /** - * Retrieve nodes from openflow - */ - @Override - public ConcurrentMap> getNodeProps() { - logger.debug("getNodePros for container {}", containerName); - return nodeProps; - } - - // nothing to return - @Override - public Set getConfiguredNotConnectedNodes() { - return Collections.emptySet(); - } - - @Override - public ConcurrentMap> getNodeConnectorProps( - Boolean refresh) { - if (nodeConnectorProps == null) { - return null; - } - - if (isDefaultContainer && refresh) { - Map switches = controller.getSwitches(); - for (ISwitch sw : switches.values()) { - Map> ncProps = InventoryServiceHelper - .OFSwitchToProps(sw); - for (Map.Entry> entry : ncProps - .entrySet()) { - updateNodeConnector(entry.getKey(), UpdateType.ADDED, - entry.getValue()); - } - } - } - - return nodeConnectorProps; - } - - @Override - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props) { - logger.trace("updateNodeConnector {} type {}", nodeConnector, - type.getName()); - if (nodeConnectorProps == null) { - logger.trace("nodeConnectorProps is null"); - return; - } - - Map propMap = nodeConnectorProps.get(nodeConnector); - switch (type) { - case ADDED: - case CHANGED: - if (propMap == null) { - propMap = new HashMap(); - } - if (props != null) { - for (Property prop : props) { - propMap.put(prop.getName(), prop); - } - } - nodeConnectorProps.put(nodeConnector, propMap); - break; - case REMOVED: - nodeConnectorProps.remove(nodeConnector); - break; - default: - return; - } - - // update sal and discovery - for (IPluginOutInventoryService service : pluginOutInventoryServices) { - service.updateNodeConnector(nodeConnector, type, props); - } - - } - - private void addNode(Node node, Set props) { - if (nodeProps == null) { - return; - } - - logger.trace("addNode: {} added, props: {} for container {}", - new Object[] { node, props, containerName }); - - // update local cache - Map propMap = nodeProps.get(node); - if (propMap == null) { - propMap = new HashMap(); - } - - if (props != null) { - for (Property prop : props) { - propMap.put(prop.getName(), prop); - } - } - nodeProps.put(node, propMap); - - // update sal - for (IPluginOutInventoryService service : pluginOutInventoryServices) { - service.updateNode(node, UpdateType.ADDED, props); - } - } - - private void removeNode(Node node) { - logger.trace("{} removed", node); - if (nodeProps == null) { - return; - } - - // update local cache - nodeProps.remove(node); - - Set removeSet = new HashSet(); - for (NodeConnector nodeConnector : nodeConnectorProps.keySet()) { - if (nodeConnector.getNode().equals(node)) { - removeSet.add(nodeConnector); - } - } - for (NodeConnector nodeConnector : removeSet) { - nodeConnectorProps.remove(nodeConnector); - } - - // update sal - for (IPluginOutInventoryService service : pluginOutInventoryServices) { - service.updateNode(node, UpdateType.REMOVED, null); - } - } - - private void updateNode(Node node, Set properties) { - logger.trace("{} updated, props: {}", node, properties); - if ((nodeProps == null) || !nodeProps.containsKey(node) || - (properties == null) || properties.isEmpty()) { - return; - } - - // Update local cache with new properties - Set newProperties = new HashSet(properties.size()); - Map propertyMap = nodeProps.get(node); - for (Property property : properties) { - String name = property.getName(); - Property currentProperty = propertyMap.get(name); - if (!property.equals(currentProperty)) { - propertyMap.put(name, property); - newProperties.add(property); - } - } - - // Update SAL if we got new properties - if (!newProperties.isEmpty()) { - for (IPluginOutInventoryService service : pluginOutInventoryServices) { - service.updateNode(node, UpdateType.CHANGED, newProperties); - } - } - } - - @Override - public void updateNode(Node node, UpdateType type, Set props) { - switch (type) { - case ADDED: - addNode(node, props); - break; - case REMOVED: - removeNode(node); - break; - case CHANGED: - updateNode(node, props); - break; - default: - break; - } - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceHelper.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceHelper.java deleted file mode 100644 index 5e5f056c5a..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceHelper.java +++ /dev/null @@ -1,167 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.AdvertisedBandwidth; -import org.opendaylight.controller.sal.core.SupportedBandwidth; -import org.opendaylight.controller.sal.core.PeerBandwidth; -import org.opendaylight.controller.sal.core.Config; -import org.opendaylight.controller.sal.core.Name; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; - -import org.opendaylight.controller.sal.utils.NodeCreator; - -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.openflow.protocol.OFPhysicalPort; -import org.openflow.protocol.OFPhysicalPort.OFPortConfig; -import org.openflow.protocol.OFPhysicalPort.OFPortFeatures; -import org.openflow.protocol.OFPhysicalPort.OFPortState; - -/** - * The class provides helper functions to retrieve inventory properties from - * OpenFlow messages - */ -public class InventoryServiceHelper { - /* - * Returns BandWidth property from OpenFlow OFPhysicalPort features - */ - public static Bandwidth OFPortToBandWidth(int portFeatures) { - Bandwidth bw = null; - int value = portFeatures - & (OFPortFeatures.OFPPF_10MB_FD.getValue() - | OFPortFeatures.OFPPF_10MB_HD.getValue() - | OFPortFeatures.OFPPF_100MB_FD.getValue() - | OFPortFeatures.OFPPF_100MB_HD.getValue() - | OFPortFeatures.OFPPF_1GB_FD.getValue() - | OFPortFeatures.OFPPF_1GB_HD.getValue() | OFPortFeatures.OFPPF_10GB_FD - .getValue()); - - switch (value) { - case 1: - case 2: - bw = new Bandwidth(Bandwidth.BW10Mbps); - break; - case 4: - case 8: - bw = new Bandwidth(Bandwidth.BW100Mbps); - break; - case 16: - case 32: - bw = new Bandwidth(Bandwidth.BW1Gbps); - break; - case 64: - bw = new Bandwidth(Bandwidth.BW10Gbps); - break; - default: - break; - } - return bw; - } - - /* - * Returns Config property from OpenFLow OFPhysicalPort config - */ - public static Config OFPortToConfig(int portConfig) { - Config config; - if ((OFPortConfig.OFPPC_PORT_DOWN.getValue() & portConfig) != 0) - config = new Config(Config.ADMIN_DOWN); - else - config = new Config(Config.ADMIN_UP); - return config; - } - - /* - * Returns State property from OpenFLow OFPhysicalPort state - */ - public static State OFPortToState(int portState) { - State state; - if ((OFPortState.OFPPS_LINK_DOWN.getValue() & portState) != 0) - state = new State(State.EDGE_DOWN); - else - state = new State(State.EDGE_UP); - return state; - } - - /* - * Returns set of properties from OpenFLow OFPhysicalPort - */ - public static Set OFPortToProps(OFPhysicalPort port) { - Set props = new HashSet(); - Bandwidth bw = InventoryServiceHelper.OFPortToBandWidth(port - .getCurrentFeatures()); - if (bw != null) { - props.add(bw); - } - - Bandwidth abw = InventoryServiceHelper.OFPortToBandWidth(port.getAdvertisedFeatures()); - if (abw != null) { - AdvertisedBandwidth a = new AdvertisedBandwidth(abw.getValue()); - if (a != null) { - props.add(a); - } - } - Bandwidth sbw = InventoryServiceHelper.OFPortToBandWidth(port.getSupportedFeatures()); - if (sbw != null) { - SupportedBandwidth s = new SupportedBandwidth(sbw.getValue()); - if (s != null) { - props.add(s); - } - } - Bandwidth pbw = InventoryServiceHelper.OFPortToBandWidth(port.getPeerFeatures()); - if (pbw != null) { - PeerBandwidth p = new PeerBandwidth(pbw.getValue()); - if (p != null) { - props.add(p); - } - } - props.add(new Name(port.getName())); - props.add(InventoryServiceHelper.OFPortToConfig(port.getConfig())); - props.add(InventoryServiceHelper.OFPortToState(port.getState())); - return props; - } - - /* - * Returns set of properties for each nodeConnector in an OpenFLow switch - */ - public static Map> OFSwitchToProps(ISwitch sw) { - Map> ncProps = new HashMap>(); - - if (sw == null) { - return ncProps; - } - - Node node = NodeCreator.createOFNode(sw.getId()); - if (node == null) { - return ncProps; - } - - Set props; - NodeConnector nodeConnector; - OFPhysicalPort port; - Map ports = sw.getPhysicalPorts(); - for (Map.Entry entry : ports.entrySet()) { - nodeConnector = PortConverter.toNodeConnector(entry.getKey(), node); - port = entry.getValue(); - props = InventoryServiceHelper.OFPortToProps(port); - ncProps.put(nodeConnector, props); - } - - return ncProps; - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceShim.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceShim.java deleted file mode 100644 index 2b26ecb749..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/InventoryServiceShim.java +++ /dev/null @@ -1,643 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CopyOnWriteArraySet; - -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimInternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageListener; -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitchStateListener; -import org.opendaylight.controller.sal.action.SupportedFlowActions; -import org.opendaylight.controller.sal.connection.ConnectionLocality; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.Buffers; -import org.opendaylight.controller.sal.core.Capabilities; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.Description; -import org.opendaylight.controller.sal.core.IContainerAware; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.opendaylight.controller.sal.core.MacAddress; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.Tables; -import org.opendaylight.controller.sal.core.TimeStamp; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.openflow.protocol.OFMessage; -import org.openflow.protocol.OFPortStatus; -import org.openflow.protocol.OFPortStatus.OFPortReason; -import org.openflow.protocol.OFType; -import org.openflow.protocol.statistics.OFDescriptionStatistics; -import org.openflow.protocol.statistics.OFStatistics; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class describes a shim layer that bridges inventory events from Openflow - * core to various listeners. The notifications are filtered based on container - * configurations. - * - * - */ -public class InventoryServiceShim implements IContainerListener, - IMessageListener, ISwitchStateListener, IOFStatisticsListener, IContainerAware { - protected static final Logger logger = LoggerFactory - .getLogger(InventoryServiceShim.class); - private IController controller = null; - private final ConcurrentMap inventoryShimInternalListeners = new ConcurrentHashMap(); - private final Set globalInventoryShimInternalListeners = new HashSet(); - private final List inventoryShimExternalListeners = new CopyOnWriteArrayList(); - private final ConcurrentMap> nodeConnectorContainerMap = new ConcurrentHashMap>(); - private final ConcurrentMap> nodeContainerMap = new ConcurrentHashMap>(); - private final ConcurrentMap> nodeConnectorProps = new ConcurrentHashMap>(); - private final ConcurrentMap> nodeProps = new ConcurrentHashMap>(); - private IPluginOutConnectionService connectionOutService; - - void setController(IController s) { - this.controller = s; - } - - void unsetController(IController s) { - if (this.controller == s) { - this.controller = null; - } - } - - void setInventoryShimGlobalInternalListener(Map props, - IInventoryShimInternalListener s) { - if ((this.globalInventoryShimInternalListeners != null)) { - this.globalInventoryShimInternalListeners.add(s); - } - } - - void unsetInventoryShimGlobalInternalListener(Map props, - IInventoryShimInternalListener s) { - if ((this.globalInventoryShimInternalListeners != null)) { - this.globalInventoryShimInternalListeners.remove(s); - } - } - - void setInventoryShimInternalListener(Map props, - IInventoryShimInternalListener s) { - if (props == null) { - logger.error("setInventoryShimInternalListener property is null"); - return; - } - String containerName = (String) props.get("containerName"); - if (containerName == null) { - logger.error("setInventoryShimInternalListener containerName not supplied"); - return; - } - if ((this.inventoryShimInternalListeners != null) - && !this.inventoryShimInternalListeners.containsValue(s)) { - this.inventoryShimInternalListeners.put(containerName, s); - logger.trace( - "Added inventoryShimInternalListener for container {}", - containerName); - } - } - - void unsetInventoryShimInternalListener(Map props, - IInventoryShimInternalListener s) { - if (props == null) { - logger.error("unsetInventoryShimInternalListener property is null"); - return; - } - String containerName = (String) props.get("containerName"); - if (containerName == null) { - logger.error("setInventoryShimInternalListener containerName not supplied"); - return; - } - if ((this.inventoryShimInternalListeners != null) - && this.inventoryShimInternalListeners.get(containerName) != null - && this.inventoryShimInternalListeners.get(containerName) - .equals(s)) { - this.inventoryShimInternalListeners.remove(containerName); - logger.trace( - "Removed inventoryShimInternalListener for container {}", - containerName); - } - } - - void setInventoryShimExternalListener(IInventoryShimExternalListener s) { - logger.trace("Set inventoryShimExternalListener {}", s); - if ((this.inventoryShimExternalListeners != null) - && !this.inventoryShimExternalListeners.contains(s)) { - this.inventoryShimExternalListeners.add(s); - } - } - - void unsetInventoryShimExternalListener(IInventoryShimExternalListener s) { - logger.trace("Unset inventoryShimExternalListener {}", s); - if ((this.inventoryShimExternalListeners != null) - && this.inventoryShimExternalListeners.contains(s)) { - this.inventoryShimExternalListeners.remove(s); - } - } - - void setIPluginOutConnectionService(IPluginOutConnectionService s) { - connectionOutService = s; - } - - void unsetIPluginOutConnectionService(IPluginOutConnectionService s) { - if (connectionOutService == s) { - connectionOutService = null; - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - this.controller.addMessageListener(OFType.PORT_STATUS, this); - this.controller.addSwitchStateListener(this); - } - - /** - * Function called after registering the service in OSGi service registry. - */ - void started() { - /* Start with existing switches */ - startService(); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - this.controller.removeMessageListener(OFType.PACKET_IN, this); - this.controller.removeSwitchStateListener(this); - - this.inventoryShimInternalListeners.clear(); - this.nodeConnectorContainerMap.clear(); - this.nodeContainerMap.clear(); - this.globalInventoryShimInternalListeners.clear(); - this.controller = null; - } - - @Override - public void receive(ISwitch sw, OFMessage msg) { - if (msg instanceof OFPortStatus) { - handlePortStatusMessage(sw, (OFPortStatus) msg); - } - return; - } - - protected void handlePortStatusMessage(ISwitch sw, OFPortStatus m) { - Node node = NodeCreator.createOFNode(sw.getId()); - NodeConnector nodeConnector = PortConverter.toNodeConnector( - m.getDesc().getPortNumber(), node); - // get node connector properties - Set props = InventoryServiceHelper.OFPortToProps(m.getDesc()); - - UpdateType type = null; - if (m.getReason() == (byte) OFPortReason.OFPPR_ADD.ordinal()) { - type = UpdateType.ADDED; - nodeConnectorProps.put(nodeConnector, props); - } else if (m.getReason() == (byte) OFPortReason.OFPPR_DELETE.ordinal()) { - type = UpdateType.REMOVED; - nodeConnectorProps.remove(nodeConnector); - } else if (m.getReason() == (byte) OFPortReason.OFPPR_MODIFY.ordinal()) { - type = UpdateType.CHANGED; - nodeConnectorProps.put(nodeConnector, props); - } - - logger.trace("handlePortStatusMessage {} type {}", nodeConnector, type); - - if (type != null) { - notifyInventoryShimListener(nodeConnector, type, props); - } - } - - @Override - public void switchAdded(ISwitch sw) { - if (sw == null) { - logger.debug("Ignore null switch addition"); - return; - } - Node node = NodeCreator.createOFNode(sw.getId()); - if ((nodeProps.get(node) != null) && (connectionOutService.isLocal(node))) { - logger.debug("Ignore switchAdded {}", sw); - return; - } - - // Add all the nodeConnectors of this switch if any - Map> ncProps = InventoryServiceHelper.OFSwitchToProps(sw); - if (!ncProps.isEmpty()) { - for (Map.Entry> entry : ncProps.entrySet()) { - Set props = new HashSet(); - Set prop = entry.getValue(); - if (prop != null) { - props.addAll(prop); - } - nodeConnectorProps.put(entry.getKey(), props); - notifyInventoryShimListener(entry.getKey(), UpdateType.ADDED, entry.getValue()); - } - } else { - /* - * If no node connector is present, publish the node addition itself - * in order to let Connection Manager properly set the node locality - */ - this.notifyInventoryShimListener(node, UpdateType.ADDED, Collections.emptySet()); - } - - // Add this node - if (connectionOutService.getLocalityStatus(node) != ConnectionLocality.NOT_CONNECTED) { - addNode(sw); - } else { - logger.debug("Skipping node addition due to Connectivity Status : {}", connectionOutService.getLocalityStatus(node).name()); - } - } - - @Override - public void switchDeleted(ISwitch sw) { - if (sw == null) { - return; - } - - removeNode(sw); - } - - @Override - public void containerModeUpdated(UpdateType t) { - // do nothing - } - - @Override - public void tagUpdated(String containerName, Node n, short oldTag, - short newTag, UpdateType t) { - logger.debug("tagUpdated: {} type {} for container {}", new Object[] { - n, t, containerName }); - } - - @Override - public void containerFlowUpdated(String containerName, - ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) { - } - - @Override - public void nodeConnectorUpdated(String containerName, NodeConnector nc, UpdateType t) { - logger.debug("nodeConnectorUpdated: {} type {} for container {}", new Object[] { nc, t, containerName }); - Node node = nc.getNode(); - Set ncContainers = this.nodeConnectorContainerMap.get(nc); - Set nodeContainers = this.nodeContainerMap.get(node); - if (ncContainers == null) { - ncContainers = new CopyOnWriteArraySet(); - } - if (nodeContainers == null) { - nodeContainers = new CopyOnWriteArraySet(); - } - boolean notifyNodeUpdate = false; - - switch (t) { - case ADDED: - if (ncContainers.add(containerName)) { - this.nodeConnectorContainerMap.put(nc, ncContainers); - } - if (nodeContainers.add(containerName)) { - this.nodeContainerMap.put(node, nodeContainers); - notifyNodeUpdate = true; - } - break; - case REMOVED: - if (ncContainers.remove(containerName)) { - if (ncContainers.isEmpty()) { - // Do cleanup to reduce memory footprint if no - // elements to be tracked - this.nodeConnectorContainerMap.remove(nc); - } else { - this.nodeConnectorContainerMap.put(nc, ncContainers); - } - } - boolean nodeContainerUpdate = true; - for (NodeConnector ncContainer : nodeConnectorContainerMap.keySet()) { - if ((ncContainer.getNode().equals(node)) && (nodeConnectorContainerMap.get(ncContainer).contains(containerName))) { - nodeContainerUpdate = false; - break; - } - } - if (nodeContainerUpdate) { - nodeContainers.remove(containerName); - notifyNodeUpdate = true; - if (nodeContainers.isEmpty()) { - this.nodeContainerMap.remove(node); - } else { - this.nodeContainerMap.put(node, nodeContainers); - } - } - break; - case CHANGED: - break; - } - - Set nodeProp = nodeProps.get(node); - if (nodeProp == null) { - return; - } - Set ncProp = nodeConnectorProps.get(nc); - // notify InventoryService - notifyInventoryShimInternalListener(containerName, nc, t, ncProp); - - if (notifyNodeUpdate) { - notifyInventoryShimInternalListener(containerName, node, t, nodeProp); - } - } - - private void notifyInventoryShimExternalListener(Node node, UpdateType type, Set props) { - for (IInventoryShimExternalListener s : this.inventoryShimExternalListeners) { - s.updateNode(node, type, props); - } - } - - private void notifyInventoryShimExternalListener(NodeConnector nodeConnector, UpdateType type, Set props) { - for (IInventoryShimExternalListener s : this.inventoryShimExternalListeners) { - s.updateNodeConnector(nodeConnector, type, props); - } - } - - private void notifyInventoryShimInternalListener(String container, - NodeConnector nodeConnector, UpdateType type, Set props) { - IInventoryShimInternalListener inventoryShimInternalListener = inventoryShimInternalListeners.get(container); - if (inventoryShimInternalListener != null) { - inventoryShimInternalListener.updateNodeConnector(nodeConnector, type, props); - logger.trace("notifyInventoryShimInternalListener {} type {} for container {}", new Object[] { - nodeConnector, type, container }); - } - } - - /* - * Notify all internal and external listeners - */ - private void notifyInventoryShimListener(NodeConnector nodeConnector, UpdateType type, Set props) { - - //establish locality before notifying - boolean isNodeLocal; - if (type == UpdateType.REMOVED){ - //if removing get the locality first - isNodeLocal = connectionOutService.isLocal(nodeConnector.getNode()); - notifyGlobalInventoryShimInternalListener(nodeConnector, type, props); - } else { - notifyGlobalInventoryShimInternalListener(nodeConnector, type, props); - isNodeLocal = connectionOutService.isLocal(nodeConnector.getNode()); - } - - if (isNodeLocal) { - // notify other containers - Set containers = (nodeConnectorContainerMap.get(nodeConnector) == null) ? new HashSet() - : new HashSet(nodeConnectorContainerMap.get(nodeConnector)); - containers.add(GlobalConstants.DEFAULT.toString()); - for (String container : containers) { - notifyInventoryShimInternalListener(container, nodeConnector, type, props); - } - - // Notify plugin listeners (Discovery, DataPacket, OFstats etc.) - notifyInventoryShimExternalListener(nodeConnector, type, props); - - logger.debug("Connection service accepted the inventory notification for {} {}", nodeConnector, type); - } else { - logger.debug("Connection service dropped the inventory notification for {} {}", nodeConnector, type); - } - } - - /* - * Notify all internal and external listeners - */ - private void notifyInventoryShimListener(Node node, UpdateType type, Set props) { - - //establish locality before notifying - boolean isNodeLocal; - if (type == UpdateType.REMOVED){ - //if removing get the locality first - isNodeLocal = connectionOutService.isLocal(node); - notifyGlobalInventoryShimInternalListener(node, type, props); - } else { - notifyGlobalInventoryShimInternalListener(node, type, props); - isNodeLocal = connectionOutService.isLocal(node); - } - - if (isNodeLocal) { - // Now notify other containers - Set containers = (nodeContainerMap.get(node) == null) ? new HashSet() - : new HashSet(nodeContainerMap.get(node)); - containers.add(GlobalConstants.DEFAULT.toString()); - for (String container : containers) { - notifyInventoryShimInternalListener(container, node, type, props); - } - - // Notify plugin listeners (Discovery, DataPacket, OFstats etc.) - notifyInventoryShimExternalListener(node, type, props); - - logger.debug("Connection service accepted the inventory notification for {} {}", node, type); - } else { - logger.debug("Connection service dropped the inventory notification for {} {}", node, type); - } - } - - private void notifyGlobalInventoryShimInternalListener(Node node, UpdateType type, Set props) { - for (IInventoryShimInternalListener globalListener : globalInventoryShimInternalListeners) { - globalListener.updateNode(node, type, props); - logger.trace("notifyGlobalInventoryShimInternalListener {} type {}", new Object[] { node, type }); - } - } - - private void notifyGlobalInventoryShimInternalListener(NodeConnector nodeConnector, UpdateType type, Set props) { - for (IInventoryShimInternalListener globalListener : globalInventoryShimInternalListeners) { - globalListener.updateNodeConnector(nodeConnector, type, props); - logger.trace( - "notifyGlobalInventoryShimInternalListener {} type {}", - new Object[] { nodeConnector, type }); - } - } - - private void notifyInventoryShimInternalListener(String container, - Node node, UpdateType type, Set props) { - IInventoryShimInternalListener inventoryShimInternalListener = inventoryShimInternalListeners - .get(container); - if (inventoryShimInternalListener != null) { - inventoryShimInternalListener.updateNode(node, type, props); - logger.trace( - "notifyInventoryShimInternalListener {} type {} for container {}", - new Object[] { node, type, container }); - } - } - - private void addNode(ISwitch sw) { - Node node = NodeCreator.createOFNode(sw.getId()); - UpdateType type = UpdateType.ADDED; - - Set props = new HashSet(); - Long sid = (Long) node.getID(); - - Date connectedSince = sw.getConnectedDate(); - Long connectedSinceTime = (connectedSince == null) ? 0 : connectedSince - .getTime(); - props.add(new TimeStamp(connectedSinceTime, "connectedSince")); - props.add(new MacAddress(deriveMacAddress(sid))); - - byte tables = sw.getTables(); - Tables t = new Tables(tables); - if (t != null) { - props.add(t); - } - int cap = sw.getCapabilities(); - Capabilities c = new Capabilities(cap); - if (c != null) { - props.add(c); - } - int act = sw.getActions(); - SupportedFlowActions a = new SupportedFlowActions(FlowConverter.getFlowActions(act)); - if (a != null) { - props.add(a); - } - int buffers = sw.getBuffers(); - Buffers b = new Buffers(buffers); - if (b != null) { - props.add(b); - } - - if ((nodeProps.get(node) == null) && (connectionOutService.isLocal(node))) { - // The switch is connected for the first time, flush all flows - // that may exist on this switch - sw.deleteAllFlows(); - } - nodeProps.put(node, props); - // Notify all internal and external listeners - notifyInventoryShimListener(node, type, props); - } - - private void removeNode(ISwitch sw) { - Node node = NodeCreator.createOFNode(sw.getId()); - if(node == null) { - return; - } - removeNodeConnectorProps(node); - nodeProps.remove(node); - UpdateType type = UpdateType.REMOVED; - // Notify all internal and external listeners - notifyInventoryShimListener(node, type, null); - } - - private void startService() { - // Get a snapshot of all the existing switches - Map switches = this.controller.getSwitches(); - for (ISwitch sw : switches.values()) { - switchAdded(sw); - } - } - - private void removeNodeConnectorProps(Node node) { - List ncList = new ArrayList(); - for (NodeConnector nc : nodeConnectorProps.keySet()) { - if (nc.getNode().equals(node)) { - ncList.add(nc); - } - } - for (NodeConnector nc : ncList) { - nodeConnectorProps.remove(nc); - } - } - - @Override - public void descriptionStatisticsRefreshed(Long switchId, List descriptionStats) { - Node node = NodeCreator.createOFNode(switchId); - Set properties = new HashSet(1); - OFDescriptionStatistics ofDesc = (OFDescriptionStatistics) descriptionStats.get(0); - Description desc = new Description(ofDesc.getDatapathDescription()); - properties.add(desc); - - // Notify all internal and external listeners - notifyInventoryShimListener(node, UpdateType.CHANGED, properties); - } - - private byte[] deriveMacAddress(long dpid) { - byte[] mac = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - - for (short i = 0; i < 6; i++) { - mac[5 - i] = (byte) dpid; - dpid >>= 8; - } - - return mac; - } - - @Override - public void flowStatisticsRefreshed(Long switchId, List flows) { - // Nothing to do - } - - @Override - public void portStatisticsRefreshed(Long switchId, List ports) { - // Nothing to do - } - - @Override - public void tableStatisticsRefreshed(Long switchId, List tables) { - // Nothing to do - } - - @Override - public void containerCreate(String containerName) { - // Nothing to do - } - - @Override - public void containerDestroy(String containerName) { - Set removeNodeConnectorSet = new HashSet(); - Set removeNodeSet = new HashSet(); - for (Map.Entry> entry : nodeConnectorContainerMap.entrySet()) { - Set ncContainers = entry.getValue(); - if (ncContainers.contains(containerName)) { - NodeConnector nodeConnector = entry.getKey(); - removeNodeConnectorSet.add(nodeConnector); - } - } - for (Map.Entry> entry : nodeContainerMap.entrySet()) { - Set nodeContainers = entry.getValue(); - if (nodeContainers.contains(containerName)) { - Node node = entry.getKey(); - removeNodeSet.add(node); - } - } - for (NodeConnector nodeConnector : removeNodeConnectorSet) { - Set ncContainers = nodeConnectorContainerMap.get(nodeConnector); - ncContainers.remove(containerName); - if (ncContainers.isEmpty()) { - nodeConnectorContainerMap.remove(nodeConnector); - } - } - for (Node node : removeNodeSet) { - Set nodeContainers = nodeContainerMap.get(node); - nodeContainers.remove(containerName); - if (nodeContainers.isEmpty()) { - nodeContainerMap.remove(node); - } - } - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/OFStatisticsManager.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/OFStatisticsManager.java deleted file mode 100644 index e5883d6717..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/OFStatisticsManager.java +++ /dev/null @@ -1,1216 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Deque; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.LinkedBlockingDeque; -import java.util.concurrent.LinkedBlockingQueue; - -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsListener; -import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsManager; -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch; -import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6Match; -import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6StatsReply; -import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6StatsRequest; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.openflow.protocol.OFError; -import org.openflow.protocol.OFMatch; -import org.openflow.protocol.OFPort; -import org.openflow.protocol.OFStatisticsRequest; -import org.openflow.protocol.statistics.OFAggregateStatisticsRequest; -import org.openflow.protocol.statistics.OFFlowStatisticsReply; -import org.openflow.protocol.statistics.OFFlowStatisticsRequest; -import org.openflow.protocol.statistics.OFPortStatisticsReply; -import org.openflow.protocol.statistics.OFPortStatisticsRequest; -import org.openflow.protocol.statistics.OFQueueStatisticsRequest; -import org.openflow.protocol.statistics.OFStatistics; -import org.openflow.protocol.statistics.OFStatisticsType; -import org.openflow.protocol.statistics.OFTableStatistics; -import org.openflow.protocol.statistics.OFVendorStatistics; -import org.openflow.util.HexString; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Periodically polls the different OF statistics from the OF switches, caches - * them, and publishes results towards SAL. It also provides an API to directly - * query the switch for any specific statistics. - */ -public class OFStatisticsManager implements IOFStatisticsManager, IInventoryShimExternalListener, CommandProvider { - private static final Logger log = LoggerFactory.getLogger(OFStatisticsManager.class); - private static final int INITIAL_SIZE = 64; - private static final long FLOW_STATS_PERIOD = 10000; - private static final long DESC_STATS_PERIOD = 60000; - private static final long PORT_STATS_PERIOD = 5000; - private static final long TABLE_STATS_PERIOD = 10000; - private static final long TICK = 1000; - private static short statisticsTickNumber = (short) (FLOW_STATS_PERIOD / TICK); - private static short descriptionTickNumber = (short) (DESC_STATS_PERIOD / TICK); - private static short portTickNumber = (short) (PORT_STATS_PERIOD / TICK); - private static short tableTickNumber = (short) (TABLE_STATS_PERIOD / TICK); - private static short factoredSamples = (short) 2; - private static short counter = 1; - private IController controller = null; - private ConcurrentMap> flowStatistics; - private ConcurrentMap> descStatistics; - private ConcurrentMap> portStatistics; - private ConcurrentMap> tableStatistics; - private ConcurrentMap statisticsTimerTicks; - protected BlockingQueue pendingStatsRequests; - protected BlockingQueue switchPortStatsUpdated; - private Thread statisticsCollector; - private Thread txRatesUpdater; - private Timer statisticsTimer; - private TimerTask statisticsTimerTask; - private ConcurrentMap switchSupportsVendorExtStats; - // Per port sampled (every portStatsPeriod) transmit rate - private Map> txRates; - private Set statisticsListeners = new CopyOnWriteArraySet(); - - /** - * The object containing the latest factoredSamples tx rate samples for a - * given switch port - */ - protected class TxRates { - // contains the latest factoredSamples sampled transmitted bytes - Deque sampledTxBytes; - - public TxRates() { - sampledTxBytes = new LinkedBlockingDeque(); - } - - public void update(Long txBytes) { - /* - * Based on how many samples our average works on, we might have to - * remove the oldest sample - */ - if (sampledTxBytes.size() == factoredSamples) { - sampledTxBytes.removeLast(); - } - - // Add the latest sample to the top of the queue - sampledTxBytes.addFirst(txBytes); - } - - /** - * Returns the average transmit rate in bps - * - * @return the average transmit rate [bps] - */ - public long getAverageTxRate() { - long average = 0; - /* - * If we cannot provide the value for the time window length set - */ - if (sampledTxBytes.size() < factoredSamples) { - return average; - } - long increment = sampledTxBytes.getFirst() - sampledTxBytes - .getLast(); - long timePeriod = factoredSamples * PORT_STATS_PERIOD / TICK; - average = (8L * increment) / timePeriod; - return average; - } - } - - public void setController(IController core) { - this.controller = core; - } - - public void unsetController(IController core) { - if (this.controller == core) { - this.controller = null; - } - } - - private short getStatsQueueSize() { - String statsQueueSizeStr = System.getProperty("of.statsQueueSize"); - short statsQueueSize = INITIAL_SIZE; - if (statsQueueSizeStr != null) { - try { - statsQueueSize = Short.parseShort(statsQueueSizeStr); - if (statsQueueSize <= 0) { - statsQueueSize = INITIAL_SIZE; - } - } catch (Exception e) { - } - } - return statsQueueSize; - } - - IPluginOutConnectionService connectionPluginOutService; - void setIPluginOutConnectionService(IPluginOutConnectionService s) { - connectionPluginOutService = s; - } - - void unsetIPluginOutConnectionService(IPluginOutConnectionService s) { - if (connectionPluginOutService == s) { - connectionPluginOutService = null; - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - flowStatistics = new ConcurrentHashMap>(); - descStatistics = new ConcurrentHashMap>(); - portStatistics = new ConcurrentHashMap>(); - tableStatistics = new ConcurrentHashMap>(); - pendingStatsRequests = new LinkedBlockingQueue(getStatsQueueSize()); - statisticsTimerTicks = new ConcurrentHashMap(INITIAL_SIZE); - switchPortStatsUpdated = new LinkedBlockingQueue(INITIAL_SIZE); - switchSupportsVendorExtStats = new ConcurrentHashMap(INITIAL_SIZE); - txRates = new HashMap>(INITIAL_SIZE); - - configStatsPollIntervals(); - - // Initialize managed timers - statisticsTimer = new Timer("Statistics Timer Ticks"); - statisticsTimerTask = new TimerTask() { - @Override - public void run() { - decrementTicks(); - } - }; - - // Initialize Statistics collector thread - statisticsCollector = new Thread(new Runnable() { - @Override - public void run() { - while (true) { - try { - StatsRequest req = pendingStatsRequests.take(); - queryStatisticsInternal(req.switchId, req.type); - } catch (InterruptedException e) { - log.warn("Flow Statistics Collector thread " - + "interrupted", e); - return; - } - } - } - }, "Statistics Collector"); - - // Initialize Tx Rate Updater thread - txRatesUpdater = new Thread(new Runnable() { - @Override - public void run() { - while (true) { - try { - long switchId = switchPortStatsUpdated.take(); - updatePortsTxRate(switchId); - } catch (InterruptedException e) { - log.warn("TX Rate Updater thread interrupted", e); - return; - } - } - } - }, "TX Rate Updater"); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - statisticsListeners.clear(); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - // Start managed timers - statisticsTimer.scheduleAtFixedRate(statisticsTimerTask, 0, TICK); - - // Start statistics collector thread - statisticsCollector.start(); - - // Start bandwidth utilization computer thread - txRatesUpdater.start(); - - // OSGI console - registerWithOSGIConsole(); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - // Stop managed timers - statisticsTimer.cancel(); - } - - public void setStatisticsListener(IOFStatisticsListener s) { - this.statisticsListeners.add(s); - } - - public void unsetStatisticsListener(IOFStatisticsListener s) { - if (s != null) { - this.statisticsListeners.remove(s); - } - } - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, null); - } - - private static class StatsRequest { - protected Long switchId; - protected OFStatisticsType type; - - public StatsRequest(Long d, OFStatisticsType t) { - switchId = d; - type = t; - } - - @Override - public String toString() { - return "SReq = {switchId=" + switchId + ", type=" + type + "}"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((switchId == null) ? 0 : switchId.hashCode()); - result = prime * result + ((type == null) ? 0 : type.ordinal()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - StatsRequest other = (StatsRequest) obj; - if (switchId == null) { - if (other.switchId != null) { - return false; - } - } else if (!switchId.equals(other.switchId)) { - return false; - } - if (type != other.type) { - return false; - } - return true; - } - } - - private void addStatisticsTicks(Long switchId) { - switchSupportsVendorExtStats.put(switchId, Boolean.TRUE); // Assume - // switch - // supports - // Vendor - // extension - // stats - statisticsTimerTicks.put(switchId, new StatisticsTicks(true)); - log.debug("Added Switch {} to target pool", - HexString.toHexString(switchId.longValue())); - } - - protected static class StatisticsTicks { - private short flowStatisticsTicks; - private short descriptionTicks; - private short portStatisticsTicks; - private short tableStatisticsTicks; - - public StatisticsTicks(boolean scattered) { - if (scattered) { - // scatter bursts by statisticsTickPeriod - if (++counter < 0) { - counter = 0; - } // being paranoid here - flowStatisticsTicks = (short) (1 + counter - % statisticsTickNumber); - descriptionTicks = (short) (1 + counter % descriptionTickNumber); - portStatisticsTicks = (short) (1 + counter % portTickNumber); - tableStatisticsTicks = (short) (1 + counter % tableTickNumber); - } else { - flowStatisticsTicks = statisticsTickNumber; - descriptionTicks = descriptionTickNumber; - portStatisticsTicks = portTickNumber; - tableStatisticsTicks = tableTickNumber; - } - } - - public boolean decrementFlowTicksIsZero() { - // Please ensure no code is inserted between the if check and the - // flowStatisticsTicks reset - if (--flowStatisticsTicks == 0) { - flowStatisticsTicks = statisticsTickNumber; - return true; - } - return false; - } - - public boolean decrementDescTicksIsZero() { - // Please ensure no code is inserted between the if check and the - // descriptionTicks reset - if (--descriptionTicks == 0) { - descriptionTicks = descriptionTickNumber; - return true; - } - return false; - } - - public boolean decrementPortTicksIsZero() { - // Please ensure no code is inserted between the if check and the - // descriptionTicks reset - if (--portStatisticsTicks == 0) { - portStatisticsTicks = portTickNumber; - return true; - } - return false; - } - - public boolean decrementTableTicksIsZero() { - // Please ensure no code is inserted between the if check and the - // descriptionTicks reset - if(--tableStatisticsTicks == 0) { - tableStatisticsTicks = tableTickNumber; - return true; - } - return false; - } - - @Override - public String toString() { - return "{fT=" + flowStatisticsTicks + ",dT=" + descriptionTicks - + ",pT=" + portStatisticsTicks + ",tT=" + tableStatisticsTicks + "}"; - } - } - - private void printInfoMessage(String type, StatsRequest request) { - log.trace("{} stats request not inserted for switch: {}. Queue size: {}. Collector state: {}.", - new Object[] {type, HexString.toHexString(request.switchId), pendingStatsRequests.size(), - statisticsCollector.getState().toString() }); - } - - protected void decrementTicks() { - StatsRequest request = null; - for (Map.Entry entry : statisticsTimerTicks - .entrySet()) { - StatisticsTicks clock = entry.getValue(); - Long switchId = entry.getKey(); - if (clock.decrementFlowTicksIsZero()) { - request = (switchSupportsVendorExtStats.get(switchId) == Boolean.TRUE) ? - new StatsRequest(switchId, OFStatisticsType.VENDOR) : - new StatsRequest(switchId, OFStatisticsType.FLOW); - // If a request for this switch is already in the queue, skip to - // add this new request - if (!pendingStatsRequests.contains(request) - && false == pendingStatsRequests.offer(request)) { - printInfoMessage("Flow", request); - } - } - - if (clock.decrementDescTicksIsZero()) { - request = new StatsRequest(switchId, OFStatisticsType.DESC); - // If a request for this switch is already in the queue, skip to - // add this new request - if (!pendingStatsRequests.contains(request) - && false == pendingStatsRequests.offer(request)) { - printInfoMessage("Description", request); - } - } - - if (clock.decrementPortTicksIsZero()) { - request = new StatsRequest(switchId, OFStatisticsType.PORT); - // If a request for this switch is already in the queue, skip to - // add this new request - if (!pendingStatsRequests.contains(request) - && false == pendingStatsRequests.offer(request)) { - printInfoMessage("Port", request); - } - } - - if(clock.decrementTableTicksIsZero()) { - request = new StatsRequest(switchId, OFStatisticsType.TABLE); - // If a request for this switch is already in the queue, skip to - // add this new request - if (!pendingStatsRequests.contains(request) - && false == pendingStatsRequests.offer(request)) { - printInfoMessage("Table", request); - } - } - } - } - - private void removeStatsRequestTasks(Long switchId) { - log.debug("Cleaning Statistics database for switch {}", - HexEncode.longToHexString(switchId)); - // To be safe, let's attempt removal of both VENDOR and FLOW request. It - // does not hurt - pendingStatsRequests.remove(new StatsRequest(switchId, - OFStatisticsType.VENDOR)); - pendingStatsRequests.remove(new StatsRequest(switchId, - OFStatisticsType.FLOW)); - pendingStatsRequests.remove(new StatsRequest(switchId, - OFStatisticsType.DESC)); - pendingStatsRequests.remove(new StatsRequest(switchId, - OFStatisticsType.PORT)); - pendingStatsRequests.remove(new StatsRequest(switchId, - OFStatisticsType.TABLE)); - // Take care of the TX rate databases - switchPortStatsUpdated.remove(switchId); - txRates.remove(switchId); - } - - private void clearFlowStatsAndTicks(Long switchId) { - statisticsTimerTicks.remove(switchId); - removeStatsRequestTasks(switchId); - flowStatistics.remove(switchId); - log.debug("Statistics removed for switch {}", - HexString.toHexString(switchId)); - } - - private void queryStatisticsInternal(Long switchId, OFStatisticsType statType) { - - // Query the switch on all matches - List values = this.fetchStatisticsFromSwitch(switchId, statType, null); - - // If got a valid response update local cache and notify listeners - if (!values.isEmpty()) { - switch (statType) { - case FLOW: - case VENDOR: - flowStatistics.put(switchId, values); - notifyFlowUpdate(switchId, values); - break; - case DESC: - // Overwrite cache - descStatistics.put(switchId, values); - // Notify who may be interested in a description change - notifyDescriptionUpdate(switchId, values); - break; - case PORT: - // Overwrite cache with new port statistics for this switch - portStatistics.put(switchId, values); - - // Wake up the thread which maintains the TX byte counters for - // each port - switchPortStatsUpdated.offer(switchId); - notifyPortUpdate(switchId, values); - break; - case TABLE: - // Overwrite cache - tableStatistics.put(switchId, values); - notifyTableUpdate(switchId, values); - break; - default: - } - } - } - - private void notifyDescriptionUpdate(Long switchId, List values) { - for (IOFStatisticsListener l : this.statisticsListeners) { - l.descriptionStatisticsRefreshed(switchId, values); - } - } - - private void notifyFlowUpdate(Long switchId, List values) { - if (values.get(0) instanceof OFVendorStatistics) { - values = this.v6StatsListToOFStatsList(values); - } - - for (IOFStatisticsListener l : this.statisticsListeners) { - l.flowStatisticsRefreshed(switchId, values); - } - - } - - private void notifyPortUpdate(Long switchId, List values) { - for (IOFStatisticsListener l : this.statisticsListeners) { - l.portStatisticsRefreshed(switchId, values); - } - } - - private void notifyTableUpdate(Long switchId, List values) { - for (IOFStatisticsListener l : this.statisticsListeners) { - l.tableStatisticsRefreshed(switchId, values); - } - } - - /* - * Generic function to get the statistics form an OF switch - */ - @SuppressWarnings("unchecked") - private List fetchStatisticsFromSwitch(Long switchId, - OFStatisticsType statsType, Object target) { - List values = Collections.emptyList(); - String type = null; - ISwitch sw = controller.getSwitch(switchId); - - if (sw != null) { - OFStatisticsRequest req = new OFStatisticsRequest(); - req.setStatisticType(statsType); - int requestLength = req.getLengthU(); - - if (statsType == OFStatisticsType.FLOW) { - OFMatch match = null; - if (target == null) { - // All flows request - match = new OFMatch(); - match.setWildcards(0xffffffff); - } else if (!(target instanceof OFMatch)) { - // Malformed request - log.warn("Invalid target type for Flow stats request: {}", - target.getClass()); - return Collections.emptyList(); - } else { - // Specific flow request - match = (OFMatch) target; - } - OFFlowStatisticsRequest specificReq = new OFFlowStatisticsRequest(); - specificReq.setMatch(match); - specificReq.setOutPort(OFPort.OFPP_NONE.getValue()); - specificReq.setTableId((byte) 0xff); - req.setStatistics(Collections - .singletonList((OFStatistics) specificReq)); - requestLength += specificReq.getLength(); - type = "FLOW"; - } else if (statsType == OFStatisticsType.VENDOR) { - V6StatsRequest specificReq = new V6StatsRequest(); - specificReq.setOutPort(OFPort.OFPP_NONE.getValue()); - specificReq.setTableId((byte) 0xff); - req.setStatistics(Collections - .singletonList((OFStatistics) specificReq)); - requestLength += specificReq.getLength(); - type = "VENDOR"; - } else if (statsType == OFStatisticsType.AGGREGATE) { - OFAggregateStatisticsRequest specificReq = new OFAggregateStatisticsRequest(); - OFMatch match = new OFMatch(); - match.setWildcards(0xffffffff); - specificReq.setMatch(match); - specificReq.setOutPort(OFPort.OFPP_NONE.getValue()); - specificReq.setTableId((byte) 0xff); - req.setStatistics(Collections - .singletonList((OFStatistics) specificReq)); - requestLength += specificReq.getLength(); - type = "AGGREGATE"; - } else if (statsType == OFStatisticsType.PORT) { - short targetPort; - if (target == null) { - // All ports request - targetPort = OFPort.OFPP_NONE.getValue(); - } else if (!(target instanceof Short)) { - // Malformed request - log.warn("Invalid target type for Port stats request: {}", - target.getClass()); - return Collections.emptyList(); - } else { - // Specific port request - targetPort = (Short) target; - } - OFPortStatisticsRequest specificReq = new OFPortStatisticsRequest(); - specificReq.setPortNumber(targetPort); - req.setStatistics(Collections - .singletonList((OFStatistics) specificReq)); - requestLength += specificReq.getLength(); - type = "PORT"; - } else if (statsType == OFStatisticsType.QUEUE) { - OFQueueStatisticsRequest specificReq = new OFQueueStatisticsRequest(); - specificReq.setPortNumber(OFPort.OFPP_ALL.getValue()); - specificReq.setQueueId(0xffffffff); - req.setStatistics(Collections - .singletonList((OFStatistics) specificReq)); - requestLength += specificReq.getLength(); - type = "QUEUE"; - } else if (statsType == OFStatisticsType.DESC) { - type = "DESC"; - } else if (statsType == OFStatisticsType.TABLE) { - if(target != null){ - if (!(target instanceof Byte)) { - // Malformed request - log.warn("Invalid table id for table stats request: {}", - target.getClass()); - return Collections.emptyList(); - } - byte targetTable = (Byte) target; - OFTableStatistics specificReq = new OFTableStatistics(); - specificReq.setTableId(targetTable); - req.setStatistics(Collections - .singletonList((OFStatistics) specificReq)); - requestLength += specificReq.getLength(); - } - type = "TABLE"; - } - req.setLengthU(requestLength); - Object result = sw.getStatistics(req); - - if (result == null) { - log.warn("Request Timed Out for ({}) from switch {}", type, - HexString.toHexString(switchId)); - } else if (result instanceof OFError) { - log.warn("Switch {} failed to handle ({}) stats request: {}", - new Object[] { HexString.toHexString(switchId), type, - Utils.getOFErrorString((OFError) result) }); - if (this.switchSupportsVendorExtStats.get(switchId) == Boolean.TRUE) { - log.warn( - "Switching back to regular Flow stats requests for switch {}", - HexString.toHexString(switchId)); - this.switchSupportsVendorExtStats.put(switchId, - Boolean.FALSE); - } - } else { - values = (List) result; - } - } - return values; - } - - @Override - public List getOFFlowStatistics(Long switchId) { - List list = flowStatistics.get(switchId); - - /* - * Check on emptiness as interference between add and get is still - * possible on the inner list (the concurrentMap entry's value) - */ - return (list == null || list.isEmpty()) ? Collections.emptyList() - : (list.get(0) instanceof OFVendorStatistics) ? this - .v6StatsListToOFStatsList(list) : list; - } - - @Override - public List getOFFlowStatistics(Long switchId, OFMatch ofMatch, short priority) { - List statsList = flowStatistics.get(switchId); - - /* - * Check on emptiness as interference between add and get is still - * possible on the inner list (the concurrentMap entry's value) - */ - if (statsList == null || statsList.isEmpty()) { - return Collections.emptyList(); - } - - if (statsList.get(0) instanceof OFVendorStatistics) { - /* - * Caller could provide regular OF match when we instead pull the - * vendor statistics from this node Caller is not supposed to know - * whether this switch supports vendor extensions statistics - * requests - */ - V6Match targetMatch = (ofMatch instanceof V6Match) ? (V6Match) ofMatch - : new V6Match(ofMatch); - - List targetList = v6StatsListToOFStatsList(statsList); - for (OFStatistics stats : targetList) { - V6StatsReply v6Stats = (V6StatsReply) stats; - V6Match v6Match = v6Stats.getMatch(); - if (v6Stats.getPriority() == priority && targetMatch.equals(v6Match)) { - List list = new ArrayList(); - list.add(stats); - return list; - } - } - } else { - for (OFStatistics stats : statsList) { - OFFlowStatisticsReply flowStats = (OFFlowStatisticsReply) stats; - if (flowStats.getPriority() == priority && ofMatch.equals(flowStats.getMatch())) { - List list = new ArrayList(); - list.add(stats); - return list; - } - } - } - return Collections.emptyList(); - } - - /* - * Converts the v6 vendor statistics to the OFStatistics - */ - private List v6StatsListToOFStatsList(List statistics) { - if (statistics == null || statistics.isEmpty()) { - return Collections.emptyList(); - } - List v6statistics = new ArrayList(); - for (OFStatistics stats : statistics) { - if (stats instanceof OFVendorStatistics) { - List r = getV6ReplyStatistics((OFVendorStatistics) stats); - if (r != null) { - v6statistics.addAll(r); - } - } - } - return v6statistics; - } - - private static List getV6ReplyStatistics( - OFVendorStatistics stat) { - int length = stat.getLength(); - List results = new ArrayList(); - if (length < 12) { - // Nicira Hdr is 12 bytes. We need at least that much - return Collections.emptyList(); - } - ByteBuffer data = ByteBuffer.allocate(length); - stat.writeTo(data); - data.rewind(); - if (log.isTraceEnabled()) { - log.trace("getV6ReplyStatistics: Buffer BYTES ARE {}", - HexString.toHexString(data.array())); - } - - int vendor = data.getInt(); // first 4 bytes is vendor id. - if (vendor != V6StatsRequest.NICIRA_VENDOR_ID) { - log.warn("Unexpected vendor id: 0x{}", Integer.toHexString(vendor)); - return Collections.emptyList(); - } else { - // go ahead by 8 bytes which is 8 bytes of 0 - data.getLong(); // should be all 0's - length -= 12; // 4 bytes Nicira Hdr + 8 bytes from above line have - // been consumed - } - - V6StatsReply v6statsreply; - int min_len; - while (length > 0) { - v6statsreply = new V6StatsReply(); - min_len = v6statsreply.getLength(); - if (length < v6statsreply.getLength()) { - break; - } - v6statsreply.setActionFactory(stat.getActionFactory()); - v6statsreply.readFrom(data); - if (v6statsreply.getLength() < min_len) { - break; - } - v6statsreply.setVendorId(vendor); - log.trace("V6StatsReply: {}", v6statsreply); - length -= v6statsreply.getLength(); - results.add(v6statsreply); - } - return results; - } - - @Override - public List queryStatistics(Long switchId, - OFStatisticsType statType, Object target) { - /* - * Caller does not know and it is not supposed to know whether this - * switch supports vendor extension. We adjust the target for him - */ - if (statType == OFStatisticsType.FLOW) { - if (switchSupportsVendorExtStats.get(switchId) == Boolean.TRUE) { - statType = OFStatisticsType.VENDOR; - } - } - - List list = this.fetchStatisticsFromSwitch(switchId, statType, target); - - return (statType == OFStatisticsType.VENDOR) ? v6StatsListToOFStatsList(list) : list; - } - - @Override - public List getOFDescStatistics(Long switchId) { - if (!descStatistics.containsKey(switchId)) { - return Collections.emptyList(); - } - - return descStatistics.get(switchId); - } - - @Override - public List getOFPortStatistics(Long switchId) { - if (!portStatistics.containsKey(switchId)) { - return Collections.emptyList(); - } - - return portStatistics.get(switchId); - } - - @Override - public List getOFPortStatistics(Long switchId, short portId) { - if (!portStatistics.containsKey(switchId)) { - return Collections.emptyList(); - } - List list = new ArrayList(1); - for (OFStatistics stats : portStatistics.get(switchId)) { - if (((OFPortStatisticsReply) stats).getPortNumber() == portId) { - list.add(stats); - break; - } - } - return list; - } - - @Override - public List getOFTableStatistics(Long switchId) { - if (!tableStatistics.containsKey(switchId)) { - return Collections.emptyList(); - } - - return tableStatistics.get(switchId); - } - - @Override - public List getOFTableStatistics(Long switchId, Byte tableId) { - if (!tableStatistics.containsKey(switchId)) { - return Collections.emptyList(); - } - - List list = new ArrayList(1); - for (OFStatistics stats : tableStatistics.get(switchId)) { - if (((OFTableStatistics) stats).getTableId() == tableId) { - list.add(stats); - break; - } - } - return list; - } - - @Override - public int getFlowsNumber(long switchId) { - return this.flowStatistics.get(switchId).size(); - } - - /* - * InventoryShim replay for us all the switch addition which happened before - * we were brought up - */ - @Override - public void updateNode(Node node, UpdateType type, Set props) { - Long switchId = (Long) node.getID(); - switch (type) { - case ADDED: - addStatisticsTicks(switchId); - break; - case REMOVED: - clearFlowStatsAndTicks(switchId); - default: - } - } - - @Override - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props) { - // No action - } - - /** - * Update the cached port rates for this switch with the latest retrieved - * port transmit byte count - * - * @param switchId - */ - private synchronized void updatePortsTxRate(long switchId) { - List newPortStatistics = this.portStatistics.get(switchId); - if (newPortStatistics == null) { - return; - } - Map rates = this.txRates.get(switchId); - if (rates == null) { - // First time rates for this switch are added - rates = new HashMap(); - txRates.put(switchId, rates); - } - for (OFStatistics stats : newPortStatistics) { - OFPortStatisticsReply newPortStat = (OFPortStatisticsReply) stats; - short port = newPortStat.getPortNumber(); - TxRates portRatesHolder = rates.get(port); - if (portRatesHolder == null) { - // First time rates for this port are added - portRatesHolder = new TxRates(); - rates.put(port, portRatesHolder); - } - // Get and store the number of transmitted bytes for this port - // And handle the case where agent does not support the counter - long transmitBytes = newPortStat.getTransmitBytes(); - long value = (transmitBytes < 0) ? 0 : transmitBytes; - portRatesHolder.update(value); - } - } - - @Override - public synchronized long getTransmitRate(Long switchId, Short port) { - long average = 0; - if (switchId == null || port == null) { - return average; - } - Map perSwitch = txRates.get(switchId); - if (perSwitch == null) { - return average; - } - TxRates portRates = perSwitch.get(port); - if (portRates == null) { - return average; - } - return portRates.getAverageTxRate(); - } - - /* - * Manual switch name configuration code - */ - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---OF Statistics Manager utilities---\n"); - help.append("\t ofdumpstatsmgr - " - + "Print Internal Stats Mgr db\n"); - help.append("\t ofstatsmgrintervals (all in seconds) - " - + "Set/Show flow/port/dedscription stats poll intervals\n"); - return help.toString(); - } - - private boolean isValidSwitchId(String switchId) { - String regexDatapathID = "^([0-9a-fA-F]{1,2}[:-]){7}[0-9a-fA-F]{1,2}$"; - String regexDatapathIDLong = "^[0-9a-fA-F]{1,16}$"; - - return (switchId != null && (switchId.matches(regexDatapathID) || switchId - .matches(regexDatapathIDLong))); - } - - public long getSwitchIDLong(String switchId) { - int radix = 16; - String switchString = "0"; - - if (isValidSwitchId(switchId)) { - if (switchId.contains(":")) { - // Handle the 00:00:AA:BB:CC:DD:EE:FF notation - switchString = switchId.replace(":", ""); - } else if (switchId.contains("-")) { - // Handle the 00-00-AA-BB-CC-DD-EE-FF notation - switchString = switchId.replace("-", ""); - } else { - // Handle the 0123456789ABCDEF notation - switchString = switchId; - } - } - return Long.parseLong(switchString, radix); - } - - /* - * Internal information dump code - */ - private String prettyPrintSwitchMap(ConcurrentMap map) { - StringBuffer buffer = new StringBuffer(); - buffer.append("{"); - for (Entry entry : map.entrySet()) { - buffer.append(HexString.toHexString(entry.getKey()) + "=" - + entry.getValue().toString() + " "); - } - buffer.append("}"); - return buffer.toString(); - } - - public void _ofdumpstatsmgr(CommandInterpreter ci) { - ci.println("Global Counter: " + counter); - ci.println("Timer Ticks: " + prettyPrintSwitchMap(statisticsTimerTicks)); - ci.println("PendingStatsQueue: " + pendingStatsRequests); - ci.println("PendingStatsQueue size: " + pendingStatsRequests.size()); - ci.println("Stats Collector alive: " + statisticsCollector.isAlive()); - ci.println("Stats Collector State: " - + statisticsCollector.getState().toString()); - ci.println("StatsTimer: " + statisticsTimer.toString()); - ci.println("Flow Stats Period: " + statisticsTickNumber + " s"); - ci.println("Desc Stats Period: " + descriptionTickNumber + " s"); - ci.println("Port Stats Period: " + portTickNumber + " s"); - ci.println("Table Stats Period: " + tableTickNumber + " s"); - } - - public void _resetSwitchCapability(CommandInterpreter ci) { - String sidString = ci.nextArgument(); - Long sid = null; - if (sidString == null) { - ci.println("Insert the switch id (numeric value)"); - return; - } - try { - sid = Long.valueOf(sidString); - this.switchSupportsVendorExtStats.put(sid, Boolean.TRUE); - ci.println("Vendor capability for switch " + sid + " set to " - + this.switchSupportsVendorExtStats.get(sid)); - } catch (NumberFormatException e) { - ci.println("Invalid switch id. Has to be numeric."); - } - - } - - public void _ofbw(CommandInterpreter ci) { - String sidString = ci.nextArgument(); - Long sid = null; - if (sidString == null) { - ci.println("Insert the switch id (numeric value)"); - return; - } - try { - sid = Long.valueOf(sidString); - } catch (NumberFormatException e) { - ci.println("Invalid switch id. Has to be numeric."); - } - if (sid != null) { - Map thisSwitchRates = txRates.get(sid); - ci.println("Bandwidth utilization (" + factoredSamples - * portTickNumber + " sec average) for switch " - + HexEncode.longToHexString(sid) + ":"); - if (thisSwitchRates == null) { - ci.println("Not available"); - } else { - for (Entry entry : thisSwitchRates.entrySet()) { - ci.println("Port: " + entry.getKey() + ": " - + entry.getValue().getAverageTxRate() + " bps"); - } - } - } - } - - public void _txratewindow(CommandInterpreter ci) { - String averageWindow = ci.nextArgument(); - short seconds = 0; - if (averageWindow == null) { - ci.println("Insert the length in seconds of the median " - + "window for tx rate"); - ci.println("Current: " + factoredSamples * portTickNumber + " secs"); - return; - } - try { - seconds = Short.valueOf(averageWindow); - } catch (NumberFormatException e) { - ci.println("Invalid period."); - } - OFStatisticsManager.factoredSamples = (short) (seconds / portTickNumber); - ci.println("New: " + factoredSamples * portTickNumber + " secs"); - } - - public void _ofstatsmgrintervals(CommandInterpreter ci) { - String flowStatsInterv = ci.nextArgument(); - String portStatsInterv = ci.nextArgument(); - String descStatsInterv = ci.nextArgument(); - String tableStatsInterv = ci.nextArgument(); - - if (flowStatsInterv == null || portStatsInterv == null - || descStatsInterv == null) { - ci.println("Usage: ofstatsmgrintervals (all in seconds)"); - ci.println("Current Values: fP=" + statisticsTickNumber + "sec pP=" - + portTickNumber + "sec dP=" + descriptionTickNumber + "sec tP=" + tableTickNumber + " sec"); - return; - } - Short fP, pP, dP, tP; - try { - fP = Short.parseShort(flowStatsInterv); - pP = Short.parseShort(portStatsInterv); - dP = Short.parseShort(descStatsInterv); - tP = Short.parseShort(tableStatsInterv); - } catch (Exception e) { - ci.println("Invalid format values: " + e.getMessage()); - return; - } - - if (pP <= 1 || fP <= 1 || dP <= 1 || tP <= 1) { - ci.println("Invalid values. fP, pP, dP, tP have to be greater than 1."); - return; - } - - statisticsTickNumber = fP; - portTickNumber = pP; - descriptionTickNumber = dP; - tableTickNumber = tP; - - ci.println("New Values: fP=" + statisticsTickNumber + "s pP=" - + portTickNumber + "s dP=" + descriptionTickNumber + "s tP=" - + tableTickNumber + "s"); - } - - /** - * This method retrieves user configurations from config.ini and updates - * statisticsTickNumber/portTickNumber/descriptionTickNumber accordingly. - */ - private void configStatsPollIntervals() { - String fsStr = System.getProperty("of.flowStatsPollInterval"); - String psStr = System.getProperty("of.portStatsPollInterval"); - String dsStr = System.getProperty("of.descStatsPollInterval"); - String tsStr = System.getProperty("of.tableStatsPollInterval"); - Short fs, ps, ds, ts; - - if (fsStr != null) { - try { - fs = Short.parseShort(fsStr); - if (fs > 0) { - statisticsTickNumber = fs; - } - } catch (Exception e) { - } - } - - if (psStr != null) { - try { - ps = Short.parseShort(psStr); - if (ps > 0) { - portTickNumber = ps; - } - } catch (Exception e) { - } - } - - if (dsStr != null) { - try { - ds = Short.parseShort(dsStr); - if (ds > 0) { - descriptionTickNumber = ds; - } - } catch (Exception e) { - } - } - - if (tsStr != null) { - try{ - ts = Short.parseShort(tsStr); - if (ts > 0) { - tableTickNumber = ts; - } - } catch (Exception e) { - } - } - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortConverter.java deleted file mode 100644 index 0b605ab875..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortConverter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.openflow.protocol.OFPort; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Abstract class which provides the utilities for converting the Openflow port - * number to the equivalent NodeConnector and vice versa - * - * - * - */ -public abstract class PortConverter { - private static final Logger log = LoggerFactory - .getLogger(PortConverter.class); - private static final int maxOFPhysicalPort = NetUtils - .getUnsignedShort(OFPort.OFPP_MAX.getValue()); - - /** - * Converts the Openflow port number to the equivalent NodeConnector. - */ - public static NodeConnector toNodeConnector(short ofPort, Node node) { - // Restore original OF unsigned 16 bits value for the comparison - int unsignedOFPort = NetUtils.getUnsignedShort(ofPort); - log.trace("Openflow port number signed: {} unsigned: {}", ofPort, - unsignedOFPort); - if (unsignedOFPort > maxOFPhysicalPort) { - if (ofPort == OFPort.OFPP_LOCAL.getValue()) { - return NodeConnectorCreator.createNodeConnector( - NodeConnectorIDType.SWSTACK, - NodeConnector.SPECIALNODECONNECTORID, node); - } else if (ofPort == OFPort.OFPP_NORMAL.getValue()) { - return NodeConnectorCreator.createNodeConnector( - NodeConnectorIDType.HWPATH, - NodeConnector.SPECIALNODECONNECTORID, node); - } else if (ofPort == OFPort.OFPP_CONTROLLER.getValue()) { - return NodeConnectorCreator.createNodeConnector( - NodeConnectorIDType.CONTROLLER, - NodeConnector.SPECIALNODECONNECTORID, node); - } - } - return NodeConnectorCreator.createNodeConnector(ofPort, node); - } - - /** - * Converts the NodeConnector to the equivalent Openflow port number - */ - public static short toOFPort(NodeConnector salPort) { - log.trace("SAL Port", salPort); - if (salPort.getType().equals(NodeConnectorIDType.SWSTACK)) { - return OFPort.OFPP_LOCAL.getValue(); - } else if (salPort.getType().equals(NodeConnectorIDType.HWPATH)) { - return OFPort.OFPP_NORMAL.getValue(); - } else if (salPort.getType().equals(NodeConnectorIDType.CONTROLLER)) { - return OFPort.OFPP_CONTROLLER.getValue(); - } - return (Short) salPort.getID(); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortStatisticsConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortStatisticsConverter.java deleted file mode 100644 index 0fe1c72345..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/PortStatisticsConverter.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.openflow.protocol.statistics.OFPortStatisticsReply; -import org.openflow.protocol.statistics.OFStatistics; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Converts an openflow list of port statistics in a SAL list of - * NodeConnectorStatistics objects - * - * - * - */ -public class PortStatisticsConverter { - private static final Logger log = LoggerFactory - .getLogger(PortStatisticsConverter.class); - private long switchId; - private List ofStatsList; - private List ncStatsList; - - public PortStatisticsConverter(long switchId, List statsList) { - this.switchId = switchId; - if (statsList == null || statsList.isEmpty()) { - this.ofStatsList = Collections.emptyList(); - } else { - this.ofStatsList = new ArrayList(statsList); - } - this.ncStatsList = null; - } - - public List getNodeConnectorStatsList() { - if (this.ofStatsList != null && this.ncStatsList == null) { - this.ncStatsList = new ArrayList(); - OFPortStatisticsReply ofPortStat; - Node node = NodeCreator.createOFNode(switchId); - for (OFStatistics ofStat : this.ofStatsList) { - ofPortStat = (OFPortStatisticsReply) ofStat; - NodeConnectorStatistics NCStat = new NodeConnectorStatistics(); - NCStat.setNodeConnector(PortConverter.toNodeConnector( - ofPortStat.getPortNumber(), node)); - NCStat.setReceivePacketCount(ofPortStat.getreceivePackets()); - NCStat.setTransmitPacketCount(ofPortStat.getTransmitPackets()); - NCStat.setReceiveByteCount(ofPortStat.getReceiveBytes()); - NCStat.setTransmitByteCount(ofPortStat.getTransmitBytes()); - NCStat.setReceiveDropCount(ofPortStat.getReceiveDropped()); - NCStat.setTransmitDropCount(ofPortStat.getTransmitDropped()); - NCStat.setReceiveErrorCount(ofPortStat.getreceiveErrors()); - NCStat.setTransmitErrorCount(ofPortStat.getTransmitErrors()); - NCStat.setReceiveFrameErrorCount(ofPortStat - .getReceiveFrameErrors()); - NCStat.setReceiveOverRunErrorCount(ofPortStat - .getReceiveOverrunErrors()); - NCStat.setReceiveCRCErrorCount(ofPortStat.getReceiveCRCErrors()); - NCStat.setCollisionCount(ofPortStat.getCollisions()); - this.ncStatsList.add(NCStat); - } - } - log.trace("OFStatistics: {} NodeConnectorStatistics: {}", ofStatsList, - ncStatsList); - return this.ncStatsList; - } - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadService.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadService.java deleted file mode 100644 index f1f5944f37..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadService.java +++ /dev/null @@ -1,285 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.Collections; -import java.util.Dictionary; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.protocol_plugin.openflow.IReadFilterInternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.IReadServiceFilter; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.Node.NodeIDType; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.IPluginInReadService; -import org.opendaylight.controller.sal.reader.IPluginOutReadService; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Container Instance of IPluginInReadService implementation class - */ -public class ReadService implements IPluginInReadService, IReadFilterInternalListener { - private static final Logger logger = LoggerFactory - .getLogger(ReadService.class); - private IReadServiceFilter filter; - private Set pluginOutReadServices = new CopyOnWriteArraySet(); - private String containerName; - private IPluginOutConnectionService connectionOutService; - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - @SuppressWarnings("unchecked") - void init(Component c) { - Dictionary props = c.getServiceProperties(); - containerName = (props != null) ? (String) props.get("containerName") : null; - } - - /** - * Function called by the dependency manager when at least one - * dependency become unsatisfied or when the component is shutting - * down because for example bundle is being stopped. - * - */ - void destroy() { - pluginOutReadServices.clear(); - } - - /** - * Function called by dependency manager after "init ()" is called - * and after the services provided by the class are registered in - * the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services - * exported by the component are unregistered, this will be - * followed by a "destroy ()" calls - * - */ - void stop() { - } - - public void setService(IReadServiceFilter filter) { - this.filter = filter; - } - - public void unsetService(IReadServiceFilter filter) { - this.filter = null; - } - - public void setPluginOutReadServices(IPluginOutReadService service) { - logger.trace("Got a service set request {}", service); - if (this.pluginOutReadServices != null) { - this.pluginOutReadServices.add(service); - } - } - - public void unsetPluginOutReadServices( - IPluginOutReadService service) { - logger.trace("Got a service UNset request"); - if (this.pluginOutReadServices != null) { - this.pluginOutReadServices.remove(service); - } - } - @Override - public FlowOnNode readFlow(Node node, Flow flow, boolean cached) { - if (!node.getType().equals(NodeIDType.OPENFLOW)) { - logger.error("Invalid node type"); - return null; - } - - if (!connectionOutService.isLocal(node)) { - logger.debug("This Controller is not the master for the node : " + node); - return null; - } - return filter.readFlow(containerName, node, flow, cached); - } - - @Override - public List readAllFlow(Node node, boolean cached) { - if (!node.getType().equals(NodeIDType.OPENFLOW)) { - logger.error("Invalid node type"); - return Collections.emptyList(); - } - - if (!connectionOutService.isLocal(node)) { - logger.debug("This Controller is not the master for the node : " + node); - return Collections.emptyList(); - } - - return filter.readAllFlow(containerName, node, cached); - } - - @Override - public NodeDescription readDescription(Node node, boolean cached) { - if (!node.getType().equals(NodeIDType.OPENFLOW)) { - logger.error("Invalid node type"); - return null; - } - - if (!connectionOutService.isLocal(node)) { - logger.debug("This Controller is not the master for the node : " + node); - return null; - } - - return filter.readDescription(node, cached); - } - - @Override - public NodeConnectorStatistics readNodeConnector(NodeConnector connector, - boolean cached) { - if (!connector.getNode().getType() - .equals(NodeIDType.OPENFLOW)) { - logger.error("Invalid node type"); - return null; - } - - if (!connectionOutService.isLocal(connector.getNode())) { - logger.debug("This Controller is not the master for connector : "+connector); - return null; - } - - return filter.readNodeConnector(containerName, connector, cached); - } - - @Override - public List readAllNodeConnector(Node node, - boolean cached) { - if (!node.getType().equals(NodeIDType.OPENFLOW)) { - logger.error("Invalid node type"); - return Collections.emptyList(); - } - - if (!connectionOutService.isLocal(node)) { - logger.debug("This Controller is not the master for node : " + node); - return Collections.emptyList(); - } - - return filter.readAllNodeConnector(containerName, node, cached); - } - - @Override - public long getTransmitRate(NodeConnector connector) { - if (!connector.getNode().getType() - .equals(NodeIDType.OPENFLOW)) { - logger.error("Invalid node type"); - return 0; - } - - if (!connectionOutService.isLocal(connector.getNode())) { - logger.debug("This Controller is not the master for connector : "+connector); - return 0; - } - - return filter.getTransmitRate(containerName, connector); - } - - @Override - public NodeTableStatistics readNodeTable(NodeTable table, boolean cached) { - if (!table.getNode().getType() - .equals(NodeIDType.OPENFLOW)) { - logger.error("Invalid node type"); - return null; - } - - if (!connectionOutService.isLocal(table.getNode())) { - logger.debug("This Controller is not the master for connector : "+table); - return null; - } - - return filter.readNodeTable(containerName, table, cached); - } - - @Override - public List readAllNodeTable(Node node, boolean cached) { - if (!node.getType().equals(NodeIDType.OPENFLOW)) { - logger.error("Invalid node type"); - return Collections.emptyList(); - } - - if (!connectionOutService.isLocal(node)) { - logger.debug("This Controller is not the master for node : " + node); - return Collections.emptyList(); - } - - return filter.readAllNodeTable(containerName, node, cached); - } - - @Override - public void nodeFlowStatisticsUpdated(Node node, List flowStatsList) { - if (!connectionOutService.isLocal(node)) { - logger.debug("This Controller is not the master for node : " + node); - return; - } - for (IPluginOutReadService service : pluginOutReadServices) { - service.nodeFlowStatisticsUpdated(node, flowStatsList); - } - } - - @Override - public void nodeConnectorStatisticsUpdated(Node node, List ncStatsList) { - if (!connectionOutService.isLocal(node)) { - logger.debug("This Controller is not the master for node : " + node); - return; - } - for (IPluginOutReadService service : pluginOutReadServices) { - service.nodeConnectorStatisticsUpdated(node, ncStatsList); - } - } - - @Override - public void nodeTableStatisticsUpdated(Node node, List tableStatsList) { - if (!connectionOutService.isLocal(node)) { - logger.debug("This Controller is not the master for node : " + node); - return; - } - for (IPluginOutReadService service : pluginOutReadServices) { - service.nodeTableStatisticsUpdated(node, tableStatsList); - } - } - - @Override - public void nodeDescriptionStatisticsUpdated(Node node, NodeDescription nodeDescription) { - if (!connectionOutService.isLocal(node)) { - logger.debug("This Controller is not the master for node : " + node); - return; - } - for (IPluginOutReadService service : pluginOutReadServices) { - service.descriptionStatisticsUpdated(node, nodeDescription); - } - } - - void setIPluginOutConnectionService(IPluginOutConnectionService s) { - connectionOutService = s; - } - - void unsetIPluginOutConnectionService(IPluginOutConnectionService s) { - if (connectionOutService == s) { - connectionOutService = null; - } - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadServiceFilter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadServiceFilter.java deleted file mode 100644 index e1b244f2c1..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/ReadServiceFilter.java +++ /dev/null @@ -1,647 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsListener; -import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsManager; -import org.opendaylight.controller.protocol_plugin.openflow.IReadFilterInternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.IReadServiceFilter; -import org.opendaylight.controller.protocol_plugin.openflow.core.IController; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.ActionType; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.IContainerAware; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.utils.NodeTableCreator; -import org.openflow.protocol.OFMatch; -import org.openflow.protocol.statistics.OFFlowStatisticsReply; -import org.openflow.protocol.statistics.OFPortStatisticsReply; -import org.openflow.protocol.statistics.OFStatistics; -import org.openflow.protocol.statistics.OFStatisticsType; -import org.openflow.protocol.statistics.OFTableStatistics; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -/** - * Read Service shim layer which is in charge of filtering the flow statistics - * based on container. It is a Global instance. - */ -public class ReadServiceFilter implements IReadServiceFilter, IContainerListener, IOFStatisticsListener, IContainerAware { - private static final Logger logger = LoggerFactory - .getLogger(ReadServiceFilter.class); - private IController controller = null; - private IOFStatisticsManager statsMgr = null; - private ConcurrentMap> containerToNc; - private ConcurrentMap> containerToNode; - private ConcurrentMap> containerToNt; - private ConcurrentMap> containerFlows; - private ConcurrentMap readFilterInternalListeners = - new ConcurrentHashMap(); - - public void setController(IController core) { - this.controller = core; - } - - public void unsetController(IController core) { - if (this.controller == core) { - this.controller = null; - } - } - - public void setReadFilterInternalListener(Map props, IReadFilterInternalListener s) { - if (props == null) { - logger.error("Failed setting Read Filter Listener, property map is null."); - return; - } - String containerName = (String) props.get("containerName"); - if (containerName == null) { - logger.error("Failed setting Read Filter Listener, container name not supplied."); - return; - } - if ((this.readFilterInternalListeners != null) && !this.readFilterInternalListeners.containsValue(s)) { - this.readFilterInternalListeners.put(containerName, s); - logger.trace("Added Read Filter Listener for container {}", containerName); - } - } - - public void unsetReadFilterInternalListener(Map props, IReadFilterInternalListener s) { - if (props == null) { - logger.error("Failed unsetting Read Filter Listener, property map is null."); - return; - } - String containerName = (String) props.get("containerName"); - if (containerName == null) { - logger.error("Failed unsetting Read Filter Listener, containerName not supplied"); - return; - } - if ((this.readFilterInternalListeners != null) && this.readFilterInternalListeners.get(containerName) != null - && this.readFilterInternalListeners.get(containerName).equals(s)) { - this.readFilterInternalListeners.remove(containerName); - logger.trace("Removed Read Filter Listener for container {}", containerName); - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - containerToNc = new ConcurrentHashMap>(); - containerToNt = new ConcurrentHashMap>(); - containerToNode = new ConcurrentHashMap>(); - containerFlows = new ConcurrentHashMap>(); - } - - /** - * Function called by the dependency manager when at least one - * dependency become unsatisfied or when the component is shutting - * down because for example bundle is being stopped. - * - */ - void destroy() { - readFilterInternalListeners.clear(); - } - - /** - * Function called by dependency manager after "init ()" is called - * and after the services provided by the class are registered in - * the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services - * exported by the component are unregistered, this will be - * followed by a "destroy ()" calls - * - */ - void stop() { - } - - public void setService(IOFStatisticsManager service) { - this.statsMgr = service; - } - - public void unsetService(IOFStatisticsManager service) { - this.statsMgr = null; - } - - @Override - public FlowOnNode readFlow(String container, Node node, Flow flow, boolean cached) { - - if (controller == null) { - // Avoid to provide cached statistics if controller went down. - // They are not valid anymore anyway - logger.error("Internal plugin error"); - return null; - } - - long sid = (Long) node.getID(); - OFMatch ofMatch = new FlowConverter(flow).getOFMatch(); - List ofList; - if (cached == true){ - ofList = statsMgr.getOFFlowStatistics(sid, ofMatch, flow.getPriority()); - } else { - ofList = statsMgr.queryStatistics(sid, OFStatisticsType.FLOW, ofMatch); - for (OFStatistics ofStat : ofList) { - if (((OFFlowStatisticsReply)ofStat).getPriority() == flow.getPriority()){ - ofList = new ArrayList(1); - ofList.add(ofStat); - break; - } - } - } - - // Convert and filter the statistics per container - List flowOnNodeList = new FlowStatisticsConverter(ofList).getFlowOnNodeList(node); - List filteredList = filterFlowListPerContainer(container, node, flowOnNodeList); - - return (filteredList.isEmpty()) ? null : filteredList.get(0); - } - - @Override - public List readAllFlow(String container, Node node, - boolean cached) { - - long sid = (Long) node.getID(); - List ofList = (cached == true) ? statsMgr - .getOFFlowStatistics(sid) : statsMgr.queryStatistics(sid, - OFStatisticsType.FLOW, null); - - // Convert and filter the statistics per container - List flowOnNodeList = new FlowStatisticsConverter(ofList).getFlowOnNodeList(node); - - return filterFlowListPerContainer(container, node, flowOnNodeList); - } - - @Override - public NodeDescription readDescription(Node node, boolean cached) { - - if (controller == null) { - logger.error("Internal plugin error"); - return null; - } - - long sid = (Long) node.getID(); - List ofList = (cached == true) ? statsMgr - .getOFDescStatistics(sid) : statsMgr.queryStatistics(sid, - OFStatisticsType.DESC, null); - - return new DescStatisticsConverter(ofList).getHwDescription(); - } - - /** - * Filters a list of FlowOnNode elements based on the container - * - * @param container - * @param nodeId - * @param list - * @return - */ - private List filterFlowListPerContainer(String container, - Node nodeId, List list) { - if (list == null) { - return Collections.emptyList(); - } - - // Create new filtered list of flows - List newList = new ArrayList(); - - for (FlowOnNode target : list) { - // Check whether the described flow (match + actions) belongs to this container - if (flowBelongToContainer(container, nodeId, target.getFlow())) { - newList.add(target); - } - } - - return newList; - } - - /** - * Filters a list of OFStatistics elements based on the container - * - * @param container - * @param nodeId - * @param list - * @return - */ - private List filterPortListPerContainer(String container, long switchId, List list) { - if (list == null) { - return Collections.emptyList(); - } - - // Create new filtered list of flows - List newList = new ArrayList(); - - for (OFStatistics stat : list) { - OFPortStatisticsReply target = (OFPortStatisticsReply) stat; - NodeConnector nc = NodeConnectorCreator.createOFNodeConnector( - target.getPortNumber(), NodeCreator.createOFNode(switchId)); - if (containerOwnsNodeConnector(container, nc)) { - newList.add(target); - } - } - - return newList; - } - - - private List filterTableListPerContainer( - String container, long switchId, List list) { - if (list == null) { - return Collections.emptyList(); - } - - // Create new filtered list of node tables - List newList = new ArrayList(); - - for (OFStatistics stat : list) { - OFTableStatistics target = (OFTableStatistics) stat; - NodeTable nt = NodeTableCreator.createOFNodeTable(target.getTableId(), NodeCreator.createOFNode(switchId)); - if (containerOwnsNodeTable(container, nt)) { - newList.add(target); - } - } - - return newList; - } - - /** - * Returns whether the specified flow (flow match + actions) - * belongs to the container - * - * @param container - * @param node - * @param flow - * @return true if it belongs - */ - public boolean flowBelongToContainer(String container, Node node, Flow flow) { - // All flows belong to the default container - if (container.equals(GlobalConstants.DEFAULT.toString())) { - return true; - } - return (flowPortsBelongToContainer(container, node, flow) && - flowVlanBelongsToContainer(container, node, flow) && - isFlowAllowedByContainer(container, flow)); - } - - /** - * Returns whether the passed NodeConnector belongs to the container - * - * @param container container name - * @param p node connector to test - * @return true if belongs false otherwise - */ - public boolean containerOwnsNodeConnector(String container, NodeConnector p) { - // All node connectors belong to the default container - if (container.equals(GlobalConstants.DEFAULT.toString())) { - return true; - } - Set portSet = containerToNc.get(container); - return (portSet == null) ? false : portSet.contains(p); - } - - /** - * Returns whether the passed NodeConnector belongs to the container - * - * @param container container name - * @param table node table to test - * @return true if belongs false otherwise - */ - public boolean containerOwnsNodeTable(String container, NodeTable table) { - // All node table belong to the default container - if (container.equals(GlobalConstants.DEFAULT.toString())) { - return true; - } - Set tableSet = containerToNt.get(container); - return (tableSet == null) ? false : tableSet.contains(table); - } - - /** - * Returns whether the container flows allow the passed flow - * - * @param container - * @param match - * @return - */ - private boolean isFlowAllowedByContainer(String container, Flow flow) { - Set cFlowSet = this.containerFlows.get(container); - if (cFlowSet == null || cFlowSet.isEmpty()) { - return true; - } - for (ContainerFlow cFlow : cFlowSet) { - if (cFlow.allowsFlow(flow)) { - return true; - } - } - return false; - } - - /** - * Check whether the vlan field in the flow match is the same - * of the static vlan configured for the container - * - * @param container - * @param node - * @param flow - * @return - */ - private boolean flowVlanBelongsToContainer(String container, Node node, Flow flow) { - return true; // Always true for now - } - - /** - * Check whether the ports in the flow match and flow actions for - * the specified node belong to the container - * - * @param container - * @param node - * @param flow - * @return - */ - private boolean flowPortsBelongToContainer(String container, Node node, - Flow flow) { - Match m = flow.getMatch(); - if (m.isPresent(MatchType.IN_PORT)) { - NodeConnector inPort = (NodeConnector) m.getField(MatchType.IN_PORT).getValue(); - // If the incoming port is specified, check if it belongs to - if (!containerOwnsNodeConnector(container, inPort)) { - return false; - } - } - - // If an outgoing port is specified, it must belong to this container - for (Action action : flow.getActions()) { - if (action.getType() == ActionType.OUTPUT) { - NodeConnector outPort = ((Output) action).getPort(); - if (!containerOwnsNodeConnector(container, outPort)) { - return false; - } - } - } - return true; - } - - @Override - public void containerFlowUpdated(String containerName, ContainerFlow previousFlow, - ContainerFlow currentFlow, UpdateType t) { - Set cFlowSet = containerFlows.get(containerName); - switch (t) { - case ADDED: - if (cFlowSet == null) { - cFlowSet = new HashSet(); - containerFlows.put(containerName, cFlowSet); - } - cFlowSet.add(currentFlow); - case CHANGED: - break; - case REMOVED: - if (cFlowSet != null) { - cFlowSet.remove(currentFlow); - } - break; - default: - break; - } - } - - @Override - public void nodeConnectorUpdated(String containerName, NodeConnector p, UpdateType type) { - - switch (type) { - case ADDED: - if (!containerToNc.containsKey(containerName)) { - containerToNc.put(containerName, - Collections.newSetFromMap(new ConcurrentHashMap())); - } - containerToNc.get(containerName).add(p); - if (!containerToNode.containsKey(containerName)) { - containerToNode.put(containerName, new HashSet()); - } - containerToNode.get(containerName).add(p.getNode()); - break; - case REMOVED: - Set ncSet = containerToNc.get(containerName); - if (ncSet != null) { - //remove this nc from container map - ncSet.remove(p); - - //check if there are still ports of this node in this container - //and if not, remove its mapping - boolean nodeInContainer = false; - Node node = p.getNode(); - for (NodeConnector nodeConnector : ncSet) { - if (nodeConnector.getNode().equals(node)){ - nodeInContainer = true; - break; - } - } - if (! nodeInContainer) { - Set nodeSet = containerToNode.get(containerName); - if (nodeSet != null) { - nodeSet.remove(node); - } - } - } - break; - case CHANGED: - default: - } - } - - @Override - public void tagUpdated(String containerName, Node n, short oldTag, short newTag, UpdateType t) { - // Not interested in this event - } - - @Override - public void containerModeUpdated(UpdateType t) { - // Not interested in this event - } - - @Override - public NodeConnectorStatistics readNodeConnector(String containerName, NodeConnector connector, boolean cached) { - if (!containerOwnsNodeConnector(containerName, connector)) { - return null; - } - Node node = connector.getNode(); - long sid = (Long) node.getID(); - short portId = (Short) connector.getID(); - List ofList = (cached == true) ? statsMgr - .getOFPortStatistics(sid, portId) : statsMgr.queryStatistics( - sid, OFStatisticsType.PORT, portId); - - List ncStatistics = new PortStatisticsConverter(sid, ofList) - .getNodeConnectorStatsList(); - return (ncStatistics.isEmpty()) ? new NodeConnectorStatistics() : ncStatistics.get(0); - } - - @Override - public List readAllNodeConnector(String containerName, Node node, boolean cached) { - - long sid = (Long) node.getID(); - List ofList = (cached == true) ? statsMgr - .getOFPortStatistics(sid) : statsMgr.queryStatistics(sid, - OFStatisticsType.PORT, null); - - List filteredList = filterPortListPerContainer(containerName, sid, ofList); - - return new PortStatisticsConverter(sid, filteredList).getNodeConnectorStatsList(); - } - - @Override - public long getTransmitRate(String containerName, NodeConnector connector) { - if (!containerOwnsNodeConnector(containerName, connector)) { - return 0; - } - - long switchId = (Long) connector.getNode().getID(); - short port = (Short) connector.getID(); - - return statsMgr.getTransmitRate(switchId, port); - } - - @Override - public NodeTableStatistics readNodeTable(String containerName, - NodeTable table, boolean cached) { - if (!containerOwnsNodeTable(containerName, table)) { - return null; - } - Node node = table.getNode(); - long sid = (Long) node.getID(); - Byte tableId = (Byte) table.getID(); - List ofList = (cached == true) ? statsMgr.getOFTableStatistics(sid, tableId) : - statsMgr.queryStatistics(sid, OFStatisticsType.TABLE, tableId); - - List ntStatistics = new TableStatisticsConverter(sid, ofList).getNodeTableStatsList(); - - return (ntStatistics.isEmpty()) ? new NodeTableStatistics() : ntStatistics.get(0); - } - - @Override - public List readAllNodeTable(String containerName, Node node, boolean cached) { - long sid = (Long) node.getID(); - List ofList = (cached == true) ? - statsMgr.getOFTableStatistics(sid) : statsMgr.queryStatistics(sid, OFStatisticsType.TABLE, null); - - List filteredList = filterTableListPerContainer(containerName, sid, ofList); - - return new TableStatisticsConverter(sid, filteredList).getNodeTableStatsList(); - } - - @Override - public void descriptionStatisticsRefreshed(Long switchId, List description) { - String container; - IReadFilterInternalListener listener; - Node node = NodeCreator.createOFNode(switchId); - NodeDescription nodeDescription = new DescStatisticsConverter(description).getHwDescription(); - for (Map.Entry l : readFilterInternalListeners.entrySet()) { - container = l.getKey(); - listener = l.getValue(); - if (container == GlobalConstants.DEFAULT.toString() - || (containerToNode.containsKey(container) && containerToNode.get(container).contains(node))) { - listener.nodeDescriptionStatisticsUpdated(node, nodeDescription); - } - } - } - - @Override - public void flowStatisticsRefreshed(Long switchId, List flows) { - String container; - IReadFilterInternalListener listener; - Node node = NodeCreator.createOFNode(switchId); - for (Map.Entry l : readFilterInternalListeners.entrySet()) { - container = l.getKey(); - listener = l.getValue(); - - // Convert and filter the statistics per container - List flowOnNodeList = new FlowStatisticsConverter(flows).getFlowOnNodeList(node); - flowOnNodeList = filterFlowListPerContainer(container, node, flowOnNodeList); - - // notify listeners - listener.nodeFlowStatisticsUpdated(node, flowOnNodeList); - } - } - - @Override - public void portStatisticsRefreshed(Long switchId, List ports) { - String container; - IReadFilterInternalListener listener; - Node node = NodeCreator.createOFNode(switchId); - for (Map.Entry l : readFilterInternalListeners.entrySet()) { - container = l.getKey(); - listener = l.getValue(); - - // Convert and filter the statistics per container - List filteredPorts = filterPortListPerContainer(container, switchId, ports); - List ncStatsList = new PortStatisticsConverter(switchId, filteredPorts) - .getNodeConnectorStatsList(); - - // notify listeners - listener.nodeConnectorStatisticsUpdated(node, ncStatsList); - } - } - - @Override - public void tableStatisticsRefreshed(Long switchId, List tables) { - String container; - Node node = NodeCreator.createOFNode(switchId); - for (Map.Entry l : readFilterInternalListeners.entrySet()) { - container = l.getKey(); - - // Convert and filter the statistics per container - List filteredList = filterTableListPerContainer(container, switchId, tables); - List tableStatsList = new TableStatisticsConverter(switchId, filteredList) - .getNodeTableStatsList(); - - // notify listeners - l.getValue().nodeTableStatisticsUpdated(node, tableStatsList); - } - } - - @Override - public void containerCreate(String containerName) { - // do nothing - } - - @Override - public void containerDestroy(String containerName) { - containerToNc.remove(containerName); - containerToNode.remove(containerName); - containerToNt.remove(containerName); - containerFlows.remove(containerName); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableConverter.java deleted file mode 100644 index 0b532848f7..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableConverter.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.utils.NodeTableCreator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class TableConverter { - private static final Logger log = LoggerFactory - .getLogger(TableConverter.class); - - public static NodeTable toNodeTable(byte tableId, Node node) { - log.trace("Openflow table ID: {}", Byte.toString(tableId)); - return NodeTableCreator.createNodeTable(tableId, node); - } - - public static byte toOFTable(NodeTable salTable) { - log.trace("SAL Table: {}", salTable); - return (Byte) salTable.getID(); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableStatisticsConverter.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableStatisticsConverter.java deleted file mode 100644 index 35a763869b..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TableStatisticsConverter.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.openflow.protocol.statistics.OFStatistics; -import org.openflow.protocol.statistics.OFTableStatistics; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Converts an openflow list of table statistics in a SAL list of - * NodeTableStatistics objects - */ -public class TableStatisticsConverter { - private static final Logger log = LoggerFactory - .getLogger(TableStatisticsConverter.class); - - private final long switchId; - private List ofStatsList; - private List ntStatsList; - - public TableStatisticsConverter(long switchId, List statsList) { - this.switchId = switchId; - if (statsList == null || statsList.isEmpty()) { - this.ofStatsList = Collections.emptyList(); - } else { - this.ofStatsList = new ArrayList(statsList); - } - this.ntStatsList = null; - } - - public List getNodeTableStatsList() { - if (this.ofStatsList != null && this.ntStatsList == null) { - this.ntStatsList = new ArrayList(); - OFTableStatistics ofTableStat; - Node node = NodeCreator.createOFNode(switchId); - for (OFStatistics ofStat : this.ofStatsList) { - ofTableStat = (OFTableStatistics) ofStat; - NodeTableStatistics ntStat = new NodeTableStatistics(); - ntStat.setNodeTable(TableConverter.toNodeTable( - ofTableStat.getTableId(), node)); - ntStat.setActiveCount(ofTableStat.getActiveCount()); - ntStat.setLookupCount(ofTableStat.getLookupCount()); - ntStat.setMatchedCount(ofTableStat.getMatchedCount()); - ntStat.setMaximumEntries(ofTableStat.getMaximumEntries()); - this.ntStatsList.add(ntStat); - } - } - log.trace("OFStatistics: {} NodeTableStatistics: {}", ofStatsList, - ntStatsList); - return this.ntStatsList; - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServiceShim.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServiceShim.java deleted file mode 100644 index 08ddbde30a..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServiceShim.java +++ /dev/null @@ -1,959 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.LinkedBlockingQueue; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.protocol_plugin.openflow.IDiscoveryListener; -import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener; -import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsManager; -import org.opendaylight.controller.protocol_plugin.openflow.IRefreshInternalProvider; -import org.opendaylight.controller.protocol_plugin.openflow.ITopologyServiceShimListener; -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.Config; -import org.opendaylight.controller.sal.core.ContainerFlow; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.IContainerAware; -import org.opendaylight.controller.sal.core.IContainerListener; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class describes a shim layer that relays the topology events from - * OpenFlow core to various listeners. The notifications are filtered based on - * container configurations. - */ -public class TopologyServiceShim implements IDiscoveryListener, - IContainerListener, CommandProvider, IRefreshInternalProvider, - IInventoryShimExternalListener, IContainerAware { - protected static final Logger logger = LoggerFactory - .getLogger(TopologyServiceShim.class); - private ConcurrentMap topologyServiceShimListeners = new ConcurrentHashMap(); - private ConcurrentMap> containerMap = new ConcurrentHashMap>(); - private ConcurrentMap>>> edgeMap = new ConcurrentHashMap>>>(); - - private BlockingQueue notifyQ; - private Thread notifyThread; - private BlockingQueue bulkNotifyQ; - private Thread ofPluginTopoBulkUpdate; - private volatile Boolean shuttingDown = false; - private IOFStatisticsManager statsMgr; - private Timer pollTimer; - private TimerTask txRatePoller; - private Thread bwUtilNotifyThread; - private BlockingQueue bwUtilNotifyQ; - private List connectorsOverUtilized; - private float bwThresholdFactor = (float) 0.8; // Threshold = 80% of link - // bandwidth - - class NotifyEntry { - String container; - List teuList; - - public NotifyEntry(String container, TopoEdgeUpdate teu) { - this.container = container; - this.teuList = new ArrayList(); - if (teu != null) { - this.teuList.add(teu); - } - } - - public NotifyEntry(String container, List teuList) { - this.container = container; - this.teuList = new ArrayList(); - if (teuList != null) { - this.teuList.addAll(teuList); - } - } - } - - class TopologyNotify implements Runnable { - private final BlockingQueue notifyQ; - private NotifyEntry entry; - private Map> teuMap = new HashMap>(); - private List teuList; - private boolean notifyListeners; - - TopologyNotify(BlockingQueue notifyQ) { - this.notifyQ = notifyQ; - } - - @Override - public void run() { - while (true) { - try { - teuMap.clear(); - notifyListeners = false; - while (!notifyQ.isEmpty()) { - entry = notifyQ.take(); - teuList = teuMap.get(entry.container); - if (teuList == null) { - teuList = new ArrayList(); - } - // group all the updates together - teuList.addAll(entry.teuList); - teuMap.put(entry.container, teuList); - notifyListeners = true; - } - - if (notifyListeners) { - for (String container : teuMap.keySet()) { - // notify the listener - ITopologyServiceShimListener l = topologyServiceShimListeners.get(container); - // container topology service may not have come up yet - if (l != null) { - l.edgeUpdate(teuMap.get(container)); - } - } - } - - Thread.sleep(100); - } catch (InterruptedException e1) { - logger.trace("TopologyNotify interrupted {}", - e1.getMessage()); - if (shuttingDown) { - return; - } - } catch (Exception e2) { - logger.error("", e2); - } - } - } - } - - class UtilizationUpdate { - NodeConnector connector; - UpdateType type; - - UtilizationUpdate(NodeConnector connector, UpdateType type) { - this.connector = connector; - this.type = type; - } - } - - class BwUtilizationNotify implements Runnable { - private final BlockingQueue notifyQ; - - BwUtilizationNotify(BlockingQueue notifyQ) { - this.notifyQ = notifyQ; - } - - @Override - public void run() { - while (true) { - try { - UtilizationUpdate update = notifyQ.take(); - NodeConnector connector = update.connector; - Set containerList = edgeMap.keySet(); - for (String container : containerList) { - Map>> edgePropsMap = edgeMap - .get(container); - // the edgePropsMap for a particular container may not have - // the connector. - // so check for null - Pair> edgeProp = edgePropsMap.get(connector); - if(edgeProp != null) { - Edge edge = edgeProp.getLeft(); - if (edge.getTailNodeConnector().equals(connector)) { - ITopologyServiceShimListener topologServiceShimListener = topologyServiceShimListeners - .get(container); - if (update.type == UpdateType.ADDED) { - topologServiceShimListener - .edgeOverUtilized(edge); - } else { - topologServiceShimListener - .edgeUtilBackToNormal(edge); - } - } - } - } - } catch (InterruptedException e1) { - logger.trace( - "Edge Bandwidth Utilization Notify Thread interrupted {}", - e1.getMessage()); - if (shuttingDown) { - return; - } - } catch (Exception e2) { - logger.error("", e2); - } - } - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - logger.trace("Init called"); - connectorsOverUtilized = new ArrayList(); - notifyQ = new LinkedBlockingQueue(); - notifyThread = new Thread(new TopologyNotify(notifyQ)); - bwUtilNotifyQ = new LinkedBlockingQueue(); - bwUtilNotifyThread = new Thread(new BwUtilizationNotify(bwUtilNotifyQ)); - bulkNotifyQ = new LinkedBlockingQueue(); - ofPluginTopoBulkUpdate = new Thread(new Runnable() { - @Override - public void run() { - while (true) { - try { - String containerName = bulkNotifyQ.take(); - logger.debug("Bulk Notify container:{}", containerName); - TopologyBulkUpdate(containerName); - } catch (InterruptedException e) { - logger.trace("Topology Bulk update thread interrupted"); - if (shuttingDown) { - return; } - } - } - } - }, "Topology Bulk Update"); - - // Initialize node connector tx bit rate poller timer - pollTimer = new Timer(); - txRatePoller = new TimerTask() { - @Override - public void run() { - pollTxBitRates(); - } - }; - - registerWithOSGIConsole(); - } - - /** - * Continuously polls the transmit bit rate for all the node connectors from - * statistics manager and trigger the warning notification upward when the - * transmit rate is above a threshold which is a percentage of the edge - * bandwidth - */ - protected void pollTxBitRates() { - Map>> globalContainerEdges = edgeMap - .get(GlobalConstants.DEFAULT.toString()); - if (shuttingDown) { - logger.trace("Getting out the pollTxBitRates because bundle going down"); - return; - } - if (globalContainerEdges == null) { - return; - } - - for (NodeConnector connector : globalContainerEdges.keySet()) { - // Skip if node connector belongs to production switch - if (connector.getType().equals( - NodeConnector.NodeConnectorIDType.PRODUCTION)) { - continue; - } - - // Get edge for which this node connector is head - Pair> props = this.edgeMap.get( - GlobalConstants.DEFAULT.toString()).get(connector); - // On switch mgr restart the props get reset - if (props == null) { - continue; - } - Set propSet = props.getRight(); - if (propSet == null) { - continue; - } - - float bw = 0; - for (Property prop : propSet) { - if (prop instanceof Bandwidth) { - bw = ((Bandwidth) prop).getValue(); - break; - } - } - - // Skip if agent did not provide a bandwidth info for the edge - if (bw == 0) { - continue; - } - - // Compare bandwidth usage - Long switchId = (Long) connector.getNode().getID(); - Short port = (Short) connector.getID(); - if (statsMgr != null) { - float rate = statsMgr.getTransmitRate(switchId, port); - if (rate > bwThresholdFactor * bw) { - if (!connectorsOverUtilized.contains(connector)) { - connectorsOverUtilized.add(connector); - this.bwUtilNotifyQ.add(new UtilizationUpdate(connector, UpdateType.ADDED)); - } - } else { - if (connectorsOverUtilized.contains(connector)) { - connectorsOverUtilized.remove(connector); - this.bwUtilNotifyQ.add(new UtilizationUpdate(connector, UpdateType.REMOVED)); - } - } - } - } - - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - logger.trace("DESTROY called!"); - notifyQ = null; - notifyThread = null; - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - logger.trace("START called!"); - notifyThread.start(); - bwUtilNotifyThread.start(); - ofPluginTopoBulkUpdate.start(); - pollTimer.scheduleAtFixedRate(txRatePoller, 10000, 5000); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - logger.trace("STOP called!"); - shuttingDown = true; - notifyThread.interrupt(); - bwUtilNotifyThread.interrupt(); - ofPluginTopoBulkUpdate.interrupt(); - pollTimer.cancel(); - } - - void setTopologyServiceShimListener(Map props, - ITopologyServiceShimListener s) { - if (props == null) { - logger.error("Didn't receive the service properties"); - return; - } - String containerName = (String) props.get("containerName"); - if (containerName == null) { - logger.error("containerName not supplied"); - return; - } - if ((this.topologyServiceShimListeners != null) - && !this.topologyServiceShimListeners - .containsKey(containerName)) { - this.topologyServiceShimListeners.put(containerName, s); - logger.trace("Added topologyServiceShimListener for container: {}", - containerName); - } - } - - void unsetTopologyServiceShimListener(Map props, - ITopologyServiceShimListener s) { - if (props == null) { - logger.error("Didn't receive the service properties"); - return; - } - String containerName = (String) props.get("containerName"); - if (containerName == null) { - logger.error("containerName not supplied"); - return; - } - if ((this.topologyServiceShimListeners != null) - && this.topologyServiceShimListeners.containsKey(containerName) - && this.topologyServiceShimListeners.get(containerName).equals( - s)) { - this.topologyServiceShimListeners.remove(containerName); - logger.trace( - "Removed topologyServiceShimListener for container: {}", - containerName); - } - } - - void setStatisticsManager(IOFStatisticsManager s) { - this.statsMgr = s; - } - - void unsetStatisticsManager(IOFStatisticsManager s) { - if (this.statsMgr == s) { - this.statsMgr = null; - } - } - - private void updateContainerMap(List containers, NodeConnector p) { - if (containers.isEmpty()) { - // Do cleanup to reduce memory footprint if no - // elements to be tracked - this.containerMap.remove(p); - } else { - this.containerMap.put(p, containers); - } - } - - /** - * From a given edge map, retrieve the edge sourced by the port and update - * the local cache in the container - * - * @param container - * the container name - * @param nodeConnector - * the node connector - * @param edges - * the given edge map - * @return the found edge - */ - private Edge addEdge(String container, NodeConnector nodeConnector, - Map>> edges) { - logger.debug("Search edge sourced by port {} in container {}", nodeConnector, container); - - // Retrieve the associated edge - Pair> edgeProps = edges.get(nodeConnector); - if (edgeProps == null) { - logger.debug("edgePros is null for port {} in container {}", nodeConnector, container); - return null; - } - - Edge edge = edgeProps.getLeft(); - if (edge == null) { - logger.debug("edge is null for port {} in container {}", nodeConnector, container); - return null; - } - - // Make sure the peer port is in the same container - NodeConnector peerConnector = edge.getHeadNodeConnector(); - List containers = this.containerMap.get(peerConnector); - if ((containers == null) || !containers.contains(container)) { - logger.debug("peer port {} of edge {} is not part of the container {}", new Object[] { peerConnector, edge, - container }); - return null; - } - - // Update the local cache - updateLocalEdgeMap(container, edge, UpdateType.ADDED, edgeProps.getRight()); - logger.debug("Added edge {} to local cache in container {}", edge, container); - - return edge; - } - - private void addNodeConnector(String container, - NodeConnector nodeConnector) { - // Use the global edge map for the newly added port in a container - Map>> globalEdgeMap = edgeMap.get(GlobalConstants.DEFAULT - .toString()); - if (globalEdgeMap == null) { - return; - } - - // Get the edge and update local cache in the container - Edge edge1, edge2; - edge1 = addEdge(container, nodeConnector, globalEdgeMap); - if (edge1 == null) { - return; - } - - // Get the edge in reverse direction and update local cache in the container - NodeConnector peerConnector = edge1.getHeadNodeConnector(); - edge2 = addEdge(container, peerConnector, globalEdgeMap); - - // Send notification upwards in one shot - List teuList = new ArrayList(); - teuList.add(new TopoEdgeUpdate(edge1, null, UpdateType.ADDED)); - logger.debug("Notify edge1: {} in container {}", edge1, container); - if (edge2 != null) { - teuList.add(new TopoEdgeUpdate(edge2, null, UpdateType.ADDED)); - logger.debug("Notify edge2: {} in container {}", edge2, container); - } - notifyEdge(container, teuList); - } - - private void removeNodeConnector(String container, - NodeConnector nodeConnector) { - List teuList = new ArrayList(); - Map>> edgePropsMap = edgeMap - .get(container); - if (edgePropsMap == null) { - return; - } - - // Remove edge in one direction - Pair> edgeProps = edgePropsMap.get(nodeConnector); - if (edgeProps == null) { - return; - } - teuList.add(new TopoEdgeUpdate(edgeProps.getLeft(), null, - UpdateType.REMOVED)); - - // Remove edge in another direction - edgeProps = edgePropsMap - .get(edgeProps.getLeft().getHeadNodeConnector()); - if (edgeProps == null) { - return; - } - teuList.add(new TopoEdgeUpdate(edgeProps.getLeft(), null, - UpdateType.REMOVED)); - - // Update in one shot - notifyEdge(container, teuList); - } - - /** - * Update local cache and return true if it needs to notify upper layer - * Topology listeners. - * - * @param container - * The network container - * @param edge - * The edge - * @param type - * The update type - * @param props - * The edge properties - * @return true if it needs to notify upper layer Topology listeners - */ - private boolean updateLocalEdgeMap(String container, Edge edge, - UpdateType type, Set props) { - ConcurrentMap>> edgePropsMap = edgeMap - .get(container); - NodeConnector src = edge.getTailNodeConnector(); - Pair> edgeProps = new ImmutablePair>( - edge, props); - boolean rv = false; - - switch (type) { - case ADDED: - case CHANGED: - if (edgePropsMap == null) { - edgePropsMap = new ConcurrentHashMap>>(); - rv = true; - } else { - if (edgePropsMap.containsKey(src) - && edgePropsMap.get(src).equals(edgeProps)) { - // Entry already exists. No update. - rv = false; - } else { - rv = true; - } - } - if (rv) { - edgePropsMap.put(src, edgeProps); - edgeMap.put(container, edgePropsMap); - } - break; - case REMOVED: - if ((edgePropsMap != null) && edgePropsMap.containsKey(src)) { - edgePropsMap.remove(src); - if (edgePropsMap.isEmpty()) { - edgeMap.remove(container); - } else { - edgeMap.put(container, edgePropsMap); - } - rv = true; - } - break; - default: - logger.debug( - "notifyLocalEdgeMap: invalid {} for Edge {} in container {}", - new Object[] { type.getName(), edge, container }); - } - - if (rv) { - logger.debug( - "notifyLocalEdgeMap: {} for Edge {} in container {}", - new Object[] { type.getName(), edge, container }); - } - - return rv; - } - - private void notifyEdge(String container, Edge edge, UpdateType type, - Set props) { - boolean notifyListeners; - - // Update local cache - notifyListeners = updateLocalEdgeMap(container, edge, type, props); - - // Prepare to update TopologyService - if (notifyListeners) { - notifyQ.add(new NotifyEntry(container, new TopoEdgeUpdate(edge, props, - type))); - logger.debug("notifyEdge: {} Edge {} in container {}", - new Object[] { type.getName(), edge, container }); - } - } - - private void notifyEdge(String container, List etuList) { - if (etuList == null) { - return; - } - - Edge edge; - UpdateType type; - List etuNotifyList = new ArrayList(); - boolean notifyListeners = false, rv; - - for (TopoEdgeUpdate etu : etuList) { - edge = etu.getEdge(); - type = etu.getUpdateType(); - - // Update local cache - rv = updateLocalEdgeMap(container, edge, type, etu.getProperty()); - if (rv) { - if (!notifyListeners) { - notifyListeners = true; - } - etuNotifyList.add(etu); - logger.debug( - "notifyEdge(TopoEdgeUpdate): {} Edge {} in container {}", - new Object[] { type.getName(), edge, container }); - } - } - - // Prepare to update TopologyService - if (notifyListeners) { - notifyQ.add(new NotifyEntry(container, etuNotifyList)); - logger.debug("notifyEdge(TopoEdgeUpdate): add notifyQ"); - } - } - - @Override - public void notifyEdge(Edge edge, UpdateType type, Set props) { - if ((edge == null) || (type == null)) { - return; - } - - // Notify default container - notifyEdge(GlobalConstants.DEFAULT.toString(), edge, type, props); - - // Notify the corresponding containers - List containers = getEdgeContainers(edge); - if (containers != null) { - for (String container : containers) { - notifyEdge(container, edge, type, props); - } - } - } - - /* - * Return a list of containers the edge associated with - */ - private List getEdgeContainers(Edge edge) { - NodeConnector src = edge.getTailNodeConnector(), dst = edge - .getHeadNodeConnector(); - - if (!src.getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) { - /* Find the common containers for both ends */ - List srcContainers = this.containerMap.get(src), dstContainers = this.containerMap - .get(dst), cmnContainers = null; - if ((srcContainers != null) && (dstContainers != null)) { - cmnContainers = new ArrayList(srcContainers); - cmnContainers.retainAll(dstContainers); - } - return cmnContainers; - } else { - /* - * If the neighbor is part of a monitored production network, get - * the containers that the edge port belongs to - */ - return this.containerMap.get(dst); - } - } - - @Override - public void tagUpdated(String containerName, Node n, short oldTag, - short newTag, UpdateType t) { - } - - @Override - public void containerFlowUpdated(String containerName, - ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t) { - } - - @Override - public void nodeConnectorUpdated(String containerName, NodeConnector p, - UpdateType t) { - if (this.containerMap == null) { - logger.error("containerMap is NULL"); - return; - } - List containers = this.containerMap.get(p); - if (containers == null) { - containers = new CopyOnWriteArrayList(); - } - switch (t) { - case ADDED: - if (!containers.contains(containerName)) { - containers.add(containerName); - updateContainerMap(containers, p); - addNodeConnector(containerName, p); - } - break; - case REMOVED: - if (containers.contains(containerName)) { - containers.remove(containerName); - updateContainerMap(containers, p); - removeNodeConnector(containerName, p); - } - break; - case CHANGED: - break; - } - } - - @Override - public void containerModeUpdated(UpdateType t) { - // do nothing - } - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, - null); - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---Topology Service Shim---\n"); - help.append("\t pem [container] - Print edgeMap entries"); - help.append(" for a given container\n"); - return help.toString(); - } - - public void _pem(CommandInterpreter ci) { - String container = ci.nextArgument(); - if (container == null) { - container = GlobalConstants.DEFAULT.toString(); - } - - ci.println("Container: " + container); - ci.println(" Edge Bandwidth"); - - Map>> edgePropsMap = edgeMap - .get(container); - if (edgePropsMap == null) { - return; - } - int count = 0; - for (Pair> edgeProps : edgePropsMap.values()) { - if (edgeProps == null) { - continue; - } - - long bw = 0; - Set props = edgeProps.getRight(); - if (props != null) { - for (Property prop : props) { - if (prop.getName().equals(Bandwidth.BandwidthPropName)) { - bw = ((Bandwidth) prop).getValue(); - } - } - } - count++; - ci.println(edgeProps.getLeft() + " " + bw); - } - ci.println("Total number of Edges: " + count); - } - - public void _bwfactor(CommandInterpreter ci) { - String factorString = ci.nextArgument(); - if (factorString == null) { - ci.println("Bw threshold: " + this.bwThresholdFactor); - ci.println("Insert a non null bw threshold"); - return; - } - bwThresholdFactor = Float.parseFloat(factorString); - ci.println("New Bw threshold: " + this.bwThresholdFactor); - } - - /** - * This method will trigger topology updates to be sent toward SAL. SAL then - * pushes the updates to ALL the applications that have registered as - * listeners for this service. SAL has no way of knowing which application - * requested for the refresh. - * - * As an example of this case, is stopping and starting the Topology - * Manager. When the topology Manager is stopped, and restarted, it will no - * longer have the latest topology. Hence, a request is sent here. - * - * @param containerName - * @return void - */ - @Override - public void requestRefresh(String containerName) { - // wake up a bulk update thread and exit - // the thread will execute the bulkUpdate() - bulkNotifyQ.add(containerName); - } - - /** - * Retrieve the edges for a given container - * - * @param containerName - * the container name - * @return the edges and their properties - */ - private Collection>> getEdgeProps(String containerName) { - Map>> edgePropMap = null; - edgePropMap = edgeMap.get(containerName); - if (edgePropMap == null) { - return null; - } - return edgePropMap.values(); - } - - /** - * Reading the current topology database, the method will replay all the - * edge updates for the ITopologyServiceShimListener instance in the given - * container, which will in turn publish them toward SAL. - * - * @param containerName - * the container name - */ - private void TopologyBulkUpdate(String containerName) { - Collection>> edgeProps = null; - - logger.debug("Try bulk update for container:{}", containerName); - edgeProps = getEdgeProps(containerName); - if (edgeProps == null) { - logger.debug("No edges known for container:{}", containerName); - return; - } - ITopologyServiceShimListener topologServiceShimListener = topologyServiceShimListeners - .get(containerName); - if (topologServiceShimListener == null) { - logger.debug("No topology service shim listener for container:{}", - containerName); - return; - } - int i = 0; - List teuList = new ArrayList(); - for (Pair> edgeProp : edgeProps) { - if (edgeProp != null) { - i++; - teuList.add(new TopoEdgeUpdate(edgeProp.getLeft(), edgeProp - .getRight(), UpdateType.ADDED)); - logger.trace("Add edge {}", edgeProp.getLeft()); - } - } - if (i > 0) { - topologServiceShimListener.edgeUpdate(teuList); - } - logger.debug("Sent {} updates", i); - } - - @Override - public void updateNode(Node node, UpdateType type, Set props) { - } - - @Override - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props) { - List containers = new ArrayList(); - List conList = this.containerMap.get(nodeConnector); - - containers.add(GlobalConstants.DEFAULT.toString()); - if (conList != null) { - containers.addAll(conList); - } - - switch (type) { - case ADDED: - break; - case CHANGED: - if (props == null) { - break; - } - - boolean rmEdge = false; - for (Property prop : props) { - if (((prop instanceof Config) && (((Config) prop).getValue() != Config.ADMIN_UP)) - || ((prop instanceof State) && (((State) prop) - .getValue() != State.EDGE_UP))) { - /* - * If port admin down or link down, remove the edges - * associated with the port - */ - rmEdge = true; - break; - } - } - - if (rmEdge) { - for (String cName : containers) { - removeNodeConnector(cName, nodeConnector); - } - } - break; - case REMOVED: - for (String cName : containers) { - removeNodeConnector(cName, nodeConnector); - } - break; - default: - break; - } - } - - @Override - public void containerCreate(String containerName) { - // do nothing - } - - @Override - public void containerDestroy(String containerName) { - Set removeNodeConnectorSet = new HashSet(); - for (Map.Entry> entry : containerMap.entrySet()) { - List ncContainers = entry.getValue(); - if (ncContainers.contains(containerName)) { - NodeConnector nodeConnector = entry.getKey(); - removeNodeConnectorSet.add(nodeConnector); - } - } - for (NodeConnector nodeConnector : removeNodeConnectorSet) { - List ncContainers = containerMap.get(nodeConnector); - ncContainers.remove(containerName); - if (ncContainers.isEmpty()) { - containerMap.remove(nodeConnector); - } - } - edgeMap.remove(containerName); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServices.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServices.java deleted file mode 100644 index 68572fb650..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/TopologyServices.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.util.Dictionary; -import java.util.List; -import org.apache.felix.dm.Component; -import org.opendaylight.controller.protocol_plugin.openflow.IRefreshInternalProvider; -import org.opendaylight.controller.protocol_plugin.openflow.ITopologyServiceShimListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.topology.IPluginInTopologyService; -import org.opendaylight.controller.sal.topology.IPluginOutTopologyService; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; - -public class TopologyServices implements ITopologyServiceShimListener, - IPluginInTopologyService { - protected static final Logger logger = LoggerFactory - .getLogger(TopologyServices.class); - private IPluginOutTopologyService salTopoService = null; - private IRefreshInternalProvider topoRefreshService = null; - private String containerName; - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - @SuppressWarnings("unchecked") - void init(Component c) { - logger.trace("INIT called!"); - Dictionary props = c.getServiceProperties(); - containerName = (props != null) ? (String) props.get("containerName") - : null; - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - logger.trace("DESTROY called!"); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - logger.trace("START called!"); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - logger.trace("STOP called!"); - } - - /** - * Retrieve SAL service IPluginOutTopologyService - * - * @param s - * Called by Dependency Manager as soon as the SAL service is - * available - */ - public void setPluginOutTopologyService(IPluginOutTopologyService s) { - logger.trace("Setting IPluginOutTopologyService to: {}", s); - this.salTopoService = s; - } - - /** - * called when SAL service IPluginOutTopologyService is no longer available - * - * @param s - * Called by Dependency Manager as soon as the SAL service is - * unavailable - */ - public void unsetPluginOutTopologyService(IPluginOutTopologyService s) { - if (this.salTopoService == s) { - logger.trace("UNSetting IPluginOutTopologyService from: {}", s); - this.salTopoService = null; - } - } - - /** - * Retrieve OF protocol_plugin service IRefreshInternalProvider - * - * @param s - * Called by Dependency Manager as soon as the SAL service is - * available - */ - public void setRefreshInternalProvider(IRefreshInternalProvider s) { - logger.trace("Setting IRefreshInternalProvider to: {}", s); - this.topoRefreshService = s; - } - - /** - * called when OF protocol_plugin service IRefreshInternalProvider is no - * longer available - * - * @param s - * Called by Dependency Manager as soon as the SAL service is - * unavailable - */ - public void unsetRefreshInternalProvider(IRefreshInternalProvider s) { - if (this.topoRefreshService == s) { - logger.trace("UNSetting IRefreshInternalProvider from: {}", s); - this.topoRefreshService = null; - } - } - - @Override - public void edgeUpdate(List topoedgeupdateList) { - if (this.salTopoService != null) { - this.salTopoService.edgeUpdate(topoedgeupdateList); - } - } - - @Override - public void sollicitRefresh() { - logger.debug("Got a request to refresh topology"); - topoRefreshService.requestRefresh(containerName); - } - - @Override - public void edgeOverUtilized(Edge edge) { - if (this.salTopoService != null) { - this.salTopoService.edgeOverUtilized(edge); - } - } - - @Override - public void edgeUtilBackToNormal(Edge edge) { - if (this.salTopoService != null) { - this.salTopoService.edgeUtilBackToNormal(edge); - } - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Utils.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Utils.java deleted file mode 100644 index 8d2ca8704a..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/Utils.java +++ /dev/null @@ -1,80 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.nio.ByteBuffer; - -import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6Error; -import org.openflow.protocol.OFError; -import org.openflow.protocol.OFError.OFBadActionCode; -import org.openflow.protocol.OFError.OFBadRequestCode; -import org.openflow.protocol.OFError.OFErrorType; -import org.openflow.protocol.OFError.OFFlowModFailedCode; -import org.openflow.protocol.OFError.OFHelloFailedCode; -import org.openflow.protocol.OFError.OFPortModFailedCode; -import org.openflow.protocol.OFError.OFQueueOpFailedCode; - -public final class Utils { - - private Utils() { //prevent instantiation - throw new AssertionError(); - } - static String getOFErrorString(OFError error) { - // Handle VENDOR extension errors here - if (error.getErrorType() == V6Error.NICIRA_VENDOR_ERRORTYPE) { - V6Error er = new V6Error(error); - byte[] b = error.getError(); - ByteBuffer bb = ByteBuffer.allocate(b.length); - bb.put(b); - bb.rewind(); - er.readFrom(bb); - return er.toString(); - } - - // Handle OF1.0 errors here - OFErrorType et = OFErrorType.values()[0xffff & error.getErrorType()]; - String errorStr = "Error : " + et.toString(); - switch (et) { - case OFPET_HELLO_FAILED: - OFHelloFailedCode hfc = OFHelloFailedCode.values()[0xffff & error - .getErrorCode()]; - errorStr += " " + hfc.toString(); - break; - case OFPET_BAD_REQUEST: - OFBadRequestCode brc = OFBadRequestCode.values()[0xffff & error - .getErrorCode()]; - errorStr += " " + brc.toString(); - break; - case OFPET_BAD_ACTION: - OFBadActionCode bac = OFBadActionCode.values()[0xffff & error - .getErrorCode()]; - errorStr += " " + bac.toString(); - break; - case OFPET_FLOW_MOD_FAILED: - OFFlowModFailedCode fmfc = OFFlowModFailedCode.values()[0xffff & error - .getErrorCode()]; - errorStr += " " + fmfc.toString(); - break; - case OFPET_PORT_MOD_FAILED: - OFPortModFailedCode pmfc = OFPortModFailedCode.values()[0xffff & error - .getErrorCode()]; - errorStr += " " + pmfc.toString(); - break; - case OFPET_QUEUE_OP_FAILED: - OFQueueOpFailedCode qofc = OFQueueOpFailedCode.values()[0xffff & error - .getErrorCode()]; - errorStr += " " + qofc.toString(); - break; - default: - break; - } - return errorStr; - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Error.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Error.java deleted file mode 100644 index dfe931f448..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Error.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -import org.openflow.protocol.OFError; - -public class V6Error extends OFError { - private static final long serialVersionUID = 1L; - public static int MINIMUM_LENGTH = 20;//OfHdr(8) + NXET_VENDOR(2) + NXEC_VENDOR_ERROR(2) + struct nx_vendor_error(8) - public static final short NICIRA_VENDOR_ERRORTYPE = (short)0xb0c2; - protected int V6VendorId; - protected short V6VendorErrorType; - protected short V6VendorErrorCode; - protected byte[] V6ErrorData; - - public V6Error(OFError e) { - this.length = (short)e.getLengthU(); - this.errorType = e.getErrorType(); - this.errorCode = e.getErrorCode(); - this.xid = e.getXid(); - } - - @Override - public void readFrom(ByteBuffer data) { - this.V6VendorId = data.getInt(); - this.V6VendorErrorType = data.getShort(); - this.V6VendorErrorCode = data.getShort(); - int dataLength = this.getLengthU() - MINIMUM_LENGTH; - if (dataLength > 0) { - this.V6ErrorData = new byte[dataLength]; - data.get(this.V6ErrorData); - } - } - - /** - * @return the V6VendorId - */ - public int getVendorId() { - return V6VendorId; - } - - /** - * @return the V6VendorErrorType - */ - public short getVendorErrorType() { - return V6VendorErrorType; - } - - /** - * @return the VendorErrorType - */ - public short getVendorErrorCode() { - return V6VendorErrorCode; - } - - /** - * @return the Error Bytes - */ - public byte[] getError() { - return V6ErrorData; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + Arrays.hashCode(V6ErrorData); - result = prime * result + V6VendorErrorCode; - result = prime * result + V6VendorErrorType; - result = prime * result + V6VendorId; - return result; - } - - @Override - public String toString() { - return "V6Error [V6VendorId=" + V6VendorId + ", V6VendorErrorType=" - + V6VendorErrorType + ", V6VendorErrorCode=" - + V6VendorErrorCode + ", V6ErrorData=" - + Arrays.toString(V6ErrorData) + ", errorType=" + errorType - + ", errorCode=" + errorCode + ", factory=" + factory - + ", error=" + Arrays.toString(error) + ", errorIsAscii=" - + errorIsAscii + ", version=" + version + ", type=" + type - + ", length=" + length + ", xid=" + xid + "]"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - V6Error other = (V6Error) obj; - if (!Arrays.equals(V6ErrorData, other.V6ErrorData)) - return false; - if (V6VendorErrorCode != other.V6VendorErrorCode) - return false; - if (V6VendorErrorType != other.V6VendorErrorType) - return false; - if (V6VendorId != other.V6VendorId) - return false; - return true; - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6FlowMod.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6FlowMod.java deleted file mode 100644 index 73cdd9898f..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6FlowMod.java +++ /dev/null @@ -1,243 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension; - -import java.nio.ByteBuffer; -import java.util.LinkedList; -import java.util.List; - -import org.openflow.protocol.OFPacketOut; -import org.openflow.protocol.OFPort; -import org.openflow.protocol.OFVendor; -import org.openflow.protocol.action.OFAction; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is used to create IPv6 Vendor Extension messages. Specfically, It - * defines the methods used in creation of Vendor specific IPv6 Flow Mod message. - * - * - */ -public class V6FlowMod extends OFVendor implements Cloneable { - private static final Logger logger = LoggerFactory - .getLogger(V6FlowMod.class); - private static final long serialVersionUID = 1L; - protected V6Match match; - protected long cookie; - protected short command; - protected short idleTimeout; - protected short hardTimeout; - protected short priority; - protected int bufferId; - protected short outPort; - protected short flags; - protected List actions; - short match_len; - short actions_len; - short pad_size; - - private static int IPV6EXT_ADD_FLOW_MSG_TYPE = 13; - private static int IPV6_EXT_MIN_HDR_LEN = 36; - - /** - * Constructor for the V6FlowMod class. Initializes OFVendor (parent class) - * fields by calling the parent class' constructor. - */ - public V6FlowMod() { - super(); - } - - /** - * This method sets the match fields of V6FlowMod object - * @param match V6Match object for this V6FlowMod message - */ - public void setMatch(V6Match match) { - this.match = match; - } - - /** - * Sets the list of actions V6FlowMod message - * @param actions a list of ordered OFAction objects - */ - public void setActions(List actions) { - this.actions = actions; - } - - /** - * Sets the priority field of V6FlowMod message - * @param priority Priority of the message - */ - public void setPriority(short priority) { - this.priority = priority; - } - - /** - * Sets the cookie field of V6FlowMod message - * @param cookie Cookie of the message - */ - public void setCookie(long cookie) { - this.cookie = cookie; - } - - /** - * Sets the command field of V6FlowMod message - * @param command Command type of the message (ADD or DELETE) - */ - public V6FlowMod setCommand(short command) { - this.command = command; - return this; - } - - /** - * Sets the outPort field of V6FlowMod message - * @param outPort outPort of the message - */ - public V6FlowMod setOutPort(OFPort port) { - this.outPort = port.getValue(); - return this; - } - - /** - * Sets the idle_timeout of V6FlowMod message - * @param idleTimeout idle timeout for this message - */ - public void setIdleTimeout(short idleTimeout) { - this.idleTimeout = idleTimeout; - } - - /** - * Sets the hardTimeout field of V6FlowMod message - * @param hardTimeout hard timeout of the message - */ - public void setHardTimeout(short hardTimeout) { - this.hardTimeout = hardTimeout; - } - - /** - * Returns the Flow Mod message subtype for V6FlowMod message - * @return message subtype - */ - private int getIPv6ExtensionFlowModAddSubType() { - return IPV6EXT_ADD_FLOW_MSG_TYPE; - } - - /** - * Returns the minimum header size for V6Flow Message type - * @return minimum header size - */ - - public int getV6FlowModMinHdrSize() { - return IPV6_EXT_MIN_HDR_LEN; - } - - /** - * Sets the Vendor type in OFVendor message - */ - - public void setVendor() { - super.setVendor(V6StatsRequest.NICIRA_VENDOR_ID); - } - - /** - * Get flags - * @return - */ - public short getFlags() { - return flags; - } - - /** - * Set flags - * @param flags - */ - public void setFlags(short flags) { - this.flags = flags; - } - - /** - * This method forms the Vendor extension IPv6 Flow Mod message.It uses the - * fields in V6FlowMod class, and writes the data according to vendor - * extension format. The fields include flow properties (cookie, timeout, - * priority, etc), flow match, and action list. It also takes care of - * required padding. - */ - - @Override - public void writeTo(ByteBuffer data) { - super.writeTo(data); - data.putInt(getIPv6ExtensionFlowModAddSubType()); - data.putLong(this.cookie); - data.putShort(command); /* should be OFPFC_ADD, OFPFC_DELETE_STRICT, etc*/ - data.putShort(this.idleTimeout); - data.putShort(this.hardTimeout); - data.putShort(this.priority); - data.putInt(OFPacketOut.BUFFER_ID_NONE); - data.putShort(outPort); /* output_port */ - data.putShort(flags); /* flags */ - match_len = this.match.getIPv6MatchLen(); - data.putShort(match_len); - byte[] pad = new byte[6]; - data.put(pad); - this.match.writeTo(data); - - pad_size = (short) (((match_len + 7) / 8) * 8 - match_len); - - /* - * action list should be preceded by a padding of 0 to 7 bytes based upon - * above formula. - */ - - byte[] pad2 = new byte[pad_size]; - data.put(pad2); - if (actions != null) { - for (OFAction action : actions) { - actions_len += action.getLength(); - action.writeTo(data); - } - } - logger.trace("{}", this); - } - - /** - * Forms the clone of V6FlowMod Object. If Object is returned - * successfully, then returns the cloned object. Throws an - * exception if cloning is not supported. - */ - @Override - public V6FlowMod clone() { - try { - V6Match neoMatch = match.clone(); - V6FlowMod v6flowMod = (V6FlowMod) super.clone(); - v6flowMod.setMatch(neoMatch); - List neoActions = new LinkedList(); - for (OFAction action : this.actions) { - neoActions.add((OFAction) action.clone()); - } - v6flowMod.setActions(neoActions); - return v6flowMod; - } catch (CloneNotSupportedException e) { - // Won't happen - throw new RuntimeException(e); - } - } - - @Override - public String toString() { - return "V6FlowMod [match=" + match + ", cookie=" + cookie - + ", command=" + command + ", idleTimeout=" + idleTimeout - + ", hardTimeout=" + hardTimeout + ", priority=" + priority - + ", bufferId=" + bufferId + ", outPort=" + outPort - + ", flags=" + flags + ", actions=" + actions + ", match_len=" - + match_len + ", actions_len=" + actions_len + ", pad_size=" - + pad_size + "]"; - } - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Match.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Match.java deleted file mode 100644 index 4b8966c546..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6Match.java +++ /dev/null @@ -1,1672 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension; - -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.util.Arrays; - -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.openflow.protocol.OFMatch; -import org.openflow.util.U16; -import org.openflow.util.U8; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This Class forms the vendor specific IPv6 Flow Match messages as well as - * processes the vendor specific IPv6 Stats Reply message. - * - * For message creation, it parses the user entered IPv6 match fields, creates a - * sub-message for each field which are later used to form the complete message. - * - * For message processing, it parses the incoming message and reads each field - * of the message and stores in appropriate field of V6Match object. - * - * - */ -public class V6Match extends OFMatch implements Cloneable { - private static final Logger logger = LoggerFactory.getLogger(V6Match.class); - private static final long serialVersionUID = 1L; - protected Inet6Address nwSrc; - protected Inet6Address nwDst; - protected short inputPortMask; - protected byte[] dataLayerSourceMask; - protected byte[] dataLayerDestinationMask; - protected int dataLayerVirtualLanTCIMask; - protected short dataLayerTypeMask; - protected byte networkTypeOfServiceMask; - protected byte networkProtocolMask; - protected short transportSourceMask; - protected short transportDestinationMask; - protected short srcIPv6SubnetMaskbits; - protected short dstIPv6SubnetMaskbits; - - protected MatchFieldState inputPortState; - protected MatchFieldState dlSourceState; - protected MatchFieldState dlDestState; - protected MatchFieldState dlVlanIDState; - protected MatchFieldState dlVlanPCPState; - protected MatchFieldState dlVlanTCIState; - protected MatchFieldState ethTypeState; - protected MatchFieldState nwTosState; - protected MatchFieldState nwProtoState; - protected MatchFieldState nwSrcState; - protected MatchFieldState nwDstState; - protected MatchFieldState tpSrcState; - protected MatchFieldState tpDstState; - protected short match_len = 0; - protected short pad_size = 0; - - private static int IPV6_EXT_MIN_HDR_LEN = 36; - - /** - * CFI bit in VLAN TCI field. - */ - private static final int VLAN_TCI_CFI = 1 << 12; - - /** - * Value of OFP_VLAN_NONE defined by OpenFlow 1.0. - */ - private static final short OFP_VLAN_NONE = (short) 0xffff; - - private enum MatchFieldState { - MATCH_ABSENT, MATCH_FIELD_ONLY, MATCH_FIELD_WITH_MASK - } - - private enum OF_Match_Types { - MATCH_OF_IN_PORT(0), MATCH_OF_ETH_DST(1), MATCH_OF_ETH_SRC(2), MATCH_OF_ETH_TYPE( - 3), MATCH_OF_VLAN_TCI(4), MATCH_OF_IP_TOS(5), MATCH_OF_IP_PROTO( - 6), MATCH_OF_IP_SRC(7), MATCH_OF_IP_DST(8), MATCH_OF_TCP_SRC(9), MATCH_OF_TCP_DST( - 10), MATCH_OF_UDP_SRC(11), MATCH_OF_UDP_DST(12), MATCH_OF_ICMTP_TYPE( - 13), MATCH_OF_ICMP_CODE(14), MATCH_OF_ARP_OP(15); - - private int value; - - private OF_Match_Types(int value) { - this.value = value; - } - - public int getValue() { - return this.value; - } - } - - private enum IPv6Extension_Match_Types { - MATCH_IPV6EXT_TUN_ID(16), MATCH_IPV6EXT_ARP_SHA(17), MATCH_IPV6EXT_ARP_THA( - 18), MATCH_IPV6EXT_IPV6_SRC(19), MATCH_IPV6EXT_IPV6_DST(20); - - private int value; - - private IPv6Extension_Match_Types(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - } - - public enum Extension_Types { - OF_10(0), IPV6EXT(1); - - protected int value; - - private Extension_Types(int value) { - this.value = value; - } - - public int getValue() { - return value; - } - } - - public V6Match() { - super(); - - this.nwSrc = null; - this.nwDst = null; - - this.inputPortMask = 0; - this.dataLayerSourceMask = null; - this.dataLayerDestinationMask = null; - this.dataLayerTypeMask = 0; - this.dataLayerVirtualLanTCIMask = 0; - this.networkTypeOfServiceMask = 0; - this.networkProtocolMask = 0; - this.transportSourceMask = 0; - this.transportDestinationMask = 0; - - this.inputPortState = MatchFieldState.MATCH_ABSENT; - this.dlSourceState = MatchFieldState.MATCH_ABSENT; - this.dlDestState = MatchFieldState.MATCH_ABSENT; - this.dlVlanIDState = MatchFieldState.MATCH_ABSENT; - this.dlVlanPCPState = MatchFieldState.MATCH_ABSENT; - this.dlVlanTCIState = MatchFieldState.MATCH_ABSENT; - this.ethTypeState = MatchFieldState.MATCH_ABSENT; - this.nwTosState = MatchFieldState.MATCH_ABSENT; - this.nwProtoState = MatchFieldState.MATCH_ABSENT; - this.nwSrcState = MatchFieldState.MATCH_ABSENT; - this.nwDstState = MatchFieldState.MATCH_ABSENT; - this.tpSrcState = MatchFieldState.MATCH_ABSENT; - this.tpDstState = MatchFieldState.MATCH_ABSENT; - - this.match_len = 0; - this.pad_size = 0; - } - - public V6Match(OFMatch match) { - super(); - this.match_len = 0; - this.pad_size = 0; - - if (match.getNetworkSource() != 0) { - InetAddress address = NetUtils.getInetAddress(match.getNetworkSource()); - InetAddress mask = NetUtils.getInetNetworkMask(match.getNetworkSourceMaskLen(), false); - this.setNetworkSource(address, mask); - } else { - this.nwSrcState = MatchFieldState.MATCH_ABSENT; - } - - if (match.getNetworkDestination() != 0) { - InetAddress address = NetUtils.getInetAddress(match.getNetworkDestination()); - InetAddress mask = NetUtils.getInetNetworkMask(match.getNetworkDestinationMaskLen(), false); - this.setNetworkDestination(address, mask); - } else { - this.nwDstState = MatchFieldState.MATCH_ABSENT; - } - - this.inputPortMask = 0; - if (match.getInputPort() != 0) { - this.setInputPort(match.getInputPort(), (short) 0); - } else { - this.inputPortMask = 0; - this.inputPortState = MatchFieldState.MATCH_ABSENT; - } - - this.dataLayerSourceMask = null; - if (match.getDataLayerSource() != null - && !NetUtils.isZeroMAC(match.getDataLayerSource())) { - this.setDataLayerSource(match.getDataLayerSource(), null); - } else { - this.dlSourceState = MatchFieldState.MATCH_ABSENT; - } - this.dataLayerDestinationMask = null; - if (match.getDataLayerDestination() != null - && !NetUtils.isZeroMAC(match.getDataLayerDestination())) { - this.setDataLayerDestination(match.getDataLayerDestination(), null); - } else { - this.dlDestState = MatchFieldState.MATCH_ABSENT; - } - - this.dataLayerTypeMask = 0; - if (match.getDataLayerType() != 0) { - this.setDataLayerType(match.getDataLayerType(), (short) 0); - } else { - this.dataLayerType = 0; - this.ethTypeState = MatchFieldState.MATCH_ABSENT; - } - - this.dataLayerVirtualLanTCIMask = 0; - this.dlVlanTCIState = MatchFieldState.MATCH_ABSENT; - if (match.getDataLayerVirtualLan() != 0) { - this.setDataLayerVirtualLan(match.getDataLayerVirtualLan(), - (short) 0); - } else { - this.dataLayerVirtualLan = 0; - this.dlVlanIDState = MatchFieldState.MATCH_ABSENT; - } - - if ((match.getWildcards() & OFMatch.OFPFW_DL_VLAN_PCP) == 0) { - this.setDataLayerVirtualLanPriorityCodePoint( - match.getDataLayerVirtualLanPriorityCodePoint(), (byte) 0); - } else { - this.dataLayerVirtualLanPriorityCodePoint = 0; - this.dlVlanPCPState = MatchFieldState.MATCH_ABSENT; - } - - this.networkProtocolMask = 0; - if (match.getNetworkProtocol() != 0) { - this.setNetworkProtocol( - this.networkProtocol = match.getNetworkProtocol(), (byte) 0); - } else { - this.networkProtocol = 0; - this.nwProtoState = MatchFieldState.MATCH_ABSENT; - } - - this.networkTypeOfServiceMask = 0; - if (match.getNetworkTypeOfService() != 0) { - this.setNetworkTypeOfService( - this.networkTypeOfService = match.getNetworkTypeOfService(), - (byte) 0); - } else { - this.networkTypeOfService = match.getNetworkTypeOfService(); - this.nwTosState = MatchFieldState.MATCH_ABSENT; - } - - this.transportSourceMask = 0; - if (match.getTransportSource() != 0) { - this.setTransportSource(match.getTransportSource(), (short) 0); - } else { - this.transportSource = 0; - this.tpSrcState = MatchFieldState.MATCH_ABSENT; - } - - this.transportDestinationMask = 0; - if (match.getTransportDestination() != 0) { - this.setTransportDestination(match.getTransportDestination(), - (short) 0); - } else { - this.transportDestination = 0; - this.tpDstState = MatchFieldState.MATCH_ABSENT; - } - - this.setWildcards(match.getWildcards()); - } - - private enum IPProtocols { - ICMP(1), TCP(6), UDP(17), ICMPV6(58); - - private int protocol; - - private IPProtocols(int value) { - this.protocol = value; - } - - private byte getValue() { - return (byte) this.protocol; - } - } - - public short getIPv6MatchLen() { - return match_len; - } - - public int getIPv6ExtMinHdrLen() { - return IPV6_EXT_MIN_HDR_LEN; - } - - public short getPadSize() { - return (short) (((match_len + 7) / 8) * 8 - match_len); - } - - private int getIPv6ExtensionMatchHeader(Extension_Types extType, int field, - int has_mask, int length) { - return (((extType.getValue() & 0x0000ffff) << 16) - | ((field & 0x0000007f) << 9) | ((has_mask & 0x00000001) << 8) | (length & 0x000000ff)); - } - - private byte[] getIPv6ExtensionPortMatchMsg(short port) { - ByteBuffer ipv6ext_port_msg = ByteBuffer.allocate(6); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_IN_PORT.getValue(), 0, 2); - ipv6ext_port_msg.putInt(nxm_header); - ipv6ext_port_msg.putShort(port); - return (ipv6ext_port_msg.array()); - } - - private byte[] getIPv6ExtensionDestMacMatchMsg(byte[] destMac) { - ByteBuffer ipv6ext_destmac_msg = ByteBuffer.allocate(10); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_ETH_DST.getValue(), 0, 6); - ipv6ext_destmac_msg.putInt(nxm_header); - ipv6ext_destmac_msg.put(destMac); - return (ipv6ext_destmac_msg.array()); - } - - private byte[] getIPv6ExtensionSrcMacMatchMsg(byte[] srcMac) { - ByteBuffer ipv6ext_srcmac_msg = ByteBuffer.allocate(10); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_ETH_SRC.getValue(), 0, 6); - ipv6ext_srcmac_msg.putInt(nxm_header); - ipv6ext_srcmac_msg.put(srcMac); - return (ipv6ext_srcmac_msg.array()); - } - - private byte[] getIPv6ExtensionEtherTypeMatchMsg(short EtherType) { - ByteBuffer ipv6ext_etype_msg = ByteBuffer.allocate(6); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_ETH_TYPE.getValue(), 0, 2); - ipv6ext_etype_msg.putInt(nxm_header); - ipv6ext_etype_msg.putShort(EtherType); - return (ipv6ext_etype_msg.array()); - } - - private byte[] getVlanTCI(short dataLayerVirtualLanID, - byte dataLayerVirtualLanPriorityCodePoint) { - ByteBuffer vlan_tci = ByteBuffer.allocate(2); - int vlan_tci_int; - if (dataLayerVirtualLanID == OFP_VLAN_NONE) { - // Match only packets without VLAN tag. - vlan_tci_int = 0; - } else { - // the pcp fields have to move by 13 - int pcp = dataLayerVirtualLanPriorityCodePoint << 13; - vlan_tci_int = pcp + VLAN_TCI_CFI + dataLayerVirtualLanID; - } - vlan_tci.put((byte) (vlan_tci_int >> 8)); // bits 8 to 15 - vlan_tci.put((byte) vlan_tci_int); // bits 0 to 7 - return vlan_tci.array(); - } - - private byte[] getIPv6ExtensionVlanTCIMatchMsg(short dataLayerVirtualLanID, - byte dataLayerVirtualLanPriorityCodePoint) { - ByteBuffer ipv6ext_vlan_tci_msg = ByteBuffer.allocate(6); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_VLAN_TCI.getValue(), 0, 2); - ipv6ext_vlan_tci_msg.putInt(nxm_header); - ipv6ext_vlan_tci_msg.put(getVlanTCI(dataLayerVirtualLanID, - dataLayerVirtualLanPriorityCodePoint)); - return (ipv6ext_vlan_tci_msg.array()); - } - - private byte[] getIPv6ExtensionVlanTCIMatchWithMaskMsg( - short dataLayerVirtualLan, - byte dataLayerVirtualLanPriorityCodePoint, - int dataLayerVirtualLanTCIMask) { - ByteBuffer ipv6ext_vlan_tci_msg = ByteBuffer.allocate(8); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_VLAN_TCI.getValue(), 1, 4); - ipv6ext_vlan_tci_msg.putInt(nxm_header); - ipv6ext_vlan_tci_msg.put(getVlanTCI(dataLayerVirtualLan, - dataLayerVirtualLanPriorityCodePoint)); - ipv6ext_vlan_tci_msg.put((byte) (dataLayerVirtualLanTCIMask >> 8)); // bits - // 8 - // to - // 15 - ipv6ext_vlan_tci_msg.put((byte) (dataLayerVirtualLanTCIMask)); // bits 0 - // to 7 - return (ipv6ext_vlan_tci_msg.array()); - } - - private byte[] getIPv6ExtensionSrcIPv6MatchMsg(byte[] srcIpv6) { - ByteBuffer ipv6ext_ipv6_msg = ByteBuffer.allocate(20); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.IPV6EXT, - IPv6Extension_Match_Types.MATCH_IPV6EXT_IPV6_SRC.getValue(), 0, - 16); - ipv6ext_ipv6_msg.putInt(nxm_header); - ipv6ext_ipv6_msg.put(srcIpv6); - return (ipv6ext_ipv6_msg.array()); - } - - private byte[] getIPv6ExtensionSrcIPv6MatchwithMaskMsg(byte[] srcIpv6, - short masklen) { - ByteBuffer ipv6ext_ipv6_msg = ByteBuffer.allocate(36); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.IPV6EXT, - IPv6Extension_Match_Types.MATCH_IPV6EXT_IPV6_SRC.getValue(), 1, - 32); - ipv6ext_ipv6_msg.putInt(nxm_header); - ipv6ext_ipv6_msg.put(srcIpv6); - byte[] ipv6_mask = getIPv6NetworkMaskinBytes(masklen); - ipv6ext_ipv6_msg.put(ipv6_mask); - return (ipv6ext_ipv6_msg.array()); - } - - private byte[] getIPv6ExtensionDstIPv6MatchMsg(byte[] dstIpv6) { - ByteBuffer ipv6ext_ipv6_msg = ByteBuffer.allocate(20); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.IPV6EXT, - IPv6Extension_Match_Types.MATCH_IPV6EXT_IPV6_DST.getValue(), 0, - 16); - ipv6ext_ipv6_msg.putInt(nxm_header); - ipv6ext_ipv6_msg.put(dstIpv6); - return (ipv6ext_ipv6_msg.array()); - } - - private byte[] getIPv6ExtensionDstIPv6MatchwithMaskMsg(byte[] dstIpv6, - short masklen) { - ByteBuffer ipv6ext_ipv6_msg = ByteBuffer.allocate(36); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.IPV6EXT, - IPv6Extension_Match_Types.MATCH_IPV6EXT_IPV6_DST.getValue(), 1, - 32); - ipv6ext_ipv6_msg.putInt(nxm_header); - ipv6ext_ipv6_msg.put(dstIpv6); - byte[] ipv6_mask = getIPv6NetworkMaskinBytes(masklen); - ipv6ext_ipv6_msg.put(ipv6_mask); - return (ipv6ext_ipv6_msg.array()); - } - - private byte[] getIPv6ExtensionProtocolMatchMsg(byte protocol) { - ByteBuffer ipv6ext_proto_msg = ByteBuffer.allocate(5); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_IP_PROTO.getValue(), 0, 1); - if (protocol == 0) { - return null; - } - ipv6ext_proto_msg.putInt(nxm_header); - if (protocol == IPProtocols.ICMP.getValue()) { - /* - * The front end passes the same protocol type values for IPv4 and - * IPv6 flows. For the Protocol types we allow in our GUI (ICMP, - * TCP, UDP), ICMP is the only one which is different for IPv6. It - * is 1 for v4 and 58 for v6 Therefore, we overwrite it here. - */ - protocol = IPProtocols.ICMPV6.getValue(); - } - ipv6ext_proto_msg.put(protocol); - return (ipv6ext_proto_msg.array()); - } - - private byte[] getIPv6ExtensionTOSMatchMsg(byte tos) { - ByteBuffer ipv6ext_tos_msg = ByteBuffer.allocate(5); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_IP_TOS.getValue(), 0, 1); - ipv6ext_tos_msg.putInt(nxm_header); - ipv6ext_tos_msg.put(tos); - return (ipv6ext_tos_msg.array()); - } - - private byte[] getIPv6ExtensionTCPSrcPortMatchMsg(short src_port) { - ByteBuffer ipv6ext_tcp_srcport_msg = ByteBuffer.allocate(6); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_TCP_SRC.getValue(), 0, 2); - ipv6ext_tcp_srcport_msg.putInt(nxm_header); - ipv6ext_tcp_srcport_msg.putShort(src_port); - return (ipv6ext_tcp_srcport_msg.array()); - } - - private byte[] getIPv6ExtensionTCPDstPortMatchMsg(short dst_port) { - ByteBuffer ipv6ext_tcp_dstport_msg = ByteBuffer.allocate(6); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_TCP_DST.getValue(), 0, 2); - ipv6ext_tcp_dstport_msg.putInt(nxm_header); - ipv6ext_tcp_dstport_msg.putShort(dst_port); - return (ipv6ext_tcp_dstport_msg.array()); - } - - private byte[] getIPv6ExtensionUDPSrcPortMatchMsg(short src_port) { - ByteBuffer ipv6ext_udp_srcport_msg = ByteBuffer.allocate(6); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_UDP_SRC.getValue(), 0, 2); - ipv6ext_udp_srcport_msg.putInt(nxm_header); - ipv6ext_udp_srcport_msg.putShort(src_port); - return (ipv6ext_udp_srcport_msg.array()); - } - - private byte[] getIPv6ExtensionUDPDstPortMatchMsg(short dst_port) { - ByteBuffer ipv6ext_udp_dstport_msg = ByteBuffer.allocate(6); - int nxm_header = getIPv6ExtensionMatchHeader(Extension_Types.OF_10, - OF_Match_Types.MATCH_OF_UDP_DST.getValue(), 0, 2); - ipv6ext_udp_dstport_msg.putInt(nxm_header); - ipv6ext_udp_dstport_msg.putShort(dst_port); - return (ipv6ext_udp_dstport_msg.array()); - } - - /** - * Sets this (V6Match) object's member variables based on a comma-separated - * key=value pair similar to OFMatch's fromString. - * - * @param match - * a key=value comma separated string. - */ - @Override - public void fromString(String match) throws IllegalArgumentException { - if (match.equals("") || match.equalsIgnoreCase("any") - || match.equalsIgnoreCase("all") || match.equals("[]")) { - match = "OFMatch[]"; - } - String[] tokens = match.split("[\\[,\\]]"); - String[] values; - int initArg = 0; - if (tokens[0].equals("OFMatch")) { - initArg = 1; - } - this.wildcards = OFPFW_ALL; - int i; - for (i = initArg; i < tokens.length; i++) { - values = tokens[i].split("="); - if (values.length != 2) { - throw new IllegalArgumentException("Token " + tokens[i] - + " does not have form 'key=value' parsing " + match); - } - values[0] = values[0].toLowerCase(); // try to make this case insens - if (values[0].equals(STR_IN_PORT) || values[0].equals("input_port")) { - this.inputPort = U16.t(Integer.valueOf(values[1])); - inputPortState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 6; - } else if (values[0].equals(STR_DL_DST) - || values[0].equals("eth_dst")) { - this.dataLayerDestination = HexEncode - .bytesFromHexString(values[1]); - dlDestState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 10; - } else if (values[0].equals(STR_DL_SRC) - || values[0].equals("eth_src")) { - this.dataLayerSource = HexEncode.bytesFromHexString(values[1]); - dlSourceState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 10; - this.wildcards &= ~OFPFW_DL_SRC; - } else if (values[0].equals(STR_DL_TYPE) - || values[0].equals("eth_type")) { - if (values[1].startsWith("0x")) { - this.dataLayerType = U16.t(Integer.valueOf(values[1] - .replaceFirst("0x", ""), 16)); - } else { - - this.dataLayerType = U16.t(Integer.valueOf(values[1])); - } - ethTypeState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 6; - } else if (values[0].equals(STR_DL_VLAN)) { - short vlan = U16.t(Integer.valueOf(values[1])); - if (this.dlVlanPCPState != MatchFieldState.MATCH_ABSENT && - vlan == OFP_VLAN_NONE) { - throw new IllegalArgumentException("DL_VLAN_PCP is set."); - } - this.dataLayerVirtualLan = vlan; - this.dlVlanIDState = MatchFieldState.MATCH_FIELD_ONLY; - // the variable dlVlanIDState is not really used as a flag - // for serializing and deserializing. Rather it is used as a - // flag - // to check if the vlan id is being set so that we can set the - // dlVlanTCIState appropriately. - if (this.dlVlanPCPState != MatchFieldState.MATCH_ABSENT) { - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_ONLY; - match_len -= 2; - } else if (this.dataLayerVirtualLan == OFP_VLAN_NONE) { - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 6; - } else { - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.dataLayerVirtualLanTCIMask = 0x1fff; - match_len += 8; - } - this.wildcards &= ~OFPFW_DL_VLAN; - } else if (values[0].equals(STR_DL_VLAN_PCP)) { - if (this.dlVlanIDState != MatchFieldState.MATCH_ABSENT && - this.dataLayerVirtualLan == OFP_VLAN_NONE) { - throw new IllegalArgumentException - ("OFP_VLAN_NONE is specified to DL_VLAN."); - } - this.dataLayerVirtualLanPriorityCodePoint = U8.t(Short - .valueOf(values[1])); - this.dlVlanPCPState = MatchFieldState.MATCH_FIELD_ONLY; - // the variable dlVlanPCPState is not really used as a flag - // for serializing and deserializing. Rather it is used as a - // flag - // to check if the vlan pcp is being set so that we can set the - // dlVlanTCIState appropriately. - if (this.dlVlanIDState != MatchFieldState.MATCH_ABSENT) { - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_ONLY; - match_len -= 2; - } else { - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.dataLayerVirtualLanTCIMask = 0xf000; - match_len += 8; - } - this.wildcards &= ~OFPFW_DL_VLAN_PCP; - } else if (values[0].equals(STR_NW_DST) - || values[0].equals("ip_dst")) { - try { - InetAddress address = null; - InetAddress mask = null; - if (values[1].contains("/")) { - String addressString[] = values[1].split("/"); - address = InetAddress.getByName(addressString[0]); - int masklen = Integer.valueOf(addressString[1]); - mask = NetUtils.getInetNetworkMask(masklen, address instanceof Inet6Address); - } else { - address = InetAddress.getByName(values[1]); - } - this.setNetworkDestination(address, mask); - } catch (UnknownHostException e) { - logger.error("", e); - } - } else if (values[0].equals(STR_NW_SRC) - || values[0].equals("ip_src")) { - try { - InetAddress address = null; - InetAddress mask = null; - if (values[1].contains("/")) { - String addressString[] = values[1].split("/"); - address = InetAddress.getByName(addressString[0]); - int masklen = Integer.valueOf(addressString[1]); - mask = NetUtils.getInetNetworkMask(masklen, address instanceof Inet6Address); - } else { - address = InetAddress.getByName(values[1]); - } - this.setNetworkSource(address, mask); - } catch (UnknownHostException e) { - logger.error("", e); - } - } else if (values[0].equals(STR_NW_PROTO)) { - this.networkProtocol = U8.t(Short.valueOf(values[1])); - if (!(this.networkProtocol == 0)) { - /* - * if user selects proto 0, don't use it - */ - nwProtoState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 5; - } - } else if (values[0].equals(STR_NW_TOS)) { - this.networkTypeOfService = U8.t(Short.valueOf(values[1])); - nwTosState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 5; - } else if (values[0].equals(STR_TP_DST)) { - this.transportDestination = U16.t(Integer.valueOf(values[1])); - tpDstState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 6; - } else if (values[0].equals(STR_TP_SRC)) { - this.transportSource = U16.t(Integer.valueOf(values[1])); - tpSrcState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 6; - } else { - throw new IllegalArgumentException("unknown token " + tokens[i] - + " parsing " + match); - } - } - - /* - * In a V6 extension message action list should be preceded by a padding - * of 0 to 7 bytes based upon following formula. - */ - - pad_size = (short) (((match_len + 7) / 8) * 8 - match_len); - - } - - /** - * Write this message's binary format to the specified ByteBuffer - * - * @param data - */ - @Override - public void writeTo(ByteBuffer data) { - if (inputPortState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_ingress_port_msg = getIPv6ExtensionPortMatchMsg(this.inputPort); - data.put(ipv6ext_ingress_port_msg); - } - if (ethTypeState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_ether_type_msg = getIPv6ExtensionEtherTypeMatchMsg(this.dataLayerType); - data.put(ipv6ext_ether_type_msg); - } - if (dlDestState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_destmac_msg = getIPv6ExtensionDestMacMatchMsg(this.dataLayerDestination); - data.put(ipv6ext_destmac_msg); - } - if (dlSourceState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_srcmac_msg = getIPv6ExtensionSrcMacMatchMsg(this.dataLayerSource); - data.put(ipv6ext_srcmac_msg); - } - if (dlVlanTCIState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_vlan_tci_msg = getIPv6ExtensionVlanTCIMatchMsg( - this.dataLayerVirtualLan, - this.dataLayerVirtualLanPriorityCodePoint); - data.put(ipv6ext_vlan_tci_msg); - } else if (dlVlanTCIState == MatchFieldState.MATCH_FIELD_WITH_MASK) { - byte[] ipv6ext_vlan_tci_msg_with_mask = getIPv6ExtensionVlanTCIMatchWithMaskMsg( - this.dataLayerVirtualLan, - this.dataLayerVirtualLanPriorityCodePoint, - this.dataLayerVirtualLanTCIMask); - data.put(ipv6ext_vlan_tci_msg_with_mask); - } - if (nwSrcState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_src_ipv6_msg = getIPv6ExtensionSrcIPv6MatchMsg(this.nwSrc - .getAddress()); - data.put(ipv6ext_src_ipv6_msg); - } else if (nwSrcState == MatchFieldState.MATCH_FIELD_WITH_MASK) { - byte[] ipv6ext_src_ipv6_with_mask_msg = getIPv6ExtensionSrcIPv6MatchwithMaskMsg( - this.nwSrc.getAddress(), this.srcIPv6SubnetMaskbits); - data.put(ipv6ext_src_ipv6_with_mask_msg); - } - if (nwDstState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_dst_ipv6_msg = getIPv6ExtensionDstIPv6MatchMsg(this.nwDst - .getAddress()); - data.put(ipv6ext_dst_ipv6_msg); - } else if (nwDstState == MatchFieldState.MATCH_FIELD_WITH_MASK) { - byte[] ipv6ext_dst_ipv6_with_mask_msg = getIPv6ExtensionDstIPv6MatchwithMaskMsg( - this.nwDst.getAddress(), this.dstIPv6SubnetMaskbits); - data.put(ipv6ext_dst_ipv6_with_mask_msg); - } - if (nwProtoState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_protocol_msg = getIPv6ExtensionProtocolMatchMsg(this.networkProtocol); - if (ipv6ext_protocol_msg != null) { - data.put(ipv6ext_protocol_msg); - } - } - if (nwTosState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_tos_msg = getIPv6ExtensionTOSMatchMsg(this.networkTypeOfService); - data.put(ipv6ext_tos_msg); - } - if (tpSrcState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_srcport_msg = null; - if (this.networkProtocol == IPProtocols.TCP.getValue()) { - ipv6ext_srcport_msg = getIPv6ExtensionTCPSrcPortMatchMsg(this.transportSource); - } else if (this.networkProtocol == IPProtocols.UDP.getValue()) { - ipv6ext_srcport_msg = getIPv6ExtensionUDPSrcPortMatchMsg(this.transportSource); - } - if (ipv6ext_srcport_msg != null) { - data.put(ipv6ext_srcport_msg); - } - } - if (tpDstState == MatchFieldState.MATCH_FIELD_ONLY) { - byte[] ipv6ext_dstport_msg = null; - if (this.networkProtocol == IPProtocols.TCP.getValue()) { - ipv6ext_dstport_msg = getIPv6ExtensionTCPDstPortMatchMsg(this.transportDestination); - } else if (this.networkProtocol == IPProtocols.UDP.getValue()) { - ipv6ext_dstport_msg = getIPv6ExtensionUDPDstPortMatchMsg(this.transportDestination); - } - if (ipv6ext_dstport_msg != null) { - data.put(ipv6ext_dstport_msg); - } - } - logger.trace("{}", this); - } - - private void readInPort(ByteBuffer data, int nxmLen, boolean hasMask) { - if ((nxmLen != 2) || (data.remaining() < 2) || (hasMask)) { - /* - * mask is not allowed for inport port - */ - return; - } - super.setInputPort(data.getShort()); - this.inputPortState = MatchFieldState.MATCH_FIELD_ONLY; - this.wildcards ^= (1 << 0); // Sync with 0F 1.0 Match - this.match_len += 6; - } - - private void readDataLinkDestination(ByteBuffer data, int nxmLen, - boolean hasMask) { - if (hasMask) { - if ((nxmLen != 2 * 6) || (data.remaining() < 2 * 6)) { - return; - } else { - byte[] bytes = new byte[6]; - data.get(bytes); - super.setDataLayerDestination(bytes); - this.dataLayerDestinationMask = new byte[6]; - data.get(this.dataLayerDestinationMask); - this.dlDestState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += 16; - } - } else { - if ((nxmLen != 6) || (data.remaining() < 6)) { - return; - } else { - byte[] bytes = new byte[6]; - data.get(bytes); - super.setDataLayerDestination(bytes); - this.dlDestState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 10; - } - } - this.wildcards ^= (1 << 3); // Sync with 0F 1.0 Match - } - - private void readDataLinkSource(ByteBuffer data, int nxmLen, boolean hasMask) { - /* - * mask is not allowed in data link source - */ - if ((nxmLen != 6) || (data.remaining() < 6) || (hasMask)) { - return; - } - byte[] bytes = new byte[6]; - data.get(bytes); - super.setDataLayerSource(bytes); - this.dlSourceState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 10; - this.wildcards ^= (1 << 2); // Sync with 0F 1.0 Match - } - - private void readEtherType(ByteBuffer data, int nxmLen, boolean hasMask) { - /* - * mask is not allowed in ethertype - */ - if ((nxmLen != 2) || (data.remaining() < 2) || (hasMask)) { - return; - } - super.setDataLayerType(data.getShort()); - this.ethTypeState = MatchFieldState.MATCH_FIELD_ONLY; - this.wildcards ^= (1 << 4); // Sync with 0F 1.0 Match - this.match_len += 6; - } - - private short getVlanID(byte firstByte, byte secondByte) { - short vlan_id_mask_firstByte = 0x0f;// this is the mask for the first - // byte - short vlan_id_mask_secondByte = 0xff;// this is the mask for the second - // byte - int vlanPart1 = (firstByte & vlan_id_mask_firstByte) << 8; - int vlanPart2 = secondByte & vlan_id_mask_secondByte; - return (short) (vlanPart1 + vlanPart2); - } - - private byte getVlanPCP(byte pcpByte) { - short vlan_pcp_mask = 0xe0;// this is the vlan pcp mask - int pcp_int = pcpByte & vlan_pcp_mask; - return (byte) (pcp_int >> 5); - } - - private void readVlanTci(ByteBuffer data, int nxmLen, boolean hasMask) { - if (hasMask) { - if ((nxmLen != 2 * 2) || (data.remaining() < 2 * 2)) { - return; - } - else { - byte firstByte = data.get(); - byte secondByte = data.get(); - this.dataLayerVirtualLanTCIMask = data.getShort() & 0xffff; // we - // need - // the - // last - // 16 - // bits - // check the mask now - if ((this.dataLayerVirtualLanTCIMask & 0x0fff) != 0) { - // if its a vlan id mask - // extract the vlan id - super.setDataLayerVirtualLan(getVlanID(firstByte, - secondByte)); - this.wildcards ^= (1 << 1); // Sync with 0F 1.0 Match - } - if ((this.dataLayerVirtualLanTCIMask & 0xe000) != 0) { - // else if its a vlan pcp mask - // extract the vlan pcp - super.setDataLayerVirtualLanPriorityCodePoint(getVlanPCP(firstByte)); - this.wildcards ^= (1 << 20); - } - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += 8; - } - } else { - if ((nxmLen != 2) || (data.remaining() < 2)) { - return; - } - else { - // get the vlan pcp - byte firstByte = data.get(); - byte secondByte = data.get(); - if (firstByte == 0 && secondByte == 0) { - // Match only packets without VLAN tag. - setDataLayerVirtualLan(OFP_VLAN_NONE); - } else if (((firstByte << 8) & VLAN_TCI_CFI) == 0) { - // Ignore invalid TCI field. - return; - } else { - super.setDataLayerVirtualLanPriorityCodePoint(getVlanPCP(firstByte)); - super.setDataLayerVirtualLan(getVlanID(firstByte, secondByte)); - this.wildcards ^= (1 << 20); - } - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 6; - this.wildcards ^= (1 << 1); // Sync with 0F 1.0 Match - } - } - } - - private void readIpTos(ByteBuffer data, int nxmLen, boolean hasMask) { - /* - * mask is not allowed in IP TOS - */ - if ((nxmLen != 1) || (data.remaining() < 1) || (hasMask)) { - return; - } - super.setNetworkTypeOfService(data.get()); - this.nwTosState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 5; - this.wildcards ^= (1 << 21); // Sync with 0F 1.0 Match - } - - private void readIpProto(ByteBuffer data, int nxmLen, boolean hasMask) { - /* - * mask is not allowed in IP protocol - */ - if ((nxmLen != 1) || (data.remaining() < 1) || (hasMask)) { - return; - } - super.setNetworkProtocol(data.get()); - this.nwProtoState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 5; - this.wildcards ^= (1 << 5); // Sync with 0F 1.0 Match - } - - private void readIpv4Src(ByteBuffer data, int nxmLen, boolean hasMask) { - if (hasMask) { - if ((nxmLen != 2 * 4) || (data.remaining() < 2 * 4)) { - return; - } else { - byte[] sbytes = new byte[4]; - data.get(sbytes); - // For compatibility, let's set the IPv4 in the parent OFMatch - int address = NetUtils.byteArray4ToInt(sbytes); - super.setNetworkSource(address); - byte[] mbytes = new byte[4]; - data.get(mbytes); - this.nwSrcState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += 12; - int prefixlen = getNetworkMaskPrefixLength(mbytes); - this.wildcards ^= (((1 << 6) - 1) << 8); // Sync with 0F 1.0 Match - this.wildcards |= ((32 - prefixlen) << 8); // Sync with 0F 1.0 Match - } - } else { - if ((nxmLen != 4) || (data.remaining() < 4)) { - return; - } else { - byte[] sbytes = new byte[4]; - data.get(sbytes); - // For compatibility, let's also set the IPv4 in the parent OFMatch - int address = NetUtils.byteArray4ToInt(sbytes); - super.setNetworkSource(address); - this.nwSrcState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 8; - this.wildcards ^= (((1 << 6) - 1) << 8); // Sync with 0F 1.0 - // Match - } - } - } - - private void readIpv4Dst(ByteBuffer data, int nxmLen, boolean hasMask) { - if (hasMask) { - if ((nxmLen != 2 * 4) || (data.remaining() < 2 * 4)) { - return; - } else { - byte[] dbytes = new byte[4]; - data.get(dbytes); - // For compatibility, let's also set the IPv4 in the parent OFMatch - int address = NetUtils.byteArray4ToInt(dbytes); - super.setNetworkDestination(address); - byte[] mbytes = new byte[4]; - data.get(mbytes); - this.nwDstState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += 12; - int prefixlen = getNetworkMaskPrefixLength(mbytes); - this.wildcards ^= (((1 << 6) - 1) << 14); // Sync with 0F 1.0 - // Match - this.wildcards |= ((32 - prefixlen) << 14); // Sync with 0F 1.0 - // Match - } - } else { - if ((nxmLen != 4) || (data.remaining() < 4)) { - return; - } else { - byte[] dbytes = new byte[4]; - data.get(dbytes); - int address = NetUtils.byteArray4ToInt(dbytes); - super.setNetworkDestination(address); - this.nwDstState = MatchFieldState.MATCH_FIELD_ONLY; - this.wildcards ^= (((1 << 6) - 1) << 14); // Sync with 0F 1.0 - // Match - this.match_len += 8; - } - } - } - - private void readTcpSrc(ByteBuffer data, int nxmLen, boolean hasMask) { - /* - * mask is not allowed in TCP SRC - */ - if ((nxmLen != 2) || (data.remaining() < 2) || (hasMask)) { - return; - } - super.setTransportSource(data.getShort()); - this.tpSrcState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 6; - this.wildcards ^= (1 << 6); // Sync with 0F 1.0 Match - } - - private void readTcpDst(ByteBuffer data, int nxmLen, boolean hasMask) { - /* - * mask is not allowed in TCP DST - */ - if ((nxmLen != 2) || (data.remaining() < 2) || (hasMask)) { - return; - } - super.setTransportDestination(data.getShort()); - this.tpDstState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 6; - this.wildcards ^= (1 << 7); // Sync with 0F 1.0 Match - } - - private void readUdpSrc(ByteBuffer data, int nxmLen, boolean hasMask) { - /* - * mask is not allowed in UDP SRC - */ - if ((nxmLen != 2) || (data.remaining() < 2) || (hasMask)) { - return; - } - super.setTransportSource(data.getShort()); - this.tpSrcState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 6; - this.wildcards ^= (1 << 6); // Sync with 0F 1.0 Match - } - - private void readUdpDst(ByteBuffer data, int nxmLen, boolean hasMask) { - /* - * mask is not allowed in UDP DST - */ - if ((nxmLen != 2) || (data.remaining() < 2) || (hasMask)) { - return; - } - super.setTransportDestination(data.getShort()); - this.tpDstState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 6; - this.wildcards ^= (1 << 7); // Sync with 0F 1.0 Match - } - - private void readIpv6Src(ByteBuffer data, int nxmLen, boolean hasMask) { - if (hasMask) { - if ((nxmLen != 2 * 16) || (data.remaining() < 2 * 16)) { - return; - } else { - byte[] sbytes = new byte[16]; - data.get(sbytes); - try { - this.nwSrc = (Inet6Address) InetAddress.getByAddress(sbytes); - } catch (UnknownHostException e) { - return; - } - byte[] mbytes = new byte[16]; - data.get(mbytes); - this.srcIPv6SubnetMaskbits = (short)NetUtils.getSubnetMaskLength(mbytes); - this.nwSrcState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += 36; - } - } else { - if ((nxmLen != 16) || (data.remaining() < 16)) { - return; - } else { - byte[] sbytes = new byte[16]; - data.get(sbytes); - try { - this.nwSrc = (Inet6Address) InetAddress.getByAddress(sbytes); - } catch (UnknownHostException e) { - return; - } - this.nwSrcState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 20; - } - } - } - - private void readIpv6Dst(ByteBuffer data, int nxmLen, boolean hasMask) { - if (hasMask) { - if ((nxmLen != 2 * 16) || (data.remaining() < 2 * 16)) { - return; - } else { - byte[] dbytes = new byte[16]; - data.get(dbytes); - try { - this.nwDst = (Inet6Address) InetAddress.getByAddress(dbytes); - } catch (UnknownHostException e) { - return; - } - byte[] mbytes = new byte[16]; - data.get(mbytes); - this.dstIPv6SubnetMaskbits = (short)NetUtils.getSubnetMaskLength(mbytes); - this.nwDstState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += 36; - } - } else { - if ((nxmLen != 16) || (data.remaining() < 16)) { - return; - } else { - byte[] dbytes = new byte[16]; - data.get(dbytes); - try { - this.nwDst = (Inet6Address) InetAddress.getByAddress(dbytes); - } catch (UnknownHostException e) { - return; - } - this.nwDstState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 20; - } - } - } - - @Override - public String toString() { - return "V6Match [nwSrc=" + nwSrc + ", nwDst=" + nwDst - + ", inputPortMask=" + inputPortMask + ", dataLayerSourceMask=" - + HexEncode.bytesToHexStringFormat(dataLayerSourceMask) - + ", dataLayerDestinationMask=" - + HexEncode.bytesToHexStringFormat(dataLayerDestinationMask) - + ", dataLayerVirtualLanTCIMask=" + dataLayerVirtualLanTCIMask - + ", dataLayerTypeMask=" + dataLayerTypeMask - + ", networkTypeOfServiceMask=" + networkTypeOfServiceMask - + ", networkProtocolMask=" + networkProtocolMask - + ", transportSourceMask=" + transportSourceMask - + ", transportDestinationMask=" + transportDestinationMask - + ", srcIPv6SubnetMaskbits=" + srcIPv6SubnetMaskbits - + ", dstIPv6SubnetMaskbits=" + dstIPv6SubnetMaskbits - + ", inputPortState=" + inputPortState + ", dlSourceState=" - + dlSourceState + ", dlDestState=" + dlDestState - + ", dlVlanTCIState=" + dlVlanTCIState + ", ethTypeState=" - + ethTypeState + ", nwTosState=" + nwTosState - + ", nwProtoState=" + nwProtoState + ", nwSrcState=" - + nwSrcState + ", nwDstState=" + nwDstState + ", tpSrcState=" - + tpSrcState + ", tpDstState=" + tpDstState + ", match_len=" - + match_len + ", pad_size=" + pad_size + "]"; - } - - /** - * Read the data corresponding to the match field (received from the wire) - * Input: data: match field(s). Since match field is of variable length, the - * whole data that are passed in are assumed to fem0tbd.be the match fields. - * - * @param data - */ - @Override - public void readFrom(ByteBuffer data) { - readFromInternal(data); - postprocessWildCardInfo(); - } - - private void readFromInternal(ByteBuffer data) { - this.match_len = 0; - while (data.remaining() > 0) { - if (data.remaining() < 4) { - /* - * at least 4 bytes for each match header - */ - logger.error("Invalid Vendor Extension Header. Size {}", - data.remaining()); - return; - } - /* - * read the 4 byte match header - */ - int nxmVendor = data.getShort(); - int b = data.get(); - int nxmField = b >> 1; - boolean hasMask = ((b & 0x01) == 1) ? true : false; - int nxmLen = data.get(); - if (nxmVendor == Extension_Types.OF_10.getValue()) { - if (nxmField == OF_Match_Types.MATCH_OF_IN_PORT.getValue()) { - readInPort(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_ETH_DST - .getValue()) { - readDataLinkDestination(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_ETH_SRC - .getValue()) { - readDataLinkSource(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_ETH_TYPE - .getValue()) { - readEtherType(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_VLAN_TCI - .getValue()) { - readVlanTci(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_IP_TOS - .getValue()) { - readIpTos(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_IP_PROTO - .getValue()) { - readIpProto(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_IP_SRC - .getValue()) { - readIpv4Src(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_IP_DST - .getValue()) { - readIpv4Dst(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_TCP_SRC - .getValue()) { - readTcpSrc(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_TCP_DST - .getValue()) { - readTcpDst(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_UDP_SRC - .getValue()) { - readUdpSrc(data, nxmLen, hasMask); - } else if (nxmField == OF_Match_Types.MATCH_OF_UDP_DST - .getValue()) { - readUdpDst(data, nxmLen, hasMask); - } else { - // unexpected nxmField - return; - } - } else if (nxmVendor == Extension_Types.IPV6EXT.getValue()) { - if (nxmField == IPv6Extension_Match_Types.MATCH_IPV6EXT_IPV6_SRC - .getValue()) { - readIpv6Src(data, nxmLen, hasMask); - } else if (nxmField == IPv6Extension_Match_Types.MATCH_IPV6EXT_IPV6_DST - .getValue()) { - readIpv6Dst(data, nxmLen, hasMask); - } else { - // unexpected nxmField - return; - } - } else { - // invalid nxmVendor - return; - } - } - } - - private void postprocessWildCardInfo() { - // Sync with 0F 1.0 Match - if (super.getDataLayerType() == 0x800) { - if (((this.wildcards >> 8) & 0x3f) == 0x3f) { - // ipv4 src processing - this.wildcards ^= (((1 << 5) - 1) << 8); - } - if (((this.wildcards >> 14) & 0x3f) == 0x3f) { - // ipv4 dest processing - this.wildcards ^= (((1 << 5) - 1) << 14); - } - } - } - - @Override - public V6Match clone() { - - V6Match ret = (V6Match) super.clone(); - try { - if (this.nwSrc != null) { - ret.nwSrc = (Inet6Address) InetAddress.getByAddress(this.nwSrc.getAddress()); - } - if (this.nwDst != null) { - ret.nwDst = (Inet6Address) InetAddress.getByAddress(this.nwDst.getAddress()); - } - return ret; - } catch (UnknownHostException e) { - throw new RuntimeException(e); - } - } - - /** - * Get nw_dst - * - * @return - */ - public Inet6Address getNetworkDest() { - return this.nwDst; - } - - /** - * Set nw_src - * - * @return - */ - public Inet6Address getNetworkSrc() { - return this.nwSrc; - } - - private int getNetworkMaskPrefixLength(byte[] netMask) { - ByteBuffer nm = ByteBuffer.wrap(netMask); - int trailingZeros = Integer.numberOfTrailingZeros(nm.getInt()); - return 32 - trailingZeros; - } - - public short getInputPortMask() { - return inputPortMask; - } - - public void setInputPort(short port, short mask) { - super.inputPort = port; - this.inputPortState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 6; - // Looks like mask is not allowed for input port. Will discard it - } - - public byte[] getDataLayerSourceMask() { - return dataLayerSourceMask; - } - - public void setDataLayerSource(byte[] mac, byte[] mask) { - if (mac != null) { - System.arraycopy(mac, 0, super.dataLayerSource, 0, mac.length); - } - if (mask == null) { - this.dlSourceState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 10; - } else { - if (this.dataLayerSourceMask == null) { - this.dataLayerSourceMask = new byte[mask.length]; - } - System.arraycopy(mask, 0, this.dataLayerSourceMask, 0, mask.length); - this.dlSourceState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += 16; - } - } - - public byte[] getDataLayerDestinationMask() { - return dataLayerDestinationMask; - } - - public void setDataLayerDestination(byte[] mac, byte[] mask) { - if (mac != null) { - System.arraycopy(mac, 0, super.dataLayerDestination, 0, mac.length); - } - if (mask == null) { - this.dlDestState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 10; - } else { - if (this.dataLayerDestinationMask == null) { - this.dataLayerDestinationMask = new byte[mask.length]; - } - System.arraycopy(mask, 0, this.dataLayerDestinationMask, 0, - mask.length); - this.dlDestState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += 16; - } - } - - /** - * Set a value to VLAN ID match field. - * - * @param vlan A value to match for VLAN ID. - * @param mask A bitmask for VLAN ID. - */ - public void setDataLayerVirtualLan(short vlan, short mask) { - if (vlan == OFP_VLAN_NONE - && this.dlVlanIDState != MatchFieldState.MATCH_ABSENT) { - throw new IllegalStateException - ("DL_VLAN_PCP is set."); - } - - // mask is ignored as the code sets the appropriate mask - super.dataLayerVirtualLan = vlan; - this.dlVlanIDState = MatchFieldState.MATCH_FIELD_ONLY; - // the variable dlVlanIDState is not really used as a flag - // for serializing and deserializing. Rather it is used as a flag - // to check if the vlan id is being set so that we can set the - // dlVlanTCIState appropriately. - if (this.dlVlanPCPState != MatchFieldState.MATCH_ABSENT) { - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_ONLY; - match_len -= 2; - } else if (this.dataLayerVirtualLan == OFP_VLAN_NONE) { - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 6; - } else { - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.dataLayerVirtualLanTCIMask = 0x1fff; - match_len += 8; - } - } - - /** - * Set a value to VLAN PCP match field. - * - * @param pcp A value to match for VLAN PCP. - * @param mask A bitmask for VLAN PCP. - */ - public void setDataLayerVirtualLanPriorityCodePoint(byte pcp, byte mask) { - if (this.dlVlanIDState != MatchFieldState.MATCH_ABSENT - && this.dataLayerVirtualLan == OFP_VLAN_NONE) { - throw new IllegalStateException - ("OFP_VLAN_NONE is specified to DL_VLAN."); - } - - // mask is ignored as the code sets the appropriate mask - super.dataLayerVirtualLanPriorityCodePoint = pcp; - this.dlVlanPCPState = MatchFieldState.MATCH_FIELD_ONLY; - // the variable dlVlanPCPState is not really used as a flag - // for serializing and deserializing. Rather it is used as a flag - // to check if the vlan pcp is being set so that we can set the - // dlVlanTCIState appropriately. - if (this.dlVlanIDState != MatchFieldState.MATCH_ABSENT) { - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_ONLY; - match_len -= 2; - } else { - this.dlVlanTCIState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.dataLayerVirtualLanTCIMask = 0xf000; - match_len += 8; - } - } - - public void setDataLayerType(short ethType, short mask) { - // mask not allowed - super.dataLayerType = ethType; - this.ethTypeState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 6; - } - - public void setNetworkTypeOfService(byte tos, byte mask) { - // mask not allowed - super.networkTypeOfService = tos; - this.nwTosState = MatchFieldState.MATCH_FIELD_ONLY; - match_len += 5; - } - - public void setNetworkProtocol(byte ipProto, byte mask) { - // mask not allowed - super.networkProtocol = ipProto; - this.nwProtoState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 5; - } - - public Inet6Address getNetworkSourceMask() { - return (this.nwSrcState == MatchFieldState.MATCH_FIELD_WITH_MASK) ? (Inet6Address) NetUtils.getInetNetworkMask( - this.srcIPv6SubnetMaskbits, true) : null; - } - - public void setNetworkSource(InetAddress address, InetAddress mask) { - if (address instanceof Inet6Address) { - this.nwSrc = (Inet6Address) address; - if (mask == null) { - this.nwSrcState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += (address instanceof Inet6Address) ? 20 : 8; - } else { - this.srcIPv6SubnetMaskbits = (short)NetUtils.getSubnetMaskLength(mask); - this.nwSrcState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += (address instanceof Inet6Address) ? 36 : 12; - } - } else { - super.setNetworkSource(NetUtils.byteArray4ToInt(address.getAddress())); - this.wildcards ^= (((1 << 6) - 1) << 8); - if (mask == null) { - this.nwSrcState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 8; - } else { - this.nwSrcState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += 12; - this.wildcards |= ((32 - NetUtils.getSubnetMaskLength(mask)) << 8); - } - } - } - - public Inet6Address getNetworkDestinationMask() { - return (this.nwDstState == MatchFieldState.MATCH_FIELD_WITH_MASK) ? (Inet6Address) NetUtils.getInetNetworkMask( - this.dstIPv6SubnetMaskbits, true) : null; - } - - public void setNetworkDestination(InetAddress address, InetAddress mask) { - if (address instanceof Inet6Address) { - this.nwDst = (Inet6Address) address; - if (mask == null) { - this.nwDstState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += (address instanceof Inet6Address) ? 20 : 8; - } else { - this.dstIPv6SubnetMaskbits = (short)NetUtils.getSubnetMaskLength(mask); - this.nwDstState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += (address instanceof Inet6Address) ? 36 : 12; - } - } else { - this.setNetworkDestination(NetUtils.byteArray4ToInt(address.getAddress())); - this.wildcards ^= (((1 << 6) - 1) << 14); - if (mask == null) { - this.nwDstState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 8; - } else { - this.nwDstState = MatchFieldState.MATCH_FIELD_WITH_MASK; - this.match_len += 12; - this.wildcards |= ((32 - NetUtils.getSubnetMaskLength(mask)) << 14); - } - } - } - - public void setTransportSource(short tpSrc, short mask) { - // mask not allowed - super.transportSource = tpSrc; - this.tpSrcState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 6; - } - - public short getTransportDestinationMask() { - return transportDestinationMask; - } - - public void setTransportDestination(short tpDst, short mask) { - // mask not allowed - super.transportDestination = tpDst; - this.tpDstState = MatchFieldState.MATCH_FIELD_ONLY; - this.match_len += 6; - } - - private byte[] getIPv6NetworkMaskinBytes(short num) { - byte[] nbytes = new byte[16]; - int quot = num / 8; - int bits = num % 8; - int i; - - for (i = 0; i < quot; i++) { - nbytes[i] = (byte) 0xff; - } - - if (bits > 0) { - nbytes[i] = (byte) 0xff; - nbytes[i] <<= 8 - bits; - } - return nbytes; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + Arrays.hashCode(dataLayerDestinationMask); - result = prime * result + Arrays.hashCode(dataLayerSourceMask); - result = prime * result + dataLayerTypeMask; - result = prime * result + dataLayerVirtualLanTCIMask; - result = prime * result - + ((dlDestState == null) ? 0 : dlDestState.hashCode()); - result = prime * result - + ((dlSourceState == null) ? 0 : dlSourceState.hashCode()); - result = prime * result - + ((dlVlanTCIState == null) ? 0 : dlVlanTCIState.hashCode()); - result = prime * result + dstIPv6SubnetMaskbits; - result = prime * result - + ((ethTypeState == null) ? 0 : ethTypeState.hashCode()); - result = prime * result + inputPortMask; - result = prime * result - + ((inputPortState == null) ? 0 : inputPortState.hashCode()); - result = prime * result + match_len; - result = prime * result + networkProtocolMask; - result = prime * result + networkTypeOfServiceMask; - result = prime * result + ((nwDst == null) ? 0 : nwDst.hashCode()); - result = prime * result - + ((nwDstState == null) ? 0 : nwDstState.hashCode()); - result = prime * result - + ((nwProtoState == null) ? 0 : nwProtoState.hashCode()); - result = prime * result + ((nwSrc == null) ? 0 : nwSrc.hashCode()); - result = prime * result - + ((nwSrcState == null) ? 0 : nwSrcState.hashCode()); - result = prime * result - + ((nwTosState == null) ? 0 : nwTosState.hashCode()); - result = prime * result + pad_size; - result = prime * result + srcIPv6SubnetMaskbits; - result = prime * result - + ((tpDstState == null) ? 0 : tpDstState.hashCode()); - result = prime * result - + ((tpSrcState == null) ? 0 : tpSrcState.hashCode()); - result = prime * result + transportDestinationMask; - result = prime * result + transportSourceMask; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - V6Match other = (V6Match) obj; - if (!Arrays.equals(dataLayerDestinationMask, other.dataLayerDestinationMask)) { - return false; - } - if (!Arrays.equals(dataLayerSourceMask, other.dataLayerSourceMask)) { - return false; - } - if (dataLayerTypeMask != other.dataLayerTypeMask) { - return false; - } - if (dataLayerVirtualLanTCIMask != other.dataLayerVirtualLanTCIMask) { - return false; - } - if (dlVlanTCIState != other.dlVlanTCIState) { - return false; - } - if (dlSourceState != other.dlSourceState) { - return false; - } - if (dstIPv6SubnetMaskbits != other.dstIPv6SubnetMaskbits) { - return false; - } - if (ethTypeState != other.ethTypeState) { - return false; - } - if (inputPortMask != other.inputPortMask) { - return false; - } - if (inputPortState != other.inputPortState) { - return false; - } - if (match_len != other.match_len) { - return false; - } - if (networkProtocolMask != other.networkProtocolMask) { - return false; - } - if (networkTypeOfServiceMask != other.networkTypeOfServiceMask) { - return false; - } - if (nwDst == null) { - if (other.nwDst != null) { - return false; - } - } else if (!nwDst.equals(other.nwDst)) { - return false; - } - if (nwDstState != other.nwDstState) { - return false; - } - if (nwProtoState != other.nwProtoState) { - return false; - } - if (nwSrc == null) { - if (other.nwSrc != null) { - return false; - } - } else if (!nwSrc.equals(other.nwSrc)) { - return false; - } - if (nwSrcState != other.nwSrcState) { - return false; - } - if (nwTosState != other.nwTosState) { - return false; - } - if (pad_size != other.pad_size) { - return false; - } - if (srcIPv6SubnetMaskbits != other.srcIPv6SubnetMaskbits) { - return false; - } - if (tpDstState != other.tpDstState) { - return false; - } - if (tpSrcState != other.tpSrcState) { - return false; - } - if (transportDestinationMask != other.transportDestinationMask) { - return false; - } - if (transportSourceMask != other.transportSourceMask) { - return false; - } - return true; - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsReply.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsReply.java deleted file mode 100644 index 3ae19838a2..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsReply.java +++ /dev/null @@ -1,389 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension; - -import java.nio.ByteBuffer; -import java.util.List; - -import org.openflow.protocol.action.OFAction; -import org.openflow.protocol.statistics.OFVendorStatistics; -import org.openflow.util.U16; - -/** - * This Class processes the OpenFlow Vendor Extension Reply message of a Stats - * Request. It parses the reply message and initializes fields of V6StatsReply - * object. Multiple instances of this class objects are created and used by - * OpenDaylight's Troubleshooting Application. - * - */ - -public class V6StatsReply extends OFVendorStatistics { - private static final long serialVersionUID = 1L; - - public static int MINIMUM_LENGTH = 48; //48 for nx_flow_stats - - protected short length = (short) MINIMUM_LENGTH; - protected byte tableId; - protected int durationSeconds; - protected int durationNanoseconds; - protected short priority; - protected short idleTimeout; - protected short hardTimeout; - protected short match_len; - protected short idleAge; - protected short hardAge; - protected long cookie; - protected long packetCount; - protected long byteCount; - protected V6Match match; - protected List actions; - - /** - * @return vendor id - */ - public int getVendorId() { - return vendor; - } - - /** - * @param vendor the vendor to set - */ - public void setVendorId(int vendor) { - this.vendor = vendor; - } - - /** - * @return the tableId - */ - public byte getTableId() { - return tableId; - } - - /** - * @param tableId the tableId to set - */ - public void setTableId(byte tableId) { - this.tableId = tableId; - } - - /** - * @return the durationSeconds - */ - public int getDurationSeconds() { - return durationSeconds; - } - - /** - * @param durationSeconds the durationSeconds to set - */ - public void setDurationSeconds(int durationSeconds) { - this.durationSeconds = durationSeconds; - } - - /** - * @return the durationNanoseconds - */ - public int getDurationNanoseconds() { - return durationNanoseconds; - } - - /** - * @param durationNanoseconds the durationNanoseconds to set - */ - public void setDurationNanoseconds(int durationNanoseconds) { - this.durationNanoseconds = durationNanoseconds; - } - - /** - * @return the priority - */ - public short getPriority() { - return priority; - } - - /** - * @param priority the priority to set - */ - public void setPriority(short priority) { - this.priority = priority; - } - - /** - * @return the idleTimeout - */ - public short getIdleTimeout() { - return idleTimeout; - } - - /** - * @param idleTimeout the idleTimeout to set - */ - public void setIdleTimeout(short idleTimeout) { - this.idleTimeout = idleTimeout; - } - - /** - * @return the hardTimeout - */ - public short getHardTimeout() { - return hardTimeout; - } - - /** - * @param hardTimeout the hardTimeout to set - */ - public void setHardTimeout(short hardTimeout) { - this.hardTimeout = hardTimeout; - } - - /** - * @param match_len the match_len to set - */ - public void setMatchLen(short match_len) { - this.match_len = match_len; - } - - /** - * @return the match_len - */ - public short getMatchLen() { - return match_len; - } - - /** - * @return the idleAge - */ - public short getIdleAge() { - return idleAge; - } - - /** - * @param idleAge the idleAge to set - */ - public void setIdleAge(short idleAge) { - this.idleAge = idleAge; - } - - /** - * @return the hardAge - */ - public short getHardAge() { - return hardAge; - } - - /** - * @param hardAge the hardAge to set - */ - public void setHardAge(short hardAge) { - this.hardAge = hardAge; - } - - /** - * @return the cookie - */ - public long getCookie() { - return cookie; - } - - /** - * @param cookie the cookie to set - */ - public void setCookie(long cookie) { - this.cookie = cookie; - } - - /** - * @return the packetCount - */ - public long getPacketCount() { - return packetCount; - } - - /** - * @param packetCount the packetCount to set - */ - public void setPacketCount(long packetCount) { - this.packetCount = packetCount; - } - - /** - * @return the byteCount - */ - public long getByteCount() { - return byteCount; - } - - /** - * @param byteCount the byteCount to set - */ - public void setByteCount(long byteCount) { - this.byteCount = byteCount; - } - - /** - * @param length the length to set - */ - public void setLength(short length) { - this.length = length; - } - - @Override - public int getLength() { - return U16.f(length); - } - - /** - * @return the match - */ - public V6Match getMatch() { - return match; - } - - /** - * @return the actions - */ - public List getActions() { - return actions; - } - - /** - * @param actions the actions to set - */ - public void setActions(List actions) { - this.actions = actions; - } - - @Override - public void readFrom(ByteBuffer data) { - short i; - this.length = data.getShort(); - if (length < MINIMUM_LENGTH) - return; //TBD - Spurious Packet? - this.tableId = data.get(); - data.get(); // pad - this.durationSeconds = data.getInt(); - this.durationNanoseconds = data.getInt(); - this.priority = data.getShort(); - this.idleTimeout = data.getShort(); - this.hardTimeout = data.getShort(); - this.match_len = data.getShort(); - this.idleAge = data.getShort(); - this.hardAge = data.getShort(); - this.cookie = data.getLong(); - this.packetCount = data.getLong(); - this.byteCount = data.getLong(); - if (this.length == MINIMUM_LENGTH) { - return; //TBD - can this happen?? - } - if (this.match == null) - this.match = new V6Match(); - ByteBuffer mbuf = ByteBuffer.allocate(match_len); - for (i = 0; i < match_len; i++) { - mbuf.put(data.get()); - } - mbuf.rewind(); - this.match.readFrom(mbuf); - if (this.actionFactory == null) - throw new RuntimeException("OFActionFactory not set"); - /* - * action list may be preceded by a padding of 0 to 7 bytes based upon this: - */ - short pad_size = (short) (((match_len + 7) / 8) * 8 - match_len); - for (i = 0; i < pad_size; i++) { - data.get(); - } - int action_len = this.length - MINIMUM_LENGTH - (match_len + pad_size); - if (action_len > 0) - this.actions = this.actionFactory.parseActions(data, action_len); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((actions == null) ? 0 : actions.hashCode()); - result = prime * result + (int) (byteCount ^ (byteCount >>> 32)); - result = prime * result + (int) (cookie ^ (cookie >>> 32)); - result = prime * result + durationNanoseconds; - result = prime * result + durationSeconds; - result = prime * result + hardAge; - result = prime * result + hardTimeout; - result = prime * result + idleAge; - result = prime * result + idleTimeout; - result = prime * result + length; - result = prime * result + ((match == null) ? 0 : match.hashCode()); - result = prime * result + match_len; - result = prime * result + (int) (packetCount ^ (packetCount >>> 32)); - result = prime * result + priority; - result = prime * result + tableId; - return result; - } - - @Override - public String toString() { - return "V6StatsReply [length=" + length + ", tableId=" + tableId - + ", durationSeconds=" + durationSeconds - + ", durationNanoseconds=" + durationNanoseconds - + ", priority=" + priority + ", idleTimeout=" + idleTimeout - + ", hardTimeout=" + hardTimeout + ", match_len=" + match_len - + ", idleAge=" + idleAge + ", hardAge=" + hardAge + ", cookie=" - + cookie + ", packetCount=" + packetCount + ", byteCount=" - + byteCount + ", match=" + match + ", actions=" + actions + "]"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - V6StatsReply other = (V6StatsReply) obj; - if (actions == null) { - if (other.actions != null) - return false; - } else if (!actions.equals(other.actions)) - return false; - if (byteCount != other.byteCount) - return false; - if (cookie != other.cookie) - return false; - if (durationNanoseconds != other.durationNanoseconds) - return false; - if (durationSeconds != other.durationSeconds) - return false; - if (hardAge != other.hardAge) - return false; - if (hardTimeout != other.hardTimeout) - return false; - if (idleAge != other.idleAge) - return false; - if (idleTimeout != other.idleTimeout) - return false; - if (length != other.length) - return false; - if (match == null) { - if (other.match != null) - return false; - } else if (!match.equals(other.match)) - return false; - if (match_len != other.match_len) - return false; - if (packetCount != other.packetCount) - return false; - if (priority != other.priority) - return false; - if (tableId != other.tableId) - return false; - return true; - } - -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsRequest.java b/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsRequest.java deleted file mode 100644 index d9c460b32e..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6StatsRequest.java +++ /dev/null @@ -1,178 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension; - -import java.nio.ByteBuffer; - -import org.openflow.protocol.statistics.OFVendorStatistics; - - -/** - * This Class creates the OpenFlow Vendor Extension IPv6 Flow Stats Request - * messages and also reads the Reply of a stats request message. - * - */ - -public class V6StatsRequest extends OFVendorStatistics { - private static final long serialVersionUID = 1L; - protected int msgsubtype; - protected short outPort; - protected short match_len; - protected byte tableId; - - public static final int NICIRA_VENDOR_ID = 0x00002320; //Nicira ID - private static final int NXST_FLOW = 0x0; //Nicira Flow Stats Request Id - - public V6StatsRequest() { - this.vendor = NICIRA_VENDOR_ID; - this.msgsubtype = NXST_FLOW; - this.match_len = 0; - } - - /** - * @param None. Being set with local variable (TBD). - */ - public void setVendorId() { - this.vendor = NICIRA_VENDOR_ID; - } - - /** - * @return vendor id - */ - public int getVendorId() { - return vendor; - } - - /** - * @param None. Being set with local variable (TBD). - */ - public void setMsgtype() { - this.msgsubtype = NXST_FLOW; - } - - /** - * @return vendor_msgtype - */ - public int getMsgtype() { - return msgsubtype; - } - - /** - * @param outPort the outPort to set - */ - public void setOutPort(short outPort) { - this.outPort = outPort; - } - - /** - * @return the outPort - */ - public short getOutPort() { - return outPort; - } - - /** - * @param match_len the match_len to set - */ - public void setMatchLen(short match_len) { - this.match_len = match_len; - } - - /** - * @return the match_len - */ - public short getMatchLen() { - return match_len; - } - - /** - * @param tableId the tableId to set - */ - public void setTableId(byte tableId) { - this.tableId = tableId; - } - - /** - * @return the tableId - */ - public byte getTableId() { - return tableId; - } - - @Override - public int getLength() { - return 20;// 4(vendor)+4(msgsubtype)+4(pad)+2(outPort)+2(match_len)+1(tableid)+3(pad) - } - - @Override - public void readFrom(ByteBuffer data) { - this.vendor = data.getInt(); - this.msgsubtype = data.getInt(); - data.getInt();//pad 4 bytes - this.outPort = data.getShort(); - this.match_len = data.getShort(); - this.tableId = data.get(); - for (int i = 0; i < 3; i++) { - data.get();//pad byte - } - - } - - @Override - public void writeTo(ByteBuffer data) { - data.putInt(this.vendor); - data.putInt(this.msgsubtype); - data.putInt((int) 0x0);//pad0 - data.putShort(this.outPort); - data.putShort(this.match_len); - data.put(this.tableId); - for (int i = 0; i < 3; i++) { - data.put((byte) 0x0);//pad byte - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + match_len; - result = prime * result + msgsubtype; - result = prime * result + outPort; - result = prime * result + tableId; - return result; - } - - @Override - public String toString() { - return "V6StatsRequest [msgsubtype=" + msgsubtype + ", outPort=" - + outPort + ", match_len=" + match_len + ", tableId=" + tableId - + "]"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - V6StatsRequest other = (V6StatsRequest) obj; - if (match_len != other.match_len) - return false; - if (msgsubtype != other.msgsubtype) - return false; - if (outPort != other.outPort) - return false; - if (tableId != other.tableId) - return false; - return true; - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerServiceTest.java b/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerServiceTest.java deleted file mode 100644 index 96f0d80022..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/internal/FlowProgrammerServiceTest.java +++ /dev/null @@ -1,417 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6Match; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.Flood; -import org.opendaylight.controller.sal.action.FloodAll; -import org.opendaylight.controller.sal.action.HwPath; -import org.opendaylight.controller.sal.action.Loopback; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.action.PopVlan; -import org.opendaylight.controller.sal.action.SetDlDst; -import org.opendaylight.controller.sal.action.SetDlSrc; -import org.opendaylight.controller.sal.action.SetNwDst; -import org.opendaylight.controller.sal.action.SetNwSrc; -import org.opendaylight.controller.sal.action.SetNwTos; -import org.opendaylight.controller.sal.action.SetTpDst; -import org.opendaylight.controller.sal.action.SetTpSrc; -import org.opendaylight.controller.sal.action.SetVlanId; -import org.opendaylight.controller.sal.action.SwPath; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.openflow.protocol.OFMatch; -import org.openflow.protocol.action.OFAction; -import org.openflow.util.U32; - -public class FlowProgrammerServiceTest { - - @Test - public void testSALtoOFFlowConverter() throws UnknownHostException { - Node node = NodeCreator.createOFNode(1000L); - NodeConnector port = NodeConnectorCreator.createNodeConnector( - (short) 24, node); - NodeConnector oport = NodeConnectorCreator.createNodeConnector( - (short) 30, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, - (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, - (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress.getByName("172.28.30.50"); - InetAddress dstIP = InetAddress.getByName("171.71.9.52"); - InetAddress ipMask = InetAddress.getByName("255.255.255.0"); - short ethertype = EtherTypes.IPv4.shortValue(); - short vlan = (short) 27; - byte vlanPr = 3; - Byte tos = 4; - byte proto = IPProtocols.TCP.byteValue(); - short src = (short) 55000; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(MatchType.IN_PORT, port); - match.setField(MatchType.DL_SRC, srcMac); - match.setField(MatchType.DL_DST, dstMac); - match.setField(MatchType.DL_TYPE, ethertype); - match.setField(MatchType.DL_VLAN, vlan); - match.setField(MatchType.DL_VLAN_PR, vlanPr); - match.setField(MatchType.NW_SRC, srcIP, ipMask); - match.setField(MatchType.NW_DST, dstIP, ipMask); - match.setField(MatchType.NW_TOS, tos); - match.setField(MatchType.NW_PROTO, proto); - match.setField(MatchType.TP_SRC, src); - match.setField(MatchType.TP_DST, dst); - - Assert.assertTrue(match.isIPv4()); - - List actions = new ArrayList(); - // Setting all the actions supported by of - actions.add(new PopVlan()); - actions.add(new Output(oport)); - actions.add(new Flood()); - actions.add(new FloodAll()); - actions.add(new SwPath()); - actions.add(new HwPath()); - actions.add(new Loopback()); - byte mac[] = { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5 }; - actions.add(new SetDlSrc(mac)); - actions.add(new SetDlDst(mac)); - actions.add(new SetNwSrc(dstIP)); - actions.add(new SetNwDst(srcIP)); - actions.add(new SetNwTos(3)); - actions.add(new SetTpSrc(10)); - actions.add(new SetTpDst(20)); - actions.add(new SetVlanId(200)); - - Flow aFlow = new Flow(match, actions); - - /* - * Convert the SAL aFlow to OF Flow - */ - FlowConverter salToOF = new FlowConverter(aFlow); - OFMatch ofMatch = salToOF.getOFMatch(); - List ofActions = salToOF.getOFActions(); - - /* - * Convert the OF Flow to SAL Flow bFlow - */ - FlowConverter ofToSal = new FlowConverter(ofMatch, ofActions); - Flow bFlow = ofToSal.getFlow(node); - Match bMatch = bFlow.getMatch(); - List bActions = bFlow.getActions(); - - /* - * Verify the converted SAL flow bFlow is equivalent to the original SAL Flow - */ - Assert.assertTrue(((NodeConnector) match.getField(MatchType.IN_PORT) - .getValue()).equals(((NodeConnector) bMatch.getField( - MatchType.IN_PORT).getValue()))); - Assert.assertTrue(Arrays.equals((byte[]) match.getField( - MatchType.DL_SRC).getValue(), (byte[]) bMatch.getField( - MatchType.DL_SRC).getValue())); - Assert.assertTrue(Arrays.equals((byte[]) match.getField( - MatchType.DL_DST).getValue(), (byte[]) bMatch.getField( - MatchType.DL_DST).getValue())); - Assert - .assertTrue(((Short) match.getField(MatchType.DL_TYPE) - .getValue()).equals((Short) bMatch.getField( - MatchType.DL_TYPE).getValue())); - Assert - .assertTrue(((Short) match.getField(MatchType.DL_VLAN) - .getValue()).equals((Short) bMatch.getField( - MatchType.DL_VLAN).getValue())); - Assert.assertTrue(((Byte) match.getField(MatchType.DL_VLAN_PR) - .getValue()).equals((Byte) bMatch - .getField(MatchType.DL_VLAN_PR).getValue())); - Assert.assertTrue(((InetAddress) match.getField(MatchType.NW_SRC) - .getValue()).equals((InetAddress) bMatch.getField( - MatchType.NW_SRC).getValue())); - Assert.assertTrue(((InetAddress) match.getField(MatchType.NW_SRC) - .getMask()).equals((InetAddress) bMatch.getField( - MatchType.NW_SRC).getMask())); - Assert.assertTrue(((InetAddress) match.getField(MatchType.NW_DST) - .getValue()).equals((InetAddress) bMatch.getField( - MatchType.NW_DST).getValue())); - Assert.assertTrue(((InetAddress) match.getField(MatchType.NW_DST) - .getMask()).equals((InetAddress) bMatch.getField( - MatchType.NW_DST).getMask())); - Assert - .assertTrue(((Byte) match.getField(MatchType.NW_PROTO) - .getValue()).equals((Byte) bMatch.getField( - MatchType.NW_PROTO).getValue())); - Assert.assertTrue(((Byte) match.getField(MatchType.NW_TOS).getValue()) - .equals((Byte) bMatch.getField(MatchType.NW_TOS).getValue())); - Assert.assertTrue(((Short) match.getField(MatchType.TP_SRC).getValue()) - .equals((Short) bMatch.getField(MatchType.TP_SRC).getValue())); - Assert.assertTrue(((Short) match.getField(MatchType.TP_DST).getValue()) - .equals((Short) bMatch.getField(MatchType.TP_DST).getValue())); - - // FlowConverter parses and sets the actions in the same order for sal match and of match - for (short i = 0; i < actions.size(); i++) { - Assert.assertTrue(actions.get(i).equals(bActions.get(i))); - } - } - - @Test - public void testVlanNoneIdFlowConversion() throws Exception { - Node node = NodeCreator.createOFNode(1000L); - - /* - * The value 0 is used to indicate that no VLAN ID is set - * for SAL Flow. - */ - short vlan = (short) 0; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(MatchType.DL_VLAN, vlan); - - List actions = new ArrayList(); - - Flow aFlow = new Flow(match, actions); - - /* - * Convert the SAL aFlow to OF Flow - */ - FlowConverter salToOF = new FlowConverter(aFlow); - OFMatch ofMatch = salToOF.getOFMatch(); - List ofActions = salToOF.getOFActions(); - - /* - * The value 0xffff (OFP_VLAN_NONE) is used to indicate - * that no VLAN ID is set for OF Flow. - */ - Assert.assertEquals((short) 0xffff, ofMatch.getDataLayerVirtualLan()); - - /* - * Convert the OF Flow to SAL Flow bFlow - */ - FlowConverter ofToSal = new FlowConverter(ofMatch, ofActions); - Flow bFlow = ofToSal.getFlow(node); - Match bMatch = bFlow.getMatch(); - - /* - * Verify the converted SAL flow bFlow is equivalent to the original SAL Flow - */ - Assert - .assertTrue(((Short) match.getField(MatchType.DL_VLAN) - .getValue()).equals((Short) bMatch.getField( - MatchType.DL_VLAN).getValue())); - } - - @Test - public void testV6toSALFlowConversion() throws Exception { - Node node = NodeCreator.createOFNode(12L); - NodeConnector port = NodeConnectorCreator.createNodeConnector( - (short) 34, node); - NodeConnector oport = NodeConnectorCreator.createNodeConnector( - (short) 30, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, - (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, - (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress - .getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress - .getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMask = InetAddress - .getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27; - byte vlanPr = 3; - Byte tos = 4; - byte proto = IPProtocols.TCP.byteValue(); - short src = (short) 55000; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match aMatch = new Match(); - - aMatch.setField(MatchType.IN_PORT, port); - aMatch.setField(MatchType.DL_SRC, srcMac); - aMatch.setField(MatchType.DL_DST, dstMac); - aMatch.setField(MatchType.DL_TYPE, ethertype); - aMatch.setField(MatchType.DL_VLAN, vlan); - aMatch.setField(MatchType.DL_VLAN_PR, vlanPr); - aMatch.setField(MatchType.NW_SRC, srcIP, ipMask); - aMatch.setField(MatchType.NW_DST, dstIP, ipMask); - aMatch.setField(MatchType.NW_TOS, tos); - aMatch.setField(MatchType.NW_PROTO, proto); - aMatch.setField(MatchType.TP_SRC, src); - aMatch.setField(MatchType.TP_DST, dst); - - Assert.assertTrue(aMatch.isIPv6()); - - List actions = new ArrayList(); - // Setting all the actions supported by of for v6 - actions.add(new PopVlan()); - actions.add(new Output(oport)); - actions.add(new Flood()); - actions.add(new FloodAll()); - actions.add(new SwPath()); - actions.add(new HwPath()); - actions.add(new Loopback()); - byte mac[] = { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5 }; - actions.add(new SetDlSrc(mac)); - actions.add(new SetDlDst(mac)); - //actions.add(new SetNwSrc(dstIP)); Nicira extensions do not provide IPv6 match addresses change - //actions.add(new SetNwDst(srcIP)); - actions.add(new SetNwTos(3)); - actions.add(new SetTpSrc(10)); - actions.add(new SetTpDst(65535)); - actions.add(new SetVlanId(200)); - - Flow aFlow = new Flow(aMatch, actions); - - /* - * Convert the SAL aFlow to OF Flow - */ - FlowConverter salToOF = new FlowConverter(aFlow); - V6Match v6Match = (V6Match) salToOF.getOFMatch(); - // need this hardcoding here to make the test pass. - // this should not be a problem in actual code. - // in the test the sal match is converted to a V6 match. - // we lose the wildcard info as the V6 match is used for nicira extensions - // and nicira deals with wildcards in a different way. - // converting the V6 match back to sal match is not going to preserve the wildcard info. - // and we need the wildcard info for reading the vlan pcp now. - // when creating a V6Match using the readFrom method - // we do convert the nicira extensions format correctly to populate the wildcard info. - v6Match.setWildcards(U32.t(Long.valueOf(~OFMatch.OFPFW_DL_VLAN_PCP))); - List ofActions = salToOF.getOFActions(); - - /* - * Convert the OF Flow to SAL Flow bFlow - */ - FlowConverter ofToSal = new FlowConverter(v6Match, ofActions); - Flow bFlow = ofToSal.getFlow(node); - Match bMatch = bFlow.getMatch(); - List bActions = bFlow.getActions(); - - /* - * Verify the converted SAL flow bFlow is equivalent to the original SAL Flow - */ - Assert.assertTrue(((NodeConnector) aMatch.getField(MatchType.IN_PORT) - .getValue()).equals(((NodeConnector) bMatch.getField( - MatchType.IN_PORT).getValue()))); - Assert.assertTrue(Arrays.equals((byte[]) aMatch.getField( - MatchType.DL_SRC).getValue(), (byte[]) bMatch.getField( - MatchType.DL_SRC).getValue())); - Assert.assertTrue(Arrays.equals((byte[]) aMatch.getField( - MatchType.DL_DST).getValue(), (byte[]) bMatch.getField( - MatchType.DL_DST).getValue())); - Assert.assertTrue(((Short) aMatch.getField(MatchType.DL_TYPE) - .getValue()).equals((Short) bMatch.getField(MatchType.DL_TYPE) - .getValue())); - Assert.assertTrue(((Short) aMatch.getField(MatchType.DL_VLAN) - .getValue()).equals((Short) bMatch.getField(MatchType.DL_VLAN) - .getValue())); - Assert.assertTrue(((Byte) aMatch.getField(MatchType.DL_VLAN_PR) - .getValue()).equals((Byte) bMatch - .getField(MatchType.DL_VLAN_PR).getValue())); - Assert.assertTrue(((InetAddress) aMatch.getField(MatchType.NW_SRC) - .getValue()).equals((InetAddress) bMatch.getField( - MatchType.NW_SRC).getValue())); - Assert.assertTrue(((InetAddress) aMatch.getField(MatchType.NW_SRC) - .getMask()).equals((InetAddress) bMatch.getField( - MatchType.NW_SRC).getMask())); - Assert.assertTrue(((InetAddress) aMatch.getField(MatchType.NW_DST) - .getValue()).equals((InetAddress) bMatch.getField( - MatchType.NW_DST).getValue())); - Assert.assertTrue(((InetAddress) aMatch.getField(MatchType.NW_DST) - .getMask()).equals((InetAddress) bMatch.getField( - MatchType.NW_DST).getMask())); - Assert.assertTrue(((Byte) aMatch.getField(MatchType.NW_PROTO) - .getValue()).equals((Byte) bMatch.getField(MatchType.NW_PROTO) - .getValue())); - Assert.assertTrue(((Byte) aMatch.getField(MatchType.NW_TOS).getValue()) - .equals((Byte) bMatch.getField(MatchType.NW_TOS).getValue())); - Assert - .assertTrue(((Short) aMatch.getField(MatchType.TP_SRC) - .getValue()).equals((Short) bMatch.getField( - MatchType.TP_SRC).getValue())); - Assert - .assertTrue(((Short) aMatch.getField(MatchType.TP_DST) - .getValue()).equals((Short) bMatch.getField( - MatchType.TP_DST).getValue())); - - // FlowConverter parses and sets the actions in the same order for sal match and of match - for (short i = 0; i < actions.size(); i++) { - Assert.assertTrue(actions.get(i).equals(bActions.get(i))); - } - } - - @Test - public void testV6MatchToSALMatchToV6MatchConversion() - throws UnknownHostException { - NodeConnector port = NodeConnectorCreator.createNodeConnector( - (short) 24, NodeCreator.createOFNode(6L)); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, - (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, - (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress - .getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress - .getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMask = null;//InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27; - byte vlanPr = 3; - Byte tos = 4; - byte proto = IPProtocols.TCP.byteValue(); - short src = (short) 55000; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match aMatch = new Match(); - - aMatch.setField(MatchType.IN_PORT, port); - aMatch.setField(MatchType.DL_SRC, srcMac); - aMatch.setField(MatchType.DL_DST, dstMac); - aMatch.setField(MatchType.DL_TYPE, ethertype); - aMatch.setField(MatchType.DL_VLAN, vlan); - aMatch.setField(MatchType.DL_VLAN_PR, vlanPr); - aMatch.setField(MatchType.NW_SRC, srcIP, ipMask); - aMatch.setField(MatchType.NW_DST, dstIP, ipMask); - aMatch.setField(MatchType.NW_TOS, tos); - aMatch.setField(MatchType.NW_PROTO, proto); - aMatch.setField(MatchType.TP_SRC, src); - aMatch.setField(MatchType.TP_DST, dst); - - Assert.assertTrue(aMatch.isIPv6()); - - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6ExtensionTest.java b/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6ExtensionTest.java deleted file mode 100644 index abbc43809d..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6ExtensionTest.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension; - -import static org.junit.Assert.fail; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.util.Arrays; - -import org.junit.Assert; -import org.junit.Test; -import org.openflow.protocol.OFMatch; -import org.openflow.util.U32; - -public class V6ExtensionTest { - - @Test - public void testFromString() throws UnknownHostException { - // This tests creating V6Match using fromString and OFMatch by comparing - // the results to each other - V6Match match = new V6Match(); - V6Match match2 = new V6Match(); - - OFMatch ofm = new OFMatch(); - V6Match match4 = new V6Match(ofm); - - match.fromString(""); - Assert.assertTrue(match.equals(match2)); - match.fromString("any"); - Assert.assertTrue(match.equals(match2)); - Assert.assertTrue(match.equals(match4)); - try { - match.fromString("invalidArgument"); - - fail("Did not throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // passed test for throwing exception. - } - try { - match.fromString("invalidParameter=abcdefg"); - fail("Did not throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // passed test for throwing exception. - } - - match.fromString("input_port=1"); - match.fromString("dl_dst=20:A0:11:10:00:99"); - match.fromString("dl_src=00:10:08:22:12:75"); - match.fromString("ip_src=10.1.1.1"); - match.fromString("ip_dst=1.2.3.4"); - match.fromString("eth_type=0x800"); - match.fromString("dl_vlan=10"); - match.fromString("nw_proto=6"); - match.fromString("nw_tos=100"); - match.fromString("tp_dst=8080"); - match.fromString("tp_src=60"); - match.fromString("dl_vpcp=1"); - - Assert.assertTrue(match.getInputPort() == 1); - // Assert.assertTrue(match.getIPv6MatchLen()==6); - ofm.setInputPort((short) 1); - // V6Match is meant for IPv6, but if using OFMatch, it will be set to - // IPv4 values, as OF1.0 doesn't support IPv6. - InetAddress addr = InetAddress.getByName("10.1.1.1"); - int ipsrc = ByteBuffer.wrap(addr.getAddress()).getInt(); - ofm.setNetworkSource(ipsrc); - - addr = InetAddress.getByName("1.2.3.4"); - int ipdst = ByteBuffer.wrap(addr.getAddress()).getInt(); - ofm.setNetworkDestination(ipdst); - - byte[] macSrc = { 0x00, 0x10, 0x08, 0x22, 0x12, 0x75 }; - ofm.setDataLayerSource(macSrc); - byte[] macDst = { 0x20, (byte) 0xA0, 0x11, 0x10, 0x00, (byte) 0x99 }; - ofm.setDataLayerDestination(macDst); - ofm.setDataLayerType((short) 0x800); - ofm.setDataLayerVirtualLan((short) 10); - ofm.setDataLayerVirtualLanPriorityCodePoint((byte) 1); - ofm.setNetworkProtocol((byte) 6); - ofm.setNetworkTypeOfService((byte) 100); - ofm.setTransportSource((short) 60); - ofm.setTransportDestination((short) 8080); - - // this v6match ctor now looks at the wildcard field to - // determine if vlan pcp has been set - // so set the wildcards appropriately to reflect that vlan pcp - // has been set. - int wildcards = OFMatch.OFPFW_ALL; - wildcards &= ~OFMatch.OFPFW_DL_VLAN_PCP; - ofm.setWildcards(U32.t(Long.valueOf(wildcards))); - V6Match match3 = new V6Match(ofm); - - Assert.assertTrue(match.getInputPort() == match3.getInputPort()); - Assert.assertTrue(Arrays.equals(match.getDataLayerSource(), - match3.getDataLayerSource())); - Assert.assertTrue(Arrays.equals(match.getDataLayerDestination(), - match3.getDataLayerDestination())); - Assert.assertNull(match.getNetworkSrc()); - Assert.assertNull(match3.getNetworkSrc()); - Assert.assertNull(match.getNetworkDest()); - Assert.assertNull(match3.getNetworkDest()); - Assert.assertTrue(match.getDataLayerVirtualLan() == match3 - .getDataLayerVirtualLan()); - Assert.assertTrue(match.getDataLayerVirtualLanPriorityCodePoint() == match3 - .getDataLayerVirtualLanPriorityCodePoint()); - Assert.assertTrue(match.getNetworkProtocol() == match3 - .getNetworkProtocol()); - Assert.assertTrue(match.getNetworkTypeOfService() == match3 - .getNetworkTypeOfService()); - Assert.assertTrue(match.getTransportSource() == match3 - .getTransportSource()); - Assert.assertTrue(match.getTransportDestination() == match3 - .getTransportDestination()); - Assert.assertTrue(match.getWildcards() == match3.getWildcards()); - - } - - @Test - public void testReadWriteBuffer() { - V6Match match = new V6Match(); - match.fromString("input_port=1"); - match.fromString("dl_dst=20:A0:11:10:00:99"); - match.fromString("dl_src=00:10:08:22:12:75"); - // writeTo(ByteBuffer) will only write IPv6 - match.fromString("ip_src=2001:ddd:3e1:1234:0000:1111:2222:3333/64"); - match.fromString("ip_dst=2001:123:222:abc:111:aaa:1111:2222/64"); - match.fromString("dl_vlan=10"); - match.fromString("dl_vpcp=1"); - match.fromString("nw_proto=6"); - match.fromString("nw_tos=100"); - match.fromString("tp_dst=8080"); - match.fromString("tp_src=60"); - match.fromString("dl_type=0x800"); - - ByteBuffer data = ByteBuffer.allocateDirect(10000); - match.writeTo(data); - data.flip(); - V6Match match2 = new V6Match(); - match2.readFrom(data); - Assert.assertTrue(match.getInputPort() == match2.getInputPort()); - Assert.assertTrue(Arrays.equals(match.getDataLayerSource(), - match2.getDataLayerSource())); - Assert.assertTrue(Arrays.equals(match.getDataLayerDestination(), - match2.getDataLayerDestination())); - - Assert.assertTrue(match.getNetworkSrc().equals(match2.getNetworkSrc())); - Assert.assertTrue(match.getNetworkDest() - .equals(match2.getNetworkDest())); - - Assert.assertTrue(match.getDataLayerVirtualLan() == match2 - .getDataLayerVirtualLan()); - Assert.assertTrue(match.getDataLayerVirtualLanPriorityCodePoint() == match2 - .getDataLayerVirtualLanPriorityCodePoint()); - Assert.assertTrue(match.getNetworkProtocol() == match2 - .getNetworkProtocol()); - Assert.assertTrue(match.getNetworkTypeOfService() == match2 - .getNetworkTypeOfService()); - Assert.assertTrue(match.getTransportSource() == match2 - .getTransportSource()); - Assert.assertTrue(match.getTransportDestination() == match2 - .getTransportDestination()); - - } - - @Test - public void testClone() { - V6Match match = new V6Match(); - match.fromString("input_port=1"); - match.fromString("dl_dst=20:A0:11:10:00:99"); - match.fromString("dl_src=00:10:08:22:12:75"); - match.fromString("ip_src=2001:ddd:3e1:1234:0000:1111:2222:3333/64"); - match.fromString("ip_dst=2001:123:222:abc:111:aaa:1111:2222/64"); - match.fromString("dl_vlan=10"); - match.fromString("dl_vpcp=1"); - match.fromString("nw_proto=6"); - match.fromString("nw_tos=100"); - match.fromString("tp_dst=8080"); - match.fromString("tp_src=60"); - match.fromString("dl_type=0x800"); - - V6Match match2 = match.clone(); - Assert.assertTrue(match.getInputPort() == match2.getInputPort()); - Assert.assertTrue(Arrays.equals(match.getDataLayerSource(), - match2.getDataLayerSource())); - Assert.assertTrue(Arrays.equals(match.getDataLayerDestination(), - match2.getDataLayerDestination())); - Assert.assertTrue(match.getNetworkSrc().equals(match2.getNetworkSrc())); - Assert.assertTrue(match.getNetworkDest() - .equals(match2.getNetworkDest())); - Assert.assertTrue(match.getDataLayerVirtualLan() == match2 - .getDataLayerVirtualLan()); - Assert.assertTrue(match.getDataLayerVirtualLanPriorityCodePoint() == match2 - .getDataLayerVirtualLanPriorityCodePoint()); - Assert.assertTrue(match.getNetworkProtocol() == match2 - .getNetworkProtocol()); - Assert.assertTrue(match.getNetworkTypeOfService() == match2 - .getNetworkTypeOfService()); - Assert.assertTrue(match.getTransportSource() == match2 - .getTransportSource()); - Assert.assertTrue(match.getTransportDestination() == match2 - .getTransportDestination()); - Assert.assertTrue(match.getWildcards() == match2.getWildcards()); - } - - @Test - public void testPadding() { - // testing that matchlen+pad keeps the 8byte alignment - V6Match match = new V6Match(); - - match.fromString("input_port=1"); - Assert.assertTrue((match.getPadSize() + match.getIPv6MatchLen()) % 8 == 0); - match.fromString("dl_dst=20:A0:11:10:00:99"); - match.fromString("dl_src=00:10:08:22:12:75"); - Assert.assertTrue((match.getPadSize() + match.getIPv6MatchLen()) % 8 == 0); - match.fromString("ip_src=2001:ddd:3e1:1234:0000:1111:2222:3333"); - Assert.assertTrue((match.getPadSize() + match.getIPv6MatchLen()) % 8 == 0); - match.fromString("ip_dst=2001:123:222:abc:111:aaa:1111:2222"); - Assert.assertTrue((match.getPadSize() + match.getIPv6MatchLen()) % 8 == 0); - match.fromString("dl_vlan=10"); - match.fromString("dl_vpcp=1"); - match.fromString("nw_proto=6"); - Assert.assertTrue((match.getPadSize() + match.getIPv6MatchLen()) % 8 == 0); - match.fromString("nw_tos=100"); - match.fromString("tp_dst=8080"); - Assert.assertTrue((match.getPadSize() + match.getIPv6MatchLen()) % 8 == 0); - match.fromString("tp_src=60"); - Assert.assertTrue((match.getPadSize() + match.getIPv6MatchLen()) % 8 == 0); - } -} diff --git a/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6MatchTest.java b/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6MatchTest.java deleted file mode 100644 index fceaaf46c9..0000000000 --- a/opendaylight/adsal/protocol_plugins/openflow/src/test/java/org/opendaylight/controller/protocol_plugin/openflow/vendorextension/v6extension/V6MatchTest.java +++ /dev/null @@ -1,461 +0,0 @@ -/* - * Copyright (c) 2014 NEC Corporation - * All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this - * distribution, and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.openflow.protocol.OFMatch.OFPFW_ALL; -import static org.openflow.protocol.OFMatch.OFPFW_DL_VLAN; -import static org.openflow.protocol.OFMatch.OFPFW_DL_VLAN_PCP; -import static org.openflow.protocol.OFMatch.OFPFW_IN_PORT; - -import java.nio.ByteBuffer; -import org.junit.Test; - -/** - * JUnit test for {@link V6Match}. - */ -public class V6MatchTest { - /** - * Header of a match entry for input port field without a mask. - * The vendor-specific value is 0, and the length of value is 2. - */ - private static int HEADER_INPUT_PORT = (0 << 9) | 2; - - /** - * Header of a match entry for VLAN TCI field without a mask. - * The vendor-specific value is 4, and the length of value is 2. - */ - private static int HEADER_VLAN_TCI= (4 << 9) | 2; - - /** - * Header of a match entry for VLAN TCI field with a mask. - * The vendor-specific value is 4, and the length of value is 4. - */ - private static int HEADER_VLAN_TCI_W = (4 << 9) | (1 << 8) | 4; - - /** - * Length of a match entry for input port field. - * Header (4 bytes) + value (2 bytes) = 6 bytes. - */ - private static short MATCH_LEN_INPUT_PORT = 6; - - /** - * Length of a match entry for VLAN TCI field without a mask. - * Header (4 bytes) + value (2 bytes) = 6 bytes. - */ - private static short MATCH_LEN_VLAN_TCI = 6; - - /** - * Length of a match entry for VLAN TCI field with a mask. - * Header (4 bytes) + value (2 bytes) + bitmask (2 bytes) = 8 bytes. - */ - private static short MATCH_LEN_VLAN_TCI_WITH_MASK = 8; - - /** - * Value of OFP_VLAN_NONE defined by OpenFlow 1.0. - */ - private static final short OFP_VLAN_NONE = (short)0xffff; - - /** - * CFI bit in VLAN TCI field. - */ - private static final int VLAN_TCI_CFI = 1 << 12; - - /** - * Test case for {@link V6Match#fromString(String)} about VLAN TCI field. - * This test passes values to "dl_vlan" and "dl_vpcp". - */ - @Test - public void testFromStringVlanTci() { - // Test for "dl_vlan" using non OFP_VLAN_NONE values. - short vlans[] = {1, 10, 1000, 4095}; - short mask = 0; - for (short vlan: vlans) { - V6Match match = new V6Match(); - match.fromString("dl_vlan=" + vlan); - assertEquals(MATCH_LEN_VLAN_TCI_WITH_MASK, match.getIPv6MatchLen()); - assertEquals(vlan, match.getDataLayerVirtualLan()); - int wildcards = OFPFW_ALL & ~OFPFW_DL_VLAN; - assertEquals(wildcards, match.getWildcards()); - } - - // Test for "dl_vpcp". - byte pcps[] = {1, 3, 7}; - for (byte pcp: pcps) { - V6Match match = new V6Match(); - match.fromString("dl_vpcp=" + pcp); - assertEquals(MATCH_LEN_VLAN_TCI_WITH_MASK, match.getIPv6MatchLen()); - assertEquals(pcp, match.getDataLayerVirtualLanPriorityCodePoint()); - int wildcards = OFPFW_ALL & ~OFPFW_DL_VLAN_PCP; - assertEquals(wildcards, match.getWildcards()); - } - - // Set "dl_vlan" field firstly, "dl_vpcp" field secondly. - for (short vlan: vlans) { - for (byte pcp: pcps) { - V6Match match = new V6Match(); - match.fromString("dl_vlan=" + vlan); - match.fromString("dl_vpcp=" + pcp); - assertEquals(MATCH_LEN_VLAN_TCI, match.getIPv6MatchLen()); - assertEquals(vlan, match.getDataLayerVirtualLan()); - assertEquals(pcp, - match.getDataLayerVirtualLanPriorityCodePoint()); - } - } - - // Set "dl_vpcp" field firstly, "dl_vlan" field secondly. - for (short vlan: vlans) { - for (byte pcp: pcps) { - V6Match match = new V6Match(); - match.fromString("dl_vpcp=" + pcp); - match.fromString("dl_vlan=" + vlan); - assertEquals(MATCH_LEN_VLAN_TCI, match.getIPv6MatchLen()); - assertEquals(vlan, match.getDataLayerVirtualLan()); - assertEquals(pcp, - match.getDataLayerVirtualLanPriorityCodePoint()); - } - } - - // Test for OFP_VLAN_NONE when VLAN PCP is not set. - V6Match match = new V6Match(); - match.fromString("dl_vlan=" + OFP_VLAN_NONE); - assertEquals(MATCH_LEN_VLAN_TCI, match.getIPv6MatchLen()); - assertEquals(OFP_VLAN_NONE, match.getDataLayerVirtualLan()); - - // Test for OFP_VLAN_NONE when VLAN PCP is set. - match = new V6Match(); - match.fromString("dl_vpcp=" + 1); - try { - match.fromString("dl_vlan=" + OFP_VLAN_NONE); - fail("Throwing exception was expected."); - } catch (IllegalArgumentException e) { - // Throwing exception was expected. - } - } - - /** - * Test case for {@link V6Match#writeTo(ByteBuffer)} for VLAN TCI field. - */ - @Test - public void testWriteToVlanTci() { - byte mask = 0; - - // Set only VLAN ID. - short vlans[] = {1, 10, 1000, 4095}; - for (short vlan: vlans) { - V6Match match = new V6Match(); - match.setDataLayerVirtualLan(vlan, mask); - ByteBuffer data = ByteBuffer.allocate(10); - match.writeTo(data); - assertEquals(MATCH_LEN_VLAN_TCI_WITH_MASK, data.position()); - data.flip(); - // Header - assertEquals(HEADER_VLAN_TCI_W, data.getInt()); - // Value - short expectedTci = (short) (VLAN_TCI_CFI | vlan); - assertEquals(expectedTci, data.getShort()); - // Mask - short expectedMask = 0x1fff; - assertEquals(expectedMask, data.getShort()); - } - - // Set only VLAN PCP. - byte pcps[] = {1, 3, 7}; - for (byte pcp: pcps) { - V6Match match = new V6Match(); - match.setDataLayerVirtualLanPriorityCodePoint(pcp, mask); - ByteBuffer data = ByteBuffer.allocate(10); - match.writeTo(data); - assertEquals(MATCH_LEN_VLAN_TCI_WITH_MASK, data.position()); - data.flip(); - // Header - assertEquals(HEADER_VLAN_TCI_W, data.getInt()); - // Value - short expectedTci = (short) (pcp << 13 | VLAN_TCI_CFI); - assertEquals(expectedTci, data.getShort()); - // Mask - short expectedMask = (short) 0xf000; - assertEquals(expectedMask, data.getShort()); - } - - // Set both VLAN ID and PCP. - for (short vlan: vlans) { - for (byte pcp: pcps) { - V6Match match = new V6Match(); - match.setDataLayerVirtualLan(vlan, mask); - match.setDataLayerVirtualLanPriorityCodePoint(pcp, mask); - ByteBuffer data = ByteBuffer.allocate(10); - match.writeTo(data); - assertEquals(MATCH_LEN_VLAN_TCI, data.position()); - data.flip(); - // Header - assertEquals(HEADER_VLAN_TCI, data.getInt()); - // Value - short expectedTci = (short) (pcp << 13 | VLAN_TCI_CFI | vlan); - assertEquals(expectedTci, data.getShort()); - } - } - - // Set OFP_VLAN_NONE. - V6Match match = new V6Match(); - match.setDataLayerVirtualLan(OFP_VLAN_NONE, mask); - ByteBuffer data = ByteBuffer.allocate(10); - match.writeTo(data); - assertEquals(MATCH_LEN_VLAN_TCI, data.position()); - data.flip(); - // Header - assertEquals(HEADER_VLAN_TCI, data.getInt()); - // Value - assertEquals(0, data.getShort()); - } - - /** - * Test case for {@link V6Match#writeTo(ByteBuffer)} for input port field. - */ - @Test - public void testWriteToInputPort() { - // Set input port. - short ports[] = {1, 10, 100, 1000}; - for (short port: ports) { - V6Match match = new V6Match(); - match.setInputPort(port, (short) 0); - ByteBuffer data = ByteBuffer.allocate(10); - match.writeTo(data); - assertEquals(MATCH_LEN_INPUT_PORT, data.position()); - data.flip(); - // Header - assertEquals(HEADER_INPUT_PORT, data.getInt()); - // Value - assertEquals(port, data.getShort()); - } - } - - /** - * Test case for {@link V6Match#readFrom(ByteBuffer)} for VLAN TCI field. - */ - @Test - public void testReadFromVlanTci() { - // Test for an exact match a TCI value with CFI=1. - // It matches packets that have an 802.1Q header with a specified - // VID and PCP. - short vlans[] = {1, 10, 1000, 4095}; - byte pcps[] = {1, 3, 7}; - for (short vlan: vlans) { - for (byte pcp: pcps) { - ByteBuffer data = ByteBuffer.allocate(MATCH_LEN_VLAN_TCI); - data.putInt(HEADER_VLAN_TCI); - short tci = (short) (pcp << 13 | VLAN_TCI_CFI | vlan); - data.putShort(tci); - data.flip(); - - V6Match match = new V6Match(); - match.readFrom(data); - assertEquals(MATCH_LEN_VLAN_TCI, match.getIPv6MatchLen()); - assertEquals(pcp, - match.getDataLayerVirtualLanPriorityCodePoint()); - assertEquals(vlan, match.getDataLayerVirtualLan()); - int wildcards = OFPFW_ALL & ~OFPFW_DL_VLAN_PCP & ~OFPFW_DL_VLAN; - assertEquals(wildcards, match.getWildcards()); - } - } - - // Test with a specific VID and CFI=1 with mask=0x1fff. - // It matches packets that have an 802.1Q header with that VID - // and any PCP. - for (short vlan: vlans) { - ByteBuffer data = ByteBuffer.allocate(MATCH_LEN_VLAN_TCI_WITH_MASK); - data.putInt(HEADER_VLAN_TCI_W); - short tci = (short) (VLAN_TCI_CFI | vlan); - data.putShort(tci); - short mask = (short) 0x1fff; - data.putShort(mask); - data.flip(); - - V6Match match = new V6Match(); - match.readFrom(data); - assertEquals(MATCH_LEN_VLAN_TCI_WITH_MASK, match.getIPv6MatchLen()); - assertEquals(vlan, match.getDataLayerVirtualLan()); - int wildcards = OFPFW_ALL & ~OFPFW_DL_VLAN; - assertEquals(wildcards, match.getWildcards()); - } - - // Test with a specific PCP and CFI=1 with mask=0xf000. - // It matches packets that have an 802.1Q header with that PCP - // and any VID. - for (byte pcp: pcps) { - ByteBuffer data = ByteBuffer.allocate(MATCH_LEN_VLAN_TCI_WITH_MASK); - data.putInt(HEADER_VLAN_TCI_W); - short tci = (short) (pcp << 13| VLAN_TCI_CFI); - data.putShort(tci); - short mask = (short) 0xf000; - data.putShort(mask); - data.flip(); - - V6Match match = new V6Match(); - match.readFrom(data); - assertEquals(MATCH_LEN_VLAN_TCI_WITH_MASK, match.getIPv6MatchLen()); - assertEquals(pcp, match.getDataLayerVirtualLanPriorityCodePoint()); - int wildcards = OFPFW_ALL & ~OFPFW_DL_VLAN_PCP; - assertEquals(wildcards, match.getWildcards()); - } - - // Test for an exact match with 0. - // It matches only packets without an 802.1Q header. - ByteBuffer data = ByteBuffer.allocate(MATCH_LEN_VLAN_TCI); - data.putInt(HEADER_VLAN_TCI); - short tci = 0; - data.putShort(tci); - data.flip(); - - V6Match match = new V6Match(); - match.readFrom(data); - assertEquals(MATCH_LEN_VLAN_TCI, match.getIPv6MatchLen()); - assertEquals(OFP_VLAN_NONE, match.getDataLayerVirtualLan()); - int wildcards = OFPFW_ALL & ~OFPFW_DL_VLAN; - assertEquals(wildcards, match.getWildcards()); - } - - /** - * Test case for {@link V6Match#readFrom(ByteBuffer)} for input port field. - */ - @Test - public void testReadFromInputPort() { - // Set input port. - short ports[] = {1, 10, 100, 1000}; - for (short port: ports) { - ByteBuffer data = ByteBuffer.allocate(MATCH_LEN_INPUT_PORT); - data.putInt(HEADER_INPUT_PORT); - data.putShort(port); - data.flip(); - - V6Match match = new V6Match(); - match.readFrom(data); - assertEquals(MATCH_LEN_INPUT_PORT, match.getIPv6MatchLen()); - assertEquals(port, match.getInputPort()); - int wildcards = OFPFW_ALL & ~OFPFW_IN_PORT; - assertEquals(wildcards, match.getWildcards()); - } - } - - /** - * Test case for {@link V6Match#setDataLayerVirtualLan(short, short)}. - */ - @Test - public void testSetDataLayerVirtualLan() { - short vlans[] = {1, 10, 1000, 4095}; - short mask = 0; - for (short vlan: vlans) { - V6Match match = new V6Match(); - match.setDataLayerVirtualLan(vlan, mask); - assertEquals(MATCH_LEN_VLAN_TCI_WITH_MASK, match.getIPv6MatchLen()); - assertEquals(vlan, match.getDataLayerVirtualLan()); - } - - // Test for OFP_VLAN_NONE. - V6Match match = new V6Match(); - match.setDataLayerVirtualLan(OFP_VLAN_NONE, mask); - assertEquals(MATCH_LEN_VLAN_TCI, match.getIPv6MatchLen()); - assertEquals(OFP_VLAN_NONE, match.getDataLayerVirtualLan()); - } - - /** - * Test case for - * {@link V6Match#setDataLayerVirtualLanPriorityCodePoint(byte, byte)}. - */ - @Test - public void testSetDataLayerVirtualLanPriorityCodePoint() { - byte pcps[] = {1, 3, 7}; - byte mask = 0; - for (byte pcp: pcps) { - V6Match match = new V6Match(); - match.setDataLayerVirtualLanPriorityCodePoint(pcp, mask); - assertEquals(MATCH_LEN_VLAN_TCI_WITH_MASK, match.getIPv6MatchLen()); - assertEquals(pcp, match.getDataLayerVirtualLanPriorityCodePoint()); - } - } - - /** - * Test case for setter methods for VLAN TCI field. - * - * This test case calls {@link V6Match#setDataLayerVirtualLan(short, short)} - * and {@link V6Match#setDataLayerVirtualLanPriorityCodePoint(byte, byte)}. - */ - @Test - public void testSetVlanTCI() { - short vlans[] = {1, 10, 1000, 4095}; - byte pcps[] = {1, 3, 7}; - byte mask = 0; - - // Call setDataLayerVirtualLan(short, short) firstly, - // and setDataLayerVirtualLanPriorityCodePoint(byte, byte) secondly, - for (short vlan: vlans) { - for (byte pcp: pcps) { - V6Match match = new V6Match(); - match.setDataLayerVirtualLan(vlan, mask); - match.setDataLayerVirtualLanPriorityCodePoint(pcp, mask); - assertEquals(MATCH_LEN_VLAN_TCI, match.getIPv6MatchLen()); - assertEquals(vlan, match.getDataLayerVirtualLan()); - assertEquals(pcp, - match.getDataLayerVirtualLanPriorityCodePoint()); - } - } - - // Call setDataLayerVirtualLanPriorityCodePoint(byte, byte) firstly, - // and setDataLayerVirtualLan(short, short) secondly. - for (short vlan: vlans) { - for (byte pcp: pcps) { - V6Match match = new V6Match(); - match.setDataLayerVirtualLanPriorityCodePoint(pcp, mask); - match.setDataLayerVirtualLan(vlan, mask); - assertEquals(MATCH_LEN_VLAN_TCI, match.getIPv6MatchLen()); - assertEquals(vlan, match.getDataLayerVirtualLan()); - assertEquals(pcp, - match.getDataLayerVirtualLanPriorityCodePoint()); - } - } - - // Test for setting OFP_VLAN_NONE when VLAN PCP is set. - for (byte pcp: pcps) { - V6Match match = new V6Match(); - match.setDataLayerVirtualLanPriorityCodePoint(pcp, mask); - try { - match.setDataLayerVirtualLan(OFP_VLAN_NONE, mask); - } catch (IllegalStateException e) { - // Throwing exception was expected. - } - } - - // Test for set VLAN PCP when OFP_VLAN_NONE is set to VLAN match. - for (byte pcp: pcps) { - V6Match match = new V6Match(); - match.setDataLayerVirtualLan(OFP_VLAN_NONE, mask); - try { - match.setDataLayerVirtualLanPriorityCodePoint(pcp, mask); - } catch (IllegalStateException e) { - // Throwing exception was expected. - } - } - } - - /** - * Test case for {@link V6Match#setInputPort(short, short)}. - */ - @Test - public void testSetInputPort() { - short ports[] = {1, 10, 100, 1000}; - for (short port: ports) { - V6Match match = new V6Match(); - match.setInputPort(port, (short) 0); - assertEquals(MATCH_LEN_INPUT_PORT, match.getIPv6MatchLen()); - assertEquals(port, match.getInputPort()); - } - } -} diff --git a/opendaylight/adsal/protocol_plugins/stub/pom.xml b/opendaylight/adsal/protocol_plugins/stub/pom.xml deleted file mode 100644 index 801368ad6d..0000000000 --- a/opendaylight/adsal/protocol_plugins/stub/pom.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - protocol_plugins.stub - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - sal - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.discovery, - org.opendaylight.controller.sal.topology, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.reader, - org.opendaylight.controller.sal.inventory, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.utils, - org.apache.commons.lang3.builder, - org.apache.commons.lang3.tuple, org.apache.felix.dm, - org.slf4j, org.eclipse.osgi.framework.console, - org.osgi.framework - org.opendaylight.controller.protocol_plugins.stub.internal - org.opendaylight.controller.protocol_plugins.stub.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/Activator.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/Activator.java deleted file mode 100644 index 843e60ec36..0000000000 --- a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/Activator.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - - - - -package org.opendaylight.controller.protocol_plugins.stub.internal; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.flowprogrammer.IPluginInFlowProgrammerService; -import org.opendaylight.controller.sal.inventory.IPluginInInventoryService; -import org.opendaylight.controller.sal.inventory.IPluginOutInventoryService; -import org.opendaylight.controller.sal.reader.IPluginInReadService; -import org.opendaylight.controller.sal.topology.IPluginInTopologyService; -import org.opendaylight.controller.sal.topology.IPluginOutTopologyService; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.INodeConnectorFactory; -import org.opendaylight.controller.sal.utils.INodeFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Dictionary; -import java.util.Hashtable; - -/** - * stub protocol plugin Activator - * - * - */ -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - /** - * Function called when the activator starts just after some initializations - * are done by the ComponentActivatorAbstractBase. - * - */ - @Override - public void init() { - Node.NodeIDType.registerIDType("STUB", Integer.class); - NodeConnector.NodeConnectorIDType.registerIDType("STUB", Integer.class, "STUB"); - } - - /** - * Function called when the activator stops just before the cleanup done by - * ComponentActivatorAbstractBase - * - */ - @Override - public void destroy() { - Node.NodeIDType.unRegisterIDType("STUB"); - NodeConnector.NodeConnectorIDType.unRegisterIDType("STUB"); - } - - /** - * Function that is used to communicate to dependency manager the list of - * known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { ReadService.class, InventoryService.class, TopologyServices.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies is - * required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - * @param containerName - * The containerName being configured, this allow also optional - * per-container different behavior if needed, usually should not - * be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(ReadService.class)) { - // export the service to be used by SAL - Dictionary props = new Hashtable(); - // Set the protocolPluginType property which will be used - // by SAL - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), "STUB"); - c.setInterface(IPluginInReadService.class.getName(), props); - } - - if (imp.equals(InventoryService.class)) { - // export the service to be used by SAL - Dictionary props = new Hashtable(); - // Set the protocolPluginType property which will be used - // by SAL - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), "STUB"); - c.setInterface(IPluginInInventoryService.class.getName(), props); - } - - if(imp.equals(TopologyServices.class)){ - Dictionary props = new Hashtable(); - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), "STUB"); - c.setInterface(IPluginInTopologyService.class.getName(), props); - c.add(createServiceDependency().setService(IPluginOutTopologyService.class, "") - .setCallbacks("setPluginOutTopologyService", "unsetPluginOutTopologyService") - .setRequired(true)); - - } - - } - - @Override - public Object[] getGlobalImplementations() { - Object[] res = - { - FlowProgrammerService.class, - StubNodeFactory.class, - StubNodeConnectorFactory.class, - InventoryService.class - }; - return res; - } - - @Override - public void configureGlobalInstance(Component c, Object imp){ - if (imp.equals(FlowProgrammerService.class)) { - // export the service to be used by SAL - Dictionary props = new Hashtable(); - // Set the protocolPluginType property which will be used - // by SAL - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), "STUB"); - c.setInterface(IPluginInFlowProgrammerService.class.getName(), props); - } - if (imp.equals(StubNodeFactory.class)) { - // export the service to be used by SAL - Dictionary props = new Hashtable(); - // Set the protocolPluginType property which will be used - // by SAL - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), "STUB"); - props.put("protocolName", "STUB"); - c.setInterface(INodeFactory.class.getName(), props); - } - if (imp.equals(StubNodeConnectorFactory.class)) { - // export the service to be used by SAL - Dictionary props = new Hashtable(); - // Set the protocolPluginType property which will be used - // by SAL - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), "STUB"); - props.put("protocolName", "STUB"); - c.setInterface(INodeConnectorFactory.class.getName(), props); - } - if (imp.equals(InventoryService.class)) { - // export the service to be used by SAL - Dictionary props = new Hashtable(); - // Set the protocolPluginType property which will be used - // by SAL - props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), "STUB"); - props.put("scope", "Global"); - c.setInterface(IPluginInInventoryService.class.getName(), props); - c.add(createServiceDependency().setService(IPluginOutInventoryService.class, "(scope=Global)") - .setCallbacks("setPluginOutInventoryServices", "unsetPluginOutInventoryServices") - .setRequired(true)); - } - - } -} diff --git a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/FlowProgrammerService.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/FlowProgrammerService.java deleted file mode 100644 index 305829705a..0000000000 --- a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/FlowProgrammerService.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugins.stub.internal; - -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.flowprogrammer.IPluginInFlowProgrammerService; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; - - - -/** - * Represents the openflow plugin component in charge of programming the flows - * the flow programming and relay them to functional modules above SAL. - */ -public class FlowProgrammerService implements IPluginInFlowProgrammerService - { - void init() { - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - } - - - /** - * Synchronously add a flow to the network node - * - * @param node - * @param flow - */ - public Status addFlow(Node node, Flow flow){ - return new Status(StatusCode.SUCCESS); - } - - /** - * Synchronously modify existing flow on the switch - * - * @param node - * @param flow - */ - public Status modifyFlow(Node node, Flow oldFlow, Flow newFlow){ - return new Status(StatusCode.SUCCESS); - } - /** - * Synchronously remove the flow from the network node - * - * @param node - * @param flow - */ - public Status removeFlow(Node node, Flow flow){ - return new Status(StatusCode.SUCCESS); - } - - /** - * Asynchronously add a flow to the network node - * - * @param node - * @param flow - * @param rid - */ - public Status addFlowAsync(Node node, Flow flow, long rid){ - return new Status(StatusCode.SUCCESS); - } - - /** - * Asynchronously modify existing flow on the switch - * - * @param node - * @param flow - * @param rid - */ - public Status modifyFlowAsync(Node node, Flow oldFlow, Flow newFlow, long rid){ - return new Status(StatusCode.SUCCESS); - } - - /** - * Asynchronously remove the flow from the network node - * - * @param node - * @param flow - * @param rid - */ - public Status removeFlowAsync(Node node, Flow flow, long rid){ - return new Status(StatusCode.SUCCESS); - } - - /** - * Remove all flows present on the network node - * - * @param node - */ - public Status removeAllFlows(Node node){ - return new Status(StatusCode.SUCCESS); - } - - /** - * Send Barrier message synchronously. The caller will be blocked until the - * Barrier reply arrives. - * - * @param node - */ - public Status syncSendBarrierMessage(Node node){ - return new Status(StatusCode.SUCCESS); - } - - /** - * Send Barrier message asynchronously. The caller is not blocked. - * - * @param node - */ - public Status asyncSendBarrierMessage(Node node){ - return new Status(StatusCode.SUCCESS); - } - } \ No newline at end of file diff --git a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/InventoryService.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/InventoryService.java deleted file mode 100644 index 365813bd16..0000000000 --- a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/InventoryService.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.protocol_plugins.stub.internal; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArraySet; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.opendaylight.controller.sal.core.Actions; -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.Buffers; -import org.opendaylight.controller.sal.core.Capabilities; -import org.opendaylight.controller.sal.core.Capabilities.CapabilitiesType; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.Tables; -import org.opendaylight.controller.sal.core.TimeStamp; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.inventory.IPluginInInventoryService; -import org.opendaylight.controller.sal.inventory.IPluginOutInventoryService; - -/** - * Stub Implementation for IPluginInReadService used by SAL - * - * - */ -public class InventoryService implements IPluginInInventoryService { - private static final Logger logger = LoggerFactory - .getLogger(InventoryService.class); - - private ConcurrentMap> nodeProps; // properties - // are - // maintained - // in global - // container - // only - private ConcurrentMap> nodeConnectorProps; // properties - // are - // maintained - // in - // global - // container - // only - private final Set pluginOutInventoryServices = - new CopyOnWriteArraySet(); - - public void setPluginOutInventoryServices(IPluginOutInventoryService service) { - logger.trace("Got a service set request {}", service); - if (this.pluginOutInventoryServices != null) { - this.pluginOutInventoryServices.add(service); - } - } - - public void unsetPluginOutInventoryServices(IPluginOutInventoryService service) { - logger.trace("Got a service UNset request"); - if (this.pluginOutInventoryServices != null) { - this.pluginOutInventoryServices.remove(service); - } - } - - @Override - public Set getConfiguredNotConnectedNodes() { - // TODO - return null; - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - nodeProps = new ConcurrentHashMap>(); - nodeConnectorProps = new ConcurrentHashMap>(); - Node.NodeIDType.registerIDType("STUB", Integer.class); - NodeConnector.NodeConnectorIDType.registerIDType("STUB", Integer.class, - "STUB"); - - setupNodeProps(); - setupNodeConnectorProps(); - } - - private void setupNodeConnectorProps() { - Map ncPropMap = new HashMap(); - Capabilities cap = new Capabilities( - CapabilitiesType.FLOW_STATS_CAPABILITY.getValue()); - ncPropMap.put(Capabilities.CapabilitiesPropName, cap); - Bandwidth bw = new Bandwidth(Bandwidth.BW1Gbps); - ncPropMap.put(Bandwidth.BandwidthPropName, bw); - State st = new State(State.EDGE_UP); - ncPropMap.put(State.StatePropName, st); - - // setup property map for all node connectors - NodeConnector nc; - Node node; - try { - node = new Node("STUB", new Integer(0xCAFE)); - nc = new NodeConnector("STUB", 0xCAFE, node); - } catch (ConstructionException e) { - nc = null; - node = null; - } - nodeConnectorProps.put(nc, ncPropMap); - - try { - node = new Node("STUB", 3366); - nc = new NodeConnector("STUB", 12, node); - } catch (ConstructionException e) { - nc = null; - node = null; - } - nodeConnectorProps.put(nc, ncPropMap); - - try { - node = new Node("STUB", 4477); - nc = new NodeConnector("STUB", 34, node); - } catch (ConstructionException e) { - nc = null; - node = null; - } - nodeConnectorProps.put(nc, ncPropMap); - - } - - private void setupNodeProps() { - Map propMap = new HashMap(); - - Tables t = new Tables((byte) 1); - propMap.put(Tables.TablesPropName, t); - Capabilities c = new Capabilities((int) 3); - propMap.put(Capabilities.CapabilitiesPropName, c); - Actions a = new Actions((int) 2); - propMap.put(Actions.ActionsPropName, a); - Buffers b = new Buffers((int) 1); - propMap.put(Buffers.BuffersPropName, b); - Long connectedSinceTime = 100000L; - TimeStamp timeStamp = new TimeStamp(connectedSinceTime, - "connectedSince"); - propMap.put(TimeStamp.TimeStampPropName, timeStamp); - - // setup property map for all nodes - Node node; - try { - node = new Node("STUB", new Integer(0xCAFE)); - } catch (ConstructionException e) { - node = null; - } - - nodeProps.put(node, propMap); - - try { - node = new Node("STUB", 3366); - } catch (ConstructionException e) { - node = null; - } - nodeProps.put(node, propMap); - - try { - node = new Node("STUB", 4477); - } catch (ConstructionException e) { - node = null; - } - nodeProps.put(node, propMap); - - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - } - - /** - * Method called when the plugin has exposed it's services, this will be - * used to publish the updates so connection manager can think the - * connection is local - */ - void started() { - // update sal and discovery - for (IPluginOutInventoryService service : pluginOutInventoryServices) { - for (Node node : nodeProps.keySet()) { - Set props = new HashSet(nodeProps.get(node) - .values()); - service.updateNode(node, UpdateType.ADDED, props); - logger.trace("Adding Node {} with props {}", node, props); - } - for (NodeConnector nc : nodeConnectorProps.keySet()) { - Set props = new HashSet(nodeConnectorProps.get(nc) - .values()); - service.updateNodeConnector(nc, UpdateType.ADDED, props); - logger.trace("Adding NodeConnectors {} with props {}", nc, props); - } - } - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - pluginOutInventoryServices.clear(); - } - - /** - * Retrieve nodes from openflow - */ - @Override - public ConcurrentMap> getNodeProps() { - return nodeProps; - } - - /** - * Retrieve nodeConnectors from openflow - */ - @Override - public ConcurrentMap> getNodeConnectorProps( - Boolean refresh) { - return nodeConnectorProps; - } - -} diff --git a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/ReadService.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/ReadService.java deleted file mode 100644 index 0ff60835c8..0000000000 --- a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/ReadService.java +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.protocol_plugins.stub.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.Controller; -import org.opendaylight.controller.sal.action.Drop; -import org.opendaylight.controller.sal.action.Flood; -import org.opendaylight.controller.sal.action.FloodAll; -import org.opendaylight.controller.sal.action.HwPath; -import org.opendaylight.controller.sal.action.Loopback; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.action.PopVlan; -import org.opendaylight.controller.sal.action.PushVlan; -import org.opendaylight.controller.sal.action.SetDlDst; -import org.opendaylight.controller.sal.action.SetDlSrc; -import org.opendaylight.controller.sal.action.SetDlType; -import org.opendaylight.controller.sal.action.SetNwDst; -import org.opendaylight.controller.sal.action.SetNwSrc; -import org.opendaylight.controller.sal.action.SetNwTos; -import org.opendaylight.controller.sal.action.SetTpDst; -import org.opendaylight.controller.sal.action.SetTpSrc; -import org.opendaylight.controller.sal.action.SetVlanCfi; -import org.opendaylight.controller.sal.action.SetVlanId; -import org.opendaylight.controller.sal.action.SetVlanPcp; -import org.opendaylight.controller.sal.action.SwPath; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.IPluginInReadService; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -/** - * Stub Implementation for IPluginInReadService used by SAL - * - * - */ -public class ReadService implements IPluginInReadService { - private static final Logger logger = LoggerFactory - .getLogger(ReadService.class); - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - } - - @Override - public FlowOnNode readFlow(Node node, Flow flow, boolean cached) { - FlowOnNode fn1 = new FlowOnNode(flow); - fn1.setByteCount(100); - fn1.setDurationNanoseconds(400); - fn1.setDurationSeconds(40); - fn1.setTableId((byte) 0x1); - fn1.setPacketCount(200); - return fn1; - } - - @Override - public List readAllFlow(Node node, boolean cached) { - - ArrayList list = new ArrayList(); - ArrayList actionList = new ArrayList(); - actionList.add(new Drop()); //IT assumes this is first element - actionList.add(new Loopback()); - actionList.add(new Flood()); - actionList.add(new FloodAll()); - actionList.add(new Controller()); - actionList.add(new SwPath()); - actionList.add(new HwPath()); - try { - actionList.add(new Output(new NodeConnector("STUB", 0xCAFE, node))); - } catch (ConstructionException e) { - - } - byte dst[] = { (byte) 1, (byte) 2, (byte) 3, (byte) 4, (byte) 5 }; - byte src[] = { (byte) 5, (byte) 4, (byte) 3, (byte) 2, (byte) 1 }; - actionList.add(new SetDlSrc(src)); - actionList.add(new SetDlDst(dst)); - actionList.add(new SetDlType(10)); - - actionList.add(new SetVlanId(2)); - actionList.add(new SetVlanPcp(3)); - actionList.add(new SetVlanCfi(1)); - - actionList.add(new PopVlan()); - actionList.add(new PushVlan(0x8100, 1, 1, 1234)); - - try { - actionList.add(new SetNwSrc(InetAddress.getByName("2.2.2.2"))); - actionList.add(new SetNwDst(InetAddress.getByName("1.1.1.1"))); - } catch (UnknownHostException e) { - - } - actionList.add(new SetNwTos(0x10)); - actionList.add(new SetTpSrc(4201)); - actionList.add(new SetTpDst(8080)); - - short priority = 3500; //IT assumes this value - for (Action a : actionList) { - Flow flow = new Flow(); - Match match = new Match(); - try { - match.setField(MatchType.NW_DST, - InetAddress.getByName("1.1.1.1")); - } catch (UnknownHostException e) { - - } - flow.setMatch(match); - List actions = new ArrayList(); - actions.add(a); - flow.setActions(actions); - flow.setPriority(priority++); - flow.setIdleTimeout((short) 1000); - flow.setHardTimeout((short) 2000); - flow.setId(12345); - - FlowOnNode fn1 = new FlowOnNode(flow); - fn1.setByteCount(100); - fn1.setDurationNanoseconds(400); - fn1.setDurationSeconds(40); - fn1.setTableId((byte) 0x1); - fn1.setPacketCount(200); - - list.add(fn1); - } - return list; - } - - @Override - public NodeDescription readDescription(Node node, boolean cached) { - NodeDescription desc = new NodeDescription(); - desc.setDescription("This is a sample node description"); - desc.setHardware("stub hardware"); - desc.setSoftware("stub software"); - desc.setSerialNumber("123"); - desc.setManufacturer("opendaylight"); - return desc; - } - - @Override - public NodeConnectorStatistics readNodeConnector(NodeConnector connector, - boolean cached) { - NodeConnectorStatistics stats = new NodeConnectorStatistics(); - stats.setNodeConnector(connector); - stats.setCollisionCount(4); - stats.setReceiveByteCount(1000); - stats.setReceiveCRCErrorCount(1); - stats.setReceiveDropCount(2); - stats.setReceiveErrorCount(3); - stats.setReceiveFrameErrorCount(5); - stats.setReceiveOverRunErrorCount(6); - stats.setReceivePacketCount(250); - stats.setTransmitByteCount(5000); - stats.setTransmitDropCount(50); - stats.setTransmitErrorCount(10); - stats.setTransmitPacketCount(500); - - return stats; - } - - @Override - public List readAllNodeConnector(Node node, - boolean cached) { - NodeConnectorStatistics stats = new NodeConnectorStatistics(); - try { - NodeConnector nc = new NodeConnector("STUB", 0xCAFE, node); - stats.setNodeConnector(nc); - } catch (ConstructionException e) { - // couldn't create nodeconnector. - } - stats.setCollisionCount(4); - stats.setReceiveByteCount(1000); - stats.setReceiveCRCErrorCount(1); - stats.setReceiveDropCount(2); - stats.setReceiveErrorCount(3); - stats.setReceiveFrameErrorCount(5); - stats.setReceiveOverRunErrorCount(6); - stats.setReceivePacketCount(250); - stats.setTransmitByteCount(5000); - stats.setTransmitDropCount(50); - stats.setTransmitErrorCount(10); - stats.setTransmitPacketCount(500); - - List result = new ArrayList(); - result.add(stats); - return result; - } - - @Override - public long getTransmitRate(NodeConnector connector) { - return 100; - } - - @Override - public NodeTableStatistics readNodeTable(NodeTable table, boolean b) { - NodeTableStatistics stats = new NodeTableStatistics(); - stats.setNodeTable(table); - stats.setActiveCount(4); - stats.setLookupCount(4); - stats.setMatchedCount(4); - - return stats; - } - - @Override - public List readAllNodeTable(Node node, boolean cached) { - NodeTableStatistics stats = new NodeTableStatistics(); - try { - NodeTable nt = new NodeTable(NodeTable.NodeTableIDType.OPENFLOW, Byte.valueOf("10"), node); - stats.setNodeTable(nt); - } catch (ConstructionException e) { - // couldn't create nodetable. - } - - stats.setActiveCount(4); - stats.setLookupCount(4); - stats.setMatchedCount(4); - - List result = new ArrayList(); - result.add(stats); - return result; - } -} diff --git a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeConnectorFactory.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeConnectorFactory.java deleted file mode 100644 index 743c4a54e7..0000000000 --- a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeConnectorFactory.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.protocol_plugins.stub.internal; - -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.INodeConnectorFactory; -import org.opendaylight.controller.sal.core.Node; - -public class StubNodeConnectorFactory implements INodeConnectorFactory - { - void init() { - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - } - - public NodeConnector fromStringNoNode(String typeStr, String IDStr, - Node n){ - if(typeStr.equals("STUB")){ - try { - return new NodeConnector(typeStr, Integer.parseInt(IDStr), n); - } catch (Exception ex) { - return null; - } - } - return null; - } -} diff --git a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeFactory.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeFactory.java deleted file mode 100644 index 439519fa41..0000000000 --- a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/StubNodeFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.protocol_plugins.stub.internal; - -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.utils.INodeFactory; -import org.opendaylight.controller.sal.core.Node; - -public class StubNodeFactory implements INodeFactory { - void init() { - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - } - - public Node fromString(String nodeType, String nodeId){ - if(nodeType.equals("STUB")) { - try { - return new Node("STUB", Integer.parseInt(nodeId)); - } catch(ConstructionException e) { - return null; - } - } - return null; - } -} diff --git a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/TopologyServices.java b/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/TopologyServices.java deleted file mode 100644 index 104df0a94c..0000000000 --- a/opendaylight/adsal/protocol_plugins/stub/src/main/java/org/opendaylight/controller/protocol_plugins/stub/internal/TopologyServices.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.protocol_plugins.stub.internal; - -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.topology.IPluginInTopologyService; -import org.opendaylight.controller.sal.topology.IPluginOutTopologyService; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -public class TopologyServices implements IPluginInTopologyService { - private IPluginOutTopologyService pluginOutTopologyService; - - - @Override - public void sollicitRefresh() { - } - - public void setPluginOutTopologyService(IPluginOutTopologyService pluginOutTopologyService){ - this.pluginOutTopologyService = pluginOutTopologyService; - } - - public void unsetPluginOutTopologyService(IPluginOutTopologyService pluginOutTopologyService){ - this.pluginOutTopologyService = null; - } - - - public void addEdge(Edge edge, Set properties, UpdateType updateType){ - - List topoedgeupdateList = new ArrayList(); - - topoedgeupdateList.add(new TopoEdgeUpdate(edge, properties, updateType)); - - this.pluginOutTopologyService.edgeUpdate(topoedgeupdateList); - - } -} diff --git a/opendaylight/adsal/routing/dijkstra_implementation/pom.xml b/opendaylight/adsal/routing/dijkstra_implementation/pom.xml deleted file mode 100644 index 8df6db5bbf..0000000000 --- a/opendaylight/adsal/routing/dijkstra_implementation/pom.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - routing.dijkstra_implementation - 0.6.0-SNAPSHOT - bundle - - - equinoxSDK381 - org.apache.felix.gogo.runtime - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - topologymanager - - - org.opendaylight.controller.thirdparty - net.sf.jung2 - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.slf4j, - org.opendaylight.controller.sal.routing, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.topology, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.reader, - org.opendaylight.controller.clustering.services, - org.apache.commons.collections15, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.topologymanager, - edu.uci.ics.jung.graph, - edu.uci.ics.jung.algorithms.shortestpath, - edu.uci.ics.jung.graph.util, - org.apache.felix.dm, - org.osgi.framework, - org.apache.felix.service.command, - org.junit;resolution:=optional - org.opendaylight.controller.routing.dijkstra_implementation.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/Activator.java b/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/Activator.java deleted file mode 100644 index 7d7833b013..0000000000 --- a/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/Activator.java +++ /dev/null @@ -1,93 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.routing.dijkstra_implementation.internal; - -import java.util.Dictionary; -import java.util.Hashtable; - -import org.apache.felix.dm.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.routing.IListenRoutingUpdates; -import org.opendaylight.controller.sal.routing.IRouting; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { DijkstraImplementation.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - @Override - public void configureInstance(final Component c, final Object imp, final String containerName) { - if (imp.equals(DijkstraImplementation.class)) { - // export the service - final Dictionary props = new Hashtable(); - props.put("topoListenerName", "routing.Dijkstra"); - - c.setInterface(new String[] { ITopologyManagerClusterWideAware.class.getName(), IRouting.class.getName() }, - props); - - // Now lets add a service dependency to make sure the - // provider of service exists - c.add(createContainerServiceDependency(containerName).setService(IListenRoutingUpdates.class) - .setCallbacks("setListenRoutingUpdates", "unsetListenRoutingUpdates") - .setRequired(false)); - - c.add(createContainerServiceDependency(containerName).setService(ISwitchManager.class) - .setCallbacks("setSwitchManager", "unsetSwitchManager") - .setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService(ITopologyManager.class) - .setCallbacks("setTopologyManager", "unsetTopologyManager") - .setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService(IClusterContainerServices.class) - .setCallbacks("setClusterContainerService", "unsetClusterContainerService") - .setRequired(true)); - } - } - - @Override - protected Object[] getGlobalImplementations() { - final Object[] res = { DijkstraImplementationCLI.class }; - return res; - } -} diff --git a/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementation.java b/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementation.java deleted file mode 100644 index b68cc0cab2..0000000000 --- a/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementation.java +++ /dev/null @@ -1,503 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file DijkstraImplementation.java - * - * - * @brief Implementation of a routing engine using - * dijkstra. Implementation of dijkstra come from Jung2 library - * - */ -package org.opendaylight.controller.routing.dijkstra_implementation.internal; - -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Path; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.routing.IListenRoutingUpdates; -import org.opendaylight.controller.sal.routing.IRouting; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware; - -import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath; -import edu.uci.ics.jung.graph.Graph; -import edu.uci.ics.jung.graph.SparseMultigraph; -import edu.uci.ics.jung.graph.util.EdgeType; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.ArrayList; -import java.util.Set; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.apache.commons.collections15.Transformer; - -@SuppressWarnings("rawtypes") -public class DijkstraImplementation implements IRouting, ITopologyManagerClusterWideAware { - private static Logger log = LoggerFactory.getLogger(DijkstraImplementation.class); - private ConcurrentMap> topologyBWAware; - private ConcurrentMap> sptBWAware; - DijkstraShortestPath mtp; // Max Throughput Path - private Set routingAware; - private ISwitchManager switchManager; - private ITopologyManager topologyManager; - private static final long DEFAULT_LINK_SPEED = Bandwidth.BW1Gbps; - private IClusterContainerServices clusterContainerService; - - public void setListenRoutingUpdates(final IListenRoutingUpdates i) { - if (this.routingAware == null) { - this.routingAware = new HashSet(); - } - if (this.routingAware != null) { - log.debug("Adding routingAware listener: {}", i); - this.routingAware.add(i); - } - } - - public void unsetListenRoutingUpdates(final IListenRoutingUpdates i) { - if (this.routingAware == null) { - return; - } - log.debug("Removing routingAware listener"); - this.routingAware.remove(i); - if (this.routingAware.isEmpty()) { - // We don't have any listener lets dereference - this.routingAware = null; - } - } - - @Override - public synchronized void initMaxThroughput( - final Map EdgeWeightMap) { - if (mtp != null) { - log.error("Max Throughput Dijkstra is already enabled!"); - return; - } - Transformer mtTransformer = null; - if (EdgeWeightMap == null) { - mtTransformer = new Transformer() { - @Override - public Double transform(Edge e) { - if (switchManager == null) { - log.error("switchManager is null"); - return (double) -1; - } - NodeConnector srcNC = e.getTailNodeConnector(); - NodeConnector dstNC = e.getHeadNodeConnector(); - if ((srcNC == null) || (dstNC == null)) { - log.error("srcNC:{} or dstNC:{} is null", srcNC, dstNC); - return (double) -1; - } - Bandwidth bwSrc = (Bandwidth) switchManager.getNodeConnectorProp(srcNC, - Bandwidth.BandwidthPropName); - Bandwidth bwDst = (Bandwidth) switchManager.getNodeConnectorProp(dstNC, - Bandwidth.BandwidthPropName); - - long srcLinkSpeed = 0, dstLinkSpeed = 0; - if ((bwSrc == null) || ((srcLinkSpeed = bwSrc.getValue()) == 0)) { - log.debug("srcNC: {} - Setting srcLinkSpeed to Default!", srcNC); - srcLinkSpeed = DEFAULT_LINK_SPEED; - } - - if ((bwDst == null) || ((dstLinkSpeed = bwDst.getValue()) == 0)) { - log.debug("dstNC: {} - Setting dstLinkSpeed to Default!", dstNC); - dstLinkSpeed = DEFAULT_LINK_SPEED; - } - - // TODO: revisit the logic below with the real use case in - // mind - // For now we assume the throughput to be the speed of the - // link itself - // this kind of logic require information that should be - // polled by statistic manager and are not yet available, - // also this service at the moment is not used, so to be - // revisited later on - long avlSrcThruPut = srcLinkSpeed; - long avlDstThruPut = dstLinkSpeed; - - // Use lower of the 2 available throughput as the available - // throughput - long avlThruPut = avlSrcThruPut < avlDstThruPut ? avlSrcThruPut : avlDstThruPut; - - if (avlThruPut <= 0) { - log.debug("Edge {}: Available Throughput {} <= 0!", e, avlThruPut); - return (double) -1; - } - return (double) (Bandwidth.BW1Pbps / avlThruPut); - } - }; - } else { - mtTransformer = new Transformer() { - @Override - public Number transform(Edge e) { - return EdgeWeightMap.get(e); - } - }; - } - Short baseBW = Short.valueOf((short) 0); - // Initialize mtp also using the default topo - Graph g = this.topologyBWAware.get(baseBW); - if (g == null) { - log.error("Default Topology Graph is null"); - return; - } - mtp = new DijkstraShortestPath(g, mtTransformer); - } - - @Override - public Path getRoute(final Node src, final Node dst) { - if ((src == null) || (dst == null)) { - return null; - } - return getRoute(src, dst, (short) 0); - } - - @Override - public synchronized Path getMaxThroughputRoute(Node src, Node dst) { - if (mtp == null) { - log.error("Max Throughput Path Calculation Uninitialized!"); - return null; - } - - List path; - try { - path = mtp.getMaxThroughputPath(src, dst); - } catch (IllegalArgumentException ie) { - log.debug("A vertex is yet not known between {} {}", src, dst); - return null; - } - Path res; - try { - res = new Path(path); - } catch (ConstructionException e) { - log.debug("A vertex is yet not known between {} {}", src, dst); - return null; - } - return res; - } - - @Override - public synchronized Path getRoute(final Node src, final Node dst, final Short Bw) { - DijkstraShortestPath spt = this.sptBWAware.get(Bw); - if (spt == null) { - return null; - } - List path; - try { - path = spt.getPath(src, dst); - } catch (IllegalArgumentException ie) { - log.debug("A vertex is yet not known between {} {}", src, dst); - return null; - } - Path res; - try { - res = new Path(path); - } catch (ConstructionException e) { - log.debug("A vertex is yet not known between {} {}", src, dst); - return null; - } - return res; - } - - @Override - public synchronized void clear() { - DijkstraShortestPath spt; - for (Short bw : this.sptBWAware.keySet()) { - spt = this.sptBWAware.get(bw); - if (spt != null) { - spt.reset(); - } - } - clearMaxThroughput(); - } - - @Override - public synchronized void clearMaxThroughput() { - if (mtp != null) { - mtp.reset(); // reset max throughput path - } - } - - @SuppressWarnings({ "unchecked" }) - private synchronized boolean updateTopo(Edge edge, Short bw, UpdateType type) { - Graph topo = this.topologyBWAware.get(bw); - DijkstraShortestPath spt = this.sptBWAware.get(bw); - boolean edgePresentInGraph = false; - Short baseBW = Short.valueOf((short) 0); - - if (topo == null) { - // Create topology for this BW - Graph g = new SparseMultigraph(); - this.topologyBWAware.put(bw, g); - topo = this.topologyBWAware.get(bw); - this.sptBWAware.put(bw, new DijkstraShortestPath(g)); - spt = this.sptBWAware.get(bw); - } - - if (topo != null) { - NodeConnector src = edge.getTailNodeConnector(); - NodeConnector dst = edge.getHeadNodeConnector(); - if (spt == null) { - spt = new DijkstraShortestPath(topo); - this.sptBWAware.put(bw, spt); - } - - switch (type) { - case ADDED: - // Make sure the vertex are there before adding the edge - topo.addVertex(src.getNode()); - topo.addVertex(dst.getNode()); - // Add the link between - edgePresentInGraph = topo.containsEdge(edge); - if (edgePresentInGraph == false) { - try { - topo.addEdge(new Edge(src, dst), src.getNode(), dst.getNode(), EdgeType.DIRECTED); - } catch (final ConstructionException e) { - log.error("", e); - return edgePresentInGraph; - } - } - case CHANGED: - // Mainly raised only on properties update, so not really useful - // in this case - break; - case REMOVED: - // Remove the edge - try { - topo.removeEdge(new Edge(src, dst)); - } catch (final ConstructionException e) { - log.error("", e); - return edgePresentInGraph; - } - - // If the src and dst vertex don't have incoming or - // outgoing links we can get ride of them - if (topo.containsVertex(src.getNode()) && (topo.inDegree(src.getNode()) == 0) - && (topo.outDegree(src.getNode()) == 0)) { - log.debug("Removing vertex {}", src); - topo.removeVertex(src.getNode()); - } - - if (topo.containsVertex(dst.getNode()) && (topo.inDegree(dst.getNode()) == 0) - && (topo.outDegree(dst.getNode()) == 0)) { - log.debug("Removing vertex {}", dst); - topo.removeVertex(dst.getNode()); - } - break; - } - spt.reset(); - if (bw.equals(baseBW)) { - clearMaxThroughput(); - } - } else { - log.error("Cannot find topology for BW {} this is unexpected!", bw); - } - return edgePresentInGraph; - } - - private boolean edgeUpdate(Edge e, UpdateType type, Set props, boolean local) { - String srcType = null; - String dstType = null; - - log.trace("Got an edgeUpdate: {} props: {} update type: {} local: {}", new Object[] { e, props, type, local }); - - if ((e == null) || (type == null)) { - log.error("Edge or Update type are null!"); - return false; - } else { - srcType = e.getTailNodeConnector().getType(); - dstType = e.getHeadNodeConnector().getType(); - - if (srcType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) { - log.debug("Skip updates for {}", e); - return false; - } - - if (dstType.equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) { - log.debug("Skip updates for {}", e); - return false; - } - } - - Bandwidth bw = new Bandwidth(0); - boolean newEdge = false; - if (props != null) { - props.remove(bw); - } - - Short baseBW = Short.valueOf((short) 0); - // Update base topo - newEdge = !updateTopo(e, baseBW, type); - if (newEdge == true) { - if (bw.getValue() != baseBW) { - // Update BW topo - updateTopo(e, (short) bw.getValue(), type); - } - } - return newEdge; - } - - @Override - public void edgeUpdate(List topoedgeupdateList) { - log.trace("Start of a Bulk EdgeUpdate with " + topoedgeupdateList.size() + " elements"); - boolean callListeners = false; - for (int i = 0; i < topoedgeupdateList.size(); i++) { - Edge e = topoedgeupdateList.get(i).getEdge(); - Set p = topoedgeupdateList.get(i) - .getProperty(); - UpdateType type = topoedgeupdateList.get(i) - .getUpdateType(); - boolean isLocal = topoedgeupdateList.get(i) - .isLocal(); - if ((edgeUpdate(e, type, p, isLocal)) && (!callListeners)) { - callListeners = true; - } - } - - // The routing listeners should only be called on the coordinator, to - // avoid multiple controller cluster nodes to actually do the - // recalculation when only one need to react - boolean amICoordinator = true; - if (this.clusterContainerService != null) { - amICoordinator = this.clusterContainerService.amICoordinator(); - } - if ((callListeners) && (this.routingAware != null) && amICoordinator) { - log.trace("Calling the routing listeners"); - for (IListenRoutingUpdates ra : this.routingAware) { - try { - ra.recalculateDone(); - } catch (Exception ex) { - log.error("Exception on routingAware listener call", ex); - } - } - } - log.trace("End of a Bulk EdgeUpdate"); - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - @SuppressWarnings("unchecked") - public void init() { - log.debug("Routing init() is called"); - this.topologyBWAware = new ConcurrentHashMap>(); - this.sptBWAware = new ConcurrentHashMap>(); - // Now create the default topology, which doesn't consider the - // BW, also create the corresponding Dijkstra calculation - Graph g = new SparseMultigraph(); - Short sZero = Short.valueOf((short) 0); - this.topologyBWAware.put(sZero, g); - this.sptBWAware.put(sZero, new DijkstraShortestPath(g)); - // Topologies for other BW will be added on a needed base - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - log.debug("Routing destroy() is called"); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - log.debug("Routing start() is called"); - // build the routing database from the topology if it exists. - Map> edges = topologyManager.getEdges(); - if (edges.isEmpty()) { - return; - } - List topoedgeupdateList = new ArrayList(); - log.debug("Creating routing database from the topology"); - for (Iterator>> i = edges.entrySet() - .iterator(); i.hasNext();) { - Map.Entry> entry = i.next(); - Edge e = entry.getKey(); - Set props = entry.getValue(); - TopoEdgeUpdate topoedgeupdate = new TopoEdgeUpdate(e, props, - UpdateType.ADDED); - topoedgeupdateList.add(topoedgeupdate); - } - edgeUpdate(topoedgeupdateList); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - public void stop() { - log.debug("Routing stop() is called"); - } - - public void setSwitchManager(ISwitchManager switchManager) { - this.switchManager = switchManager; - } - - public void unsetSwitchManager(ISwitchManager switchManager) { - if (this.switchManager == switchManager) { - this.switchManager = null; - } - } - - public void setTopologyManager(ITopologyManager tm) { - this.topologyManager = tm; - } - - public void unsetTopologyManager(ITopologyManager tm) { - if (this.topologyManager == tm) { - this.topologyManager = null; - } - } - - void setClusterContainerService(IClusterContainerServices s) { - log.debug("Cluster Service set"); - this.clusterContainerService = s; - } - - void unsetClusterContainerService(IClusterContainerServices s) { - if (this.clusterContainerService == s) { - log.debug("Cluster Service removed!"); - this.clusterContainerService = null; - } - } - - @Override - public void edgeOverUtilized(Edge edge) { - // TODO Auto-generated method stub - - } - - @Override - public void edgeUtilBackToNormal(Edge edge) { - // TODO Auto-generated method stub - - } -} diff --git a/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementationCLI.java b/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementationCLI.java deleted file mode 100644 index a6645cce14..0000000000 --- a/opendaylight/adsal/routing/dijkstra_implementation/src/main/java/org/opendaylight/controller/routing/dijkstra_implementation/internal/DijkstraImplementationCLI.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.routing.dijkstra_implementation.internal; - -import java.util.Dictionary; -import java.util.Hashtable; - -import org.apache.felix.service.command.Descriptor; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.Path; -import org.opendaylight.controller.sal.routing.IRouting; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.osgi.framework.ServiceRegistration; - -public class DijkstraImplementationCLI { - @SuppressWarnings("rawtypes") - private ServiceRegistration sr = null; - - public void init() { - } - - public void destroy() { - } - - public void start() { - final Dictionary props = new Hashtable(); - props.put("osgi.command.scope", "odpcontroller"); - props.put("osgi.command.function", new String[] { "getRoute" }); - this.sr = ServiceHelper.registerGlobalServiceWReg(DijkstraImplementationCLI.class, this, props); - } - - public void stop() { - if (this.sr != null) { - this.sr.unregister(); - this.sr = null; - } - } - - @Descriptor("Retrieves a Route between two Nodes in the discovered Topology DB") - public void getRoute( - @Descriptor("Container on the context of which the routing service need to be looked up") String container, - @Descriptor("String representation of the Source Node, this need to be consumable from Node.fromString()") String srcNode, - @Descriptor("String representation of the Destination Node") String dstNode) { - final IRouting r = (IRouting) ServiceHelper.getInstance(IRouting.class, container, this); - - if (r == null) { - System.out.println("Cannot find the routing instance on container:" + container); - return; - } - - final Node src = Node.fromString(srcNode); - final Node dst = Node.fromString(dstNode); - final Path p = r.getRoute(src, dst); - if (p != null) { - System.out.println("Route between srcNode:" + src + " and dstNode:" + dst + " = " + p); - } else { - System.out.println("There is no route between srcNode:" + src + " and dstNode:" + dst); - } - } -} diff --git a/opendaylight/adsal/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/DijkstraTest.java b/opendaylight/adsal/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/DijkstraTest.java deleted file mode 100644 index e3ae560d40..0000000000 --- a/opendaylight/adsal/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/DijkstraTest.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.routing.dijkstra_implementation; - -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Path; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.routing.dijkstra_implementation.internal.DijkstraImplementation; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DijkstraTest { - protected static final Logger logger = LoggerFactory - .getLogger(DijkstraTest.class); - - @Test - public void testSinglePathRouteNoBw() { - DijkstraImplementation imp = new DijkstraImplementation(); - imp.init(); - Node node1 = NodeCreator.createOFNode((long) 1); - Node node2 = NodeCreator.createOFNode((long) 2); - Node node3 = NodeCreator.createOFNode((long) 3); - List topoedgeupdateList = new ArrayList(); - NodeConnector nc11 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node1); - NodeConnector nc21 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node2); - Edge edge1 = null; - try { - edge1 = new Edge(nc11, nc21); - } catch (ConstructionException e) { - logger.error("", e); - } - Set props = new HashSet(); - props.add(new Bandwidth(0)); - TopoEdgeUpdate teu1 = new TopoEdgeUpdate(edge1, props, UpdateType.ADDED); - topoedgeupdateList.add(teu1); - - NodeConnector nc22 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node2); - NodeConnector nc31 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node3); - Edge edge2 = null; - try { - edge2 = new Edge(nc22, nc31); - } catch (ConstructionException e) { - logger.error("", e); - } - Set props2 = new HashSet(); - props2.add(new Bandwidth(0)); - TopoEdgeUpdate teu2 = new TopoEdgeUpdate(edge2, props2, - UpdateType.ADDED); - topoedgeupdateList.add(teu2); - imp.edgeUpdate(topoedgeupdateList); - Path res = imp.getRoute(node1, node3); - - List expectedPath = (List) new LinkedList(); - expectedPath.add(0, edge1); - expectedPath.add(1, edge2); - Path expectedRes = null; - try { - expectedRes = new Path(expectedPath); - } catch (ConstructionException e) { - logger.error("", e); - } - if (!res.equals(expectedRes)) { - System.out.println("Actual Res is " + res); - System.out.println("Expected Res is " + expectedRes); - } - Assert.assertTrue(res.equals(expectedRes)); - } - - @Test - public void testShortestPathRouteNoBw() { - DijkstraImplementation imp = new DijkstraImplementation(); - List topoedgeupdateList = new ArrayList(); - imp.init(); - Node node1 = NodeCreator.createOFNode((long) 1); - Node node2 = NodeCreator.createOFNode((long) 2); - Node node3 = NodeCreator.createOFNode((long) 3); - NodeConnector nc11 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node1); - NodeConnector nc21 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node2); - Edge edge1 = null; - try { - edge1 = new Edge(nc11, nc21); - } catch (ConstructionException e) { - logger.error("", e); - } - Set props = new HashSet(); - props.add(new Bandwidth(0)); - TopoEdgeUpdate teu1 = new TopoEdgeUpdate(edge1, props, UpdateType.ADDED); - topoedgeupdateList.add(teu1); - - NodeConnector nc22 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node2); - NodeConnector nc31 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node3); - Edge edge2 = null; - try { - edge2 = new Edge(nc22, nc31); - } catch (ConstructionException e) { - logger.error("", e); - } - Set props2 = new HashSet(); - props2.add(new Bandwidth(0)); - TopoEdgeUpdate teu2 = new TopoEdgeUpdate(edge2, props2, - UpdateType.ADDED); - topoedgeupdateList.add(teu2); - - NodeConnector nc12 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node1); - NodeConnector nc32 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node3); - Edge edge3 = null; - try { - edge3 = new Edge(nc12, nc32); - } catch (ConstructionException e) { - logger.error("", e); - } - Set props3 = new HashSet(); - props3.add(new Bandwidth(0)); - TopoEdgeUpdate teu3 = new TopoEdgeUpdate(edge3, props3, - UpdateType.ADDED); - topoedgeupdateList.add(teu3); - imp.edgeUpdate(topoedgeupdateList); - - Path res = imp.getRoute(node1, node3); - - List expectedPath = (List) new LinkedList(); - expectedPath.add(0, edge3); - Path expectedRes = null; - try { - expectedRes = new Path(expectedPath); - } catch (ConstructionException e) { - logger.error("", e); - } - if (!res.equals(expectedRes)) { - System.out.println("Actual Res is " + res); - System.out.println("Expected Res is " + expectedRes); - } - Assert.assertTrue(res.equals(expectedRes)); - } - - @Test - public void testShortestPathRouteNoBwAfterLinkDelete() { - DijkstraImplementation imp = new DijkstraImplementation(); - imp.init(); - List topoedgeupdateList = new ArrayList(); - Node node1 = NodeCreator.createOFNode((long) 1); - Node node2 = NodeCreator.createOFNode((long) 2); - Node node3 = NodeCreator.createOFNode((long) 3); - NodeConnector nc11 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node1); - NodeConnector nc21 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node2); - Edge edge1 = null; - try { - edge1 = new Edge(nc11, nc21); - } catch (ConstructionException e) { - logger.error("", e); - } - Set props = new HashSet(); - props.add(new Bandwidth(0)); - TopoEdgeUpdate teu1 = new TopoEdgeUpdate(edge1, props, UpdateType.ADDED); - topoedgeupdateList.add(teu1); - - NodeConnector nc22 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node2); - NodeConnector nc31 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node3); - Edge edge2 = null; - try { - edge2 = new Edge(nc22, nc31); - } catch (ConstructionException e) { - logger.error("", e); - } - Set props2 = new HashSet(); - props2.add(new Bandwidth(0)); - TopoEdgeUpdate teu2 = new TopoEdgeUpdate(edge2, props2, - UpdateType.ADDED); - topoedgeupdateList.add(teu2); - - NodeConnector nc12 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node1); - NodeConnector nc32 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node3); - Edge edge3 = null; - try { - edge3 = new Edge(nc12, nc32); - } catch (ConstructionException e) { - logger.error("", e); - } - Set props3 = new HashSet(); - props3.add(new Bandwidth(0)); - TopoEdgeUpdate teu3 = new TopoEdgeUpdate(edge3, props3, - UpdateType.ADDED); - topoedgeupdateList.add(teu3); - TopoEdgeUpdate teu4 = new TopoEdgeUpdate(edge3, props3, - UpdateType.REMOVED); - topoedgeupdateList.add(teu4); - - imp.edgeUpdate(topoedgeupdateList); - - Path res = imp.getRoute(node1, node3); - List expectedPath = (List) new LinkedList(); - expectedPath.add(0, edge1); - expectedPath.add(1, edge2); - Path expectedRes = null; - try { - expectedRes = new Path(expectedPath); - } catch (ConstructionException e) { - logger.error("", e); - } - if (!res.equals(expectedRes)) { - System.out.println("Actual Res is " + res); - System.out.println("Expected Res is " + expectedRes); - } - Assert.assertTrue(res.equals(expectedRes)); - } -} diff --git a/opendaylight/adsal/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/MaxThruputTest.java b/opendaylight/adsal/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/MaxThruputTest.java deleted file mode 100644 index 17952c8037..0000000000 --- a/opendaylight/adsal/routing/dijkstra_implementation/src/test/java/org/opendaylight/controller/routing/dijkstra_implementation/MaxThruputTest.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.routing.dijkstra_implementation; - -import org.junit.Test; - -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Path; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -import java.util.LinkedList; -import java.util.List; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Assert; -import org.opendaylight.controller.routing.dijkstra_implementation.internal.DijkstraImplementation; - -import org.opendaylight.controller.sal.core.UpdateType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MaxThruputTest { - protected static final Logger logger = LoggerFactory - .getLogger(MaxThruputTest.class); - Map LinkCostMap = new HashMap(); - - @Test - public void testMaxThruPut() { - DijkstraImplementation imp = new DijkstraImplementation(); - imp.init(); - Node node1 = NodeCreator.createOFNode((long) 1); - Node node2 = NodeCreator.createOFNode((long) 2); - Node node3 = NodeCreator.createOFNode((long) 3); - Node node4 = NodeCreator.createOFNode((long) 4); - Node node5 = NodeCreator.createOFNode((long) 5); - Node node6 = NodeCreator.createOFNode((long) 6); - NodeConnector nc11 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node1); - NodeConnector nc21 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node2); - NodeConnector nc31 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node3); - NodeConnector nc41 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node4); - NodeConnector nc51 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node5); - NodeConnector nc61 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, node6); - NodeConnector nc12 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node1); - NodeConnector nc22 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node2); - NodeConnector nc32 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node3); - NodeConnector nc42 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node4); - NodeConnector nc52 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node5); - NodeConnector nc62 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, node6); - - Edge edge1 = null; - try { - edge1 = new Edge(nc11, nc21); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge1, 10); - Edge edge2 = null; - try { - edge2 = new Edge(nc21, nc11); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge2, 10); - - Edge edge3 = null; - try { - edge3 = new Edge(nc22, nc31); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge3, 30); - Edge edge4 = null; - try { - edge4 = new Edge(nc31, nc22); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge4, 30); - - Edge edge5 = null; - try { - edge5 = new Edge(nc32, nc41); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge5, 10); - Edge edge6 = null; - try { - edge6 = new Edge(nc41, nc32); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge6, 10); - - Edge edge7 = null; - try { - edge7 = new Edge(nc12, nc51); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge7, 20); - Edge edge8 = null; - try { - edge8 = new Edge(nc51, nc12); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge8, 20); - - Edge edge9 = null; - try { - edge9 = new Edge(nc52, nc61); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge9, 20); - Edge edge10 = null; - try { - edge10 = new Edge(nc61, nc52); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge10, 20); - - Edge edge11 = null; - try { - edge11 = new Edge(nc62, nc42); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge11, 20); - Edge edge12 = null; - try { - edge12 = new Edge(nc42, nc62); - } catch (ConstructionException e) { - logger.error("", e); - } - LinkCostMap.put(edge12, 20); - - List topoedgeupdateList = new ArrayList(); - TopoEdgeUpdate teu1 = new TopoEdgeUpdate(edge1, null, UpdateType.ADDED); - topoedgeupdateList.add(teu1); - TopoEdgeUpdate teu2 = new TopoEdgeUpdate(edge2, null, UpdateType.ADDED); - topoedgeupdateList.add(teu2); - TopoEdgeUpdate teu3 = new TopoEdgeUpdate(edge3, null, UpdateType.ADDED); - topoedgeupdateList.add(teu3); - TopoEdgeUpdate teu4 = new TopoEdgeUpdate(edge4, null, UpdateType.ADDED); - topoedgeupdateList.add(teu4); - TopoEdgeUpdate teu5 = new TopoEdgeUpdate(edge5, null, UpdateType.ADDED); - topoedgeupdateList.add(teu5); - TopoEdgeUpdate teu6 = new TopoEdgeUpdate(edge6, null, UpdateType.ADDED); - topoedgeupdateList.add(teu6); - TopoEdgeUpdate teu7 = new TopoEdgeUpdate(edge7, null, UpdateType.ADDED); - topoedgeupdateList.add(teu7); - TopoEdgeUpdate teu8 = new TopoEdgeUpdate(edge8, null, UpdateType.ADDED); - topoedgeupdateList.add(teu8); - TopoEdgeUpdate teu9 = new TopoEdgeUpdate(edge9, null, UpdateType.ADDED); - topoedgeupdateList.add(teu9); - TopoEdgeUpdate teu10 = new TopoEdgeUpdate(edge10, null, - UpdateType.ADDED); - topoedgeupdateList.add(teu10); - TopoEdgeUpdate teu11 = new TopoEdgeUpdate(edge11, null, - UpdateType.ADDED); - topoedgeupdateList.add(teu11); - TopoEdgeUpdate teu12 = new TopoEdgeUpdate(edge12, null, - UpdateType.ADDED); - topoedgeupdateList.add(teu12); - - imp.edgeUpdate(topoedgeupdateList); - - imp.initMaxThroughput(LinkCostMap); - - Path res = imp.getMaxThroughputRoute(node1, node3); - System.out.println("Max Thruput Path between n1-n3: " + res); - - List expectedPath = (List) new LinkedList(); - expectedPath.add(0, edge7); - expectedPath.add(1, edge9); - expectedPath.add(2, edge11); - expectedPath.add(3, edge6); - - Path expectedRes = null; - try { - expectedRes = new Path(expectedPath); - } catch (ConstructionException e) { - logger.error("", e); - } - if (!res.equals(expectedRes)) { - System.out.println("Actual Res is " + res); - System.out.println("Expected Res is " + expectedRes); - } - Assert.assertTrue(res.equals(expectedRes)); - - res = imp.getRoute(node1, node3); - System.out.println("Shortest Path between n1-n3: " + res); - expectedPath.clear(); - expectedPath.add(0, edge1); - expectedPath.add(1, edge3); - - expectedRes = null; - try { - expectedRes = new Path(expectedPath); - } catch (ConstructionException e) { - logger.error("", e); - } - if (!res.equals(expectedRes)) { - System.out.println("Actual Res is " + res); - System.out.println("Expected Res is " + expectedRes); - } - Assert.assertTrue(res.equals(expectedRes)); - } -} diff --git a/opendaylight/adsal/sal/api/pom.xml b/opendaylight/adsal/sal/api/pom.xml deleted file mode 100644 index 2a618535b3..0000000000 --- a/opendaylight/adsal/sal/api/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - sal - 0.10.0-SNAPSHOT - bundle - - - junit - junit - - - org.apache.commons - commons-lang3 - - - org.apache.felix - org.apache.felix.dependencymanager - - - org.osgi - org.osgi.core - - - org.slf4j - slf4j-api - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.slf4j, - org.osgi.framework, - org.apache.commons.lang3.builder, - org.apache.felix.dm, - org.apache.commons.lang3.tuple, - javax.xml.bind.annotation, - javax.xml.bind.annotation.adapters - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.discovery, - org.opendaylight.controller.sal.topology, - org.opendaylight.controller.sal.routing, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.packet.address, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.inventory, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.reader - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Action.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Action.java deleted file mode 100644 index cf303b965e..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Action.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ConcurrentHashMap; - -import org.opendaylight.controller.sal.core.Property; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.io.Serializable; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -/** - * Represents the generic action to be applied to the matched - * frame/packet/message - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public abstract class Action implements Serializable { - private static final long serialVersionUID = 1L; - private static final Logger logger = LoggerFactory.getLogger(Action.class); - private static boolean debug = false; // Enable to find where in the code an - // invalid assignment is made - @XmlElement - protected ActionType type; - private transient boolean isValid = true; - private ConcurrentMap props; - - /* Dummy constructor for JAXB */ - public Action() { - } - - /** - * Checks if the passed value is in the valid range for this action - * - * @param value - * @return boolean - */ - protected void checkValue(int value) { - if (type.isValidTarget(value) == false) { - isValid = false; - throwValueException(value); - } - } - - /** - * Checks if the passed value is in the valid range for the passed action - * type This method is used for complex Action types which are - * - * @param value - * @return boolean - */ - protected void checkValue(ActionType type, int value) { - if (type.isValidTarget(value) == false) { - isValid = false; - throwValueException(value); - } - } - - /** - * Throw and handle the invalid value exception - * - * @param value - * @return void - */ - private void throwValueException(int value) { - String error = "Invalid field value assignement. For type: " + type.getId() + " Expected: " + type.getRange() - + ", Got: 0x" + Integer.toHexString(value); - try { - throw new Exception(error); - } catch (Exception e) { - logger.error(e.getMessage()); - if (debug) { - logger.error("", e); - } - } - } - - /** - * Gets the list of metadata currently registered with this match - * - * @return List of metadata currently registered - */ - public List getMetadatas() { - if (this.props != null) { - // Return all the values in the map - Collection res = this.props.values(); - if (res == null) { - return Collections.emptyList(); - } - return new ArrayList(res); - } - return Collections.emptyList(); - } - - /** - * Gets the metadata registered with a name if present - * - * @param name the name of the property to be extracted - * - * @return List of metadata currently registered - */ - public Property getMetadata(String name) { - if (name == null) { - return null; - } - if (this.props != null) { - // Return the Property associated to the name - return this.props.get(name); - } - return null; - } - - /** - * Sets the metadata associated to a name. If the name or prop is NULL, - * an exception NullPointerException will be raised. - * - * @param name the name of the property to be set - * @param prop, property to be set - */ - public void setMetadata(String name, Property prop) { - if (this.props == null) { - props = new ConcurrentHashMap(); - } - - if (this.props != null) { - this.props.put(name, prop); - } - } - - /** - * Remove the metadata associated to a name. If the name is NULL, - * nothing will be removed. - * - * @param name the name of the property to be set - * @param prop, property to be set - * - * @return List of metadata currently registered - */ - public void removeMetadata(String name) { - if (this.props == null) { - return; - } - - if (this.props != null) { - this.props.remove(name); - } - // It's intentional to keep the this.props still allocated - // till the parent data structure will be alive, so to avoid - // unnecessary allocation/deallocation, even if it's holding - // nothing - } - - /** - * Returns the type of this action - * - * @return ActionType - */ - public ActionType getType() { - return type; - } - - /** - * Returns the id of this action - * - * @return String - */ - public String getId() { - return type.getId(); - } - - /** - * Returns whether the Action is valid or not - * - * @return boolean - */ - public boolean isValid() { - return isValid; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((type == null) ? 0 : type.calculateConsistentHashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Action other = (Action) obj; - if (type != other.type) { - return false; - } - return true; - } - - @Override - public String toString() { - return type.toString(); - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/ActionType.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/ActionType.java deleted file mode 100644 index 0c059ea9d2..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/ActionType.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.action; - -/** - * The enumeration of actions supported by the controller - * Each entry has a unique id and the values range for the action element where applicable - */ -@Deprecated -public enum ActionType { - DROP("drop", 0, 0), - LOOPBACK("loopback", 0, 0), - FLOOD("flood", 0, 0), // regular switching flood (obeys to stp port state) - FLOOD_ALL("floodAll", 0, 0), // flood to all ports regardless of stp port state - CONTROLLER("controller", 0, 0), - INTERFACE("interface", 0, 0), // Interface - SW_PATH("software path", 0, 0), // OF Local - HW_PATH("harware path", 0, 0), - OUTPUT("output", 0, 0xffff), // physical port - ENQUEUE("enqueue", 0, 0xffff), - SET_DL_SRC("setDlSrc", 0, 0), - SET_DL_DST("setDlDst", 0, 0), - SET_VLAN_ID("setVlan", 1, 0xfff), - SET_VLAN_PCP("setVlanPcp", 0, 0x7), - SET_VLAN_CFI("setVlanCif", 0, 0x1), - POP_VLAN("stripVlan", 0, 0), // Pop - PUSH_VLAN("pushVlan", 0, 0xffff), // Push (the max value only takes into account the TCI portion of the 802.1q header) - SET_DL_TYPE("setDlType", 0, 0xffff), // Set ethertype/length field - SET_NW_SRC("setNwSrc", 0, 0), - SET_NW_DST("setNwDst", 0, 0), - SET_NW_TOS("setNwTos", 0, 0x3f), - SET_TP_SRC("setTpSrc", 0, 0xffff), // Set transport source port - SET_TP_DST("setTpDst", 0, 0xffff), // Set transport destination port - SET_NEXT_HOP("setNextHop", 0, 0); - - private String id; - private int minValue; - private int maxValue; - - private ActionType(String id, int minValue, int maxValue) { - this.id = id; - this.minValue = minValue; - this.maxValue = maxValue; - } - - public String getId() { - return id; - } - - public boolean isValidTarget(int value) { - return (value >= minValue && value <= maxValue); - } - - public String getRange() { - return "[0x" + Long.toHexString(minValue) + "-0x" + Long.toHexString(maxValue) + "]"; - } - - public boolean takesParameter() { - switch (this) { - case POP_VLAN: - case DROP: - case SW_PATH: - case HW_PATH: - case CONTROLLER: - case LOOPBACK: - case FLOOD: - case FLOOD_ALL: - return false; - default: - return true; - } - } - - public int calculateConsistentHashCode() { - if (this.id != null) { - return this.id.hashCode(); - } else { - return 0; - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Controller.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Controller.java deleted file mode 100644 index 9de09c5f46..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Controller.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Represents the action of punting the packet to the controller - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Controller extends Action { - private static final long serialVersionUID = 1L; - - public Controller() { - type = ActionType.CONTROLLER; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Drop.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Drop.java deleted file mode 100644 index bfef4c37da..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Drop.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Represent the action of dropping the matched packet - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Drop extends Action { - private static final long serialVersionUID = 1L; - - public Drop() { - type = ActionType.DROP; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Enqueue.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Enqueue.java deleted file mode 100644 index d80e2e7d68..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Enqueue.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.NodeConnector; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Enqueue extends Action { - private static final long serialVersionUID = 1L; - @XmlElement - private NodeConnector port; - @XmlElement - private int queue; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private Enqueue() { - } - - public Enqueue(NodeConnector port) { - type = ActionType.ENQUEUE; - this.port = port; - this.queue = 0; - } - - public Enqueue(NodeConnector port, int queue) { - type = ActionType.ENQUEUE; - this.port = port; - this.queue = queue; - } - - public NodeConnector getPort() { - return port; - } - - public int getQueue() { - return queue; - } - - @Override - public String toString() { - return String.format("%s[%s:%s]", type, port, queue); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Flood.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Flood.java deleted file mode 100644 index 02f5fe8e15..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Flood.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Represents the action of flooding the packet out - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Flood extends Action { - private static final long serialVersionUID = 1L; - - public Flood() { - type = ActionType.FLOOD; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/FloodAll.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/FloodAll.java deleted file mode 100644 index a11156f0c4..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/FloodAll.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Represents the action of flooding the packet out all the physical ports - * except the input port - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class FloodAll extends Action { - private static final long serialVersionUID = 1L; - - public FloodAll() { - type = ActionType.FLOOD_ALL; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/HwPath.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/HwPath.java deleted file mode 100644 index 56bcd230d9..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/HwPath.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Represents the action of sending the packet to the local hardware path for - * processing - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class HwPath extends Action { - private static final long serialVersionUID = 1L; - - public HwPath() { - type = ActionType.HW_PATH; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Loopback.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Loopback.java deleted file mode 100644 index 7b3198ab15..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Loopback.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Represents the action of looping the packet back the port it came in from - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Loopback extends Action { - private static final long serialVersionUID = 1L; - - public Loopback() { - type = ActionType.LOOPBACK; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Output.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Output.java deleted file mode 100644 index 862f656c6b..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/Output.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.NodeConnector; - -/** - * Represents the action of sending the packet out of a physical port - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Output extends Action { - private static final long serialVersionUID = 1L; - @XmlElement - private NodeConnector port; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private Output() { - } - - public Output(NodeConnector port) { - type = ActionType.OUTPUT; - this.port = port; - // checkValue(port); - } - - public NodeConnector getPort() { - return port; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Output other = (Output) obj; - if (port == null) { - if (other.port != null) { - return false; - } - } else if (!port.equals(other.port)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((port == null) ? 0 : port.hashCode()); - return result; - } - - @Override - public String toString() { - return type + "[" + port.toString() + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/PopVlan.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/PopVlan.java deleted file mode 100644 index 071ec71fed..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/PopVlan.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Pop vlan action (strip the outermost 802.1q header) - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class PopVlan extends Action { - private static final long serialVersionUID = 1L; - - public PopVlan() { - type = ActionType.POP_VLAN; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/PushVlan.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/PushVlan.java deleted file mode 100644 index 7c7c585bf4..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/PushVlan.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.EtherTypes; - -/** - * Insert a 802.1q (outermost) header action Execute it multiple times to - * achieve QinQ - * - * 802.1q = [TPID(16) + TCI(16)] TCI = [PCP(3) + CFI(1) + VID(12)] - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class PushVlan extends Action { - private static final long serialVersionUID = 1L; - private int tag; // TPID - 16 bits - private int pcp; // PCP - 3 bits - private int cfi; // CFI - 1 bit (drop eligible) - private int vlanId; // VID - 12 bits - private transient int tci; // TCI = [PCP + CFI + VID] - 16 bits - private transient int header; // full 802.1q header [TPID + TCI] - 32 bits - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private PushVlan() { - } - - public PushVlan(int tag, int pcp, int cfi, int vlanId) { - type = ActionType.PUSH_VLAN; - this.tag = tag; - this.cfi = cfi; - this.pcp = pcp; - this.vlanId = vlanId; - this.tci = createTci(); - this.header = createHeader(); - runChecks(); - } - - public PushVlan(EtherTypes tag, int pcp, int cfi, int vlanId) { - type = ActionType.PUSH_VLAN; - this.tag = tag.intValue(); - this.cfi = cfi; - this.pcp = pcp; - this.vlanId = vlanId; - this.tci = createTci(); - this.header = createHeader(); - runChecks(); - } - - /** - * Construct a new action instance which represents OF 1.3 PUSH_VLAN. - * - * @param tag An {@link EtherTypes} instance. - */ - public PushVlan(EtherTypes tag) { - this(tag.intValue()); - } - - /** - * Construct a new action instance which represents OF 1.3 PUSH_VLAN. - * - * @param tag An ethernet type of a new VLAN tag. - */ - public PushVlan(int tag) { - type = ActionType.PUSH_VLAN; - this.tag = tag; - - if (tag != EtherTypes.VLANTAGGED.intValue() && - tag != EtherTypes.QINQ.intValue()) { - // pass a value which will tell fail and tell something about the - // original wrong value - checkValue(ActionType.SET_DL_TYPE, 0xBAD << 16 | tag); - } - } - - private int createTci() { - return (pcp & 0x7) << 13 | (cfi & 0x1) << 12 | (vlanId & 0xfff); - } - - private int createHeader() { - return (tag & 0xffff) << 16 | (pcp & 0x7) << 13 | (cfi & 0x1) << 12 | (vlanId & 0xfff); - } - - private void runChecks() { - checkValue(ActionType.SET_DL_TYPE, tag); - checkValue(ActionType.SET_VLAN_PCP, pcp); - checkValue(ActionType.SET_VLAN_CFI, cfi); - checkValue(ActionType.SET_VLAN_ID, vlanId); - checkValue(tci); - - // Run action specific check which cannot be run by parent - if (tag != EtherTypes.VLANTAGGED.intValue() && tag != EtherTypes.QINQ.intValue() - && tag != EtherTypes.OLDQINQ.intValue() && tag != EtherTypes.CISCOQINQ.intValue()) { - // pass a value which will tell fail and tell something about the - // original wrong value - checkValue(ActionType.SET_DL_TYPE, 0xBAD << 16 | tag); - } - } - - /** - * Returns the VID portion of the 802.1q header this action will insert VID - * - (12 bits) - * - * @return byte[] - */ - public int getVlanId() { - return vlanId; - } - - /** - * Returns the CFI portion of the 802.1q header this action will insert CFI - * - (1 bit) - * - * @return - */ - public int getCfi() { - return cfi; - } - - /** - * Returns the vlan PCP portion of the 802.1q header this action will insert - * PCP - (3 bits) - * - * @return byte[] - */ - public int getPcp() { - return pcp; - } - - /** - * Returns the TPID portion of the 802.1q header this action will insert - * TPID - (16 bits) - */ - public int getTag() { - return tag; - } - - /** - * Returns the TCI portion of the 802.1q header this action will insert TCI - * = [PCP + CFI + VID] - (16 bits) - * - * @return - */ - public int getTci() { - return tci; - } - - /** - * Returns the full 802.1q header this action will insert header = [TPID + - * TIC] (32 bits) - * - * @return int - */ - @XmlElement(name = "VlanHeader") - public int getHeader() { - return header; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PushVlan other = (PushVlan) obj; - if (cfi != other.cfi) { - return false; - } - if (pcp != other.pcp) { - return false; - } - if (tag != other.tag) { - return false; - } - if (vlanId != other.vlanId) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + cfi; - result = prime * result + pcp; - result = prime * result + tag; - result = prime * result + vlanId; - return result; - } - - @Override - public String toString() { - return type + "[tag = " + tag + ", pcp = " + pcp + ", cfi = " + cfi + ", vlanId = " + vlanId + "]"; - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlDst.java deleted file mode 100644 index 23d0a226bc..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlDst.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import java.util.Arrays; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.HexEncode; - -/** - * Set destination datalayer address action - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetDlDst extends Action { - private static final long serialVersionUID = 1L; - private byte[] address; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private SetDlDst() { - } - - public SetDlDst(byte[] dlAddress) { - type = ActionType.SET_DL_DST; - this.address = dlAddress.clone(); - } - - /** - * Returns the datalayer address that this action will set - * - * @return byte[] - */ - public byte[] getDlAddress() { - return address.clone(); - } - - @XmlElement(name = "address") - public String getDlAddressString() { - return HexEncode.bytesToHexString(address); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetDlDst other = (SetDlDst) obj; - if (!Arrays.equals(address, other.address)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + Arrays.hashCode(address); - return result; - } - - @Override - public String toString() { - return type + "[address = " + HexEncode.bytesToHexString(address) + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlSrc.java deleted file mode 100644 index 735cda30f4..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlSrc.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import java.util.Arrays; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.HexEncode; - -/** - * Set source datalayer address action - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetDlSrc extends Action { - private static final long serialVersionUID = 1L; - private byte[] address; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private SetDlSrc() { - } - - public SetDlSrc(byte[] dlAddress) { - type = ActionType.SET_DL_SRC; - if (dlAddress != null) { - this.address = dlAddress.clone(); - } else { - this.address = null; - } - } - - /** - * Returns the datalayer address that this action will set - * - * @return byte[] - */ - public byte[] getDlAddress() { - return address.clone(); - } - - @XmlElement(name = "address") - public String getDlAddressString() { - return HexEncode.bytesToHexString(address); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetDlSrc other = (SetDlSrc) obj; - if (!Arrays.equals(address, other.address)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + Arrays.hashCode(address); - return result; - } - - @Override - public String toString() { - return type + "[address = " + HexEncode.bytesToHexString(address) + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlType.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlType.java deleted file mode 100644 index 0c8762cbc0..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetDlType.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.EtherTypes; - -/** - * Set ethertype/length field action - */ - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetDlType extends Action { - private static final long serialVersionUID = 1L; - @XmlElement - private int dlType; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private SetDlType() { - } - - public SetDlType(int dlType) { - type = ActionType.SET_DL_TYPE; - this.dlType = dlType; - checkValue(dlType); - } - - public SetDlType(EtherTypes dlType) { - type = ActionType.SET_DL_TYPE; - this.dlType = dlType.intValue(); - checkValue(this.dlType); - } - - /** - * Returns the ethertype/lenght value that this action will set - * - * @return byte[] - */ - public int getDlType() { - return dlType; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetDlType other = (SetDlType) obj; - if (dlType != other.dlType) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + dlType; - return result; - } - - @Override - public String toString() { - return type + "[dlType = 0x" + Integer.toHexString(dlType) + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNextHop.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNextHop.java deleted file mode 100644 index 7aa872d686..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNextHop.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.action; - -import java.net.InetAddress; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetNextHop extends Action { - private static final long serialVersionUID = 1L; - @XmlElement - private InetAddress address; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private SetNextHop() { - } - - public SetNextHop(InetAddress address) { - type = ActionType.SET_NEXT_HOP; - this.address = address; - } - - public InetAddress getAddress() { - return address; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((address == null) ? 0 : address.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetNextHop other = (SetNextHop) obj; - if (address == null) { - if (other.address != null) { - return false; - } - } else if (!address.equals(other.address)) { - return false; - } - return true; - } - - @Override - public String toString() { - return type + "[" + address.toString() + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwDst.java deleted file mode 100644 index bff7b35851..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwDst.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import java.net.InetAddress; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Set network destination address action - */ - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetNwDst extends Action { - private static final long serialVersionUID = 1L; - InetAddress address; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private SetNwDst() { - } - - public SetNwDst(InetAddress address) { - type = ActionType.SET_NW_DST; - this.address = address; - } - - /** - * Returns the network address this action will set - * - * @return InetAddress - */ - public InetAddress getAddress() { - return address; - } - - @XmlElement(name = "address") - public String getAddressAsString() { - return address.getHostAddress(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetNwDst other = (SetNwDst) obj; - if (address == null) { - if (other.address != null) { - return false; - } - } else if (!address.equals(other.address)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((address == null) ? 0 : address.hashCode()); - return result; - } - - @Override - public String toString() { - return type + "[address = " + address + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwSrc.java deleted file mode 100644 index b3d62bc2c1..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwSrc.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import java.net.InetAddress; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Set network source address action - */ - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetNwSrc extends Action { - private static final long serialVersionUID = 1L; - InetAddress address; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private SetNwSrc() { - } - - public SetNwSrc(InetAddress address) { - type = ActionType.SET_NW_SRC; - this.address = address; - } - - /** - * Returns the network address this action will set - * - * @return InetAddress - */ - public InetAddress getAddress() { - return address; - } - - @XmlElement(name = "address") - public String getAddressAsString() { - return address.getHostAddress(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetNwSrc other = (SetNwSrc) obj; - if (address == null) { - if (other.address != null) { - return false; - } - } else if (!address.equals(other.address)) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((address == null) ? 0 : address.hashCode()); - return result; - } - - @Override - public String toString() { - return type + "[address = " + address + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwTos.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwTos.java deleted file mode 100644 index fcb11f0a73..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwTos.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Set network TOS action - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetNwTos extends Action { - private static final long serialVersionUID = 1L; - @XmlElement - private int tos; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private SetNwTos() { - } - - public SetNwTos(int tos) { - type = ActionType.SET_NW_TOS; - this.tos = tos; - checkValue(tos); - } - - /** - * Returns the network TOS value which the action will set - * - * @return int - */ - public int getNwTos() { - return tos; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetNwTos other = (SetNwTos) obj; - if (tos != other.tos) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + tos; - return result; - } - - @Override - public String toString() { - return type + "[tos = 0x" + Integer.toHexString(tos) + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpDst.java deleted file mode 100644 index e352d1542e..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpDst.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Set destination transport port action - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetTpDst extends Action { - private static final long serialVersionUID = 1L; - @XmlElement - private int port; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private SetTpDst() { - } - - public SetTpDst(int port) { - type = ActionType.SET_TP_DST; - this.port = port; - checkValue(port); - } - - /** - * Returns the transport port the action will set - * - * @return - */ - public int getPort() { - return port; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetTpDst other = (SetTpDst) obj; - if (port != other.port) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + port; - return result; - } - - @Override - public String toString() { - return type + "[port = " + port + "]"; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpSrc.java deleted file mode 100644 index fa80c850f7..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetTpSrc.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Set source transport port action - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetTpSrc extends Action { - private static final long serialVersionUID = 1L; - @XmlElement - private int port; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private SetTpSrc() { - } - - public SetTpSrc(int port) { - type = ActionType.SET_TP_SRC; - this.port = port; - checkValue(port); - } - - /** - * Returns the transport port the action will set - * - * @return - */ - public int getPort() { - return port; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetTpSrc other = (SetTpSrc) obj; - if (port != other.port) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + port; - return result; - } - - @Override - public String toString() { - return type + "[port = " + port + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanCfi.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanCfi.java deleted file mode 100644 index e71bb68729..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanCfi.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Set vlan CFI action - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetVlanCfi extends Action { - private static final long serialVersionUID = 1L; - @XmlElement - private int cfi; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private SetVlanCfi() { - } - - public SetVlanCfi(int cfi) { - type = ActionType.SET_VLAN_CFI; - this.cfi = cfi; - checkValue(cfi); - } - - /** - * Returns the 802.1q CFI value that this action will set - * - * @return - */ - public int getCfi() { - return cfi; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetVlanCfi other = (SetVlanCfi) obj; - if (cfi != other.cfi) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + cfi; - return result; - } - - @Override - public String toString() { - return type + "[cfi = " + Integer.toHexString(cfi) + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanId.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanId.java deleted file mode 100644 index e06159bde2..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanId.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Set vlan id action - */ - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetVlanId extends Action { - private static final long serialVersionUID = 1L; - @XmlElement - private int vlanId; - - @SuppressWarnings("unused") - private SetVlanId() { - - } - - public SetVlanId(int vlanId) { - type = ActionType.SET_VLAN_ID; - this.vlanId = vlanId; - checkValue(vlanId); - } - - /** - * Returns the vlan id this action will set - * - * @return int - */ - public int getVlanId() { - return vlanId; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetVlanId other = (SetVlanId) obj; - if (vlanId != other.vlanId) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + vlanId; - return result; - } - - @Override - public String toString() { - return type + "[vlanId = " + vlanId + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanPcp.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanPcp.java deleted file mode 100644 index 31afbf3e92..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetVlanPcp.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Set vlan PCP action - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SetVlanPcp extends Action { - private static final long serialVersionUID = 1L; - @XmlElement - private int pcp; - - @SuppressWarnings("unused") - private SetVlanPcp() { - - } - - public SetVlanPcp(int pcp) { - type = ActionType.SET_VLAN_PCP; - this.pcp = pcp; - checkValue(pcp); - } - - /** - * Returns the value of the vlan PCP this action will set - * - * @return int - */ - public int getPcp() { - return pcp; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SetVlanPcp other = (SetVlanPcp) obj; - if (pcp != other.pcp) { - return false; - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + pcp; - return result; - } - - @Override - public String toString() { - return type + "[pcp = " + Integer.toHexString(pcp) + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SupportedFlowActions.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SupportedFlowActions.java deleted file mode 100644 index 4fd65310cf..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SupportedFlowActions.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; - -import org.opendaylight.controller.sal.core.Property; - -/** - * @file SupportedFlowActions.java - * - * @brief Class representing the supported flow actions - * - * Describes the supported flow actions - */ - -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SupportedFlowActions extends Property { - private static final long serialVersionUID = 1L; - public static final String SupportedFlowActionsPropName = "supportedFlowActions"; - private List> actions; - - private SupportedFlowActions() { - super(SupportedFlowActionsPropName); - this.actions = new ArrayList>(); - } - - public SupportedFlowActions(List> actions) { - super(SupportedFlowActionsPropName); - this.actions = new ArrayList>(actions); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((actions == null) ? 0 : actions.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SupportedFlowActions other = (SupportedFlowActions) obj; - if (actions == null) { - if (other.actions != null) { - return false; - } - } else if (!actions.equals(other.actions)) { - return false; - } - return true; - } - - public List> getActions() { - return new ArrayList>(this.actions); - } - - @XmlElement(name = "value") - @Override - public String getStringValue() { - List nameList = new ArrayList(); - for (Class clazz : actions) { - nameList.add(clazz.getSimpleName()); - } - Collections.sort(nameList); - return nameList.toString(); - } - - @Override - public Property clone() { - return new SupportedFlowActions(this.actions); - } - - @Override - public String toString() { - return this.getStringValue(); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SwPath.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SwPath.java deleted file mode 100644 index e700d25b62..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/action/SwPath.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.action; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Represents the action of sending the packet to the local software path for - * processing - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SwPath extends Action { - private static final long serialVersionUID = 1L; - - public SwPath() { - type = ActionType.SW_PATH; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRole.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRole.java deleted file mode 100644 index c36f981632..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRole.java +++ /dev/null @@ -1,45 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.authorization; - -import java.io.Serializable; - -/** - * Represents a user role level in the application space - * It contains the role name and the role level in the - * application context as specified by {@link AppRoleLevel} - */ -@Deprecated -public class AppRole implements Serializable { - private static final long serialVersionUID = 1L; - String name; - AppRoleLevel level; - - public AppRole(String name, AppRoleLevel level) { - this.name = name; - this.level = level; - } - - /** - * Returns the application role name - * @return the string containing the role name - */ - public String getName() { - return name; - } - - /** - * Returns the application role level - * @return the application user level - */ - public AppRoleLevel getLevel() { - return level; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRoleLevel.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRoleLevel.java deleted file mode 100644 index 98ac26e532..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AppRoleLevel.java +++ /dev/null @@ -1,56 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.authorization; - -import java.io.Serializable; - -/** - * Represents the application user role levels - * This level has meaning only inside the application context - * In the controller space such a role will be seen as APPUSER - * as specified in {@link UserLevel} - */ -@Deprecated -public enum AppRoleLevel implements Serializable { - APPADMIN(0, "App-Admin", "Application Administrator"), APPUSER(1, - "App-User", "Application User"), APPOPERATOR(2, "App-Operator", - "Application Operator"), NOUSER(255, "Unknown User", "Unknown User"); - - private int userLevel; - private String level; - private String prettyLevel; - - private AppRoleLevel(int userlevel, String level, String prettyLevel) { - this.userLevel = userlevel; - this.level = level; - this.prettyLevel = prettyLevel; - } - - public int toNumber() { - return this.userLevel; - } - - public String toString() { - return this.level; - } - - public String toStringPretty() { - return this.prettyLevel; - } - - public static AppRoleLevel fromString(String levelString) { - for (AppRoleLevel rolelevel : AppRoleLevel.values()) { - if (rolelevel.toString().equals(levelString)) { - return rolelevel; - } - } - return null; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AuthResultEnum.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AuthResultEnum.java deleted file mode 100644 index 05801bea29..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/AuthResultEnum.java +++ /dev/null @@ -1,53 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * Defines the enumerated values for possible results of an Authentication - * request made from a AAA client to a AAA server. - */ - -package org.opendaylight.controller.sal.authorization; - -import java.io.Serializable; - -@Deprecated -public enum AuthResultEnum implements Serializable { - AUTH_NONE("AUTH_NOT_ATTEMPTED"), AUTH_ACCEPT("AUTHENTICATION_ACCEPTED"), // request accepted - AUTH_REJECT("AUTHENTICATION_REJECTED"), // request rejected - AUTH_TIMEOUT("AUTHENTICATION_TIMEDOUT"), // request timeout - AUTH_USERNAME_EMPTY("AUTHENTICATION_USERNAME_EMPTY"), // user name is empty - AUTH_PASSWORD_EMPTY("AUTHENTICATION_PASSWORD_EMPTY"), // password is empty - AUTH_SECRET_EMPTY("AUTHENTICATION_SECRET_EMPTY"), // secret is empty - AUTH_COMM_ERROR("AUTHENTICATION_COMM_ERROR"), // communication channel problem - AUTH_INVALID_ADDR("AUTHENTICATION_INVALID_ADDR"), // invalid network address - AUTH_INVALID_PACKET("AUTHENTICATION_INVALID_PACKET"), // invalid packets or malformed attributes - - /* - * Local AAA values - */ - AUTH_ACCEPT_LOC("AUTHENTICATION_ACCEPTED"), // request accepted on local database - AUTH_REJECT_LOC("AUTHENTICATION_REJECTED"), // request rejected on local database - AUTH_INVALID_LOC_USER("INALID_LOCAL_USER"), - - /* - * Authorization - */ - AUTHOR_PASS("AUTHORIZATION_PASSED"), AUTHOR_FAIL("AUTHORIZATION_FAILED"), AUTHOR_ERROR( - "AUTHORIZATION_SERVER_ERROR"); - - private AuthResultEnum(String name) { - this.name = name; - } - - private String name; - - public String toString() { - return name; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/IResourceAuthorization.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/IResourceAuthorization.java deleted file mode 100644 index 0468ebd75b..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/IResourceAuthorization.java +++ /dev/null @@ -1,229 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.authorization; - -import java.util.List; -import java.util.Set; - -import org.opendaylight.controller.sal.utils.Status; - -/** - * Interface for applications which maintain an authorization - * database for their resources. Respective application web bundle - * and User Manager make use of this interface to retrieve - * authorization information at user or and role level. - */ -@Deprecated -public interface IResourceAuthorization { - - /** - * Create a Role name for the application - * - * @param role the role name - * @param userLevel the user level in the application context - * @return the status of the request - */ - public Status createRole(String role, AppRoleLevel userLevel); - - /** - * Remove a Role - * - * @param role the role name - * @return the status of the request - */ - public Status removeRole(String role); - - /** - * Return the list of roles configured for the application - * - * @return the list of roles - */ - public List getRoles(); - - /** - * Returns the application role level for the specified role. If the role is - * not known to this application NOUSER will be returned as specified in - * {@link AppRoleLevel} - * - * @param roleName - * the role name to query - * @return the application level of the given role in the application - * context as specified by {@link AppRoleLevel}. If the role is not - * part of this application's roles, NOUSER is returned. - */ - public AppRoleLevel getApplicationRoleLevel(String roleName); - - /** - * Returns whether the specified role is part of this application's roles - * - * @param roleName the role name to test - * @return true if the role belongs to this application, false otherwise - */ - public boolean isApplicationRole(String roleName); - - /** - * Create a resource group for application. - * - * NOTE: Resource addition is "best effort", if an object is not of correct type, - * it is discarded. - * - * @param groupName - * the name for the resource group - * @param resources - * the list of resources for the group - * @return the status of the request - */ - public Status createResourceGroup(String groupName, List resources); - - /** - * Removes a resource group - * - * @param groupName the name of the group - * @return the status of the request - */ - public Status removeResourceGroup(String groupName); - - /** - * Returns the list of resource groups configured for the application - * - * @return the list of resource group names - */ - public List getResourceGroups(); - - /** - * Assign a resource group to a role - * - * @param groupName the name of the resource group - * @param privilege the access privilege role will have on the resource group - * @param role the role name - * @return the status of the request - */ - @Deprecated - public Status assignResourceGroupToRole(String groupName, - Privilege privilege, String role); - - /** - * Assign a resource group to a role. The access privilege on the resources - * is inferred by the AppRoleLevel associated to role. - * - * @param groupName the name of the resource group - * @param role the role name - * @return the status of the request - */ - public Status assignResourceGroupToRole(String groupName, String role); - - /** - * Unassign the passed resource group from the specified role - * - * @param groupName the name of the resource group - * @param role the role name - * @return the status of the request - */ - public Status unassignResourceGroupFromRole(String groupName, String role); - - /** - * Returns the list of resource groups the given Role is authorized to use - * The returning object expresses the resource group name and the access - * its privilege for the given user role - * - * @param role the role name - * @return list of resources - */ - public List getAuthorizedGroups(String role); - - /** - * Returns the list of resources contained in the given resource group - * - * @param groupName the resource group name - * @return - */ - public List getResources(String groupName); - - /** - * Returns the list of authorized resources for the given role - * For each resource only the highest privilege occurrence is returned - * @param role the role name - * @return the list of Resource - */ - public List getAuthorizedResources(String role); - - /* - * Per user name API - */ - /** - * Returns the controller user role level the passed user name is associated with - * - * @param userName the user name - * @return the user role level as specified in {@link UserLevel} - */ - public UserLevel getUserLevel(String userName); - - /** - * Returns the application context user role level the passed user name is associated with - * - * @param userName the user name - * @return the user role level as specified in {@link AppRoleLevel} - */ - public AppRoleLevel getUserApplicationLevel(String userName); - - /** - * Returns the list of resources (resource + privilege) associated - * with the passed user name for this application context - * For each resource only the highest privilege occurrence is returned - * - * @param userName the user name - * @return the list of resources associated with this user name in this application context - */ - public Set getAllResourcesforUser(String userName); - - /** - * Returns the highest privilege that the user has on the specified - * resource in this application context - * - * @param userName the user name - * @param resource the given resource - * @return the privilege the user has on the passed resource - */ - public Privilege getResourcePrivilege(String userName, Object resource); - - /** - * Add a resource to a group - * - * @param groupName - * the resource group - * @param resource - * the resource object - * @return the status of the request - */ - public Status addResourceToGroup(String groupName, Object resource); - - /** - * Remove a resource from a group - * - * @param groupName - * the resource group - * @param resource - * the resource object - * @return the status of the request - */ - public Status removeResourceFromGroup(String groupName, Object resource); - - /** - * Return whether the specified user has access to this application. In - * other words if the user is associated any roles belonging to this - * application. - * - * @param userName - * the user name - * @return true if the user has access to this application's resources, - * false otherwise - */ - boolean isApplicationUser(String userName); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Privilege.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Privilege.java deleted file mode 100644 index e3d3217f21..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Privilege.java +++ /dev/null @@ -1,35 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.authorization; - -import java.io.Serializable; - -/** - * It represents the group/resource access privilege - */ -@Deprecated -public enum Privilege implements Serializable { - NONE(""), // no privilege - READ("r"), // read only - USE("u"), // use - WRITE("w"); // modify - - private String p; - - private Privilege(String p) { - this.p = p; - } - - @Override - public String toString() { - return p; - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Resource.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Resource.java deleted file mode 100644 index 9fa8b2ebb0..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/Resource.java +++ /dev/null @@ -1,71 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.authorization; - -import java.io.Serializable; - -/** - * It represents the elementary resource along with - * the access privilege associated to it - */ -@Deprecated -public class Resource implements Serializable { - private static final long serialVersionUID = 1L; - Object resource; // the generic resource - Privilege privilege; // read/use/write privilege - - public Resource(Object resource, Privilege privilege) { - this.resource = resource; - this.privilege = privilege; - } - - public Object getResource() { - return resource; - } - - public Privilege getPrivilege() { - return privilege; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((privilege == null) ? 0 : privilege.hashCode()); - result = prime * result - + ((resource == null) ? 0 : resource.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Resource other = (Resource) obj; - if (privilege != other.privilege) - return false; - if (resource == null) { - if (other.resource != null) - return false; - } else if (!resource.equals(other.resource)) - return false; - return true; - } - - @Override - public String toString() { - return "[" + resource + ", " + privilege.toString() + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/ResourceGroup.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/ResourceGroup.java deleted file mode 100644 index f5b4448916..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/ResourceGroup.java +++ /dev/null @@ -1,81 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.authorization; - -import java.io.Serializable; - -/** - * Represents a group of resources along with the privilege associated to it - * - * - * - */ -@Deprecated -public class ResourceGroup implements Serializable { - private static final long serialVersionUID = 1L; - private String groupName; // the resource group name - private Privilege privilege; // the privilege for this profile on the resource group - - public ResourceGroup(String groupName, Privilege privilege) { - this.groupName = groupName; - this.privilege = privilege; - } - - /** - * Returns the name for this resource group - * @return - */ - public String getGroupName() { - return groupName; - } - - /** - * Returns the privilege for this group on its resources - * @return - */ - public Privilege getPrivilege() { - return privilege; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((groupName == null) ? 0 : groupName.hashCode()); - result = prime * result - + ((privilege == null) ? 0 : privilege.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ResourceGroup other = (ResourceGroup) obj; - if (groupName == null) { - if (other.groupName != null) - return false; - } else if (!groupName.equals(other.groupName)) - return false; - if (privilege != other.privilege) - return false; - return true; - } - - @Override - public String toString() { - return "[" + groupName + ", " + privilege.toString() + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/UserLevel.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/UserLevel.java deleted file mode 100644 index f4db119d76..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/authorization/UserLevel.java +++ /dev/null @@ -1,47 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.authorization; - -import java.io.Serializable; - -/** - * Describes the user role level in the controller space - */ -@Deprecated -public enum UserLevel implements Serializable { - SYSTEMADMIN(0, "System-Admin", "System Administrator"), // can do everything - NETWORKADMIN(1, "Network-Admin", "Network Administrator"), // can do everything but setting a system admin user profile - NETWORKOPERATOR(2, "Network-Operator", "Network Operator"), // can only see what is configured anywhere - CONTAINERUSER(4, "Container-User", "Container User"), // container context user - APPUSER(5, "App-User", "Application User"), // application context user - NOUSER(255, "Not Authorized", "Not Authorized"); - - private int userLevel; - private String level; - private String prettyLevel; - - private UserLevel(int userlevel, String level, String prettyLevel) { - this.userLevel = userlevel; - this.level = level; - this.prettyLevel = prettyLevel; - } - - public int toNumber() { - return this.userLevel; - } - - public String toString() { - return this.level; - } - - public String toStringPretty() { - return this.prettyLevel; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Actions.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Actions.java deleted file mode 100644 index b3fa45bbc9..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Actions.java +++ /dev/null @@ -1,121 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file Actions.java - * - * @brief Class representing actions - * - * Describes supported actions - * @Deprecated This class is OF 1.0 specific. Use SupportedFlowActions instead. - */ -@Deprecated -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class Actions extends Property { - private static final long serialVersionUID = 1L; - @XmlElement(name="value") - private int actionsValue; - - public enum ActionType { - OUTPUT_PORT_ACTION(1<<0), - VLAN_VID_ACTION(1<<1), - VLAN_PCP_ACTION(1<<2), - VLAN_STRIP_ACTION(1<<3), - DLSRC_ACTION(1<<4), - DLDST_ACTION(1<<5), - NWSRC_ACTION(1<<6), - NWDST_ACTION(1<<7), - NWTOS_ACTION(1<<8), - TPTSRC_ACTION(1<<9), - TPTDST_ACTION(1<<10), - ENQUEUE_ACTION(1<<11), - VENDOR_ACTION(0xffff); - private final int at; - ActionType(int val) { - this.at = val; - } - public int getValue() { - return at; - } - } - - public static final String ActionsPropName = "actions"; - /** - * Construct a actions property - * - * @param actions the actions value - * @return Constructed object - */ - public Actions(int actions) { - super(ActionsPropName); - this.actionsValue = actions; - } - - /* - * Private constructor used for JAXB mapping - */ - private Actions() { - super(ActionsPropName); - this.actionsValue = 0; - } - - @Override - public Actions clone() { - return new Actions(this.actionsValue); - } - - public int getValue() { - return this.actionsValue; - } - - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + actionsValue; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Actions other = (Actions) obj; - if (actionsValue != other.actionsValue) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Actions[" + actionsValue + "]"; - } - - @Override - public String getStringValue() { - return Integer.toHexString(actionsValue); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/AdvertisedBandwidth.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/AdvertisedBandwidth.java deleted file mode 100644 index be42a59ab6..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/AdvertisedBandwidth.java +++ /dev/null @@ -1,58 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file AdvertisedBandWidth.java - * - * @brief Class representing advertised bandwidth - * - * Describes Advertised Bandwidth which could be of a link or whatever could have - * bandwidth as description. It's intended in multiple of bits per - * seconds. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@SuppressWarnings("serial") -@Deprecated -public class AdvertisedBandwidth extends Bandwidth { - public static final String AdvertisedBandwidthPropName = "advertisedBandwidth"; - - public AdvertisedBandwidth(long value) { - super(AdvertisedBandwidthPropName); - this.bandwidthValue = value; - } - - /* - * Private constructor used for JAXB mapping - */ - private AdvertisedBandwidth() { - super(AdvertisedBandwidthPropName); - this.bandwidthValue = 0; - } - - public AdvertisedBandwidth clone() { - return new AdvertisedBandwidth(this.bandwidthValue); - } - - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("AdvertisedBandWidth["); - sb.append(super.toString()); - sb.append("]"); - return sb.toString(); - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Bandwidth.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Bandwidth.java deleted file mode 100644 index 4fd962a65b..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Bandwidth.java +++ /dev/null @@ -1,132 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file BandWidth.java - * - * @brief Class representing bandwidth - * - * Describe Bandwidth which could be of a link or whatever could have - * bandwidth as description. It's intended in multiple of bits per - * seconds. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Bandwidth extends Property { - private static final long serialVersionUID = 1L; - - @XmlElement(name="value") - protected long bandwidthValue; - - public static final long BWUNK = 0; - public static final long BW1Kbps = (long) Math.pow(10, 3); - public static final long BW1Mbps = (long) Math.pow(10, 6); - public static final long BW10Mbps = (long) Math.pow(10, 7); - public static final long BW100Mbps = (long) Math.pow(10, 8); - public static final long BW1Gbps = (long) Math.pow(10, 9); - public static final long BW10Gbps = (long) Math.pow(10, 10); - public static final long BW40Gbps = 4 * (long) Math.pow(10, 10); - public static final long BW100Gbps = (long) Math.pow(10, 11); - public static final long BW400Gbps = 4 * (long) Math.pow(10, 11); - public static final long BW1Tbps = (long) Math.pow(10, 12); - public static final long BW1Pbps = (long) Math.pow(10, 15); - - public static final String BandwidthPropName = "bandwidth"; - - /* - * Private constructor used for JAXB mapping - */ - private Bandwidth() { - super(BandwidthPropName); - this.bandwidthValue = BWUNK; - } - - public Bandwidth(long bandwidth) { - super(BandwidthPropName); - this.bandwidthValue = bandwidth; - } - - public Bandwidth(int bandwidth) { - super(BandwidthPropName); - this.bandwidthValue = (long) bandwidth; - } - - public Bandwidth(short bandwidth) { - super(BandwidthPropName); - this.bandwidthValue = (long) bandwidth; - } - - public Bandwidth(String name) { - super(name); - } - - @Override - public Bandwidth clone() { - return new Bandwidth(this.bandwidthValue); - } - - public long getValue() { - return this.bandwidthValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result - + (int) (bandwidthValue ^ (bandwidthValue >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Bandwidth other = (Bandwidth) obj; - if (bandwidthValue != other.bandwidthValue) - return false; - return true; - } - - @Override - public String toString() { - return "BandWidth[" + getStringValue() + "]"; - } - - @Override - public String getStringValue() { - if (this.bandwidthValue == 0) { - return("UnKnown"); - } else if (this.bandwidthValue < BW1Kbps) { - return(this.bandwidthValue + "bps"); - } else if (this.bandwidthValue < BW1Mbps) { - return(Long.toString(this.bandwidthValue / BW1Kbps) + "Kbps"); - } else if (this.bandwidthValue < BW1Gbps) { - return(Long.toString(this.bandwidthValue / BW1Mbps) + "Mbps"); - } else if (this.bandwidthValue < BW1Tbps) { - return(Long.toString(this.bandwidthValue / BW1Gbps) + "Gbps"); - } else if (this.bandwidthValue < BW1Pbps) { - return(Long.toString(this.bandwidthValue / BW1Tbps) + "Tbps"); - } else { - return(this.bandwidthValue + "bps"); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Buffers.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Buffers.java deleted file mode 100644 index 010d9039f7..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Buffers.java +++ /dev/null @@ -1,93 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file Buffers.java - * - * @brief Class representing buffers - * - * Describes supported buffers (#packets) - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Buffers extends Property { - private static final long serialVersionUID = 1L; - @XmlElement(name="value") - private int buffersValue; - - public static final String BuffersPropName = "buffers"; - - /** - * Construct a Buffers property - * - * @param buffers the Buffers - * @return Constructed object - */ - public Buffers(int buffers) { - super(BuffersPropName); - this.buffersValue = buffers; - } - - /* - * Private constructor used for JAXB mapping - */ - private Buffers() { - super(BuffersPropName); - this.buffersValue = 0; - } - - @Override - public Buffers clone() { - return new Buffers(this.buffersValue); - } - - public int getValue() { - return this.buffersValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + buffersValue; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Buffers other = (Buffers) obj; - if (buffersValue != other.buffersValue) - return false; - return true; - } - - @Override - public String toString() { - return "Buffers[" + buffersValue + "]"; - } - - @Override - public String getStringValue() { - return Integer.toHexString(buffersValue); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Capabilities.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Capabilities.java deleted file mode 100644 index d6a9458fc0..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Capabilities.java +++ /dev/null @@ -1,110 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file Capabilities.java - * - * @brief Class representing capabilities - * - * Describes supported capabilities - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Capabilities extends Property { - private static final long serialVersionUID = 1L; - @XmlElement(name="value") - private int capabilitiesValue; - - public enum CapabilitiesType { - FLOW_STATS_CAPABILITY(1<<0), - TABLE_STATS_CAPABILITY(1<<1), - PORT_STATS_CAPABILITY(1<<2), - STP_CAPABILITY(1<<3), - RSVD_CAPABILITY(1<<4), - IP_REASSEM_CAPABILITY(1<<5), - QUEUE_STATS_CAPABILITY(1<<6), - ARP_MATCH_IP_CAPABILITY(1<<7); - private final int ct; - CapabilitiesType(int val) { - this.ct = val; - } - public int getValue() { - return ct; - } - } - - public static final String CapabilitiesPropName = "capabilities"; - /** - * Construct a Capabilities property - * - * @param capabilities the Capabilities value - * @return Constructed object - */ - public Capabilities(int capabilities) { - super(CapabilitiesPropName); - this.capabilitiesValue = capabilities; - } - - /* - * Private constructor used for JAXB mapping - */ - private Capabilities() { - super(CapabilitiesPropName); - this.capabilitiesValue = 0; - } - - @Override - public Capabilities clone() { - return new Capabilities(this.capabilitiesValue); - } - - public int getValue() { - return this.capabilitiesValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + capabilitiesValue; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Capabilities other = (Capabilities) obj; - if (capabilitiesValue != other.capabilitiesValue) - return false; - return true; - } - - @Override - public String toString() { - return "Capabilities[" + capabilitiesValue + "]"; - } - - @Override - public String getStringValue() { - return Integer.toHexString(capabilitiesValue); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ComponentActivatorAbstractBase.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ComponentActivatorAbstractBase.java deleted file mode 100644 index eb4ed5f6d1..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ComponentActivatorAbstractBase.java +++ /dev/null @@ -1,470 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -/** - * @file ComponentActivatorAbstractBase.java - * - * @brief Abstract class which need to be subclassed in order to - * track and register dependencies per-container - * - * Abstract class which need to be subclassed in order to - * track and register dependencies per-container - * - */ - -import java.util.Dictionary; -import java.util.Hashtable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.felix.dm.Component; -import org.apache.felix.dm.ComponentStateListener; -import org.apache.felix.dm.DependencyManager; -import org.apache.felix.dm.ServiceDependency; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Abstract class which need to be subclassed in order to track and - * register dependencies per-container - * - */ -@Deprecated -abstract public class ComponentActivatorAbstractBase implements - BundleActivator, IContainerAware { - Logger logger = LoggerFactory - .getLogger(ComponentActivatorAbstractBase.class); - private DependencyManager dm; - private ConcurrentMap, Component> dbInstances = new ConcurrentHashMap, Component>(); - private ConcurrentMap dbGlobalInstances = new ConcurrentHashMap(); - - /** - * Method that should be overriden by the derived class for customization - * during activation of the Component bundle in a container. - */ - protected void init() { - - } - - /** - * Method that should be overriden by the derived class for customization - * during DE-activation of the Component bundle in a container. - */ - public void destroy() { - - } - - /** - * Method which tells how many implementations are supported by - * the bundle. This way we can tune the number of components - * created. - * - * - * @return The list of implementations the bundle will support, - * this will be used to decide how many components need to be - * created per-container - */ - protected Object[] getImplementations() { - return null; - } - - /** - * Method which tells how many Global implementations are - * supported by the bundle. This way we can tune the number of - * components created. This components will be created ONLY at the - * time of bundle startup and will be destroyed only at time of - * bundle destruction, this is the major difference with the - * implementation retrieved via getImplementations where all of - * them are assumed to be in a container! - * - * - * @return The list of implementations the bundle will support, - * in Global version - */ - protected Object[] getGlobalImplementations() { - return null; - } - - /** - * Configure the dependency for a given instance inside a container - * - * @param c Component assigned for this instance, this will be - * what will be used for configuration - * @param imp implementation to be configured - * @param containerName container on which the configuration happens - */ - protected void configureInstance(Component c, Object imp, - String containerName) { - // do nothing by default - } - - /** - * Configure the dependency for a given instance Global - * - * @param c Component assigned for this instance, this will be - * what will be used for configuration - * @param imp implementation to be configured - * @param containerName container on which the configuration happens - */ - protected void configureGlobalInstance(Component c, Object imp) { - // Do nothing by default - } - - // Private class used to listen to state transition so we can - // implement the necessary logic to call "started" and "stopping" - // methods on the component. Right now the framework natively - // support only the call of: - // - "init": Called after dependency are satisfied - // - "start": Called after init but before services are registered - // - "stop": Called after services are unregistered but before the - // component is going to be destroyed - // - "destroy": Called to destroy the component. - // There is still a need for two notifications: - // - "started" method to be called after "start" and after the - // services has been registered in the OSGi service registry - // - "stopping" method to be called before "stop" method and - // before the services of the component are removed from OSGi - // service registry - class ListenerComponentStates implements ComponentStateListener { - @Override - public void starting(Component component) { - // do nothing - } - - @Override - public void started(Component component) { - if (component == null) { - return; - } - component.invokeCallbackMethod(new Object[] { component - .getService() }, "started", new Class[][] { - { Component.class }, {} }, new Object[][] { { component }, - {} }); - } - - @Override - public void stopped(Component component) { - // do nothing - } - - @Override - public void stopping(Component component) { - if (component == null) { - return; - } - component.invokeCallbackMethod(new Object[] { component - .getService() }, "stopping", new Class[][] { - { Component.class }, {} }, new Object[][] { { component }, - {} }); - } - } - - /** - * Method of IContainerAware called when a new container is available - * - * @param containerName Container being created - */ - @Override - public void containerCreate(String containerName) { - try { - Object[] imps = getImplementations(); - logger.trace("Creating instance {}", containerName); - if (imps != null) { - for (int i = 0; i < imps.length; i++) { - ImmutablePair key = new ImmutablePair( - containerName, imps[i]); - Component c = this.dbInstances.get(key); - if (c == null) { - c = this.dm.createComponent(); - c.addStateListener(new ListenerComponentStates()); - // Now let the derived class to configure the - // dependencies it wants - configureInstance(c, imps[i], containerName); - // Set the implementation so the component can manage - // its lifecycle - if (c.getService() == null) { - logger.trace("Setting implementation to: {}", - imps[i]); - c.setImplementation(imps[i]); - } - - //Set the service properties to include the containerName - //in the service, that is fundamental for supporting - //multiple services just distinguished via a container - @SuppressWarnings("unchecked") - Dictionary serviceProps = c - .getServiceProperties(); - if (serviceProps != null) { - logger.trace("Adding new property for container"); - serviceProps.put("containerName", containerName); - } else { - logger - .trace("Create a new properties for the service"); - serviceProps = new Hashtable(); - serviceProps.put("containerName", containerName); - } - c.setServiceProperties(serviceProps); - - // Now add the component to the dependency Manager - // which will immediately start tracking the dependencies - this.dm.add(c); - - //Now lets keep track in our shadow database of the - //association - this.dbInstances.put(key, c); - } else { - logger - .error("I have been asked again to create an instance " - + "on: " - + containerName - + "for object: " - + imps[i] - + "when i already have it!!"); - } - } - } - } catch (Exception ex) { - logger - .error("During containerDestroy invocation caught exception: " - + ex - + "\nStacktrace:" - + stackToString(ex.getStackTrace())); - } - } - - @Override - public void containerDestroy(String containerName) { - try { - Object[] imps = getImplementations(); - logger.trace("Destroying instance {}", containerName); - if (imps != null) { - for (int i = 0; i < imps.length; i++) { - ImmutablePair key = new ImmutablePair( - containerName, imps[i]); - Component c = this.dbInstances.get(key); - if (c != null) { - if (c.getService() != null) { - c.invokeCallbackMethod(new Object[] { c.getService() }, "containerStop", - new Class[][] {{ Component.class}, {} }, - new Object[][] { {c}, {} }); - } - // Now remove the component from dependency manager, - // which will implicitely stop it first - this.dm.remove(c); - } else { - logger - .error("I have been asked again to remove an instance " - + "on: " - + containerName - + "for object: " - + imps[i] - + "when i already have cleared it!!"); - } - - //Now lets remove the association from our shadow - //database so the component can be recycled, this is done - //unconditionally in case of spurious conditions - this.dbInstances.remove(key); - } - } - } catch (Exception ex) { - logger - .error("During containerDestroy invocation caught exception: " - + ex - + "\nStacktrace:" - + stackToString(ex.getStackTrace())); - } - } - - private String stackToString(StackTraceElement[] stack) { - if (stack == null) { - return ""; - } - StringBuffer buffer = new StringBuffer(); - - for (int i = 0; i < stack.length; i++) { - buffer.append("\n\t").append(stack[i].toString()); - } - return buffer.toString(); - } - - /** - * Method called by the OSGi framework when the OSGi bundle - * starts. The functionality we want to perform here are: - * - * 1) Register with the OSGi framework, that we are a provider of - * IContainerAware service and so in case of startup of a container we - * want to be called - * - * 2) Create data structures that allow to keep track of all the - * instances created per-container given the derived class of - * ComponentActivatorAbstractBase will act as a Factory manager - * - * @param context OSGi bundle context to interact with OSGi framework - */ - @Override - public void start(BundleContext context) { - try { - this.dm = new DependencyManager(context); - - logger.trace("Activating"); - - // Now create Global components - Object[] imps = getGlobalImplementations(); - if (imps != null) { - for (int i = 0; i < imps.length; i++) { - Object key = imps[i]; - Component c = this.dbGlobalInstances.get(key); - if (c == null) { - try { - c = this.dm.createComponent(); - c.addStateListener(new ListenerComponentStates()); - // Now let the derived class to configure the - // dependencies it wants - configureGlobalInstance(c, imps[i]); - // Set the implementation so the component - // can manage its lifesycle - if (c.getService() == null) { - logger.trace("Setting implementation to: {}", - imps[i]); - c.setImplementation(imps[i]); - } - - // Now add the component to the dependency - // Manager which will immediately start - // tracking the dependencies - this.dm.add(c); - } catch (Exception nex) { - logger.error("During creation of a Global " - + "instance caught exception: " + nex - + "\nStacktrace:" - + stackToString(nex.getStackTrace())); - } - - //Now lets keep track in our shadow database of the - //association - if (c != null) - this.dbGlobalInstances.put(key, c); - } else { - logger.error("I have been asked again to create an " - + "instance " + " Global for object: " - + imps[i] + "when i already have it!!"); - } - } - } - - // Register with OSGi the provider for the service IContainerAware - context.registerService( - IContainerAware.class.getName(), this, null); - - // Now call the derived class init function - this.init(); - - logger.trace("Activation DONE!"); - } catch (Exception ex) { - logger.error("During Activator start caught exception: " + ex - + "\nStacktrace:" + stackToString(ex.getStackTrace())); - } - } - - /** - * Method called by the OSGi framework when the OSGi bundle - * stops. The functionality we want to perform here are: - * - * 1) Force all the instances to stop and do cleanup and - * unreference them so garbage collection can clean them up - * - * NOTE: UN-Register with the OSGi framework,is not needed because - * the framework will automatically do it - * - * @param context OSGi bundle context to interact with OSGi framework - */ - @Override - public void stop(BundleContext context) { - try { - logger.trace("DE-Activating"); - - // Now call the derived class destroy function - this.destroy(); - - // Now remove all the components tracked for container components - for (ImmutablePair key : this.dbInstances.keySet()) { - try { - Component c = this.dbInstances.get(key); - if (c != null) { - logger.trace("Remove component on container: {} Object: {}", - key.getLeft(), key.getRight()); - this.dm.remove(c); - } - } catch (Exception nex) { - logger.error("During removal of a container component " - + "instance caught exception: " + nex - + "\nStacktrace:" - + stackToString(nex.getStackTrace())); - } - this.dbInstances.remove(key); - } - - // Now remove all the components tracked for Global Components - for (Object key : this.dbGlobalInstances.keySet()) { - try { - Component c = this.dbGlobalInstances.get(key); - if (c != null) { - logger.trace("Remove component for Object: {}" , key); - this.dm.remove(c); - } - } catch (Exception nex) { - logger.error("During removal of a Global " - + "instance caught exception: " + nex - + "\nStacktrace:" - + stackToString(nex.getStackTrace())); - } - - this.dbGlobalInstances.remove(key); - } - - // Detach Dependency Manager - this.dm = null; - - logger.trace("Deactivation DONE!"); - } catch (Exception ex) { - logger.error("During Activator stop caught exception: " + ex - + "\nStacktrace:" + stackToString(ex.getStackTrace())); - } - } - - /** - * Return a ServiceDependency customized ad hoc for slicing, this - * essentially the same org.apache.felix.dm.ServiceDependency just - * with some filters pre-set - * - * @param containerName containerName for which we want to create the dependency - * - * @return a ServiceDependency - */ - protected ServiceDependency createContainerServiceDependency( - String containerName) { - return (new ContainerServiceDependency(this.dm, containerName)); - } - - /** - * Return a ServiceDependency as provided by Dependency Manager as it's - * - * - * @return a ServiceDependency - */ - protected ServiceDependency createServiceDependency() { - return this.dm.createServiceDependency(); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Config.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Config.java deleted file mode 100644 index 3f5b173463..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Config.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * The class represents Admin Config status - * - * - */ -@XmlRootElement -@SuppressWarnings("serial") -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Config extends Property { - @XmlElement(name="value") - private short configValue; - - public static final short ADMIN_DOWN = 0; - public static final short ADMIN_UP = 1; - public static final short ADMIN_UNDEF = 0x7fff; - public static final String ConfigPropName = "config"; - - /* - * Private constructor used for JAXB mapping - */ - private Config() { - super(ConfigPropName); - this.configValue = ADMIN_UNDEF; - } - - public Config(short config) { - super(ConfigPropName); - this.configValue = config; - } - - @Override - public Config clone() { - return new Config(this.configValue); - } - - public short getValue() { - return this.configValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + configValue; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Config other = (Config) obj; - if (configValue != other.configValue) - return false; - return true; - } - - @Override - public String toString() { - return "Config["+ configValue +"]"; - } - - @Override - public String getStringValue() { - if (configValue == 0) { - return "ADMIN_DOWN"; - } else if (configValue == 1) { - return "ADMIN_UP"; - } else if (configValue == 0x7fff) { - return "ADMIN_UNDEF"; - } else { - return String.valueOf(configValue); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ConstructionException.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ConstructionException.java deleted file mode 100644 index 2dadff7b71..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ConstructionException.java +++ /dev/null @@ -1,29 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file ConstructionException.java - * - * - * @brief Describe an exception that is raised when a construction - * for a Node/NodeConnector/Edge or any of the SAL basic object fails - * because input passed are not valid or compatible - * - * - */ -package org.opendaylight.controller.sal.core; - -@Deprecated -public class ConstructionException extends Exception { - private static final long serialVersionUID = 1L; - - public ConstructionException(String message) { - super(message); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerFlow.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerFlow.java deleted file mode 100644 index aeb9fe718b..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerFlow.java +++ /dev/null @@ -1,148 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import java.io.Serializable; - -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.SetDlType; -import org.opendaylight.controller.sal.action.SetNwDst; -import org.opendaylight.controller.sal.action.SetNwSrc; -import org.opendaylight.controller.sal.action.SetTpDst; -import org.opendaylight.controller.sal.action.SetTpSrc; -import org.opendaylight.controller.sal.action.SetVlanId; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; - -/** - * Express a container flow - * - * - * - */ -@Deprecated -public class ContainerFlow implements Serializable { - private static final long serialVersionUID = 1L; - private Match match; - - public ContainerFlow(Match match) { - this.match = match; - } - - /** - * Returns a copy of the Match defined by this Container Flow - * - * @return Match - */ - public Match getMatch() { - return match.clone(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((match == null) ? 0 : match.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - ContainerFlow other = (ContainerFlow) obj; - if (match == null) { - if (other.match != null) { - return false; - } - } else if (!match.equals(other.match)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Container Flow [" + match.toString() + "]"; - } - - /** - * Returns whether the specified flow is allowed - * - * @return true if the flow is allowed, false otherwise - */ - public boolean allowsFlow(Flow flow) { - Match target = flow.getMatch(); - - // Check if flow's match is allowed - if (!this.allowsMatch(target)) { - return false; - } - - // Now check if the flow's actions are not allowed - // Create a Match which summarizes the list of actions - if (flow.getActions() == null) { - return true; - } - Match actionMatch = new Match(); - for (Action action : flow.getActions()) { - switch (action.getType()) { - case SET_VLAN_ID: - actionMatch.setField(MatchType.DL_VLAN, - ((Integer) ((SetVlanId) action).getVlanId()) - .shortValue()); - break; - case SET_DL_TYPE: - actionMatch.setField(MatchType.DL_TYPE, - ((Integer) ((SetDlType) action).getDlType()) - .shortValue()); - break; - case SET_NW_SRC: - actionMatch.setField(MatchType.NW_SRC, ((SetNwSrc) action) - .getAddress()); - break; - case SET_NW_DST: - actionMatch.setField(MatchType.NW_DST, ((SetNwDst) action) - .getAddress()); - break; - case SET_TP_SRC: - actionMatch.setField(MatchType.TP_SRC, - ((Integer) ((SetTpSrc) action).getPort()).shortValue()); - break; - case SET_TP_DST: - actionMatch.setField(MatchType.TP_DST, - ((Integer) ((SetTpDst) action).getPort()).shortValue()); - break; - default: - // This action cannot conflict - } - } - - return this.allowsMatch(actionMatch); - } - - /** - * Returns whether the specified match is allowed - * - * @param match the match to test - * @return true if the match is allowed, false otherwise - */ - public boolean allowsMatch(Match target) { - return !target.conflictWithFilter(this.match); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerServiceDependency.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerServiceDependency.java deleted file mode 100644 index 2db83340fc..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ContainerServiceDependency.java +++ /dev/null @@ -1,253 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -/** - * @file ContainerServiceDependency.java - * - * @brief Class representing a ServiceDependency on a container - * - * Class representing a ServiceDependency on a container - */ - -import java.util.Dictionary; -import org.osgi.framework.ServiceReference; -import org.apache.felix.dm.ServiceDependency; -import org.apache.felix.dm.DependencyManager; -import org.apache.felix.dm.Dependency; -import org.apache.felix.dm.DependencyActivation; -import org.apache.felix.dm.DependencyService; - -/** - * Class representing a ServiceDependency on a container - * - */ -@Deprecated -public class ContainerServiceDependency implements ServiceDependency, - DependencyActivation { - private ServiceDependency m_dep; - private String containerName; - - public ContainerServiceDependency(DependencyManager manager, - String containerName) { - this.m_dep = manager.createServiceDependency(); - this.containerName = containerName; - } - - private ContainerServiceDependency(ServiceDependency explicitDependency, - String containerName) { - this.m_dep = explicitDependency; - this.containerName = containerName; - } - - @SuppressWarnings("rawtypes") // can't change org.apache.felix.dm.ServiceDependency - @Override - public ServiceDependency setService(Class serviceName) { - this.m_dep.setService(serviceName, "(containerName=" - + this.containerName + ")"); - return this; - } - - @SuppressWarnings("rawtypes") // can't change org.apache.felix.dm.ServiceDependency - @Override - public ServiceDependency setService(Class serviceName, String serviceFilter) { - this.m_dep.setService(serviceName, "(&(containerName=" - + this.containerName + ")" + serviceFilter + ")"); - return this; - } - - @Override - public ServiceDependency setService(String serviceFilter) { - this.m_dep.setService("(&(containerName=" + this.containerName + ")" - + serviceFilter + ")"); - return this; - } - - @SuppressWarnings("rawtypes") // can't change org.apache.felix.dm.ServiceDependency - @Override - public ServiceDependency setService(Class serviceName, - ServiceReference serviceReference) { - this.m_dep.setService(serviceName, serviceReference); - return this; - } - - @Override - public ServiceDependency setDefaultImplementation(Object implementation) { - this.m_dep.setDefaultImplementation(implementation); - return this; - } - - @Override - public ServiceDependency setRequired(boolean required) { - this.m_dep.setRequired(required); - return this; - } - - @Override - public ServiceDependency setAutoConfig(boolean autoConfig) { - this.m_dep.setAutoConfig(autoConfig); - return this; - } - - @Override - public ServiceDependency setAutoConfig(String instanceName) { - this.m_dep.setAutoConfig(instanceName); - return this; - } - - @Override - public ServiceDependency setCallbacks(String added, String removed) { - this.m_dep.setCallbacks(added, removed); - return this; - } - - @Override - public ServiceDependency setCallbacks(String added, String changed, - String removed) { - this.m_dep.setCallbacks(added, changed, removed); - return this; - } - - @Override - public ServiceDependency setCallbacks(String added, String changed, - String removed, String swapped) { - this.m_dep.setCallbacks(added, changed, removed, swapped); - return this; - } - - @Override - public ServiceDependency setCallbacks(Object instance, String added, - String removed) { - this.m_dep.setCallbacks(instance, added, removed); - return this; - } - - @Override - public ServiceDependency setCallbacks(Object instance, String added, - String changed, String removed) { - this.m_dep.setCallbacks(instance, added, changed, removed); - return this; - } - - @Override - public ServiceDependency setCallbacks(Object instance, String added, - String changed, String removed, String swapped) { - this.m_dep.setCallbacks(instance, added, changed, removed, swapped); - return this; - } - - @Override - public ServiceDependency setPropagate(boolean propagate) { - this.m_dep.setPropagate(propagate); - return this; - } - - @Override - public ServiceDependency setPropagate(Object instance, String method) { - this.m_dep.setPropagate(instance, method); - return this; - } - - @Override - public ServiceDependency setInstanceBound(boolean isInstanceBound) { - this.m_dep.setInstanceBound(isInstanceBound); - return this; - } - - @Override - public Dependency createCopy() { - return new ContainerServiceDependency((ServiceDependency) this.m_dep - .createCopy(), this.containerName); - } - - @SuppressWarnings("rawtypes") // can't change org.apache.felix.dm.ServiceDependency - @Override - public Dictionary getProperties() { - return this.m_dep.getProperties(); - } - - @Override - public boolean isPropagated() { - return this.m_dep.isPropagated(); - } - - @Override - public boolean isRequired() { - return this.m_dep.isRequired(); - } - - @Override - public boolean isAvailable() { - return this.m_dep.isAvailable(); - } - - @Override - public boolean isInstanceBound() { - return this.m_dep.isInstanceBound(); - } - - @Override - public boolean isAutoConfig() { - return this.m_dep.isAutoConfig(); - } - - @SuppressWarnings("rawtypes") // can't change org.apache.felix.dm.ServiceDependency - @Override - public Class getAutoConfigType() { - return this.m_dep.getAutoConfigType(); - } - - @Override - public Object getAutoConfigInstance() { - return this.m_dep.getAutoConfigInstance(); - } - - @Override - public String getAutoConfigName() { - return this.m_dep.getAutoConfigName(); - } - - @Override - public void invokeAdded(DependencyService service) { - this.m_dep.invokeAdded(service); - } - - @Override - public void invokeRemoved(DependencyService service) { - this.m_dep.invokeRemoved(service); - } - - @Override - public String getName() { - return this.m_dep.getName(); - } - - @Override - public String getType() { - return this.m_dep.getType(); - } - - @Override - public int getState() { - return this.m_dep.getState(); - } - - @Override - public void start(DependencyService service) { - DependencyActivation a = (DependencyActivation) this.m_dep; - a.start(service); - } - - @Override - public void stop(DependencyService service) { - DependencyActivation a = (DependencyActivation) this.m_dep; - a.stop(service); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Description.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Description.java deleted file mode 100644 index 82ac8eb2a2..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Description.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * The class represents the Name property of an element. - */ -@XmlRootElement -@SuppressWarnings("serial") -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Description extends Property { - @XmlElement(name="value") - private String descriptionValue; - public static final String propertyName = "description"; - - /* - * Private constructor used for JAXB mapping - */ - private Description() { - super(propertyName); - this.descriptionValue = null; - } - - public Description(String description) { - super(propertyName); - this.descriptionValue = description; - } - - @Override - public Description clone() { - return new Description(this.descriptionValue); - } - - public String getValue() { - return this.descriptionValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result - + ((descriptionValue == null) ? 0 : descriptionValue.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Description other = (Description) obj; - if (descriptionValue == null) { - if (other.descriptionValue != null) - return false; - } else if (!descriptionValue.equals(other.descriptionValue)) - return false; - return true; - } - - @Override - public String toString() { - return "Description[" + descriptionValue + "]"; - } - - @Override - public String getStringValue() { - return descriptionValue; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Edge.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Edge.java deleted file mode 100644 index 18c38d9cd5..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Edge.java +++ /dev/null @@ -1,182 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file Edge.java - * - * @brief Describe an edge in network made of multiple SDN technologies - * - * Class that describe an Edge connecting two NodeConnector, the edge - * is directed because there is the head and the tail concept which - * implies a direction. - */ -package org.opendaylight.controller.sal.core; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * - * Class that describe an Edge connecting two NodeConnector, the edge - * is directed because there is the tail and the head concept which - * implies a direction. - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Edge implements Serializable { - private static final long serialVersionUID = 1L; - @XmlElement - private NodeConnector tailNodeConnector; - @XmlElement - private NodeConnector headNodeConnector; - - /** - * Private constructor used for JAXB mapping - */ - @SuppressWarnings("unused") - private Edge() { - this.tailNodeConnector = null; - this.headNodeConnector = null; - } - - /** - * Construct the Edge - * - * @param tailNodeConnector Tail Node output connector - * @param headNodeConnector Head Node input connector - * - */ - public Edge(NodeConnector tailNodeConnector, NodeConnector headNodeConnector) - throws ConstructionException { - if (tailNodeConnector == null || headNodeConnector == null) { - throw new ConstructionException( - "Null tail or head NodeConnector supplied"); - } else { - this.tailNodeConnector = tailNodeConnector; - this.headNodeConnector = headNodeConnector; - } - } - - /** - * Copy Construct the Edge - * - * @param src Edge to copy from - * - */ - public Edge(Edge src) throws ConstructionException { - if (src != null) { - this.tailNodeConnector = new NodeConnector(src - .getTailNodeConnector()); - this.headNodeConnector = new NodeConnector(src - .getHeadNodeConnector()); - } else { - throw new ConstructionException("src supplied was null"); - } - } - - /** - * Create the reversed edge - * @return The reversed edge. - */ - public Edge reverse() { - Edge re; - try { - re = new Edge(this.headNodeConnector, this.tailNodeConnector); - } catch (ConstructionException e) { - re = null; - } - return re; - } - /** - * getter of edge - * - * - * @return tail NodeConnector of the edge - */ - public NodeConnector getTailNodeConnector() { - return tailNodeConnector; - } - - /** - * setter for edge - * - * @param tailNodeConnector NodeConnector to set the tail - */ - public void setTailNodeConnector(NodeConnector tailNodeConnector) { - this.tailNodeConnector = tailNodeConnector; - } - - /** - * getter of edge - * - * - * @return head NodeConnector of the edge - */ - public NodeConnector getHeadNodeConnector() { - return headNodeConnector; - } - - /** - * setter for edge - * - * @param headNodeConnector NodeConnector to set the head - */ - public void setHeadNodeConnector(NodeConnector headNodeConnector) { - this.headNodeConnector = headNodeConnector; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime - * result - + ((headNodeConnector == null) ? 0 : headNodeConnector - .hashCode()); - result = prime - * result - + ((tailNodeConnector == null) ? 0 : tailNodeConnector - .hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Edge other = (Edge) obj; - if (headNodeConnector == null) { - if (other.headNodeConnector != null) - return false; - } else if (!headNodeConnector.equals(other.headNodeConnector)) - return false; - if (tailNodeConnector == null) { - if (other.tailNodeConnector != null) - return false; - } else if (!tailNodeConnector.equals(other.tailNodeConnector)) - return false; - return true; - } - - @Override - public String toString() { - return "(" + this.tailNodeConnector + "->" + this.headNodeConnector - + ")"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ForwardingMode.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ForwardingMode.java deleted file mode 100644 index 312a598194..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/ForwardingMode.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * The class represents the forwarding mode property of a node. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@SuppressWarnings("serial") -@Deprecated -public class ForwardingMode extends Property { - @XmlElement(name="value") - private final int modeValue; - public static final int REACTIVE_FORWARDING = 0; - public static final int PROACTIVE_FORWARDING = 1; - public static final String name = "forwarding"; - - /* - * Private constructor used for JAXB mapping - */ - private ForwardingMode() { - super(name); - this.modeValue = REACTIVE_FORWARDING; - } - - public ForwardingMode(int mode) { - super(name); - this.modeValue = mode; - } - - public int getValue() { - return this.modeValue; - } - - public boolean isProactive() { - return (modeValue == ForwardingMode.PROACTIVE_FORWARDING); - } - - public boolean isValid() { - return ((modeValue >= 0) && (modeValue <= 1)); - } - - @Override - public ForwardingMode clone() { - return new ForwardingMode(this.modeValue); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + modeValue; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - ForwardingMode other = (ForwardingMode) obj; - if (modeValue != other.modeValue) - return false; - return true; - } - - @Override - public String toString() { - return "Mode[" + modeValue + "]"; - } - - @Override - public String getStringValue() { - return (modeValue == ForwardingMode.PROACTIVE_FORWARDING) ? "Proactive" : "Reactive"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Host.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Host.java deleted file mode 100644 index 3e863ad711..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Host.java +++ /dev/null @@ -1,131 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import java.io.Serializable; -import java.net.InetAddress; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.packet.address.DataLinkAddress; - -@XmlRootElement(name="host") -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Host implements Serializable { - private static final long serialVersionUID = 1L; - @XmlElement - private DataLinkAddress dataLayerAddress; - private InetAddress networkAddress; - - public Host() { - - } - - /** - * Create an Host representation from the combination Data Link - * layer/Network layer address, both are needed to construct the - * object. Fake value can also be provided in case are not - * existent. - * - * @param dataLayerAddress Data Link Address for the host - * @param networkAddress Network Address for the host - * - * @return the constructed object - */ - public Host(DataLinkAddress dataLayerAddress, InetAddress networkAddress) - throws ConstructionException { - if (dataLayerAddress == null) { - throw new ConstructionException("Passed null datalink address"); - } - if (networkAddress == null) { - throw new ConstructionException("Passed null network address"); - } - this.dataLayerAddress = dataLayerAddress; - this.networkAddress = networkAddress; - } - - /** - * Copy constructor - * - * @param h Host to copy values from - * - * @return constructed copy - */ - public Host(Host h) throws ConstructionException { - if (h == null) { - throw new ConstructionException("Passed null host"); - } - this.dataLayerAddress = h.getDataLayerAddress(); - this.networkAddress = h.getNetworkAddress(); - } - - /** - * @return the dataLayerAddress - */ - public DataLinkAddress getDataLayerAddress() { - return this.dataLayerAddress; - } - - /** - * @return the networkAddress - */ - public InetAddress getNetworkAddress() { - return networkAddress; - } - - @XmlElement(name = "networkAddress") - public String getNetworkAddressAsString() { - return networkAddress.getHostAddress(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime - * result - + ((dataLayerAddress == null) ? 0 : dataLayerAddress.hashCode()); - result = prime * result - + ((networkAddress == null) ? 0 : networkAddress.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Host other = (Host) obj; - if (dataLayerAddress == null) { - if (other.dataLayerAddress != null) - return false; - } else if (!dataLayerAddress.equals(other.dataLayerAddress)) - return false; - if (networkAddress == null) { - if (other.networkAddress != null) - return false; - } else if (!networkAddress.equals(other.networkAddress)) - return false; - return true; - } - - @Override - public String toString() { - return "Host [dataLayerAddress=" + dataLayerAddress - + ", networkAddress=" + networkAddress + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainer.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainer.java deleted file mode 100644 index 98475d8e30..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainer.java +++ /dev/null @@ -1,82 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IContainer.java - * - * @brief Interface used to retrieve the status of a given Container - * - * - */ - -package org.opendaylight.controller.sal.core; - -import java.util.List; -import java.util.Set; - -/** - * - * Interface used to retrieve the status of a given Container - */ -@Deprecated -public interface IContainer { - /** - * Returns the Name of the container described - * - * @return the container Name - */ - public String getName(); - - /** - * The list of container flows associated with a container - * - * @return The list of FlowSpecs associated with the container - */ - public List getContainerFlows(); - - /** - * Return the tag on which a Node is expected to receive traffic - * for a given container. - * - * @param n The node for which we want to get the Tag - * - * @return the tag on which we expect to receive traffic on a - * given Node for a given container - */ - public short getTag(Node n); - - /** - * Return an array of all the NodeConnectors that are part of the - * container - * - * @return The array of nodeConnectors part of the container - */ - public Set getNodeConnectors(); - - /** - * Return an array of all the Nodes that are part of a container - * - * @return The array of Nodes that are part of the container - */ - public Set getNodes(); - - /** - * Return the well known administrator role for this container - * - * @return The administrator role for this container - */ - public String getContainerAdminRole(); - - /** - * Return the well known operator role for this container - * - * @return The operator role for this container - */ - public String getContainerOperatorRole(); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerAware.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerAware.java deleted file mode 100644 index 164db91cd1..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerAware.java +++ /dev/null @@ -1,32 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -/** - * The interface describes methods to be called when the Container is being - * created/destroyed - */ - -@Deprecated -public interface IContainerAware { - /** - * Method invoked to signal that a container is being created - * - * @param containerName Container being created - */ - public void containerCreate(String containerName); - - /** - * Method invoked to signal that a container is being destroyed - * - * @param containerName Container being destroyed - */ - public void containerDestroy(String containerName); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerListener.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerListener.java deleted file mode 100644 index ce94ee6de8..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerListener.java +++ /dev/null @@ -1,96 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IContainerListener.java - * - * @brief Set of methods needed to listen to changes in the Container - * configuration - * - * Set of methods needed to listen to changes in the Container - * configuration - * - * - */ -package org.opendaylight.controller.sal.core; - -/** - * The interface describes methods used to retrieve the status of a given - * Container - */ -@Deprecated -public interface IContainerListener { - /** - * Called to notify a change in the tag assigned to a switch - * - * @param containerName container for which the update has been raised - * @param n Node of the tag under notification - * @param oldTag previous version of the tag, this differ from the - * newTag only if the UpdateType is a modify - * @param newTag new value for the tag, different from oldTag only - * in case of modify operation - * @param t type of update - */ - public void tagUpdated(String containerName, Node n, short oldTag, - short newTag, UpdateType t); - - /** - * Notification raised when the container flow layout changes - * - * @param containerName - * container for which the update has been raised - * @param previousFlow - * previous value of the container flow - * {@link org.opendaylight.controller.sal.core.ContainerFlow} - * under update, differs from the currentFlow only and only if - * it's an update operation - * @param currentFlow - * current version of the container flow - * {@link org.opendaylight.controller.sal.core.ContainerFlow} - * differs from the previousFlow only in case of update - * @param t - * type of update - * {@link org.opendaylight.controller.sal.core.UpdateType} - */ - public void containerFlowUpdated(String containerName, - ContainerFlow previousFlow, ContainerFlow currentFlow, UpdateType t); - - /** - * Notification raised when a NodeConnector is added or removed in the - * container. - * - * @param containerName - * container for which the update has been raised - * @param p - * NodeConnector - * {@link org.opendaylight.controller.sal.core.NodeConnector} - * being updated - * @param t - * type of modification - * {@link org.opendaylight.controller.sal.core.UpdateType}, but - * among the types the modify operation is not expected to be - * raised because the nodeConnectors are anyway immutable so this - * is only used to add/delete - */ - public void nodeConnectorUpdated(String containerName, NodeConnector p, - UpdateType t); - - /** - * Notification raised when the container mode has changed This notification - * is needed for some bundle in the default container to cleanup some HW - * state when switching from non-slicing to slicing case and vice-versa - * - * @param t - * type of modification - * {@link org.opendaylight.controller.sal.core.UpdateType}. ADDED - * when first container is created, REMOVED when last container - * is removed - */ - public void containerModeUpdated(UpdateType t); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerLocalListener.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerLocalListener.java deleted file mode 100644 index 531f111509..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/IContainerLocalListener.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IContainerLocalListener.java - * - * @brief Set of methods needed to listen to changes in the Container - * configuration for listeners on the local cluster node only - */ -package org.opendaylight.controller.sal.core; - - -/** - * The interface describes methods used to publish the changes to a given - * Container configuration to listeners on the local cluster node only. - */ -@Deprecated -public interface IContainerLocalListener extends IContainerListener { - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Latency.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Latency.java deleted file mode 100644 index 677431abcb..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Latency.java +++ /dev/null @@ -1,136 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file Latency.java - * - * @brief Class representing Latency - * - * Describe a latency in picoseconds or multiple of its. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Latency extends Property { - private static final long serialVersionUID = 1L; - - @XmlElement(name="value") - private long latencyValue; - - public static final long LATENCYUNK = 0; - public static final long LATENCY1ns = (long) Math.pow(10, 3); - public static final long LATENCY10ns = (long) Math.pow(10, 4); - public static final long LATENCY100ns = (long) Math.pow(10, 5); - public static final long LATENCY1us = (long) Math.pow(10, 6); - public static final long LATENCY10us = (long) Math.pow(10, 7); - public static final long LATENCY100us = (long) Math.pow(10, 8); - public static final long LATENCY1ms = (long) Math.pow(10, 9); - public static final long LATENCY1s = (long) Math.pow(10, 12); - - public static final String LatencyPropName = "latency"; - - /* - * Private constructor used for JAXB mapping - */ - private Latency() { - super(LatencyPropName); - this.latencyValue = LATENCYUNK; - } - - public Latency(long latency) { - super(LatencyPropName); - this.latencyValue = latency; - } - - public Latency(int latency) { - super(LatencyPropName); - this.latencyValue = (long) latency; - } - - public Latency(short latency) { - super(LatencyPropName); - this.latencyValue = (long) latency; - } - - @Override - public Latency clone() { - return new Latency(this.latencyValue); - } - - public long getValue() { - return this.latencyValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + (int) (latencyValue ^ (latencyValue >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Latency other = (Latency) obj; - if (latencyValue != other.latencyValue) - return false; - return true; - } - - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - - sb.append("Latency["); - if (this.latencyValue == 0) { - sb.append("UnKnown"); - } else if (this.latencyValue < LATENCY1ns) { - sb.append(this.latencyValue).append("psec"); - } else if (this.latencyValue < LATENCY1us) { - sb.append(Long.toString(this.latencyValue / LATENCY1ns)).append("nsec"); - } else if (this.latencyValue < LATENCY1ms) { - sb.append(Long.toString(this.latencyValue / LATENCY1us)).append("usec"); - } else if (this.latencyValue < LATENCY1s) { - sb.append(Long.toString(this.latencyValue / LATENCY1ms)).append("msec"); - } - - sb.append("]"); - return sb.toString(); - } - - @Override - public String getStringValue() { - if (this.latencyValue == 0) { - return("UnKnown"); - } else if (this.latencyValue < LATENCY1ns) { - return(this.latencyValue + "psec"); - } else if (this.latencyValue < LATENCY1us) { - return(Long.toString(this.latencyValue / LATENCY1ns) + "nsec"); - } else if (this.latencyValue < LATENCY1ms) { - return(Long.toString(this.latencyValue / LATENCY1us) + "usec"); - } else if (this.latencyValue < LATENCY1s) { - return(Long.toString(this.latencyValue / LATENCY1ms) + "msec"); - } else { - return Long.toString(this.latencyValue) + "sec"; - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/MacAddress.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/MacAddress.java deleted file mode 100644 index 737058a7be..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/MacAddress.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.HexEncode; - -/** - * The class contains MAC address property. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class MacAddress extends Property implements Cloneable { - private static final long serialVersionUID = 1L; - @XmlElement(name="value") - private final String address; - public static final String name = "macAddress"; - - /* - * Private constructor used for JAXB mapping - */ - private MacAddress() { - super(name); - this.address = null; - } - - /** - * Constructor to create DatalinkAddress property which contains the MAC - * address. The property will be attached to a - * {@link org.opendaylight.controller.sal.core.Node}. - * - * - * @param nodeMacAddress - * Data Link Address for the node in byte array format - * - * @return the constructed object - */ - public MacAddress(byte[] nodeMacAddress) { - super(name); - this.address = HexEncode.bytesToHexStringFormat(nodeMacAddress); - } - - /** - * Constructor to create DatalinkAddress property which contains the MAC - * address. The property will be attached to a - * {@link org.opendaylight.controller.sal.core.Node}. - * - * - * @param nodeMacAddress - * Data Link Address for the node in String format - * - * @return the constructed object - */ - public MacAddress(String nodeMacAddress) { - super(name); - this.address = nodeMacAddress; - } - - /** - * @return the node MAC address in byte array format - */ - public byte[] getMacAddress() { - return HexEncode.bytesFromHexString(this.address); - } - - @Override - public MacAddress clone() { - return new MacAddress(this.address); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result - + ((address == null) ? 0 : address.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - MacAddress other = (MacAddress) obj; - if (!address.equals(other.address)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "MacAddress[" + address + "]"; - } - - @Override - public String getStringValue() { - return address; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Name.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Name.java deleted file mode 100644 index a1d80f28a7..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Name.java +++ /dev/null @@ -1,86 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * The class represents the Name property of an element. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@SuppressWarnings("serial") -@Deprecated -public class Name extends Property { - @XmlElement(name="value") - private String nameValue; - public static final String NamePropName = "name"; - - /* - * Private constructor used for JAXB mapping - */ - private Name() { - super(NamePropName); - this.nameValue = null; - } - - public Name(String name) { - super(NamePropName); - this.nameValue = name; - } - - @Override - public Name clone() { - return new Name(this.nameValue); - } - - public String getValue() { - return this.nameValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result - + ((nameValue == null) ? 0 : nameValue.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Name other = (Name) obj; - if (nameValue == null) { - if (other.nameValue != null) - return false; - } else if (!nameValue.equals(other.nameValue)) - return false; - return true; - } - - @Override - public String toString() { - return "Name[" + nameValue + "]"; - } - - @Override - public String getStringValue() { - return nameValue; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Node.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Node.java deleted file mode 100644 index be1ed0746a..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Node.java +++ /dev/null @@ -1,459 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file Node.java - * - * @brief Describe a generic network element in multiple SDNs technologies - * - * Describe a generic network element in multiple SDNs technologies. A - * Node is identified by the pair (NodeType, NodeID), the nodetype are - * needed in order to further specify the nodeID - */ -package org.opendaylight.controller.sal.core; - -import java.io.Serializable; -import java.math.BigInteger; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.INodeFactory; -import org.opendaylight.controller.sal.utils.ServiceHelper; - -/** - * Describe a generic network element in multiple SDNs technologies. A - * Node is identified by the pair (NodeType, NodeID), the nodetype are - * needed in order to further specify the nodeID - * - */ -@XmlAccessorType(XmlAccessType.NONE) -@XmlRootElement -@Deprecated -public class Node implements Serializable { - private static final long serialVersionUID = 1L; - - /** - * Enum-like static class created with the purpose of identifing - * multiple type of nodes in the SDN network. The type is - * necessary to figure out to later on correctly use the - * nodeID. Using a static class instead of an Enum so we can add - * dynamically new types without changing anything in the - * surround. - */ - public static final class NodeIDType { - private static final ConcurrentHashMap> compatibleType = - new ConcurrentHashMap>(); - /** - * Identifier for an OpenFlow node - */ - public static String OPENFLOW = "OF"; - /** - * Identifier for a PCEP node - */ - public static String PCEP = "PE"; - /** - * Identifier for a ONEPK node - */ - public static String ONEPK = "PK"; - /** - * Identifier for a node in a non-SDN network - */ - public static String PRODUCTION = "PR"; - - // Pre-populated types, just here for convenience and ease of - // unit-testing, but certainly those could live also outside. - static { - compatibleType.put(OPENFLOW, Long.class); - compatibleType.put(PCEP, UUID.class); - compatibleType.put(ONEPK, String.class); - compatibleType.put(PRODUCTION, String.class); - } - - /** - * Return the type of the class expected for the - * NodeID, it's used for validity check in the constructor - * - * @param nodeType the type of the node we want to check - * compatibility for - * - * @return The Class which is supposed to instantiate the ID - * for the NodeID - */ - public static Class getClassType(String nodeType) { - return compatibleType.get(nodeType); - } - - /** - * Returns all the registered nodeIDTypes currently available - * - * @return The current registered NodeIDTypes - */ - public static Set values() { - return compatibleType.keySet(); - } - - /** - * Register a new ID for which Node can be created - * - * @param type, the new type being registered - * @param compatibleID, the type of class to be accepted as ID - * - * @return true if registered, false otherwise - */ - public static boolean registerIDType(String type, - Class compatibleID) { - if (compatibleType.get(type) != null) { - return false; - } else { - compatibleType.put(type, compatibleID); - return true; - } - } - - /** - * UNRegister a new ID for which Node can be created - * - * @param type, the type being UN-registered - * - */ - public static void unRegisterIDType(String type) { - compatibleType.remove(type); - } - } - - // This is the identity of the Node a (Type,ID) pair!, the full - // essence of this class. - private Object nodeID; - private String nodeType; - - // Shadow value for unmarshalling - private String nodeIDString; - - /** - * Private constructor used for JAXB mapping - */ - private Node() { - this.nodeID = null; - this.nodeType = null; - this.nodeIDString = null; - } - - /** - * Constructor for the Node objects, it validate the input so if - * the ID passed is not of the type expected accordingly to the - * type an exception is raised. - * - * @param nodeType Type of the node we are building - * @param id ID used by the SDN technology to identify the node - * - */ - public Node(String nodeType, Object id) throws ConstructionException { - if (NodeIDType.getClassType(nodeType) != null && - NodeIDType.getClassType(nodeType).isInstance(id)) { - this.nodeType = nodeType; - this.nodeID = id; - } else { - throw new ConstructionException("Type of incoming object:" - + id.getClass() + " not compatible with expected type:" - + NodeIDType.getClassType(nodeType)); - } - } - - /** - * Copy Constructor for the Node objects. - * - * @param src type of nodes to copy from - * - */ - public Node(Node src) throws ConstructionException { - if (src != null) { - this.nodeType = src.getType(); - // Here we can reference the object because that is - // supposed to be an immutable identifier as well like a - // UUID/Integer and so on, hence no need to create a copy - // of it - this.nodeID = src.getID(); - } else { - throw - new ConstructionException("Null incoming object to copy from"); - } - } - - /** - * getter for node type - * - * - * @return The node Type for this Node object - */ - @XmlElement(name = "type") - public String getType() { - return this.nodeType; - } - - /** - * fill the current object from the string parameters passed, will - * be only used by JAXB - * - * @param typeStr string representing the type of the Node - * @param IDStr String representation of the ID - */ - private void fillmeFromString(String typeStr, String IDStr) { - if (typeStr == null) { - return; - } - - if (IDStr == null) { - return; - } - - this.nodeType = typeStr; - if (typeStr.equals(NodeIDType.OPENFLOW)) { - this.nodeID = Long.valueOf(HexEncode.stringToLong(IDStr)); - } else if (typeStr.equals(NodeIDType.ONEPK)) { - this.nodeID = IDStr; - } else if (typeStr.equals(NodeIDType.PCEP)) { - this.nodeID = UUID.fromString(IDStr); - } else if (typeStr.equals(NodeIDType.PRODUCTION)) { - this.nodeID = IDStr; - } else { - //Use plugin's method to get appropriate conversion from IDStr to nodeID - INodeFactory f = (INodeFactory) ServiceHelper - .getGlobalInstance(INodeFactory.class, new Node(), "(protocolName="+typeStr+")"); - if(f!=null){ - Node n = f.fromString(typeStr, IDStr); - this.nodeID = n.nodeID; - } - } - } - - /** - * Private setter for nodeType to be called by JAXB not by anyone - * else, Node is immutable - * - * @param type of node to be set - */ - @SuppressWarnings("unused") - private void setType(String type) { - this.nodeType = type; - if (this.nodeIDString != null) { - this.fillmeFromString(type, this.nodeIDString); - } - } - - /** - * getter for node ID - * - * - * @return The node ID for this Node object - */ - public Object getID() { - return this.nodeID; - } - - /** - * Getter for the node ID in string format - * - * @return The nodeID in string format - */ - @XmlElement(name = "id") - public String getNodeIDString() { - if (this.nodeType.equals(NodeIDType.OPENFLOW)) { - return HexEncode.longToHexString((Long) this.nodeID); - } else { - return this.nodeID.toString(); - } - } - - /** - * private setter to be used by JAXB - * - * @param nodeIDString String representation for NodeID - */ - @SuppressWarnings("unused") - private void setNodeIDString(String nodeIDString) { - this.nodeIDString = nodeIDString; - if (this.nodeType != null) { - this.fillmeFromString(this.nodeType, nodeIDString); - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode()); - result = prime * result - + ((nodeType == null) ? 0 : nodeType.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Node other = (Node) obj; - if (nodeID == null) { - if (other.nodeID != null) - return false; - } else if (!nodeID.equals(other.nodeID)) - return false; - if (nodeType == null) { - if (other.nodeType != null) - return false; - } else if (!nodeType.equals(other.nodeType)) - return false; - return true; - } - - @Override - public String toString() { - if (this.nodeType.equals(NodeIDType.OPENFLOW)) { - return this.nodeType + "|" - + HexEncode.longToHexString((Long) this.nodeID); - } else { - return this.nodeType + "|" + this.nodeID.toString(); - } - } - - /** - * Static method to get back a Node from a string - * - * @param str string formatted in toString mode that can be - * converted back to a Node format. - * - * @return a Node if succed or null if no - */ - public static Node fromString(String str) { - if (str == null) { - return null; - } - - String parts[] = str.split("\\|"); - if (parts.length != 2) { - // Try to guess from a String formatted as a long because - // for long time openflow has been prime citizen so lets - // keep this legacy for now - String numStr = str.toUpperCase(); - - Long ofNodeID = null; - if (numStr.startsWith("0X")) { - // Try as an hex number - try { - BigInteger b = new BigInteger( - numStr.replaceFirst("0X", ""), 16); - ofNodeID = Long.valueOf(b.longValue()); - } catch (Exception ex) { - ofNodeID = null; - } - } else { - // Try as a decimal number - try { - BigInteger b = new BigInteger(numStr); - ofNodeID = Long.valueOf(b.longValue()); - } catch (Exception ex) { - ofNodeID = null; - } - } - - // Startegy #3 parse as HexLong - if (ofNodeID == null) { - try { - ofNodeID = Long.valueOf(HexEncode.stringToLong(numStr)); - } catch (Exception ex) { - ofNodeID = null; - } - } - - // We ran out of ideas ... return null - if (ofNodeID == null) { - return null; - } - - // Lets return the cooked up NodeID - try { - return new Node(NodeIDType.OPENFLOW, ofNodeID); - } catch (ConstructionException ex) { - return null; - } - } - - String typeStr = parts[0]; - String IDStr = parts[1]; - - return fromString(typeStr, IDStr); - } - - /** - * Static method to get back a Node from a pair of strings, the - * first one being the Type representation, the second one being - * the ID string representation, expected to be heavily used in - * northbound API. - * - * @param type, the type of the node we are parsing - * @param id, the string representation of the node id - * - * @return a Node if succed or null if no - */ - public static Node fromString(String typeStr, String IDStr) { - if (typeStr == null) { - return null; - } - - if (IDStr == null) { - return null; - } - - if (typeStr.equals(NodeIDType.OPENFLOW)) { - try { - Long ID = Long.valueOf(HexEncode.stringToLong(IDStr)); - return new Node(typeStr, ID); - } catch (Exception ex) { - return null; - } - } else if (typeStr.equals(NodeIDType.ONEPK)) { - try { - return new Node(typeStr, IDStr); - } catch (Exception ex) { - return null; - } - } else if (typeStr.equals(NodeIDType.PCEP)) { - try { - UUID ID = UUID.fromString(IDStr); - return new Node(typeStr, ID); - } catch (Exception ex) { - return null; - } - } else if (typeStr.equals(NodeIDType.PRODUCTION)) { - try { - return new Node(typeStr, IDStr); - } catch (Exception ex) { - return null; - } - } else { - //Use INodeFactory to create a Node of registered Node type. - //The protocol plugin being used depends on typeStr. - INodeFactory f = (INodeFactory) ServiceHelper - .getGlobalInstance(INodeFactory.class, new Node(), "(protocolName="+typeStr+")"); - if(f==null) - return null; - return f.fromString(typeStr, IDStr); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeConnector.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeConnector.java deleted file mode 100644 index 7b1058a3c9..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeConnector.java +++ /dev/null @@ -1,652 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file NodeConnector.java - * - * @brief Describe a generic network element attachment points, - * attached to one Node, the NodeConnector is formed by the pair - * (NodeConnectorType, NodeConnectorID) because each SDN technlogy can - * identify an attachment point on the Node in different way. - * - */ -package org.opendaylight.controller.sal.core; - -import java.io.Serializable; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.opendaylight.controller.sal.utils.INodeConnectorFactory; -import org.opendaylight.controller.sal.utils.ServiceHelper; - -/** - * Describe a generic network element attachment points, - * attached to one Node, the NodeConnector is formed by the pair - * (NodeConnectorType, NodeConnectorID) because each SDN technology can - * identify an attachment point on the Node in different way. - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class NodeConnector implements Serializable { - private static final long serialVersionUID = 1L; - public static final Short SPECIALNODECONNECTORID = (short) 0; - - /** - * Enumerate the different types of NodeConnectors supported by the class - * - */ - public static class NodeConnectorIDType { - private static final - ConcurrentHashMap, String>> compatibleType = - new ConcurrentHashMap, String>>(); - /** - * Represents the OFPP_CONTROLLER reserved port to forward a - * packet to the controller, this is to send data packets - * to the controller from the data plane triggering - * a packet_in event. - */ - public static String CONTROLLER = "CTRL"; - /** - * Represents the OFPP_ALL reserved OF port - * to forward to ALL the ports in the system , - * should be used for flooding like mechanism to - * be used cautiously to avoid excessive flooding. - */ - public static String ALL = "ALL"; - /** - * Represents the OFPP_LOCAL reserved OF port - * to access the local networking stack of the node - * of which the packet is destined. Typically used for - * inband OF communications channel. - */ - public static String SWSTACK = "SW"; - /** - * Describes OFPP_Normal reserved port destination that invokes - * the traditional native L2/L3 HW normal forwarding functionality - * if supported on the forwarding element. - */ - public static String HWPATH = "HW"; - public static String OPENFLOW = "OF"; - public static String PCEP = "PE"; - public static String ONEPK = "PK"; - public static String OPENFLOW2PCEP = "O2E"; - public static String PCEP2OPENFLOW = "E2O"; - public static String OPENFLOW2ONEPK = "O2K"; - public static String ONEPK2OPENFLOW = "K2O"; - public static String PCEP2ONEPK = "E2K"; - public static String ONEPK2PCEP = "K2E"; - public static String PRODUCTION = "PR"; - - // Initialize the map with some well known, even though all of - // them could be siting outside of here, but it's convenient - // for Unit Testing coverage - static { - compatibleType.put(CONTROLLER, - new ImmutablePair, String>(Short.class, null)); - compatibleType.put(ALL, - new ImmutablePair, String>(Short.class, null)); - compatibleType.put(SWSTACK, - new ImmutablePair, String>(Short.class, null)); - compatibleType.put(HWPATH, - new ImmutablePair, String>(Short.class, null)); - compatibleType.put(OPENFLOW, - new ImmutablePair, String>(Short.class, - Node.NodeIDType.OPENFLOW)); - compatibleType.put(PCEP, - new ImmutablePair, String>(Integer.class, - Node.NodeIDType.PCEP)); - compatibleType.put(ONEPK, - new ImmutablePair, String>(String.class, - Node.NodeIDType.ONEPK)); - compatibleType.put(OPENFLOW2PCEP, - new ImmutablePair, String>(Short.class, - Node.NodeIDType.OPENFLOW)); - compatibleType.put(OPENFLOW2ONEPK, - new ImmutablePair, String>(Short.class, - Node.NodeIDType.OPENFLOW)); - compatibleType.put(PCEP2OPENFLOW, - new ImmutablePair, String>(Integer.class, - Node.NodeIDType.PCEP)); - compatibleType.put(PCEP2ONEPK, - new ImmutablePair, String>(Integer.class, - Node.NodeIDType.PCEP)); - compatibleType.put(ONEPK2OPENFLOW, - new ImmutablePair, String>(String.class, - Node.NodeIDType.ONEPK)); - compatibleType.put(ONEPK2PCEP, - new ImmutablePair, String>(String.class, - Node.NodeIDType.ONEPK)); - compatibleType.put(PRODUCTION, - new ImmutablePair, String>(String.class, - Node.NodeIDType.PRODUCTION)); - } - - /** - * Return the type of the class expected for the - * NodeConnectorID, it's used for validity check in the constructor - * - * @param type, the type of the NodeConnector for which we - * want to retrieve the compatible class to be used as ID. - * - * @return The Class which is supposed to instantiate the ID - * for the NodeConnectorID - */ - public static Class getClassType(String type) { - if (compatibleType.get(type) == null) { - return null; - } - return compatibleType.get(type).getLeft(); - } - - /** - * Return the NodeIDType compatible with this NodeConnector, - * in fact you cannot attach for example a PCEP NodeConnector - * to an OpenFlow Node. - * - * @param type, the type of the NodeConnector for which we - * want to retrieve the compatible class to be used as ID. - * - * @return The ID of the compatible Node - */ - public static String getCompatibleNode(String type) { - if (compatibleType.get(type) == null) { - return null; - } - return compatibleType.get(type).getRight(); - } - - /** - * Register a new ID for which Node can be created - * - * @param type, the new type being registered - * @param compatibleID, the type of class to be accepted as ID - * @param compatibleNode, the type of Node with which this - * NodeConnector is compatible - * - * @return true if registered, false otherwise - */ - public static boolean registerIDType(String type, - Class compatibleID, - String compatibleNode) { - if (compatibleType.get(type) != null) { - return false; - } else { - compatibleType.put(type, new ImmutablePair, String>(compatibleID, - compatibleNode)); - return true; - } - } - - /** - * UNRegister a new ID for which Node can be created - * - * @param type, the type being UN-registered - * - */ - public static void unRegisterIDType(String type) { - compatibleType.remove(type); - } - } - - // Elements that constitute the NodeConnector - private Object nodeConnectorID; - private String nodeConnectorType; - @XmlElement(name = "node") - private Node nodeConnectorNode; - - // Helper field for JAXB - private String nodeConnectorIDString; - - /** - * Private constructor used for JAXB mapping - */ - private NodeConnector() { - this.nodeConnectorIDString = null; - this.nodeConnectorID = null; - this.nodeConnectorType = null; - this.nodeConnectorNode = null; - } - - /** - * Create a NodeConnector from the component element. The - * constructor make sure the NodeConnector type is congruent with - * the Node used and also the NodeConnector ID is of type expected - * - * @param nodeConnectorType Type of the NodeConnector - * @param id ID portion of the NodeConnector - * @param node Node to which the NodeConnector is attached too - * - */ - public NodeConnector(String nodeConnectorType, Object id, - Node node) throws ConstructionException { - // In case of compatible type being null then assume that this - // port can be attached on any node. - String compatibleNode = - NodeConnectorIDType.getCompatibleNode(nodeConnectorType); - if (NodeConnectorIDType.getClassType(nodeConnectorType) != null && - NodeConnectorIDType.getClassType(nodeConnectorType).isInstance(id) && - (compatibleNode == null || - node.getType().equals(compatibleNode))) { - this.nodeConnectorType = nodeConnectorType; - this.nodeConnectorID = id; - this.nodeConnectorNode = node; - } else { - throw new ConstructionException("Type of incoming object:" - + id.getClass() + " not compatible with expected type:" - + NodeConnectorIDType.getClassType(nodeConnectorType) - + " or Node type incompatible:" + node.getType()); - } - } - - /** - * Copy constructor for NodeConnector - * - * @param src NodeConnector to copy from - * - */ - public NodeConnector(NodeConnector src) throws ConstructionException { - if (src != null) { - this.nodeConnectorType = src.getType(); - // Here we can reference the object because that is - // supposed to be an immutable identifier as well like a - // UUID/Integer and so on, hence no need to create a copy - // of it - this.nodeConnectorID = src.getID(); - this.nodeConnectorNode = new Node(src.getNode()); - } else { - throw - new ConstructionException("Null incoming object to copy from"); - } - } - - /** - * getter method for NodeConnector - * - * - * @return the NodeConnectorType of this object - */ - @XmlElement(name = "type") - public String getType() { - return this.nodeConnectorType; - } - - /** - * fill the current object from the string parameters passed, will - * be only used by JAXB - * - * @param typeStr string representing the type of the Node - * @param IDStr String representation of the ID - */ - private void fillmeFromString(String typeStr, String IDStr) { - if (typeStr == null) { - return; - } - - if (IDStr == null) { - return; - } - - this.nodeConnectorType = typeStr; - if (typeStr.equals(NodeConnectorIDType.OPENFLOW) || - typeStr.equals(NodeConnectorIDType.OPENFLOW2ONEPK) || - typeStr.equals(NodeConnectorIDType.OPENFLOW2PCEP)) { - try { - Short ID = Short.parseShort(IDStr); - this.nodeConnectorID = ID; - } catch (Exception ex) { - return; - } - } else if (typeStr.equals(NodeConnectorIDType.ONEPK) || - typeStr.equals(NodeConnectorIDType.ONEPK2OPENFLOW) || - typeStr.equals(NodeConnectorIDType.ONEPK2PCEP) || - typeStr.equals(NodeConnectorIDType.PRODUCTION)) { - try { - this.nodeConnectorID = IDStr; - } catch (Exception ex) { - return; - } - } else if (typeStr.equals(NodeConnectorIDType.PCEP) || - typeStr.equals(NodeConnectorIDType.PCEP2ONEPK) || - typeStr.equals(NodeConnectorIDType.PCEP2OPENFLOW)) { - try { - Integer ID = Integer.parseInt(IDStr); - this.nodeConnectorID = ID; - } catch (Exception ex) { - return; - } - } else { - // Lookup via OSGi service registry - } - } - - /** - * Private setter for nodeConnectorType to be called by JAXB not by anyone - * else, NodeConnector is immutable - * - * @param type of node to be set - */ - @SuppressWarnings("unused") - private void setType(String type) { - this.nodeConnectorType = type; - if (this.nodeConnectorIDString != null) { - this.fillmeFromString(type, this.nodeConnectorIDString); - } - } - - /** - * getter method for NodeConnector - * - * - * @return the NodeConnector ID of this object - */ - public Object getID() { - return this.nodeConnectorID; - } - - /** - * getter method for NodeConnector ID in string format. - * - * - * @return the NodeConnector ID of this object in String format - */ - @XmlElement(name = "id") - public String getNodeConnectorIDString() { - return this.nodeConnectorID.toString(); - } - - /** - * private setter to be used by JAXB - * - * @param nodeConnectorIDString String representation for NodeConnectorID - */ - @SuppressWarnings("unused") - private void setNodeConnectorIDString(String IDStr) { - this.nodeConnectorIDString = IDStr; - if (this.nodeConnectorType != null) { - this.fillmeFromString(this.nodeConnectorType, IDStr); - } - } - - /** - * getter method for NodeConnector - * - * - * @return the Node of this object - */ - public Node getNode() { - return this.nodeConnectorNode; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((nodeConnectorID == null) ? 0 : nodeConnectorID.hashCode()); - result = prime - * result - + ((nodeConnectorNode == null) ? 0 : nodeConnectorNode - .hashCode()); - result = prime - * result - + ((nodeConnectorType == null) ? 0 : nodeConnectorType - .hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - NodeConnector other = (NodeConnector) obj; - if (nodeConnectorID == null) { - if (other.nodeConnectorID != null) { - return false; - } - } else if (!nodeConnectorID.equals(other.nodeConnectorID)) { - return false; - } - if (nodeConnectorNode == null) { - if (other.nodeConnectorNode != null) { - return false; - } - } else if (!nodeConnectorNode.equals(other.nodeConnectorNode)) { - return false; - } - if (nodeConnectorType == null) { - if (other.nodeConnectorType != null) { - return false; - } - } else if (!nodeConnectorType.equals(other.nodeConnectorType)) { - return false; - } - return true; - } - - @Override - public String toString() { - return this.getNodeConnectorIdAsString() + "@" + this.nodeConnectorNode; - } - - /** - * A String representation of the NodeConnector without - * the Node context - * - * @return A String representation of the NodeConnector without - * the Node context - */ - public String getNodeConnectorIdAsString() { - if (this.nodeConnectorType - .equals(NodeConnectorIDType.CONTROLLER) || - this.nodeConnectorType - .equals(NodeConnectorIDType.ALL) || - this.nodeConnectorType - .equals(NodeConnectorIDType.SWSTACK) || - this.nodeConnectorType - .equals(NodeConnectorIDType.HWPATH)) { - return this.nodeConnectorType; - } else { - return this.nodeConnectorType + "|" - + this.nodeConnectorID.toString(); - } - } - - /** - * return a NodeConnector from a string - * - * @param str String to be parsed in a NodeConnector - * - * @return the NodeConnector if parse is successful, null otherwise - */ - public static NodeConnector fromString(String str) { - if (str == null) { - return null; - } - String parts[] = str.split("\\@"); - if (parts.length != 2) { - return null; - } - // Now get the Node from the Node portion - Node n = Node.fromString(parts[1]); - if (n == null) { - return null; - } - return fromStringNoNode(parts[0], n); - } - - /** - * return a set of NodeConnector from a collection of string - * - * @param stringCollection Collection of String object to be parsed as a NodeConnector - * - * @return the Set of unique NodeConnector objects if parse is successful, empty Set otherwise - */ - public static Set fromString(Collection stringCollection) { - Set set = new HashSet(); - if (stringCollection != null) { - - for (String str : stringCollection) { - NodeConnector nodeConnector = NodeConnector.fromString(str); - if (nodeConnector != null) { - set.add(nodeConnector); - } - } - } - return set; - } - - /** - * return a NodeConnector from a string not containing explicitly - * the Node portion which has to be supplied as parameter - * - * @param str String to be parsed in a NodeConnector - * @param n Node to which the NodeConnector is attached - * - * @return the NodeConnector if parse is successful, null otherwise - */ - public static NodeConnector fromStringNoNode(String str, Node n) { - if (str == null) { - return null; - } - String nodeConnectorParts[] = str.split("\\|"); - if (nodeConnectorParts.length != 2) { - // Try to guess from a String formatted as a short because - // for long time openflow has been prime citizen so lets - // keep this legacy for now - String numStr = str.toUpperCase(); - - Short ofPortID = null; - // Try as an decimal/hex number - try { - ofPortID = Short.decode(numStr); - } catch (Exception ex) { - ofPortID = null; - } - - // Lets try the special ports we know about - if (ofPortID == null) { - try { - if (str.equalsIgnoreCase(NodeConnectorIDType.CONTROLLER - .toString())) { - return new NodeConnector( - NodeConnectorIDType.CONTROLLER, - SPECIALNODECONNECTORID, n); - } - if (str.equalsIgnoreCase(NodeConnectorIDType.HWPATH - .toString())) { - return new NodeConnector(NodeConnectorIDType.HWPATH, - SPECIALNODECONNECTORID, n); - } - if (str.equalsIgnoreCase(NodeConnectorIDType.SWSTACK - .toString())) { - return new NodeConnector(NodeConnectorIDType.SWSTACK, - SPECIALNODECONNECTORID, n); - } - if (str - .equalsIgnoreCase(NodeConnectorIDType.ALL - .toString())) { - return new NodeConnector(NodeConnectorIDType.ALL, - SPECIALNODECONNECTORID, n); - } - } catch (ConstructionException ex) { - return null; - } - return null; - } - - // Lets return the cooked up NodeID - try { - return new NodeConnector(NodeConnectorIDType.OPENFLOW, - ofPortID, n); - } catch (ConstructionException ex) { - return null; - } - } - - String typeStr = nodeConnectorParts[0]; - String IDStr = nodeConnectorParts[1]; - return fromStringNoNode(typeStr, IDStr, n); - } - - /** - * return a NodeConnector from a pair (type, ID) in string format - * not containing explicitly the Node portion which has to be - * supplied as parameter - * - * @param typeStr type String to be parsed in a NodeConnector - * @param IDStr ID String portion to be parsed in a NodeConnector - * @param n Node to which the NodeConnector is attached - * - * @return the NodeConnector if parse is successful, null otherwise - */ - public static NodeConnector fromStringNoNode(String typeStr, String IDStr, - Node n) { - if (typeStr == null) { - return null; - } - if (IDStr == null) { - return null; - } - - if (typeStr.equals(NodeConnectorIDType.OPENFLOW) || - typeStr.equals(NodeConnectorIDType.OPENFLOW2ONEPK) || - typeStr.equals(NodeConnectorIDType.OPENFLOW2PCEP)) { - try { - Short ID = Short.parseShort(IDStr); - return new NodeConnector(typeStr, ID, n); - } catch (Exception ex) { - return null; - } - } else if (typeStr.equals(NodeConnectorIDType.ONEPK) || - typeStr.equals(NodeConnectorIDType.ONEPK2OPENFLOW) || - typeStr.equals(NodeConnectorIDType.ONEPK2PCEP) || - typeStr.equals(NodeConnectorIDType.PRODUCTION)) { - try { - return new NodeConnector(typeStr, IDStr, n); - } catch (Exception ex) { - return null; - } - } else if (typeStr.equals(NodeConnectorIDType.PCEP) || - typeStr.equals(NodeConnectorIDType.PCEP2ONEPK) || - typeStr.equals(NodeConnectorIDType.PCEP2OPENFLOW)) { - try { - Integer ID = Integer.parseInt(IDStr); - return new NodeConnector(typeStr, ID, n); - } catch (Exception ex) { - return null; - } - } else { - //Use INodeConnectorFactory to create a NodeConnector of registered type. - //The protocol plugin being used depends on typeStr. - INodeConnectorFactory f = (INodeConnectorFactory) ServiceHelper - .getGlobalInstance(INodeConnectorFactory.class, new NodeConnector(), "(protocolName="+typeStr+")"); - if(f==null) { - return null; - } - return f.fromStringNoNode(typeStr, IDStr, n); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeTable.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeTable.java deleted file mode 100644 index 7df20e4dcc..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/NodeTable.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.core; - -import java.io.Serializable; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class NodeTable implements Serializable { - - private static final long serialVersionUID = 1L; - public static final Short SPECIALNODETABLEID = (short) 0; - - /** - * Enum-like static class created with the purpose of identifing - * multiple type of nodes in the SDN network. The type is - * necessary to figure out to later on correctly use the - * nodeTableID. Using a static class instead of an Enum so we can add - * dynamically new types without changing anything in the - * surround. - */ - public static final class NodeTableIDType { - private static final ConcurrentHashMap> compatibleType = - new ConcurrentHashMap>(); - /** - * These are in compliance with the compatibility types in 'Node' - */ - public static String OPENFLOW = "OF"; - public static String PCEP = "PE"; - public static String ONEPK = "PK"; - public static String PRODUCTION = "PR"; - - // Pre-populated types, just here for convenience and ease of - // unit-testing, but certainly those could live also outside. - // Currently we allow these 4. It can be changed later. - static { - compatibleType.put(OPENFLOW, Byte.class); - compatibleType.put(PCEP, UUID.class); - compatibleType.put(ONEPK, String.class); - compatibleType.put(PRODUCTION, String.class); - } - - /** - * Return the type of the class expected for the - * NodeTableID, it's used for validity check in the constructor - * - * @param type, the type of the NodeTable for which we - * want to retrieve the compatible class to be used as ID. - * - * @return The Class which is supposed to instantiate the ID - * for the NodeTableID - */ - public static Class getClassType(String type) { - return compatibleType.get(type); - } - - /** - * Returns all the registered nodeTableIDTypes currently available - * - * @return The current registered NodeTableIDTypes - */ - public static Set values() { - return compatibleType.keySet(); - } - - /** - * Register a new ID for which NodeTable can be created - * - * @param type, the new type being registered - * @param compatibleID, the type of class to be accepted as ID - * - * @return true if registered, false otherwise - */ - public static boolean registerIDType(String type, - Class compatibleID) { - if (compatibleType.get(type) != null) { - return false; - } else { - compatibleType.put(type, compatibleID); - return true; - } - } - - /** - * UNRegister a new ID for which Node can be created - * - * @param type, the type being UN-registered - * - */ - public static void unRegisterIDType(String type) { - compatibleType.remove(type); - } - } - - // Elements that constitute the NodeTable - private Object nodeTableID; - private String nodeTableType; - @XmlElement(name = "node") - private Node nodeTableNode; - - // Helper field for JAXB - private String nodeTableIDString; - - /** - * Private constructor used for JAXB mapping - */ - @SuppressWarnings("unused") - private NodeTable() { - this.nodeTableIDString = null; - this.nodeTableID = null; - this.nodeTableType = null; - this.nodeTableNode = null; - } - - public NodeTable(String nodeTableType, Object id, Node node) throws ConstructionException { - if (NodeTableIDType.getClassType(nodeTableType) != null && - NodeTableIDType.getClassType(nodeTableType).isInstance(id) && - node.getType().equals(nodeTableType)) { - this.nodeTableType = nodeTableType; - this.nodeTableID = id; - this.nodeTableNode = node; - } else { - throw new ConstructionException("Type of incoming object:" - + id.getClass() + " not compatible with expected type:" - + NodeTableIDType.getClassType(nodeTableType) - + " or Node type incompatible:" + node.getType()); - } - } - - /** - * Copy constructor for NodeTable - * - * @param src NodeTable to copy from - * - */ - public NodeTable(NodeTable src) throws ConstructionException { - if (src != null) { - this.nodeTableType = src.getType(); - // Here we can reference the object because that is - // supposed to be an immutable identifier as well like a - // UUID/Integer and so on, hence no need to create a copy - // of it - this.nodeTableID = src.getID(); - this.nodeTableNode = new Node(src.getNode()); - } else { - throw - new ConstructionException("Null incoming object to copy from"); - } - } - - /** - * @return the nodeTableID - */ - public Object getID() { - return this.nodeTableID; - } - - /** - * @return the nodeTableType - */ - public String getType() { - return this.nodeTableType; - } - - /** - * Private setter for nodeConnectorType to be called by JAXB not by anyone - * else, NodeConnector is immutable - * - * @param type the nodeTableType to set - */ - @SuppressWarnings("unused") - private void setType(String type) { - this.nodeTableType = type; - if (this.nodeTableIDString != null) { - this.fillmeFromString(type, this.nodeTableIDString); - } - } - - /** - * @return the nodeTableNode - */ - public Node getNode() { - return this.nodeTableNode; - } - - /** - * @param nodeTableNode the nodeTableNode to set - */ - public void setNodeTableNode(Node nodeTableNode) { - this.nodeTableNode = nodeTableNode; - } - - /** - * @return the nodeTableIDString - */ - @XmlElement(name = "id") - public String getNodeTableIDString() { - return this.nodeTableIDString != null? this.nodeTableIDString : nodeTableID.toString(); - } - - /** - * @param nodeTableIDString the nodeTableIDString to set - */ - @SuppressWarnings("unused") - private void setNodeTableIDString(String IDStr) { - this.nodeTableIDString = IDStr; - if (this.nodeTableType != null) { - this.fillmeFromString(this.nodeTableType, IDStr); - } - } - - /** - * fill the current object from the string parameters passed, will - * be only used by JAXB - * - * @param typeStr string representing the type of the Node - * @param IDStr String representation of the ID - */ - private void fillmeFromString(String typeStr, String IDStr) { - if (typeStr == null) { - return; - } - - if (IDStr == null) { - return; - } - - this.nodeTableType = typeStr; - this.nodeTableID = (byte) Byte.parseByte(IDStr); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((nodeTableID == null) ? 0 : nodeTableID.hashCode()); - result = prime - * result - + ((nodeTableNode == null) ? 0 : nodeTableNode - .hashCode()); - result = prime - * result - + ((nodeTableType == null) ? 0 : nodeTableType - .hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - NodeTable other = (NodeTable) obj; - if (nodeTableID == null) { - if (other.nodeTableID != null) - return false; - } else if (!nodeTableID.equals(other.nodeTableID)) - return false; - if (nodeTableNode == null) { - if (other.nodeTableNode != null) - return false; - } else if (!nodeTableNode.equals(other.nodeTableNode)) - return false; - if (nodeTableType == null) { - if (other.nodeTableType != null) - return false; - } else if (!nodeTableType.equals(other.nodeTableType)) - return false; - return true; - } - - @Override - public String toString() { - return this.getNodeTableIdAsString() + "@" + this.nodeTableNode; - } - - public String getNodeTableIdAsString() { - return this.nodeTableType + "|" - + this.nodeTableID.toString(); - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Path.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Path.java deleted file mode 100644 index 6049cee256..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Path.java +++ /dev/null @@ -1,208 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file Path.java - * - * @brief Describe a path as a sequence of Edge such that from - * each of its Head Node there is an link to the next Tail Node in the sequence - * - */ -package org.opendaylight.controller.sal.core; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Describe a path as a sequence of Edge such that from - * each of its Head Node there is an link to the next Tail Node in the - * sequence - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Path implements Serializable { - private static final long serialVersionUID = 1L; - @XmlElement - private List edges; - - /** - * Private constructor used for JAXB mapping - */ - @SuppressWarnings("unused") - private Path() { - this.edges = null; - } - - /** - * Construct an object representing a path, the constructor will - * check if the passed list of edges is such that for every - * consecutive edges the head node of the first edge coincide with - * the tail node of the subsequent in order for connectivity to be there. - * - * @param edges Edges of the path - * - */ - public Path(List edges) throws ConstructionException { - // Lets check if the list of edges is such that the head node - // of an edge is also the tail node of the subsequent one - boolean sequential = true; - if (edges.size() >= 2) { - for (int i = 0; i < edges.size() - 1; i++) { - Edge current = edges.get(i); - Edge next = edges.get(i + 1); - if (!current.getHeadNodeConnector().getNode().equals(next.getTailNodeConnector().getNode())) { - sequential = false; - break; - } - } - } else if (edges.size() == 0) { - throw new ConstructionException("Path is empty"); - } - - if (!sequential) { - throw new ConstructionException("Path is not sequential"); - } - - this.edges = edges; - } - - /** - * Create the reversed path - * @return The reversed path - */ - public Path reverse() { - int j = edges.size(); // size always > 0 - Edge[] aEdges = new Edge[j]; - for (Edge e : edges) { - j--; - aEdges[j] = e.reverse(); - } - Path rp; - try { - rp = new Path(Arrays.asList(aEdges)); - } catch (ConstructionException ce) { - rp = null; - } - return rp; - } - - /** - * Return the list of nodes of this path, the first node is the start node - * @return the list of nodes - */ - public List getNodes() { - List nl = new ArrayList(); - nl.add(this.getStartNode()); - for (Edge e : edges) { - nl.add(e.getHeadNodeConnector().getNode()); - } - return nl; - } - - /** - * Copy Construct for a path - * - * @param src Path to copy from - * - */ - public Path(Path src) throws ConstructionException { - if (src != null) { - this.edges = new LinkedList(src.getEdges()); - } else { - throw new ConstructionException("src supplied was null"); - } - } - - /** - * get the First Node of the path - * - * - * @return The start Node of the Path - */ - public Node getStartNode() { - return this.edges.get(0).getTailNodeConnector().getNode(); - } - - /** - * get the Last Node of the path - * - * - * @return The last Node of the Path - */ - public Node getEndNode() { - return this.edges.get(this.edges.size() - 1).getHeadNodeConnector() - .getNode(); - } - - /** - * getter method for the Path - * - * - * @return Return the list of edges that constitute the Path - */ - public List getEdges() { - return (edges == null) ? Collections.emptyList() : new ArrayList(edges); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((edges == null) ? 0 : edges.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Path other = (Path) obj; - if (edges == null) { - if (other.edges != null) { - return false; - } - } else if (!edges.equals(other.edges)) { - return false; - } - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("["); - for (int i = 0; i < this.edges.size(); i++) { - if (i != 0) { - // add the comma to the previous element - sb.append(","); - } - sb.append(this.edges.get(i).toString()); - } - sb.append("]"); - return sb.toString(); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/PeerBandwidth.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/PeerBandwidth.java deleted file mode 100644 index 3e448e45c6..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/PeerBandwidth.java +++ /dev/null @@ -1,58 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file PeerBandWidth.java - * - * @brief Class representing peer bandwidth - * - * Describes peer Bandwidth of peer element. It's intended in multiple of - * bits per seconds. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class PeerBandwidth extends Bandwidth { - private static final long serialVersionUID = 1L; - - public static final String PeerBandwidthPropName = "peerBandwidth"; - - public PeerBandwidth(long value) { - super(PeerBandwidthPropName); - this.bandwidthValue = value; - } - - /* - * Private constructor used for JAXB mapping - */ - private PeerBandwidth() { - super(PeerBandwidthPropName); - this.bandwidthValue = 0; - } - - public PeerBandwidth clone() { - return new PeerBandwidth(this.bandwidthValue); - } - - - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("PeerBandWidth["); - sb.append(super.toString()); - sb.append("]"); - return sb.toString(); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Property.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Property.java deleted file mode 100644 index fe35ea5d32..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Property.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file Property.java - * - * @brief Abstract base class for a Property that can be attached to - * any sal core element - * - * Abstract base class for a Property that can be attached to any sal - * core element - */ - -/** - * Abstract base class for a Property that can be attached to any sal core - * element - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -abstract public class Property implements Serializable, Cloneable { - private static final long serialVersionUID = 1L; - private final String name; - - /** - * Private constructor used for JAXB mapping - */ - @SuppressWarnings("unused") - private Property() { - this.name = null; - } - - protected Property(String name) { - this.name = name; - } - - public String getName() { - return this.name; - } - - public abstract String getStringValue(); - - /** - * Used to copy the Property in a polymorphic way - * - * @return A clone of this Property - */ - @Override - public abstract Property clone(); - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Property other = (Property) obj; - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Property [name=" + name + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/State.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/State.java deleted file mode 100644 index 4bda500038..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/State.java +++ /dev/null @@ -1,96 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * The class represents the State property of an Edge - * - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@SuppressWarnings("serial") -@Deprecated -public class State extends Property { - @XmlElement(name="value") - private short stateValue; - - public static final short EDGE_DOWN = 0; - public static final short EDGE_UP = 1; - public static final short EDGE_UNK = 0x7fff; - public static final String StatePropName = "state"; - - /* - * Private constructor used for JAXB mapping - */ - private State() { - super(StatePropName); - this.stateValue = EDGE_UNK; - } - - public State(short state) { - super(StatePropName); - this.stateValue = state; - } - - @Override - public State clone() { - return new State(this.stateValue); - } - - public short getValue() { - return this.stateValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + stateValue; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - State other = (State) obj; - if (stateValue != other.stateValue) - return false; - return true; - } - - @Override - public String toString() { - return "State[" + stateValue + "]"; - } - - @Override - public String getStringValue() { - if (stateValue == 0) { - return ("EDGE_DOWN"); - } else if (stateValue == 1) { - return ("EDGE_UP"); - } else if (stateValue == 0x7fff) { - return ("EDGE_UNK"); - } else { - return String.valueOf(stateValue); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/SupportedBandwidth.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/SupportedBandwidth.java deleted file mode 100644 index 842104ff32..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/SupportedBandwidth.java +++ /dev/null @@ -1,59 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file SupportedBandWidth.java - * - * @brief Class representing supported bandwidth - * - * Describes Supported Bandwidth which could be of a link or whatever could have - * bandwidth as description. It's intended in multiple of bits per - * seconds. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class SupportedBandwidth extends Bandwidth { - private static final long serialVersionUID = 1L; - public static final String SupportedBandwidthPropName = "supportedBandwidth"; - - public SupportedBandwidth(long value) { - super(SupportedBandwidthPropName); - this.bandwidthValue = value; - } - - /* - * Private constructor used for JAXB mapping - */ - private SupportedBandwidth() { - super(SupportedBandwidthPropName); - this.bandwidthValue = 0; - } - - public SupportedBandwidth clone() { - return new SupportedBandwidth(this.bandwidthValue); - } - - @Override - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("SupportedBandWidth["); - sb.append(super.toString()); - sb.append("]"); - return sb.toString(); - } - - -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tables.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tables.java deleted file mode 100644 index 99a366119a..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tables.java +++ /dev/null @@ -1,92 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file Tables.java - * - * @brief Class representing tables - * - * Describes supported # of datapath tables - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Tables extends Property { - private static final long serialVersionUID = 1L; - @XmlElement(name="value") - private byte tablesValue; - - public static final String TablesPropName = "tables"; - /** - * Construct a Tables property - * - * @param tables the Tables - * @return Constructed object - */ - public Tables(byte tables) { - super(TablesPropName); - this.tablesValue = tables; - } - - /* - * Private constructor used for JAXB mapping - */ - private Tables() { - super(TablesPropName); - this.tablesValue = 0; - } - - @Override - public Tables clone() { - return new Tables(this.tablesValue); - } - - public byte getValue() { - return this.tablesValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + tablesValue; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Tables other = (Tables) obj; - if (tablesValue != other.tablesValue) - return false; - return true; - } - - @Override - public String toString() { - return "Tables[" + tablesValue + "]"; - } - - @Override - public String getStringValue() { - return String.format("%02x", tablesValue); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tier.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tier.java deleted file mode 100644 index 2e76e50c22..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/Tier.java +++ /dev/null @@ -1,84 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * The class represents the Tier property of a node - * - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@SuppressWarnings("serial") -@Deprecated -public class Tier extends Property { - @XmlElement(name="value") - private int tierValue; - public static final String TierPropName = "tier"; - - public Tier(int tier) { - super(TierPropName); - this.tierValue = tier; - } - - /* - * Private constructor used for JAXB mapping - */ - private Tier() { - super(TierPropName); - this.tierValue = 0; - } - - @Override - public Tier clone() { - return new Tier(this.tierValue); - } - - public int getValue() { - return this.tierValue; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + tierValue; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - Tier other = (Tier) obj; - if (tierValue != other.tierValue) - return false; - return true; - } - - @Override - public String toString() { - return "Tier[" + tierValue + "]"; - } - - @Override - public String getStringValue() { - return String.valueOf(tierValue); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/TimeStamp.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/TimeStamp.java deleted file mode 100644 index 288f7657cd..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/TimeStamp.java +++ /dev/null @@ -1,117 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - -import java.util.Date; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file TimeStamp.java - * - * @brief Class representing a TimeStamp - * - * A property describing a timestamp based following the rules of - * java.util.Date, also given the time stamp represent the time when - * something happened, then a name is attached to this property so - * to qualify what are we talking about - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class TimeStamp extends Property { - private static final long serialVersionUID = 1L; - @XmlElement(name = "value") - private long timestamp; - @XmlElement(name = "name") - private String timestampName; - - public static final String TimeStampPropName = "timeStamp"; - - /** - * Construct a TimeStamp proporty - * - * @param timestamp the time stampt we want to describe in "epoch" - * format following the rules of java.util.Date - * @param timestampName A qualifier for the timestamp, for example - * "JoinTime" or any even qualifier could come up - * - * @return Constructed object - */ - public TimeStamp(long timestamp, String timestampName) { - super(TimeStampPropName); - this.timestamp = timestamp; - this.timestampName = timestampName; - } - - /* - * Private constructor used for JAXB mapping - */ - private TimeStamp() { - super(TimeStampPropName); - this.timestamp = 0; - this.timestampName = null; - } - - @Override - public TimeStamp clone() { - return new TimeStamp(this.timestamp, this.timestampName); - } - - public long getValue() { - return this.timestamp; - } - - public String getTimeStampName() { - return this.timestampName; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + (int) (timestamp ^ (timestamp >>> 32)); - result = prime * result - + ((timestampName == null) ? 0 : timestampName.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - TimeStamp other = (TimeStamp) obj; - if (timestamp != other.timestamp) - return false; - if (timestampName == null) { - if (other.timestampName != null) - return false; - } else if (!timestampName.equals(other.timestampName)) - return false; - return true; - } - - @Override - public String toString() { - return "TimeStamp[" + timestampName + ": " + timestamp +"]"; - } - - @Override - public String getStringValue() { - return timestampName + ": " + new Date(timestamp); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/UpdateType.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/UpdateType.java deleted file mode 100644 index 99a21a85a2..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/core/UpdateType.java +++ /dev/null @@ -1,40 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.core; - - -/** - * @file UpdateType.java - * - * @brief Describes update types - * - */ -@Deprecated -public enum UpdateType { - ADDED("added"), REMOVED("removed"), CHANGED("changed"); - - private String name; - - UpdateType(String name) { - this.name = name; - } - - public String getName() { - return this.name; - } - - public int calculateConsistentHashCode() { - if (this.name != null) { - return this.name.hashCode(); - } else { - return 0; - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/discovery/IDiscoveryService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/discovery/IDiscoveryService.java deleted file mode 100644 index 26e9ab596d..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/discovery/IDiscoveryService.java +++ /dev/null @@ -1,34 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.discovery; - -import java.util.Set; - -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; - -/** - * The interface provides the methods to notify the listener when an edge is - * added/deleted/changed. - */ -@Deprecated -public interface IDiscoveryService { - /** - * The methods is called when an edge is added/deleted/changed - * - * @param edge {@link org.opendaylight.controller.sal.core.Edge} being updated - * @param type {@link org.opendaylight.controller.sal.core.UpdateType} - * @param props set of {@link org.opendaylight.controller.sal.core.Property} like - * {@link org.opendaylight.controller.sal.core.Bandwidth} and/or - * {@link org.opendaylight.controller.sal.core.Latency} etc. - */ - public void notifyEdge(Edge edge, UpdateType type, Set props); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/Flow.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/Flow.java deleted file mode 100644 index 85057935fe..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/Flow.java +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.flowprogrammer; - -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.ActionType; -import org.opendaylight.controller.sal.action.SetDlType; -import org.opendaylight.controller.sal.action.SetNwDst; -import org.opendaylight.controller.sal.action.SetNwSrc; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.io.Serializable; -import java.net.Inet6Address; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * Represent a flow: match + actions + flow specific properties - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Flow implements Cloneable, Serializable { - protected static final Logger logger = LoggerFactory.getLogger(Flow.class); - private static final long serialVersionUID = 1L; - @XmlElement - private Match match; - @XmlElement - private List actions; - @XmlElement - private short priority; - @XmlElement - private short idleTimeout; - @XmlElement - private short hardTimeout; - @XmlElement - private long id; // unique identifier for this flow - - public Flow() { - match = null; - actions = null; - } - - public Flow(Match match, List actions) { - if (match.isIPv4() && actionsAreIPv6()) { - try { - throw new Exception("Conflicting Match and Action list"); - } catch (Exception e) { - logger.error("", e); - } - } else { - this.match = match; - this.actions = actions; - } - } - - /** - * Return a copy of the Match configured on this flow - * - * @return - */ - public Match getMatch() { - return match.clone(); - } - - /** - * Set the Match for this flow This operation will overwrite an existing - * Match if present - * - * @param match - */ - public void setMatch(Match match) { - this.match = match; - } - - /** - * Returns a copy of the actions list of this flow - * - * @return - */ - public List getActions() { - return (actions == null) ? null : new ArrayList(actions); - } - - /** - * Set the actions list for this flow If a list is already present, it will - * be replaced with the passed one. During addition, only the valid actions - * will be added It is a no op if the passed actions is null An empty - * actions is a vlaid input - * - * @param actions - */ - public void setActions(List actions) { - if (actions == null) { - return; - } - - this.actions = new ArrayList(actions.size()); - for (Action action : actions) { - if (action.isValid()) { - this.actions.add(action); - } - } - } - - /** - * Returns whether the Flow is for IPv4 or IPv6 Information is derived from - * match and actions list - * - * @return - */ - public boolean isIPv6() { - return (match.isIPv6()) ? true : actionsAreIPv6(); - } - - /** - * Returns true if it finds at least one action which is for IPv6 in the - * list of actions for this Flow - * - * @return - */ - private boolean actionsAreIPv6() { - if (this.actions != null) { - for (Action action : actions) { - switch (action.getType()) { - case SET_NW_SRC: - if (((SetNwSrc) action).getAddress() instanceof Inet6Address) { - return true; - } - break; - case SET_NW_DST: - if (((SetNwDst) action).getAddress() instanceof Inet6Address) { - return true; - } - break; - case SET_DL_TYPE: - if (((SetDlType) action).getDlType() == EtherTypes.IPv6.intValue()) { - return true; - } - break; - default: - } - } - } - return false; - } - - @Override - public Flow clone() { - Flow cloned = null; - try { - cloned = (Flow) super.clone(); - cloned.match = this.getMatch(); - cloned.actions = this.getActions(); - } catch (CloneNotSupportedException e) { - logger.error("", e); - } - return cloned; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((actions == null) ? 0 : actions.hashCode()); - result = prime * result + hardTimeout; - result = prime * result + (int) (id ^ (id >>> 32)); - result = prime * result + idleTimeout; - result = prime * result + ((match == null) ? 0 : match.hashCode()); - result = prime * result + priority; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Flow other = (Flow) obj; - if (actions == null) { - if (other.actions != null) { - return false; - } - } else if (!actions.equals(other.actions)) { - return false; - } - if (hardTimeout != other.hardTimeout) { - return false; - } - if (id != other.id) { - return false; - } - if (idleTimeout != other.idleTimeout) { - return false; - } - if (match == null) { - if (other.match != null) { - return false; - } - } else if (!match.equals(other.match)) { - return false; - } - if (priority != other.priority) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Flow[match = " + match + ", actions = " + actions + ", priority = " + priority + ", id = " + id - + ", idleTimeout = " + idleTimeout + ", hardTimeout = " + hardTimeout + "]"; - } - - public short getPriority() { - return priority; - } - - public void setPriority(short priority) { - this.priority = priority; - } - - public short getIdleTimeout() { - return idleTimeout; - } - - public void setIdleTimeout(short idleTimeout) { - this.idleTimeout = idleTimeout; - } - - public short getHardTimeout() { - return hardTimeout; - } - - public void setHardTimeout(short hardTimeout) { - this.hardTimeout = hardTimeout; - } - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - /** - * Adds the specified action to the list of action of this flow - * - * @param action - * @return false if the passed action is null or not valid or if it fails to - * add it - */ - public boolean addAction(Action action) { - if (action == null || !action.isValid()) { - return false; - } - return actions.add(action); - } - - public boolean removeAction(Action action) { - if (action == null) { - return false; - } - return actions.remove(action); - } - - /** - * remove ALL actions of type actionType from the list of actions of this - * flow - * - * @param actionType - * @return false if an action of that type is present and it fails to remove - * it - */ - public boolean removeAction(ActionType actionType) { - Iterator actionIter = this.getActions().iterator(); - while (actionIter.hasNext()) { - Action action = actionIter.next(); - if (action.getType() == actionType) { - if (!this.removeAction(action)) { - return false; - } - } - } - return true; - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerListener.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerListener.java deleted file mode 100644 index c8aed91bc6..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerListener.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.flowprogrammer; - -/** - * This interface defines the methods the SAL service which relay to the - * functional modules the asynchronous messages related to flow programming - * coming from the network nodes. - */ -@Deprecated -public interface IFlowProgrammerListener extends IPluginOutFlowProgrammerService { - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerService.java deleted file mode 100644 index de4c25e188..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IFlowProgrammerService.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.flowprogrammer; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.Status; - -/** - * Interface that defines the methods available to the functional modules above - * SAL for installing/modifying/removing flows on a network node - */ -@Deprecated -public interface IFlowProgrammerService { - /** - * Synchronously add a flow to the network node - * - * @param node - * The target network node - * @param flow - * The flow to install - * @return The status of this request - */ - Status addFlow(Node node, Flow flow); - - /** - * Synchronously modify existing flow on the switch - * - * @param node - * The target network node - * @param oldFlow - * The existing flow to modify - * @param newFlow - * The new flow to install - * @return The status of this request - */ - Status modifyFlow(Node node, Flow oldFlow, Flow newFlow); - - /** - * Synchronously remove the flow from the network node - * - * @param node - * The target network node - * @param flow - * The flow to remove - * @return The status of this request - */ - Status removeFlow(Node node, Flow flow); - - /** - * Asynchronously add a flow to the network node - * - * @param node - * The target network node - * @param flow - * The flow to install - * @return The status of this request containing the unique request id - */ - Status addFlowAsync(Node node, Flow flow); - - /** - * Asynchronously modify existing flow on the switch - * - * @param node - * The target network node - * @param oldFlow - * The existing flow to modify - * @param newFlow - * The new flow to install - * @return The status of this request containing the unique request id - */ - Status modifyFlowAsync(Node node, Flow oldFlow, Flow newFlow); - - /** - * Asynchronously remove the flow from the network node - * - * @param node - * The target network node - * @param flow - * The flow to remove - * @return The status of this request containing the unique request id - */ - Status removeFlowAsync(Node node, Flow flow); - - /** - * Remove all flows present on the network node - * - * @param node - * The target network node - * @return The status of this request containing the unique request id - */ - Status removeAllFlows(Node node); - - /** - * Send Barrier message synchronously. The caller will be blocked until the - * solicitation response arrives. - * - * Solicit the network node to report whether all the requests sent so far - * are completed. When this call is done, caller knows that all past flow - * operations requested to the node in asynchronous fashion were satisfied - * by the network node and that in case of any failure, a message was sent - * to the controller. - * - * @param node - * The network node to solicit - * @return The status of this request containing the unique request id - */ - Status syncSendBarrierMessage(Node node); - - /** - * Send Barrier message asynchronously. The caller is not blocked. - * - * Solicit the network node to report whether all the requests sent so far - * are completed. When this call is done, caller knows that all past flow - * operations requested to the node in asynchronous fashion were satisfied - * by the network node and that in case of any failure, a message was sent - * to the controller. - * - * @param node - * The network node to solicit - * @return The status of this request containing the unique request id - */ - Status asyncSendBarrierMessage(Node node); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginInFlowProgrammerService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginInFlowProgrammerService.java deleted file mode 100644 index 63481eee2a..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginInFlowProgrammerService.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.flowprogrammer; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.Status; - -/** - * This interface defines the flow programmer methods to be implemented by - * protocol plugins - */ -@Deprecated -public interface IPluginInFlowProgrammerService { - /** - * Synchronously add a flow to the network node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} on which the - * flow got added - * @param flow - * the flow - * {@link org.opendaylight.controller.sal.flowprogrammer.Flow} - * that got added - * @return Status the operation status - * {@link org.opendaylight.controller.sal.utils.Status} - */ - Status addFlow(Node node, Flow flow); - - /** - * Synchronously modify existing flow on the switch - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} on which the - * flow got modified - * @param flow - * the flow - * {@link org.opendaylight.controller.sal.flowprogrammer.Flow} - * that got modified - * @return Status the operation status - * {@link org.opendaylight.controller.sal.utils.Status} - */ - Status modifyFlow(Node node, Flow oldFlow, Flow newFlow); - - /** - * Synchronously remove the flow from the network node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} on which the - * flow got removed - * @param flow - * the flow - * {@link org.opendaylight.controller.sal.flowprogrammer.Flow} - * that got removed - * @return Status the operation status - * {@link org.opendaylight.controller.sal.utils.Status} - */ - Status removeFlow(Node node, Flow flow); - - /** - * Asynchronously add a flow to the network node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} on which the - * flow got added - * @param flow - * the flow - * {@link org.opendaylight.controller.sal.flowprogrammer.Flow} - * that got added - * @param rid - * the request id - * @return Status the operation status - * {@link org.opendaylight.controller.sal.utils.Status} - */ - Status addFlowAsync(Node node, Flow flow, long rid); - - /** - * Asynchronously modify existing flow on the switch - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} on which the - * flow got modified - * @param oldFlow - * the original flow - * {@link org.opendaylight.controller.sal.flowprogrammer.Flow} - * @param newFlow - * the new flow - * {@link org.opendaylight.controller.sal.flowprogrammer.Flow} - * @param rid - * the request id - * @return Status the operation status - * {@link org.opendaylight.controller.sal.utils.Status} - */ - Status modifyFlowAsync(Node node, Flow oldFlow, Flow newFlow, long rid); - - /** - * Asynchronously remove the flow from the network node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} on which the - * flow got removed - * @param flow - * the flow - * {@link org.opendaylight.controller.sal.flowprogrammer.Flow} - * that got removed - * @param rid - * the request id - * @return Status the operation status - * {@link org.opendaylight.controller.sal.utils.Status} - */ - Status removeFlowAsync(Node node, Flow flow, long rid); - - /** - * Remove all flows present on the network node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} on which the - * flow got removed - * @return Status the operation status - * {@link org.opendaylight.controller.sal.utils.Status} - */ - Status removeAllFlows(Node node); - - /** - * Send Barrier message synchronously. The caller will be blocked until the - * Barrier reply arrives. - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @return Status the operation status - * {@link org.opendaylight.controller.sal.utils.Status} - */ - Status syncSendBarrierMessage(Node node); - - /** - * Send Barrier message asynchronously. The caller is not blocked. - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @return Status the operation status - * {@link org.opendaylight.controller.sal.utils.Status} - */ - Status asyncSendBarrierMessage(Node node); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginOutFlowProgrammerService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginOutFlowProgrammerService.java deleted file mode 100644 index 83f45d46fd..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/flowprogrammer/IPluginOutFlowProgrammerService.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.flowprogrammer; - -import org.opendaylight.controller.sal.core.Node; - -/** - * This interface defines the methods the protocol plugin must implement to - * inform the SAL layer about the asynchronous messages related to flow - * programming coming from the network nodes. - */ -@Deprecated -public interface IPluginOutFlowProgrammerService { - /** - * Inform SAL that the flow on the specified node has been removed Consumer - * has to expect this notification only for flows which were installed with - * an idle or hard timeout specified. - * - * @param node - * the network node on which the flow got removed - * @param flow - * the flow that got removed. Note: It may contain only the Match - * and flow parameters fields. Actions may not be present. - */ - public void flowRemoved(Node node, Flow flow); - - /** - * Inform SAL that an error message has been received from a switch - * regarding a flow message previously sent to the switch. A Request ID - * associated with the offending message is also returned. - * - * @param node - * the network node on which the error reported - * @param rid - * the offending message request id - * @param err - * the error message - */ - public void flowErrorReported(Node node, long rid, Object err); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IInventoryService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IInventoryService.java deleted file mode 100644 index 32eb232df2..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IInventoryService.java +++ /dev/null @@ -1,46 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.inventory; - -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; - -/** - * The Interface describes methods invoked from application toward SAL to - * solicit existing inventory data. - */ -@Deprecated -public interface IInventoryService { - /** - * The method retrieves all the existing nodes and properties attached - * - * @return map of {@link org.opendaylight.controller.sal.core.Node} and {@link org.opendaylight.controller.sal.core.Property} - */ - public ConcurrentMap> getNodeProps(); - - /** - * The method retrieves all the configured nodes that are not connected to - * the controller - * - * @return Set of {@link org.opendaylight.controller.sal.core.Node} - */ - public Set getConfiguredNotConnectedNodes(); - /** - * The method retrieve all the existing nodeConnectors and their properties - * - * @return map of {@link org.opendaylight.controller.sal.core.NodeConnector} and {@link org.opendaylight.controller.sal.core.Property} - */ - public ConcurrentMap> getNodeConnectorProps(); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IListenInventoryUpdates.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IListenInventoryUpdates.java deleted file mode 100644 index 768d90c5c5..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IListenInventoryUpdates.java +++ /dev/null @@ -1,47 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.inventory; - -import java.util.Set; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; - -/** - * The interface provides the methods to notify the upper applications in - * regards to any inventory changes. - */ -@Deprecated -public interface IListenInventoryUpdates { - /** - * This method is called when some properties of a node are added/deleted/changed. - * - * @param node {@link org.opendaylight.controller.sal.core.Node} being updated - * @param type {@link org.opendaylight.controller.sal.core.UpdateType} - * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as - * {@link org.opendaylight.controller.sal.core.Description} and/or - * {@link org.opendaylight.controller.sal.core.Tier} etc. - */ - public void updateNode(Node node, UpdateType type, Set props); - - /** - * This method is called when some properties of a node connector are added/deleted/changed. - * - * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated - * @param type {@link org.opendaylight.controller.sal.core.UpdateType} - * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as - * {@link org.opendaylight.controller.sal.core.Description} and/or - * {@link org.opendaylight.controller.sal.core.State} etc. - */ - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginInInventoryService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginInInventoryService.java deleted file mode 100644 index 203c411cca..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginInInventoryService.java +++ /dev/null @@ -1,49 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.inventory; - -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; - -/** - * The Interface describes methods invoked from SAL toward the protocol plugin - * to solicit existing inventory data. - */ -@Deprecated -public interface IPluginInInventoryService { - /** - * The method retrieves all the existing nodes and properties attached - * - * @return map of {@link org.opendaylight.controller.sal.core.Node} and {@link org.opendaylight.controller.sal.core.Property} - */ - public ConcurrentMap> getNodeProps(); - - /** - * The method retrieve all the existing nodeConnectors and their properties - * - * @param refresh true if it needs to solicit Openflow core; otherwise, retrieve from local cache. - * @return map of {@link org.opendaylight.controller.sal.core.NodeConnector} and {@link org.opendaylight.controller.sal.core.Property} - */ - public ConcurrentMap> getNodeConnectorProps( - Boolean refresh); - - /** - * The method retrieves all the configured nodes that are not connected to - * the controller - * - * @return Set of {@link org.opendaylight.controller.sal.core.Node} - */ - public Set getConfiguredNotConnectedNodes(); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginOutInventoryService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginOutInventoryService.java deleted file mode 100644 index 56a0388b7b..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/inventory/IPluginOutInventoryService.java +++ /dev/null @@ -1,47 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.inventory; - -import java.util.Set; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; - -/** - * The Interface describes Inventory update methods to be implemented by - * protocol plugin. - */ -@Deprecated -public interface IPluginOutInventoryService { - /** - * This method is called when some properties of a node are added/deleted/changed. - * - * @param node {@link org.opendaylight.controller.sal.core.Node} being updated - * @param type {@link org.opendaylight.controller.sal.core.UpdateType} - * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as - * {@link org.opendaylight.controller.sal.core.Description} and/or - * {@link org.opendaylight.controller.sal.core.Tier} etc. - */ - public void updateNode(Node node, UpdateType type, Set props); - - /** - * This method is called when some properties of a node connector are added/deleted/changed. - * - * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated - * @param type {@link org.opendaylight.controller.sal.core.UpdateType} - * @param props set of {@link org.opendaylight.controller.sal.core.Property} such as - * {@link org.opendaylight.controller.sal.core.Description} and/or - * {@link org.opendaylight.controller.sal.core.State} etc. - */ - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/Match.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/Match.java deleted file mode 100644 index 47f70b7005..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/Match.java +++ /dev/null @@ -1,580 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.match; - -import java.io.Serializable; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ConcurrentHashMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NetUtils; - -/** - * Represents the generic match criteria for a network frame/packet/message - * It contains a collection of individual field match - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Match implements Cloneable, Serializable { - private static final long serialVersionUID = 1L; - private static final Map reversableMatches; - static { - Map map = new HashMap(); - map.put(MatchType.DL_SRC, MatchType.DL_DST); - map.put(MatchType.DL_DST, MatchType.DL_SRC); - map.put(MatchType.NW_SRC, MatchType.NW_DST); - map.put(MatchType.NW_DST, MatchType.NW_SRC); - map.put(MatchType.TP_SRC, MatchType.TP_DST); - map.put(MatchType.TP_DST, MatchType.TP_SRC); - reversableMatches = Collections.unmodifiableMap(map); - } - private Map fields; - private int matches; // concise way to tell which fields the match - // is set for (may remove if not needed) - private ConcurrentMap props; - - public Match() { - fields = new HashMap(); - matches = 0; - } - - public Match(Match match) { - fields = new HashMap(match.fields); - matches = match.matches; - } - - /** - * Gets the list of metadata currently registered with this match - * - * @return List of metadata currently registered - */ - public List getMetadatas() { - if (this.props != null) { - // Return all the values in the map - Collection res = this.props.values(); - if (res == null) { - return Collections.emptyList(); - } - return new ArrayList(res); - } - return Collections.emptyList(); - } - - /** - * Gets the metadata registered with a name if present - * - * @param name the name of the property to be extracted - * - * @return List of metadata currently registered - */ - public Property getMetadata(String name) { - if (name == null) { - return null; - } - if (this.props != null) { - // Return the Property associated to the name - return this.props.get(name); - } - return null; - } - - /** - * Sets the metadata associated to a name. If the name or prop is NULL, - * an exception NullPointerException will be raised. - * - * @param name the name of the property to be set - * @param prop, property to be set - */ - public void setMetadata(String name, Property prop) { - if (this.props == null) { - props = new ConcurrentHashMap(); - } - - if (this.props != null) { - this.props.put(name, prop); - } - } - - /** - * Remove the metadata associated to a name. If the name is NULL, - * nothing will be removed. - * - * @param name the name of the property to be set - * @param prop, property to be set - * - * @return List of metadata currently registered - */ - public void removeMetadata(String name) { - if (this.props == null) { - return; - } - - if (this.props != null) { - this.props.remove(name); - } - // It's intentional to keep the this.props still allocated - // till the parent data structure will be alive, so to avoid - // unnecessary allocation/deallocation, even if it's holding - // nothing - } - - /** - * Generic setter for frame/packet/message's header fields against which to match - * Note: For MAC addresses, please pass the cloned value to this function - * - * @param type packet's header field type - * @param value field's value to assign to the match - * @param mask field's bitmask to apply to the match (has to be of the same class type of value) - */ - public void setField(MatchType type, Object value, Object mask) { - MatchField field = new MatchField(type, value, mask); - if (field.isValid()) { - fields.put(type, field); - matches |= type.getIndex(); - } - } - - /** - * Generic setter for frame/packet/message's header fields against which to match - * Note: For MAC addresses, please pass the cloned value to this function - * - * @param type packet's header field type - * @param value field's value to assign to the match - */ - public void setField(MatchType type, Object value) { - MatchField field = new MatchField(type, value); - if (field.isValid()) { - fields.put(type, field); - matches |= type.getIndex(); - } - } - - /** - * Generic setter for frame/packet/message's header field against which to match - * - * @param field the fields parameters as MAtchField object - */ - public void setField(MatchField field) { - if (field.isValid()) { - fields.put(field.getType(), field); - matches |= field.getType().getIndex(); - } - } - - /** - * Generic method to clear a field from the match - */ - public void clearField(MatchType type) { - fields.remove(type); - matches &= ~type.getIndex(); - } - - /** - * Generic getter for fields against which the match is programmed - * - * @param type frame/packet/message's header field type - * @return - */ - public MatchField getField(MatchType type) { - return fields.get(type); - } - - /** - * Returns the fields the match is set for in a bitmask fashion - * Each bit represents a field the match is configured for - * - * @return the 32 bit long mask (Refer to {@code}org.opendaylight.controller.sal.match.MatchElement) - */ - public int getMatches() { - return matches; - } - - /** - * Returns the list of MatchType fields the match is set for - * - * @return List of individual MatchType fields. - */ - public List getMatchesList() { - return new ArrayList(fields.keySet()); - } - - /** - * Returns the list of MatchFields the match is set for - * - * @return List of individual MatchField values. - */ - @XmlElement(name="matchField") - public List getMatchFields() { - return new ArrayList(fields.values()); - } - - /** - * Returns whether this match is for an IPv6 flow - */ - public boolean isIPv6() { - return (isPresent(MatchType.DL_TYPE) - && ((Short) getField(MatchType.DL_TYPE).getValue()) - .equals(EtherTypes.IPv6.shortValue()) - || isPresent(MatchType.NW_PROTO) - && ((Byte) getField(MatchType.NW_PROTO).getValue()) - .equals(IPProtocols.IPV6ICMP.byteValue()) - || isPresent(MatchType.NW_SRC) - && getField(MatchType.NW_SRC).getValue() instanceof Inet6Address || isPresent(MatchType.NW_DST) - && getField(MatchType.NW_DST).getValue() instanceof Inet6Address); - } - - /** - * Returns whether this match is for an IPv4 flow - */ - public boolean isIPv4() { - return !isIPv6(); - } - - /** - * Returns whether for the specified field type the match is to be considered "any" - * Equivalent to say this match does not care about the value of the specified field - * - * @param type - * @return - */ - public boolean isAny(MatchType type) { - //return ((fields.get(type) == null) || (fields.get(type).getBitMask() == 0L)); - return !fields.containsKey(type); - } - - /** - * Returns whether a match for the specified field type is configured - * - * @param type - * @return - */ - public boolean isPresent(MatchType type) { - return (fields.get(type) != null); - } - - @Override - public Match clone() { - Match cloned = null; - try { - cloned = (Match) super.clone(); - cloned.matches = matches; - cloned.fields = new HashMap(); - for (Entry entry : this.fields.entrySet()) { - cloned.fields.put(entry.getKey(), entry.getValue().clone()); - } - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - return cloned; - } - - /** - * Returns a reversed version of this match - * For example, in the reversed version the network source and destination - * addresses will be exchanged. Non symmetric match field will not be - * copied over into the reversed match version, like input port. - * - * @return - */ - public Match reverse() { - // Copy over all fields - Match reverse = this.clone(); - - // Flip symmetric fields - for (Map.Entry entry : Match.reversableMatches.entrySet()) { - MatchType from = entry.getKey(); - MatchType to = entry.getValue(); - if (this.isPresent(from)) { - reverse.setField(to, this.getField(from).getValue(), this.getField(from).getMask()); - if (!this.isPresent(to)) { - reverse.clearField(from); - } - } - } - - // Reset asymmetric fields - reverse.clearField(MatchType.IN_PORT); - - return reverse; - } - - /** - * Check whether the current match conflicts with the passed filter match - * This match conflicts with the filter if for at least a MatchType defined - * in the filter match, the respective MatchFields differ or are not - * compatible - * - * In other words the function returns true if the set of packets described - * by one match and the set of packets described by the other match are - * disjoint. Equivalently, if the intersection of the two sets of packets - * described by the two matches is an empty. - * - * For example, Let's suppose the filter has the following MatchFields: - * DL_TYPE = 0x800 - * NW_DST = 172.20.30.110/24 - * - * while this match has the following MatchFields: - * DL_TYPE = 0x800 - * NW_DST = 172.20.30.45/24 - * TP_DST = 80 - * - * Then the function would return false as the two Match are not - * conflicting. - * - * Note: the mask value is taken into account only for MatchType.NW_SRC and - * MatchType.NW_DST - * - * @param match - * the Match describing the filter - * @return true if the set of packets described by one match and the set of - * packets described by the other match are disjoint, false - * otherwise - */ - public boolean conflictWithFilter(Match filter) { - return !this.intersetcs(filter); - } - - /** - * Merge the current Match fields with the fields of the filter Match. A - * check is first run to see if this Match is compatible with the filter - * Match. If it is not, the merge is not attempted. - * - * The result is the match object representing the intersection of the set - * of packets described by this match with the set of packets described by - * the filter match. If the intersection of the two sets is empty, the - * return match will be null. - * - * @param filter - * the match with which attempting the merge - * @return a new Match object describing the set of packets represented by - * the intersection of this and the filter matches. null if the - * intersection is empty. - */ - public Match mergeWithFilter(Match filter) { - return this.getIntersection(filter); - } - - /** - * Return the match representing the intersection of the set of packets - * described by this match with the set of packets described by the other - * match. Such as m.getIntersection(m) == m, m.getIntersection(u) == m and - * m.getIntersection(o) == o where u is an empty match (universal set, all - * packets) and o is the null match (empty set). - * - * @param other - * the match with which computing the intersection - * @return a new Match object representing the intersection of the set of - * packets described by this match with the set of packets described - * by the other match. null when the intersection is the empty set. - */ - public Match getIntersection(Match other) { - // If no intersection, return the empty set - if (!this.intersetcs(other)) { - return null; - } - // Check if any of the two is the universal match - if (this.getMatches() == 0) { - return other.clone(); - } - if (other.getMatches() == 0) { - return this.clone(); - } - // Derive the intersection - Match intersection = new Match(); - for (MatchType type : MatchType.values()) { - if (this.isAny(type) && other.isAny(type)) { - continue; - } - if (this.isAny(type)) { - intersection.setField(other.getField(type).clone()); - continue; - } else if (other.isAny(type)) { - intersection.setField(this.getField(type).clone()); - continue; - } - // Either they are equal or it is about IP address - switch (type) { - // When it is about IP address, take the wider prefix address - // between the twos - case NW_SRC: - case NW_DST: - MatchField thisField = this.getField(type); - MatchField otherField = other.getField(type); - InetAddress thisAddress = (InetAddress) thisField.getValue(); - InetAddress otherAddress = (InetAddress) otherField.getValue(); - InetAddress thisMask = (InetAddress) thisField.getMask(); - InetAddress otherMask = (InetAddress) otherField.getMask(); - - int thisMaskLen = (thisMask == null) ? ((thisAddress instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength(thisMask); - int otherMaskLen = (otherMask == null) ? ((otherAddress instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength(otherMask); - if (thisMaskLen < otherMaskLen) { - intersection.setField(new MatchField(type, NetUtils.getSubnetPrefix(otherAddress, otherMaskLen), - otherMask)); - } else { - intersection.setField(new MatchField(type, NetUtils.getSubnetPrefix(thisAddress, thisMaskLen), - thisMask)); - } - break; - default: - // this and other match field are equal for this type, pick this - // match field - intersection.setField(this.getField(type).clone()); - } - } - return intersection; - } - - /** - * Checks whether the intersection of the set of packets described by this - * match with the set of packets described by the other match is non empty - * - * For example, if this match is: DL_SRC = 00:cc:bb:aa:11:22 - * - * and the other match is: DL_TYPE = 0x800 NW_SRC = 1.2.3.4 - * - * then their respective matching packets set intersection is non empty: - * DL_SRC = 00:cc:bb:aa:11:22 DL_TYPE = 0x800 NW_SRC = 1.2.3.4 - * - * @param other - * the other match with which testing the intersection - * @return true if the intersection of the respective matching packets sets - * is non empty - */ - public boolean intersetcs(Match other) { - // No intersection with the empty set - if (other == null) { - return false; - } - // Always intersection with the universal set - if (this.getMatches() == 0 || other.getMatches() == 0) { - return true; - } - // Iterate through the MatchType defined in the filter - for (MatchType type : MatchType.values()) { - if (this.isAny(type) || other.isAny(type)) { - continue; - } - - MatchField thisField = this.getField(type); - MatchField otherField = other.getField(type); - - switch (type) { - case DL_SRC: - case DL_DST: - if (!Arrays.equals((byte[]) thisField.getValue(), (byte[]) otherField.getValue())) { - return false; - } - break; - case NW_SRC: - case NW_DST: - InetAddress thisAddress = (InetAddress) thisField.getValue(); - InetAddress otherAddress = (InetAddress) otherField.getValue(); - // Validity check - if (thisAddress instanceof Inet4Address && otherAddress instanceof Inet6Address - || thisAddress instanceof Inet6Address && otherAddress instanceof Inet4Address) { - return false; - } - InetAddress thisMask = (InetAddress) thisField.getMask(); - InetAddress otherMask = (InetAddress) otherField.getMask(); - if (NetUtils.inetAddressConflict(thisAddress, otherAddress, thisMask, otherMask) - && NetUtils.inetAddressConflict(otherAddress, thisAddress, otherMask, thisMask)) { - return false; - } - break; - default: - if (!thisField.getValue().equals(otherField.getValue())) { - return false; - } - } - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - if (this.fields == null) { - result = prime * result; - } else { - // use a tree map as the order of hashMap is not guaranteed. - // 2 Match objects with fields in different order are still equal. - // Hence the hashCode should be the same too. - TreeMap tm = new TreeMap(this.fields); - for (MatchType field : tm.keySet()) { - MatchField f = tm.get(field); - int fieldHashCode = (field==null ? 0 : field.calculateConsistentHashCode()) ^ - (f==null ? 0 : f.hashCode()); - result = prime * result + fieldHashCode; - } - } - result = prime * result + matches; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Match other = (Match) obj; - if (fields == null) { - if (other.fields != null) { - return false; - } - } else if (!fields.equals(other.fields)) { - return false; - } - if (matches != other.matches) { - return false; - } - return true; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Match [fields="); - builder.append(fields); - builder.append(", matches="); - builder.append(matches); - builder.append("]"); - return builder.toString(); - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchField.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchField.java deleted file mode 100644 index 05e8462cdd..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchField.java +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.match; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Represents the generic matching field - * - */ - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class MatchField implements Cloneable, Serializable { - private static final long serialVersionUID = 1L; - private static final Logger logger = LoggerFactory.getLogger(MatchField.class); - private MatchType type; // the field we want to match - private Object value; // the value of the field we want to match - private Object mask; // the value of the mask we want to match on the - // specified field - private boolean isValid; - - // To satisfy JAXB - @SuppressWarnings("unused") - private MatchField() { - } - - /** - * Mask based match constructor - * - * @param type - * @param value - * @param mask - * has to be of the same class type of value. A null mask means - * full match - */ - public MatchField(MatchType type, Object value, Object mask) { - this.type = type; - this.value = value; - this.mask = mask; - // Keep this logic, value checked only if type check is fine - this.isValid = checkValueType() && checkValues(); - } - - /** - * Full match constructor - * - * @param type - * @param value - */ - public MatchField(MatchType type, Object value) { - this.type = type; - this.value = value; - this.mask = null; - // Keep this logic, value checked only if type check is fine - this.isValid = checkValueType() && checkValues(); - } - - /** - * Returns the value set for this match field - * - * @return - */ - public Object getValue() { - return value; - } - - @XmlElement(name = "value") - private String getValueString() { - return type.stringify(value); - } - - /** - * Returns the type field this match field object is for - * - * @return - */ - public MatchType getType() { - return type; - } - - @XmlElement(name = "type") - private String getTypeString() { - return type.toString(); - } - - /** - * Returns the mask value set for this field match A null mask means this is - * a full match - * - * @return - */ - public Object getMask() { - return mask; - } - - @XmlElement(name = "mask") - private String getMaskString() { - return type.stringify(mask); - } - - /** - * Returns the bitmask set for this field match - * - * @return - */ - public long getBitMask() { - return type.getBitMask(mask); - } - - /** - * Returns whether the field match configuration is valid or not - * - * @return - */ - public boolean isValid() { - return isValid; - } - - private boolean checkValueType() { - if (type.isCongruentType(value, mask) == false) { - String valueClass = (value == null) ? "null" : value.getClass().getSimpleName(); - String maskClass = (mask == null) ? "null" : mask.getClass().getSimpleName(); - String error = "Invalid match field's value or mask types.For field: " + type.id() + " Expected:" - + type.dataType().getSimpleName() + " or equivalent," + " Got:(" + valueClass + "," + maskClass - + ")"; - throwException(error); - return false; - } - return true; - } - - private boolean checkValues() { - if (type.isValid(value, mask) == false) { - String maskString = (mask == null) ? "null" : ("0x" + Integer - .toHexString(Integer.parseInt(mask.toString()))); - String error = "Invalid match field's value or mask assignement.For field: " + type.id() + " Expected: " - + type.getRange() + ", Got:(0x" + Integer.toHexString(Integer.parseInt(value.toString())) + "," - + maskString + ")"; - - throwException(error); - return false; - } - return true; - } - - private static void throwException(String error) { - try { - throw new Exception(error); - } catch (Exception e) { - logger.error(e.getMessage()); - } - } - - @Override - public MatchField clone() { - MatchField cloned = null; - try { - cloned = (MatchField) super.clone(); - if (value instanceof byte[]) { - cloned.value = ((byte[]) this.value).clone(); - if (this.mask != null) { - cloned.mask = ((byte[]) this.mask).clone(); - } - } - cloned.type = this.type; - cloned.isValid = this.isValid; - } catch (CloneNotSupportedException e) { - logger.error("", e); - } - return cloned; - } - - @Override - public String toString() { - return (mask == null) ? String.format("%s(%s)", getTypeString(), getValueString()) : - String.format("%s(%s,%s)", getTypeString(), getValueString(), getMaskString()); - } - - @Override - public int hashCode() { - return type.hashCode(value, mask); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - MatchField other = (MatchField) obj; - if (type != other.type) { - return false; - } - return type.equals(this.value, other.value, this.mask, other.mask); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchType.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchType.java deleted file mode 100644 index 05baa213d5..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/MatchType.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.match; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.util.Arrays; - -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; - -/** - * Represents the binding between the id, the value and mask type and the range - * values of the elements type that can be matched on the network - * frame/packet/message - */ -@Deprecated -public enum MatchType { - IN_PORT("inPort", 1 << 0, NodeConnector.class, 1, 0), - DL_SRC("dlSrc", 1 << 1, Byte[].class, 0, 0xffffffffffffL), - DL_DST("dlDst", 1 << 2, Byte[].class, 0, 0xffffffffffffL), - DL_VLAN("dlVlan", 1 << 3, Short.class, 0, 0xfff), // 2 bytes - DL_VLAN_PR("dlVlanPriority", 1 << 4, Byte.class, 0, 0x7), // 3 bits - DL_OUTER_VLAN("dlOuterVlan", 1 << 5, Short.class, 1, 0xfff), - DL_OUTER_VLAN_PR("dlOuterVlanPriority", 1 << 6, Short.class, 0, 0x7), - DL_TYPE("dlType", 1 << 7, Short.class, 0, 0xffff), // 2 bytes - NW_TOS("nwTOS", 1 << 8, Byte.class, 0, 0x3f), // 6 bits (DSCP field) - NW_PROTO("nwProto", 1 << 9, Byte.class, 0, 0xff), // 1 byte - NW_SRC("nwSrc", 1 << 10, InetAddress.class, 0, 0), - NW_DST("nwDst", 1 << 11, InetAddress.class, 0, 0), - TP_SRC("tpSrc", 1 << 12, Short.class, 0, 0xffff), // 2 bytes - TP_DST("tpDst", 1 << 13, Short.class, 0, 0xffff); // 2 bytes - - // Used to indicate that no VLAN ID is set. - public static final short DL_VLAN_NONE = (short) 0; - - private String id; - private int index; - private Class dataType; - private long minValue; - private long maxValue; - - private MatchType(String id, int index, Class dataType, long minValue, long maxValue) { - this.id = id; - this.index = index; - this.dataType = dataType; - this.minValue = minValue; - this.maxValue = maxValue; - } - - public String id() { - return id; - } - - public int getIndex() { - return index; - } - - public Class dataType() { - return dataType; - } - - public String getRange() { - return "[0x" + Long.toHexString(minValue) + "-0x" + Long.toHexString(maxValue) + "]"; - } - - /** - * Perform the assignment type validation - * - * @param value - * @param mask - * @return - */ - public boolean isCongruentType(Object value, Object mask) { - // Mask type has to match value type - if (mask != null && (mask.getClass() != value.getClass())) { - return false; - } - - Class e = this.dataType(); - Class g = value.getClass(); - - // This is all what we need, if value type is same of match required - // type - if (g.equals(e)) { - return true; - } - - // This is for the numeric class vs primitive congruence - // For what concerns here, for instance, Integer is congruent to int - if (e == Short.class) { - return g.equals(short.class); - } - - if (e == Integer.class) { - return g.equals(int.class); - } - - if (e == Byte.class) { - return g.equals(byte.class); - } - - if (e == Byte[].class) { - return g.equals(byte[].class); - } - - if (e == InetAddress.class) { - return g.getSuperclass().equals(InetAddress.class); - } - return false; - } - - /** - * Perform the value and mask range validation - * - * @param value - * @param mask - * @return - */ - public boolean isValid(Object value, Object mask) { - // Skip if main error - if (mask != null && (mask.getClass() != value.getClass())) { - return false; - } - // For the complex below types let's skip the value range check for now - if (this.dataType == InetAddress.class) { - return true; - } - if (this.dataType() == Byte[].class) { - return true; - } - if (this.dataType() == NodeConnector.class) { - return true; - } - - int val = 0; - int msk = 0; - if (value.getClass() == Integer.class || value.getClass() == int.class) { - val = ((Integer) value).intValue(); - msk = (mask != null) ? ((Integer) mask).intValue() : 0; - - } else if (value.getClass() == Short.class || value.getClass() == short.class) { - val = ((Short) value).intValue() & 0xffff; - msk = (mask != null) ? ((Short) mask).intValue() & 0xffff : 0; - - } else if (value.getClass() == Byte.class || value.getClass() == byte.class) { - val = ((Byte) value).intValue() & 0xff; - msk = (mask != null) ? ((Byte) mask).intValue() & 0xff : 0; - } - return ((val >= minValue && val <= maxValue) && (mask == null || (msk >= minValue && msk <= maxValue))); - - } - - /** - * Return the mask value in 64 bits bitmask form - * - * @param mask - * @return - */ - public long getBitMask(Object mask) { - if (this.dataType == InetAddress.class) { - // TODO handle Inet v4 and v6 v6 will have a second upper mask - return 0; - } - if (this.dataType() == Byte[].class) { - if (mask == null) { - return 0xffffffffffffL; - } - byte mac[] = (byte[]) mask; - long bitmask = 0; - for (short i = 0; i < 6; i++) { - bitmask |= ((mac[i] & 0xffL) << ((5 - i) * 8)); - } - return bitmask; - } - if (this.dataType == Integer.class || this.dataType == int.class) { - return (mask == null) ? this.maxValue : ((Integer) mask).longValue(); - - } - if (this.dataType == Short.class || this.dataType == short.class) { - return (mask == null) ? this.maxValue : ((Short) mask).longValue(); - } - if (this.dataType == Byte.class || this.dataType == byte.class) { - return (mask == null) ? this.maxValue : ((Byte) mask).longValue(); - - } - return 0L; - } - - public String stringify(Object value) { - if (value == null) { - return null; - } - - switch (this) { - case DL_DST: - case DL_SRC: - return HexEncode.bytesToHexStringFormat((byte[]) value); - case DL_TYPE: - case DL_VLAN: - return ((Integer) NetUtils.getUnsignedShort((Short) value)).toString(); - case NW_SRC: - case NW_DST: - return ((InetAddress) value).getHostAddress(); - case NW_TOS: - return ((Integer) NetUtils.getUnsignedByte((Byte) value)).toString(); - case TP_SRC: - case TP_DST: - return ((Integer) NetUtils.getUnsignedShort((Short) value)).toString(); - default: - break; - } - return value.toString(); - } - - public int valueHashCode(Object o) { - if (o == null) { - return 0; - } - switch (this) { - case DL_SRC: - case DL_DST: - return NetUtils.byteArray4ToInt((byte[])o); - default: - return o.hashCode(); - } - } - - public int hashCode(Object v, Object m) { - final int prime = 31; - int result = 1; - result = prime * result + this.calculateConsistentHashCode(); - - switch (this) { - case DL_SRC: - case DL_DST: - result = prime * result + ((v == null)? 0 : NetUtils.byteArray4ToInt((byte[])v)); - result = prime * result + ((m == null)? 0 : NetUtils.byteArray4ToInt((byte[])m)); - break; - case NW_SRC: - case NW_DST: - // Hash code has to take into account only prefix address - InetAddress ip = (InetAddress) v; - int maskLen = (m == null) ? ((ip instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength((InetAddress) m); - InetAddress prefix = NetUtils.getSubnetPrefix(ip, maskLen); - result = prime * result + ((v == null)? 0 : prefix.hashCode()); - break; - default: - result = prime * result + ((v == null)? 0 : v.hashCode()); - result = prime * result + ((m == null)? 0 : m.hashCode()); - } - return result; - } - public boolean equalValues(Object a, Object b) { - if (a == b) { - return true; - } - if (a == null || b == null) { - return false; - } - switch (this) { - case DL_DST: - case DL_SRC: - return Arrays.equals((byte[]) a, (byte[]) b); - default: - return a.equals(b); - } - } - - public boolean equalMasks(Object a, Object b) { - if (a == b) { - return true; - } - switch (this) { - case NW_SRC: - case NW_DST: - /* - * For network address mask, network node may return full mask for - * flows the controller generated with a null mask object - */ - if (a == null || b == null) { - InetAddress mask = (a == null) ? (InetAddress) b : (InetAddress) a; - int maxLength = (mask instanceof Inet4Address) ? 32 : 128; - return (NetUtils.getSubnetMaskLength(mask) == maxLength); - } - default: - if (a == null) { - return false; - } - return a.equals(b); - } - } - - public boolean equals(Object value1, Object value2, Object mask1, Object mask2) { - switch (this) { - case NW_SRC: - case NW_DST: - // Equality to be checked against prefix addresses - InetAddress thisIP = (InetAddress) value1; - int thisMaskLen = (mask1 == null) ? ((thisIP instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength((InetAddress) mask1); - InetAddress otherIP = (InetAddress) value2; - int otherMaskLen = (mask2 == null) ? ((otherIP instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength((InetAddress) mask2); - - return NetUtils.getSubnetPrefix(thisIP, thisMaskLen) - .equals(NetUtils.getSubnetPrefix(otherIP, otherMaskLen)); - default: - return (this.equalValues(value1, value2) && this.equalMasks(mask1, mask2)); - } - } - - public int calculateConsistentHashCode() { - if (this.id != null) { - return this.id.hashCode(); - } else { - return 0; - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlDst.java deleted file mode 100644 index b5c154d619..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlDst.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import java.util.Arrays; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class DlDst extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "DL_DST"; - private byte[] address; - - /** - * Creates a Match field for the destination data layer address - * - * @param address - * the data layer address. The constructor makes a copy of it - */ - public DlDst(byte[] address) { - super(TYPE); - if (address != null) { - this.address = Arrays.copyOf(address, address.length); - } - } - - // To satisfy JAXB - public DlDst() { - super(TYPE); - } - - @Override - public byte[] getValue() { - return Arrays.copyOf(address, address.length); - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return HexEncode.bytesToHexStringFormat(address); - } - - @Override - public byte[] getMask() { - return null; - } - - @Override - protected String getMaskString() { - return null; - } - - @Override - public boolean isValid() { - return address != null && address.length == NetUtils.MACAddrLengthInBytes; - } - - @Override - public boolean hasReverse() { - return true; - } - - @Override - public DlSrc getReverse() { - return new DlSrc(address); - } - - @Override - public DlDst clone() { - return new DlDst(address); - } - - @Override - public boolean isV6() { - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(address); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof DlDst)) { - return false; - } - DlDst other = (DlDst) obj; - return Arrays.equals(address, other.address); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlSrc.java deleted file mode 100644 index 0248073f19..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlSrc.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import java.util.Arrays; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class DlSrc extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "DL_SRC"; - private byte[] address; - - /** - * Creates a Match field for the source datalayer address - * - * @param address - * the datalayer address. The constructor makes a copy of it - */ - public DlSrc(byte[] address) { - super(TYPE); - if (address != null) { - this.address = Arrays.copyOf(address, address.length); - } - } - - // To satisfy JAXB - private DlSrc() { - super(TYPE); - } - - @Override - public byte[] getValue() { - return Arrays.copyOf(address, address.length); - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return HexEncode.bytesToHexStringFormat(address); - } - - @Override - public byte[] getMask() { - return null; - } - - @Override - protected String getMaskString() { - return null; - } - - @Override - public boolean isValid() { - return address != null && address.length == NetUtils.MACAddrLengthInBytes; - } - - @Override - public boolean hasReverse() { - return true; - } - - @Override - public DlDst getReverse() { - return new DlDst(address); - } - - @Override - public DlSrc clone() { - return new DlSrc(address); - } - - @Override - public boolean isV6() { - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(address); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof DlSrc)) { - return false; - } - DlSrc other = (DlSrc) obj; - return Arrays.equals(address, other.address); - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlType.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlType.java deleted file mode 100644 index e2433aa23a..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlType.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.NetUtils; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class DlType extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "DL_TYPE"; - private short ethertype; - - /** - * Creates a Match field for the data layer type - * - * @param address - * the data layer type - */ - public DlType(short ethertype) { - super(TYPE); - this.ethertype = ethertype; - } - - // To satisfy JAXB - private DlType() { - super(TYPE); - } - - @Override - public Short getValue() { - return ethertype; - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return String.format("0X%s", Integer.toHexString(NetUtils.getUnsignedShort(ethertype))); - } - - @Override - public Short getMask() { - return null; - } - - @Override - protected String getMaskString() { - return null; - } - - @Override - public boolean isValid() { - return true; - } - - @Override - public boolean hasReverse() { - return false; - } - - @Override - public DlType getReverse() { - return this.clone(); - } - - @Override - public DlType clone() { - return new DlType(ethertype); - } - - @Override - public boolean isV6() { - return this.ethertype == EtherTypes.IPv6.shortValue(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ethertype; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof DlType)) { - return false; - } - DlType other = (DlType) obj; - if (ethertype != other.ethertype) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlan.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlan.java deleted file mode 100644 index bde32573f0..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlan.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class DlVlan extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "DL_VLAN"; - private static final short MAX = 4095; - private short vlan; - - /** - * Creates a Match field for the data layer type - * - * @param address - * the data layer type - */ - public DlVlan(short vlan) { - super(TYPE); - this.vlan = vlan; - } - - // To satisfy JAXB - private DlVlan() { - super(TYPE); - } - - @Override - public Short getValue() { - return vlan; - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return String.valueOf(vlan); - } - - @Override - public Short getMask() { - return null; - } - - @Override - protected String getMaskString() { - return null; - } - - @Override - public boolean isValid() { - return vlan >= 0 && vlan <= MAX; - } - - @Override - public DlVlan getReverse() { - return this.clone(); - } - - @Override - public boolean hasReverse() { - return false; - } - - @Override - public DlVlan clone() { - return new DlVlan(vlan); - } - - @Override - public boolean isV6() { - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + vlan; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof DlVlan)) { - return false; - } - DlVlan other = (DlVlan) obj; - if (vlan != other.vlan) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlanPriority.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlanPriority.java deleted file mode 100644 index d899d64323..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/DlVlanPriority.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.NetUtils; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class DlVlanPriority extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "DL_VLAN_PR"; - private static final byte MAX = 7; - private byte vlanPriority; - - /** - * Creates a Match field for the data layer type - * - * @param address - * the data layer type - */ - public DlVlanPriority(byte vlanPriority) { - super(TYPE); - this.vlanPriority = vlanPriority; - } - - // To satisfy JAXB - private DlVlanPriority() { - super(TYPE); - } - - @Override - public Byte getValue() { - return vlanPriority; - } - - @Override - @XmlElement(name = "mask") - protected String getValueString() { - return String.format("0X%s", Integer.toHexString(NetUtils.getUnsignedByte(vlanPriority))); - } - - @Override - public Byte getMask() { - return null; - } - - @Override - protected String getMaskString() { - return null; - } - - @Override - public boolean isValid() { - return vlanPriority >= 0 && vlanPriority <= MAX; - } - - @Override - public boolean hasReverse() { - return false; - } - - @Override - public DlVlanPriority getReverse() { - return this.clone(); - } - - @Override - public DlVlanPriority clone() { - return new DlVlanPriority(vlanPriority); - } - - @Override - public boolean isV6() { - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + vlanPriority; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof DlVlanPriority)) { - return false; - } - DlVlanPriority other = (DlVlanPriority) obj; - if (vlanPriority != other.vlanPriority) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/InPort.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/InPort.java deleted file mode 100644 index a0b899e524..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/InPort.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.NodeConnector; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class InPort extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "IN_PORT"; - private NodeConnector port; - - /** - * Creates a Match field for the input port - * - * @param port - * the input port - */ - public InPort(NodeConnector port) { - super(TYPE); - this.port = port; - } - - // To satisfy JAXB - private InPort() { - super(TYPE); - } - - @Override - public NodeConnector getValue() { - return port; - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return port.toString(); - } - - @Override - public NodeConnector getMask() { - return null; - } - - @Override - protected String getMaskString() { - return null; - } - - @Override - public boolean isValid() { - return true; - } - - @Override - public boolean hasReverse() { - return false; - } - - @Override - public InPort getReverse() { - return this.clone(); - } - - @Override - public InPort clone() { - return new InPort(port); - } - - @Override - public boolean isV6() { - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((port == null) ? 0 : port.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof InPort)) { - return false; - } - InPort other = (InPort) obj; - if (port == null) { - if (other.port != null) { - return false; - } - } else if (!port.equals(other.port)) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/Match.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/Match.java deleted file mode 100644 index 7f4ddd0006..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/Match.java +++ /dev/null @@ -1,423 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.match.extensible; - -import java.io.Serializable; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - - -import org.opendaylight.controller.sal.utils.NetUtils; - -/** - * Represents the generic match criteria for a network frame/packet/message - * It contains a collection of individual field match - * - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class Match implements Cloneable, Serializable { - private static final long serialVersionUID = 1L; - private Map> fields; - - public Match() { - fields = new HashMap>(); - } - - public Match(Match match) { - fields = new HashMap>(match.fields); - } - - /** - * Generic setter for frame/packet/message's header field against which to match - * - * @param field the fields parameters as MAtchField object - */ - public void setField(MatchField field) { - if (field.isValid()) { - fields.put(field.getType(), field); - } - } - - /** - * Generic method to clear a field from the match - */ - public void clearField(String type) { - fields.remove(type); - } - - /** - * Generic getter for fields against which the match is programmed - * - * @param type frame/packet/message's header field type - * @return - */ - public MatchField getField(String type) { - return fields.get(type); - } - - /** - * Returns the list of MatchType fields the match is set for - * - * @return List of individual MatchType fields. - */ - public List getMatchesList() { - return new ArrayList(fields.keySet()); - } - - /** - * Returns the list of MatchFields the match is set for - * - * @return List of individual MatchField values. - */ - @XmlElement(name="matchField") - public List> getMatchFields() { - return new ArrayList>(fields.values()); - } - - /** - * Returns whether this match is for an IPv6 flow - */ - public boolean isIPv6() { - if (isPresent(DlType.TYPE)) { - for (MatchField field : fields.values()) { - if (!field.isV6()) { - return false; - } - } - } - return true; - } - - /** - * Returns whether this match is for an IPv4 flow - */ - public boolean isIPv4() { - return !isIPv6(); - } - - /** - * Returns whether for the specified field type the match is to be considered "any" - * Equivalent to say this match does not care about the value of the specified field - * - * @param type - * @return - */ - public boolean isAny(String type) { - return !fields.containsKey(type); - } - - /** - * Returns whether a match for the specified field type is configured - * - * @param type - * @return - */ - public boolean isPresent(String type) { - return (fields.get(type) != null); - } - - public boolean isEmpty() { - return fields.isEmpty(); - } - - @Override - public Match clone() { - Match cloned = null; - try { - cloned = (Match) super.clone(); - cloned.fields = new HashMap>(); - for (Entry> entry : this.fields.entrySet()) { - cloned.fields.put(entry.getKey(), entry.getValue().clone()); - } - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - return cloned; - } - - /** - * Returns a reversed version of this match - * For example, in the reversed version the network source and destination - * addresses will be exchanged. Non symmetric match field will not be - * copied over into the reversed match version, like input port. - * - * @return - */ - public Match reverse() { - Match reverse = new Match(); - for (MatchField field : fields.values()) { - reverse.setField(field.hasReverse()? field.getReverse() : field.clone()); - } - - // Reset asymmetric fields - reverse.clearField(InPort.TYPE); - - return reverse; - } - - /** - * Check whether the current match conflicts with the passed filter match - * This match conflicts with the filter if for at least a MatchType defined - * in the filter match, the respective MatchFields differ or are not - * compatible - * - * In other words the function returns true if the set of packets described - * by one match and the set of packets described by the other match are - * disjoint. Equivalently, if the intersection of the two sets of packets - * described by the two org.opendaylight.controller.sal.matches is an empty. - * - * For example, Let's suppose the filter has the following MatchFields: - * DL_TYPE = 0x800 - * NW_DST = 172.20.30.110/24 - * - * while this match has the following MatchFields: - * DL_TYPE = 0x800 - * NW_DST = 172.20.30.45/24 - * TP_DST = 80 - * - * Then the function would return false as the two Match are not - * conflicting. - * - * Note: the mask value is taken into account only for MatchType.NW_SRC and - * MatchType.NW_DST - * - * @param match - * the Match describing the filter - * @return true if the set of packets described by one match and the set of - * packets described by the other match are disjoint, false - * otherwise - */ - public boolean conflictWithFilter(Match filter) { - return !this.intersetcs(filter); - } - - /** - * Merge the current Match fields with the fields of the filter Match. A - * check is first run to see if this Match is compatible with the filter - * Match. If it is not, the merge is not attempted. - * - * The result is the match object representing the intersection of the set - * of packets described by this match with the set of packets described by - * the filter match. If the intersection of the two sets is empty, the - * return match will be null. - * - * @param filter - * the match with which attempting the merge - * @return a new Match object describing the set of packets represented by - * the intersection of this and the filter org.opendaylight.controller.sal.matches. null if the - * intersection is empty. - */ - public Match mergeWithFilter(Match filter) { - return this.getIntersection(filter); - } - - /** - * Return the match representing the intersection of the set of packets - * described by this match with the set of packets described by the other - * match. Such as m.getIntersection(m) == m, m.getIntersection(u) == m and - * m.getIntersection(o) == o where u is an empty match (universal set, all - * packets) and o is the null match (empty set). - * - * @param other - * the match with which computing the intersection - * @return a new Match object representing the intersection of the set of - * packets described by this match with the set of packets described - * by the other match. null when the intersection is the empty set. - */ - public Match getIntersection(Match other) { - // If no intersection, return the empty set - if (!this.intersetcs(other)) { - return null; - } - // Check if any of the two is the universal match - if (this.isEmpty()) { - return other.clone(); - } - if (other.isEmpty()) { - return this.clone(); - } - // Get all the match types for both filters - Set allTypes = new HashSet(this.fields.keySet()); - allTypes.addAll(new HashSet(other.fields.keySet())); - // Derive the intersection - Match intersection = new Match(); - for (String type : allTypes) { - if (this.isAny(type) && other.isAny(type)) { - continue; - } - if (this.isAny(type)) { - intersection.setField(other.getField(type).clone()); - continue; - } else if (other.isAny(type)) { - intersection.setField(this.getField(type).clone()); - continue; - } - // Either they are equal or it is about IP address - switch (type) { - // When it is about IP address, take the wider prefix address - // between the twos - case NwSrc.TYPE: - case NwDst.TYPE: - MatchField thisField = this.getField(type); - MatchField otherField = other.getField(type); - InetAddress thisAddress = (InetAddress) thisField.getValue(); - InetAddress otherAddress = (InetAddress) otherField.getValue(); - InetAddress thisMask = (InetAddress) thisField.getMask(); - InetAddress otherMask = (InetAddress) otherField.getMask(); - - int thisMaskLen = (thisMask == null) ? ((thisAddress instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength(thisMask); - int otherMaskLen = (otherMask == null) ? ((otherAddress instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength(otherMask); - - InetAddress subnetPrefix = null; - InetAddress subnetMask = null; - if (thisMaskLen < otherMaskLen) { - subnetPrefix = NetUtils.getSubnetPrefix(otherAddress, otherMaskLen); - subnetMask = otherMask; - } else { - subnetPrefix = NetUtils.getSubnetPrefix(thisAddress, thisMaskLen); - subnetMask = thisMask; - } - MatchField field = (type.equals(NwSrc.TYPE)) ? new NwSrc(subnetPrefix, subnetMask) : new NwDst( - subnetPrefix, subnetMask); - intersection.setField(field); - break; - default: - // this and other match field are equal for this type, pick this - // match field - intersection.setField(this.getField(type).clone()); - } - } - return intersection; - } - - /** - * Checks whether the intersection of the set of packets described by this - * match with the set of packets described by the other match is non empty - * - * For example, if this match is: DL_SRC = 00:cc:bb:aa:11:22 - * - * and the other match is: DL_TYPE = 0x800 NW_SRC = 1.2.3.4 - * - * then their respective matching packets set intersection is non empty: - * DL_SRC = 00:cc:bb:aa:11:22 DL_TYPE = 0x800 NW_SRC = 1.2.3.4 - * - * @param other - * the other match with which testing the intersection - * @return true if the intersection of the respective matching packets sets - * is non empty - */ - public boolean intersetcs(Match other) { - // No intersection with the empty set - if (other == null) { - return false; - } - // Always intersection with the universal set - if (this.isEmpty() || other.isEmpty()) { - return true; - } - - // Get all the match types for both filters - Set allTypes = new HashSet(this.fields.keySet()); - allTypes.addAll(new HashSet(other.fields.keySet())); - - // Iterate through all the match types defined in the two filters - for (String type : allTypes) { - if (this.isAny(type) || other.isAny(type)) { - continue; - } - - MatchField thisField = this.getField(type); - MatchField otherField = other.getField(type); - - switch (type) { - case DlSrc.TYPE: - case DlDst.TYPE: - if (!Arrays.equals((byte[]) thisField.getValue(), (byte[]) otherField.getValue())) { - return false; - } - break; - case NwSrc.TYPE: - case NwDst.TYPE: - InetAddress thisAddress = (InetAddress) thisField.getValue(); - InetAddress otherAddress = (InetAddress) otherField.getValue(); - // Validity check - if (thisAddress instanceof Inet4Address && otherAddress instanceof Inet6Address - || thisAddress instanceof Inet6Address && otherAddress instanceof Inet4Address) { - return false; - } - InetAddress thisMask = (InetAddress) thisField.getMask(); - InetAddress otherMask = (InetAddress) otherField.getMask(); - if (NetUtils.inetAddressConflict(thisAddress, otherAddress, thisMask, otherMask) - && NetUtils.inetAddressConflict(otherAddress, thisAddress, otherMask, thisMask)) { - return false; - } - break; - default: - if (!thisField.getValue().equals(otherField.getValue())) { - return false; - } - } - } - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((fields == null) ? 0 : fields.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof Match)) { - return false; - } - Match other = (Match) obj; - if (fields == null) { - if (other.fields != null) { - return false; - } - } else if (!fields.equals(other.fields)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Match[" + fields.values() + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/MatchField.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/MatchField.java deleted file mode 100644 index 8b9a71b950..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/MatchField.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.match.extensible; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * Represents the generic matching field object - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public abstract class MatchField implements Cloneable, Serializable { - private static final long serialVersionUID = 1L; - private String type; - - // To satisfy JAXB - @SuppressWarnings("unused") - private MatchField() { - } - - public MatchField(String type) { - this.type = type; - } - - @XmlElement(name = "type") - public String getType() { - return type; - } - - /** - * Returns the value set for this match field - * - * @return - */ - public abstract T getValue(); - - @XmlElement(name = "value") - protected abstract String getValueString(); - - /** - * Returns the mask value set for this field match A null mask means this is - * a full match - * - * @return - */ - public abstract T getMask(); - - @XmlElement(name = "mask") - protected abstract String getMaskString(); - - /** - * Returns whether the field match configuration is valid or not - * - * @return true if valid, false otherwise - */ - public abstract boolean isValid(); - - public abstract boolean hasReverse(); - - /** - * Returns the reverse match field. For example for a MatchField matching on - * source ip 1.1.1.1 it will return a MatchField matching on destination IP - * 1.1.1.1. For not reversable MatchField, a copy of this MatchField will be - * returned - * - * @return the correspondent reverse MatchField object or a copy of this - * object if the field is not reversable - */ - public abstract MatchField getReverse(); - - /** - * Returns whether the match field is congruent with IPv6 frames - * - * @return true if congruent with IPv6 frames - */ - public abstract boolean isV6(); - - @Override - public abstract MatchField clone(); - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof MatchField)) { - return false; - } - MatchField other = (MatchField) obj; - if (type == null) { - if (other.type != null) { - return false; - } - } else if (!type.equals(other.type)) { - return false; - } - return true; - } - - @Override - public String toString() { - return (getMask() == null) ? String.format("%s(%s)", getType(), getValueString()) : - String.format("%s(%s,%s)", getType(), getValueString(), getMaskString()); - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java deleted file mode 100644 index 4026bc2293..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwDst.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.NetUtils; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class NwDst extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "NW_DST"; - private InetAddress address; - private InetAddress mask; - - /** - * Creates a Match field for the network destination address - * - * @param address - * the network address - * @param mask - * the network mask - */ - public NwDst(InetAddress address, InetAddress mask) { - super(TYPE); - this.address = address; - this.mask = mask; - } - - // To satisfy JAXB - private NwDst() { - super(TYPE); - } - - public NwDst(InetAddress address) { - super(TYPE); - this.address = address; - this.mask = null; - } - - @Override - public InetAddress getValue() { - return address; - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return address.getHostAddress(); - } - - @Override - public InetAddress getMask() { - return mask; - } - - @Override - @XmlElement(name = "mask") - protected String getMaskString() { - return (mask == null) ? "null" : mask.getHostAddress(); - } - - @Override - public boolean isValid() { - if (address != null) { - if (mask != null) { - return address instanceof Inet4Address && mask instanceof Inet4Address - || address instanceof Inet6Address && mask instanceof Inet6Address; - } - return true; - } - return false; - } - - @Override - public boolean hasReverse() { - return true; - } - - @Override - public NwSrc getReverse() { - return new NwSrc(address, mask); - } - - @Override - public NwDst clone() { - return new NwDst(address, mask); - } - - @Override - public boolean isV6() { - return address instanceof Inet6Address; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((address == null) ? 0 : address.hashCode()); - result = prime * result + ((mask == null) ? 0 : mask.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof NwDst)) { - return false; - } - NwDst other = (NwDst) obj; - // Equality to be checked against prefix addresses - int thisMaskLen = (this.mask == null) ? ((this.address instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength(this.mask); - int otherMaskLen = (other.mask == null) ? ((other.address instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength(other.mask); - - return NetUtils.getSubnetPrefix(address, thisMaskLen).equals( - NetUtils.getSubnetPrefix(other.address, otherMaskLen)); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwProtocol.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwProtocol.java deleted file mode 100644 index ecaeff16e5..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwProtocol.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.NetUtils; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class NwProtocol extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "NW_PROTO"; - private static final short MAX = 255; - private byte protocol; - - /** - * Creates a Match field for the network protocol - * - * @param protocol - * the protocol number - */ - public NwProtocol(byte protocol) { - super(TYPE); - this.protocol = protocol; - } - - public NwProtocol(int protocol) { - super(TYPE); - this.protocol = (byte) protocol; - } - - public NwProtocol(short protocol) { - super(TYPE); - this.protocol = (byte) protocol; - } - - // To satisfy JAXB - private NwProtocol() { - super(TYPE); - } - - @Override - public Byte getValue() { - return protocol; - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return String.format("0X%s", Integer.toHexString(NetUtils.getUnsignedByte(protocol))); - } - - @Override - public Byte getMask() { - return null; - } - - @Override - protected String getMaskString() { - return null; - } - - @Override - public boolean isValid() { - int intProtocol = NetUtils.getUnsignedByte(protocol); - return intProtocol >= 0 && intProtocol <= MAX; - } - - @Override - public boolean hasReverse() { - return false; - } - - @Override - public NwProtocol getReverse() { - return this.clone(); - } - - @Override - public NwProtocol clone() { - return new NwProtocol(protocol); - } - - @Override - public boolean isV6() { - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + protocol; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof NwProtocol)) { - return false; - } - NwProtocol other = (NwProtocol) obj; - if (protocol != other.protocol) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwSrc.java deleted file mode 100644 index e74b51326e..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwSrc.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.NetUtils; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class NwSrc extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "NW_SRC"; - private InetAddress address; - private InetAddress mask; - - /** - * Creates a Match field for the network source address - * - * @param address - * the network address - * @param mask - * the network mask - */ - public NwSrc(InetAddress address, InetAddress mask) { - super(TYPE); - this.address = address; - this.mask = mask; - } - - // To satisfy JAXB - private NwSrc() { - super(TYPE); - } - - public NwSrc(InetAddress address) { - super(TYPE); - this.address = address; - this.mask = null; - } - - @Override - public InetAddress getValue() { - return address; - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return address.toString(); - } - - @Override - public InetAddress getMask() { - return mask; - } - - @Override - @XmlElement(name = "mask") - protected String getMaskString() { - return mask == null ? "null" : mask.toString(); - } - - @Override - public boolean isValid() { - if (address != null) { - if (mask != null) { - return address instanceof Inet4Address && mask instanceof Inet4Address - || address instanceof Inet6Address && mask instanceof Inet6Address; - } - return true; - } - return false; - } - - @Override - public boolean hasReverse() { - return true; - } - - @Override - public NwDst getReverse() { - return new NwDst(address, mask); - } - - @Override - public NwSrc clone() { - return new NwSrc(address, mask); - } - - @Override - public boolean isV6() { - return address instanceof Inet6Address; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((address == null) ? 0 : address.hashCode()); - result = prime * result + ((mask == null) ? 0 : mask.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof NwSrc)) { - return false; - } - NwSrc other = (NwSrc) obj; - // Equality to be checked against prefix addresses - int thisMaskLen = (this.mask == null) ? ((this.address instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength(this.mask); - int otherMaskLen = (other.mask == null) ? ((other.address instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength(other.mask); - - return NetUtils.getSubnetPrefix(address, thisMaskLen).equals( - NetUtils.getSubnetPrefix(other.address, otherMaskLen)); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwTos.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwTos.java deleted file mode 100644 index 95137ae070..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/NwTos.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.NetUtils; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class NwTos extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "NW_TOS"; - private static final short MAX = 63; - private byte tos; - - /** - * Creates a Match field for the network TOS - * - * @param address - * the network TOS - */ - public NwTos(byte tos) { - super(TYPE); - this.tos = tos; - } - - public NwTos(int tos) { - super(TYPE); - this.tos = (byte) tos; - } - - public NwTos(short tos) { - super(TYPE); - this.tos = (byte) tos; - } - - // To satisfy JAXB - private NwTos() { - super(TYPE); - } - - @Override - public Byte getValue() { - return tos; - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return String.format("0X%s", Integer.toHexString(NetUtils.getUnsignedByte(tos))); - } - - @Override - public Byte getMask() { - return null; - } - - @Override - protected String getMaskString() { - return null; - } - - @Override - public boolean isValid() { - return tos >= 0 && tos <= MAX; - } - - @Override - public boolean hasReverse() { - return false; - } - - @Override - public NwTos getReverse() { - return this.clone(); - } - - @Override - public NwTos clone() { - return new NwTos(tos); - } - - @Override - public boolean isV6() { - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + tos; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof NwTos)) { - return false; - } - NwTos other = (NwTos) obj; - if (tos != other.tos) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpDst.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpDst.java deleted file mode 100644 index 3e698d8d3e..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpDst.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.NetUtils; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class TpDst extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "TP_DST"; - private short port; - - /** - * Creates a Match field for the transport destination port - * - * @param port - * the transport port - */ - public TpDst(short port) { - super(TYPE); - this.port = port; - } - - // To satisfy JAXB - private TpDst() { - super(TYPE); - } - - @Override - public Short getValue() { - return port; - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return String.valueOf(NetUtils.getUnsignedShort(port)); - } - - @Override - public Short getMask() { - return null; - } - - @Override - protected String getMaskString() { - return null; - } - - @Override - public boolean isValid() { - return true; - } - - @Override - public TpSrc getReverse() { - return new TpSrc(port); - } - - @Override - public boolean hasReverse() { - return true; - } - - @Override - public TpDst clone() { - return new TpDst(port); - } - - @Override - public boolean isV6() { - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + port; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof TpDst)) { - return false; - } - TpDst other = (TpDst) obj; - if (port != other.port) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpSrc.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpSrc.java deleted file mode 100644 index d3e84270a5..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/match/extensible/TpSrc.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.opendaylight.controller.sal.match.extensible; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.utils.NetUtils; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class TpSrc extends MatchField { - private static final long serialVersionUID = 1L; - public static final String TYPE = "TP_SRC"; - private short port; - - /** - * Creates a Match field for the Transport source port - * - * @param port - * the transport port - */ - public TpSrc(short port) { - super(TYPE); - this.port = port; - } - - // To satisfy JAXB - private TpSrc() { - super(TYPE); - } - - @Override - public Short getValue() { - return port; - } - - @Override - @XmlElement(name = "value") - protected String getValueString() { - return String.valueOf(NetUtils.getUnsignedShort(port)); - } - - @Override - public Short getMask() { - return null; - } - - @Override - protected String getMaskString() { - return null; - } - - @Override - public boolean isValid() { - return true; - } - - @Override - public boolean hasReverse() { - return true; - } - - @Override - public TpDst getReverse() { - return new TpDst(port); - } - - @Override - public TpSrc clone() { - return new TpSrc(port); - } - - @Override - public boolean isV6() { - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + port; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof TpSrc)) { - return false; - } - TpSrc other = (TpSrc) obj; - if (port != other.port) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java deleted file mode 100644 index 3c9e9b6a6c..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java +++ /dev/null @@ -1,280 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; - -/** - * Class that represents the ARP packet objects - * - * - */ -@Deprecated -public class ARP extends Packet { - private static final String HWTYPE = "HardwareType"; - private static final String PTYPE = "ProtocolType"; - private static final String HWADDRLENGTH = "HardwareAddressLength"; - private static final String PADDRLENGTH = "ProtocolAddressLength"; - private static final String OPCODE = "OpCode"; - private static final String SENDERHWADDR = "SenderHardwareAddress"; - private static final String SENDERPADDR = "SenderProtocolAddress"; - private static final String TARGETHWADDR = "TargetHardwareAddress"; - private static final String TARGETPADDR = "TargetProtocolAddress"; - - public static short HW_TYPE_ETHERNET = (short) 0x1; - public static short REQUEST = (short) 0x1; - public static short REPLY = (short) 0x2; - - public static short PROTO_TYPE_IP = 0x800; - - private static Map> fieldCoordinates = new LinkedHashMap>() { - private static final long serialVersionUID = 1L; - { - put(HWTYPE, new ImmutablePair(0, 16)); - put(PTYPE, new ImmutablePair(16, 16)); - put(HWADDRLENGTH, new ImmutablePair(32, 8)); - put(PADDRLENGTH, new ImmutablePair(40, 8)); - put(OPCODE, new ImmutablePair(48, 16)); - put(SENDERHWADDR, new ImmutablePair(64, 48)); - put(SENDERPADDR, new ImmutablePair(112, 32)); - put(TARGETHWADDR, new ImmutablePair(144, 48)); - put(TARGETPADDR, new ImmutablePair(192, 32)); - - } - }; - private Map fieldValues; - - /** - * Default constructor that creates and sets the HashMap - */ - public ARP() { - super(); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - } - - /** - * Constructor that sets the access level for the packet and - * creates and sets the HashMap - */ - public ARP(boolean writeAccess) { - super(writeAccess); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - } - - /** - * Gets the hardware type from the stored ARP header - * @return short - the hardwareType - */ - public short getHardwareType() { - return (BitBufferHelper.getShort(fieldValues.get(HWTYPE))); - - } - - /** - * Gets the protocol type from the stored ARP header - * @return short - the protocolType - */ - public short getProtocolType() { - return (BitBufferHelper.getShort(fieldValues.get(PTYPE))); - } - - /** - * Gets the hardware address length from the stored ARP header - * @return byte - the protocolAddressLength - */ - public byte getHardwareAddressLength() { - return (BitBufferHelper.getByte(fieldValues.get(HWADDRLENGTH))); - } - - /** - * Get the protocol address length from Protocol header - * @return byte - the protocolAddressLength - */ - public byte getProtocolAddressLength() { - return (BitBufferHelper.getByte(fieldValues.get(PADDRLENGTH))); - } - - /** - * Gets the opCode from stored ARP header - * @param short - the opCode to set - */ - public short getOpCode() { - return (BitBufferHelper.getShort(fieldValues.get(OPCODE))); - } - - /** - * Gets the sender hardware address from the stored ARP header - * @return byte[] - the senderHardwareAddress - */ - public byte[] getSenderHardwareAddress() { - return (fieldValues.get(SENDERHWADDR)); - } - - /** - * Gets the IP address from the stored ARP header - * @return byte[] - the senderProtocolAddress - */ - public byte[] getSenderProtocolAddress() { - return (fieldValues.get(SENDERPADDR)); - } - - /** - * Gets the hardware address from the stored ARP header - * @return byte[] - the targetHardwareAddress - */ - public byte[] getTargetHardwareAddress() { - return (fieldValues.get(TARGETHWADDR)); - } - - /** - * Sets the hardware Type for the current ARP object instance - * @param short - hardwareType the hardwareType to set - * @return ARP - */ - public ARP setHardwareType(short hardwareType) { - byte[] hwType = BitBufferHelper.toByteArray(hardwareType); - fieldValues.put(HWTYPE, hwType); - return this; - } - - /** - * Sets the protocol Type for the current ARP object instance - * @param short - the protocolType to set - * @return ARP - */ - public ARP setProtocolType(short protocolType) { - byte[] protType = BitBufferHelper.toByteArray(protocolType); - fieldValues.put(PTYPE, protType); - return this; - } - - /** - * Sets the hardware address length for the current ARP object instance - * @param byte - the hardwareAddressLength to set - * @return ARP - */ - public ARP setHardwareAddressLength(byte hardwareAddressLength) { - byte[] hwAddressLength = BitBufferHelper - .toByteArray(hardwareAddressLength); - fieldValues.put(HWADDRLENGTH, hwAddressLength); - return this; - } - - /** - * Sets the Protocol address for the current ARP object instance - * @param byte - the protocolAddressLength to set - * @return ARP - */ - public ARP setProtocolAddressLength(byte protocolAddressLength) { - byte[] protocolAddrLength = BitBufferHelper - .toByteArray(protocolAddressLength); - fieldValues.put(PADDRLENGTH, protocolAddrLength); - return this; - } - - /** - * Sets the opCode for the current ARP object instance - * @param short - the opCode to set - * @return ARP - */ - public ARP setOpCode(short opCode) { - byte[] operationCode = BitBufferHelper.toByteArray(opCode); - fieldValues.put(OPCODE, operationCode); - return this; - } - - /** - * Sets the sender hardware address for the current ARP object instance - * @param byte[] - the senderHardwareAddress to set - * @return ARP - */ - public ARP setSenderHardwareAddress(byte[] senderHardwareAddress) { - fieldValues.put(SENDERHWADDR, senderHardwareAddress); - return this; - } - - /** - * Sets the target hardware address for the current ARP object instance - * @param byte[] - the targetHardwareAddress to set - * @return ARP - */ - public ARP setTargetHardwareAddress(byte[] targetHardwareAddress) { - fieldValues.put(TARGETHWADDR, targetHardwareAddress); - return this; - } - - /** - * Sets the target protocol address for the current ARP object instance - * @param byte[] - the targetProtocolAddress to set - * @return ARP - */ - public ARP setTargetProtocolAddress(byte[] targetProtocolAddress) { - fieldValues.put(TARGETPADDR, targetProtocolAddress); - return this; - } - - /** - * Sets the sender protocol address for the current ARP object instance - * @param byte[] - senderIP - * @return ARP - */ - public ARP setSenderProtocolAddress(byte[] senderIP) { - fieldValues.put(SENDERPADDR, senderIP); - return this; - } - - /** - * Gets the target protocol address - * @return - byte[] targetProtocolAddress - */ - public byte[] getTargetProtocolAddress() { - return fieldValues.get(TARGETPADDR); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result - + ((fieldValues == null) ? 0 : fieldValues.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - ARP other = (ARP) obj; - if (fieldValues == null) { - if (other.fieldValues != null) { - return false; - } - } else if (!fieldValues.equals(other.fieldValues)) { - return false; - } - return true; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BitBufferHelper.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BitBufferHelper.java deleted file mode 100644 index 176e446e98..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BitBufferHelper.java +++ /dev/null @@ -1,720 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * - */ -package org.opendaylight.controller.sal.packet; - -import java.util.Arrays; - -import org.opendaylight.controller.sal.utils.NetUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * BitBufferHelper class that provides utility methods to - * - fetch specific bits from a serialized stream of bits - * - convert bits to primitive data type - like short, int, long - * - store bits in specified location in stream of bits - * - convert primitive data types to stream of bits - */ -@Deprecated -public abstract class BitBufferHelper { - protected static final Logger logger = LoggerFactory - .getLogger(BitBufferHelper.class); - - public static final long ByteMask = 0xFF; - - // Getters - // data: array where data are stored - // startOffset: bit from where to start reading - // numBits: number of bits to read - // All this function return an exception if overflow or underflow - - /** - * Returns the first byte from the byte array - * @param byte[] data - * @return byte value - */ - public static byte getByte(byte[] data) { - if ((data.length * NetUtils.NumBitsInAByte) > Byte.SIZE) { - try { - throw new BufferException( - "Container is too small for the number of requested bits"); - } catch (BufferException e) { - logger.error("", e); - } - } - return (data[0]); - } - - /** - * Returns the short value for the byte array passed. - * Size of byte array is restricted to Short.SIZE - * @param byte[] data - * @return short value - */ - public static short getShort(byte[] data) { - if (data.length > Short.SIZE) { - try { - throw new BufferException( - "Container is too small for the number of requested bits"); - } catch (BufferException e) { - logger.error("", e); - } - } - return (short) toNumber(data); - } - - /** - * Returns the int value for the byte array passed. - * Size of byte array is restricted to Integer.SIZE - * @param byte[] data - * @return int - the integer value of byte array - */ - public static int getInt(byte[] data) { - if (data.length > Integer.SIZE) { - try { - throw new BufferException( - "Container is too small for the number of requested bits"); - } catch (BufferException e) { - logger.error("", e); - } - } - return (int) toNumber(data); - } - - /** - * Returns the long value for the byte array passed. - * Size of byte array is restricted to Long.SIZE - * @param byte[] data - * @return long - the integer value of byte array - */ - public static long getLong(byte[] data) { - if (data.length > Long.SIZE) { - try { - throw new BufferException( - "Container is too small for the number of requested bits"); - } catch (Exception e) { - logger.error("", e); - } - } - return (long) toNumber(data); - } - - /** - * Returns the short value for the last numBits of the byte array passed. - * Size of numBits is restricted to Short.SIZE - * @param byte[] data - * @param int - numBits - * @return short - the short value of byte array - */ - public static short getShort(byte[] data, int numBits) { - if (numBits > Short.SIZE) { - try { - throw new BufferException( - "Container is too small for the number of requested bits"); - } catch (BufferException e) { - logger.error("", e); - } - } - int startOffset = data.length * NetUtils.NumBitsInAByte - numBits; - byte[] bits = null; - try { - bits = BitBufferHelper.getBits(data, startOffset, numBits); - } catch (BufferException e) { - logger.error("", e); - } - return (short) toNumber(bits, numBits); - } - - /** - * Returns the int value for the last numBits of the byte array passed. - * Size of numBits is restricted to Integer.SIZE - * @param byte[] data - * @param int - numBits - * @return int - the integer value of byte array - */ - public static int getInt(byte[] data, int numBits) { - if (numBits > Integer.SIZE) { - try { - throw new BufferException( - "Container is too small for the number of requested bits"); - } catch (BufferException e) { - logger.error("", e); - } - } - int startOffset = data.length * NetUtils.NumBitsInAByte - numBits; - byte[] bits = null; - try { - bits = BitBufferHelper.getBits(data, startOffset, numBits); - } catch (BufferException e) { - logger.error("", e); - } - return (int) toNumber(bits, numBits); - } - - /** - * Returns the long value for the last numBits of the byte array passed. - * Size of numBits is restricted to Long.SIZE - * @param byte[] data - * @param int - numBits - * @return long - the integer value of byte array - */ - public static long getLong(byte[] data, int numBits) { - if (numBits > Long.SIZE) { - try { - throw new BufferException( - "Container is too small for the number of requested bits"); - } catch (BufferException e) { - logger.error("", e); - } - } - if (numBits > data.length * NetUtils.NumBitsInAByte) { - try { - throw new BufferException( - "Trying to read more bits than contained in the data buffer"); - } catch (BufferException e) { - logger.error("", e); - } - } - int startOffset = data.length * NetUtils.NumBitsInAByte - numBits; - byte[] bits = null; - try { - bits = BitBufferHelper.getBits(data, startOffset, numBits); - } catch (BufferException e) { - logger.error("", e); - } - return (long) toNumber(bits, numBits); - } - - /** - * Reads the specified number of bits from the passed byte array - * starting to read from the specified offset - * The bits read are stored in a byte array which size is dictated - * by the number of bits to be stored. - * The bits are stored in the byte array LSB aligned. - * - * Ex. - * Read 7 bits at offset 10 - * 0 9 10 16 17 - * 0101000010 | 0000101 | 1111001010010101011 - * will be returned as {0,0,0,0,0,1,0,1} - * - * @param byte[] data - * @param int startOffset - offset to start fetching bits from data from - * @param int numBits - number of bits to be fetched from data - * @return byte [] - LSB aligned bits - * - * @throws BufferException - * when the startOffset and numBits parameters are not congruent - * with the data buffer size - */ - public static byte[] getBits(byte[] data, int startOffset, int numBits) - throws BufferException { - - int startByteOffset = 0; - int valfromcurr, valfromnext; - int extranumBits = numBits % NetUtils.NumBitsInAByte; - int extraOffsetBits = startOffset % NetUtils.NumBitsInAByte; - int numBytes = (numBits % NetUtils.NumBitsInAByte != 0) ? 1 + numBits - / NetUtils.NumBitsInAByte : numBits / NetUtils.NumBitsInAByte; - byte[] shiftedBytes = new byte[numBytes]; - startByteOffset = startOffset / NetUtils.NumBitsInAByte; - byte[] bytes = new byte[numBytes]; - if (numBits == 0) { - return bytes; - } - - checkExceptions(data, startOffset, numBits); - - if (extraOffsetBits == 0) { - if (extranumBits == 0) { - System.arraycopy(data, startByteOffset, bytes, 0, numBytes); - return bytes; - } else { - System.arraycopy(data, startByteOffset, bytes, 0, numBytes - 1); - bytes[numBytes - 1] = (byte) ((int) data[startByteOffset - + numBytes - 1] & getMSBMask(extranumBits)); - } - } else { - int i; - for (i = 0; i < numBits / NetUtils.NumBitsInAByte; i++) { - // Reading numBytes starting from offset - valfromcurr = (data[startByteOffset + i]) - & getLSBMask(NetUtils.NumBitsInAByte - extraOffsetBits); - valfromnext = (data[startByteOffset + i + 1]) - & getMSBMask(extraOffsetBits); - bytes[i] = (byte) (valfromcurr << (extraOffsetBits) | (valfromnext >> (NetUtils.NumBitsInAByte - extraOffsetBits))); - } - // Now adding the rest of the bits if any - if (extranumBits != 0) { - if (extranumBits < (NetUtils.NumBitsInAByte - extraOffsetBits)) { - valfromnext = (byte) (data[startByteOffset + i] & ((getMSBMask(extranumBits)) >> extraOffsetBits)); - bytes[i] = (byte) (valfromnext << extraOffsetBits); - } else if (extranumBits == (NetUtils.NumBitsInAByte - extraOffsetBits)) { - valfromcurr = (data[startByteOffset + i]) - & getLSBMask(NetUtils.NumBitsInAByte - - extraOffsetBits); - bytes[i] = (byte) (valfromcurr << extraOffsetBits); - } else { - valfromcurr = (data[startByteOffset + i]) - & getLSBMask(NetUtils.NumBitsInAByte - - extraOffsetBits); - valfromnext = (data[startByteOffset + i + 1]) - & (getMSBMask(extranumBits - - (NetUtils.NumBitsInAByte - extraOffsetBits))); - bytes[i] = (byte) (valfromcurr << (extraOffsetBits) | (valfromnext >> (NetUtils.NumBitsInAByte - extraOffsetBits))); - } - - } - } - // Aligns the bits to LSB - shiftedBytes = shiftBitsToLSB(bytes, numBits); - return shiftedBytes; - } - - // Setters - // data: array where data will be stored - // input: the data that need to be stored in the data array - // startOffset: bit from where to start writing - // numBits: number of bits to read - - /** - * Bits are expected to be stored in the input byte array from LSB - * @param byte[] - data to set the input byte - * @param byte - input byte to be inserted - * @param startOffset - offset of data[] to start inserting byte from - * @param numBits - number of bits of input to be inserted into data[] - * - * @throws BufferException - * when the input, startOffset and numBits are not congruent - * with the data buffer size - */ - public static void setByte(byte[] data, byte input, int startOffset, - int numBits) throws BufferException { - byte[] inputByteArray = new byte[1]; - Arrays.fill(inputByteArray, 0, 1, input); - setBytes(data, inputByteArray, startOffset, numBits); - } - - /** - * Bits are expected to be stored in the input byte array from LSB - * @param byte[] - data to set the input byte - * @param byte[] - input bytes to be inserted - * @param startOffset - offset of data[] to start inserting byte from - * @param numBits - number of bits of input to be inserted into data[] - * @return void - * @throws BufferException - * when the startOffset and numBits parameters are not congruent - * with data and input buffers' size - */ - public static void setBytes(byte[] data, byte[] input, int startOffset, - int numBits) throws BufferException { - checkExceptions(data, startOffset, numBits); - insertBits(data, input, startOffset, numBits); - } - - /** - * Returns numBits 1's in the MSB position - * - * @param numBits - * @return - */ - public static int getMSBMask(int numBits) { - int mask = 0; - for (int i = 0; i < numBits; i++) { - mask = mask | (1 << (7 - i)); - } - return mask; - } - - /** - * Returns numBits 1's in the LSB position - * - * @param numBits - * @return - */ - public static int getLSBMask(int numBits) { - int mask = 0; - for (int i = 0; i < numBits; i++) { - mask = mask | (1 << i); - } - return mask; - } - - /** - * Returns the numerical value of the byte array passed - * - * @param byte[] - array - * @return long - numerical value of byte array passed - */ - static public long toNumber(byte[] array) { - long ret = 0; - long length = array.length; - int value = 0; - for (int i = 0; i < length; i++) { - value = array[i]; - if (value < 0) - value += 256; - ret = ret - | (long) ((long) value << ((length - i - 1) * NetUtils.NumBitsInAByte)); - } - return ret; - } - - /** - * Returns the numerical value of the last numBits (LSB bits) of the byte - * array passed - * - * @param byte[] - array - * @param int - numBits - * @return long - numerical value of byte array passed - */ - static public long toNumber(byte[] array, int numBits) { - int length = numBits / NetUtils.NumBitsInAByte; - int bitsRest = numBits % NetUtils.NumBitsInAByte; - int startOffset = array.length - length; - long ret = 0; - int value = 0; - - value = array[startOffset - 1] & getLSBMask(bitsRest); - value = (array[startOffset - 1] < 0) ? (array[startOffset - 1] + 256) - : array[startOffset - 1]; - ret = ret - | (value << ((array.length - startOffset) * NetUtils.NumBitsInAByte)); - - for (int i = startOffset; i < array.length; i++) { - value = array[i]; - if (value < 0) - value += 256; - ret = ret - | (long) ((long) value << ((array.length - i - 1) * NetUtils.NumBitsInAByte)); - } - - return ret; - } - - /** - * Accepts a number as input and returns its value in byte form in LSB - * aligned form example: input = 5000 [1001110001000] bytes = 19, -120 - * [00010011] [10001000] - * - * @param Number - * @return byte[] - * - */ - - public static byte[] toByteArray(Number input) { - Class dataType = input.getClass(); - short size = 0; - long longValue = input.longValue(); - - if (dataType == Byte.class || dataType == byte.class) { - size = Byte.SIZE; - } else if (dataType == Short.class || dataType == short.class) { - size = Short.SIZE; - } else if (dataType == Integer.class || dataType == int.class) { - size = Integer.SIZE; - } else if (dataType == Long.class || dataType == long.class) { - size = Long.SIZE; - } else { - throw new IllegalArgumentException( - "Parameter must one of the following: Short/Int/Long\n"); - } - - int length = size / NetUtils.NumBitsInAByte; - byte bytes[] = new byte[length]; - - // Getting the bytes from input value - for (int i = 0; i < length; i++) { - bytes[i] = (byte) ((longValue >> (NetUtils.NumBitsInAByte * (length - - i - 1))) & ByteMask); - } - return bytes; - } - - /** - * Accepts a number as input and returns its value in byte form in MSB - * aligned form example: input = 5000 [1001110001000] bytes = -114, 64 - * [10011100] [01000000] - * - * @param Number - * input - * @param int numBits - the number of bits to be returned - * @return byte[] - * - */ - public static byte[] toByteArray(Number input, int numBits) { - Class dataType = input.getClass(); - short size = 0; - long longValue = input.longValue(); - - if (dataType == Short.class) { - size = Short.SIZE; - } else if (dataType == Integer.class) { - size = Integer.SIZE; - } else if (dataType == Long.class) { - size = Long.SIZE; - } else { - throw new IllegalArgumentException( - "Parameter must one of the following: Short/Int/Long\n"); - } - - int length = size / NetUtils.NumBitsInAByte; - byte bytes[] = new byte[length]; - byte[] inputbytes = new byte[length]; - byte shiftedBytes[]; - - // Getting the bytes from input value - for (int i = 0; i < length; i++) { - bytes[i] = (byte) ((longValue >> (NetUtils.NumBitsInAByte * (length - - i - 1))) & ByteMask); - } - - if ((bytes[0] == 0 && dataType == Long.class) - || (bytes[0] == 0 && dataType == Integer.class)) { - int index = 0; - for (index = 0; index < length; ++index) { - if (bytes[index] != 0) { - bytes[0] = bytes[index]; - break; - } - } - System.arraycopy(bytes, index, inputbytes, 0, length - index); - Arrays.fill(bytes, length - index + 1, length - 1, (byte) 0); - } else { - System.arraycopy(bytes, 0, inputbytes, 0, length); - } - - shiftedBytes = shiftBitsToMSB(inputbytes, numBits); - - return shiftedBytes; - } - - /** - * Takes an LSB aligned byte array and returned the LSB numBits in a MSB - * aligned byte array - * - * @param inputbytes - * @param numBits - * @return - */ - /** - * It aligns the last numBits bits to the head of the byte array following - * them with numBits % 8 zero bits. - * - * Example: For inputbytes = [00000111][01110001] and numBits = 12 it - * returns: shiftedBytes = [01110111][00010000] - * - * @param byte[] inputBytes - * @param int numBits - number of bits to be left aligned - * @return byte[] - */ - public static byte[] shiftBitsToMSB(byte[] inputBytes, int numBits) { - int numBitstoShiftBy = 0, leadZeroesMSB = 8, numEndRestBits = 0; - int size = inputBytes.length; - byte[] shiftedBytes = new byte[size]; - int i; - - for (i = 0; i < Byte.SIZE; i++) { - if (((byte) (inputBytes[0] & getMSBMask(i + 1))) != 0) { - leadZeroesMSB = i; - break; - } - } - - if (numBits % NetUtils.NumBitsInAByte == 0) { - numBitstoShiftBy = 0; - } else { - numBitstoShiftBy = ((NetUtils.NumBitsInAByte - (numBits % NetUtils.NumBitsInAByte)) < leadZeroesMSB) ? (NetUtils.NumBitsInAByte - (numBits % NetUtils.NumBitsInAByte)) - : leadZeroesMSB; - } - if (numBitstoShiftBy == 0) { - return inputBytes; - } - - if (numBits < NetUtils.NumBitsInAByte) { - // inputbytes.length = 1 OR read less than a byte - shiftedBytes[0] = (byte) ((inputBytes[0] & getLSBMask(numBits)) << numBitstoShiftBy); - } else { - // # of bits to read from last byte - numEndRestBits = NetUtils.NumBitsInAByte - - (inputBytes.length * NetUtils.NumBitsInAByte - numBits - numBitstoShiftBy); - - for (i = 0; i < (size - 1); i++) { - if ((i + 1) == (size - 1)) { - if (numEndRestBits > numBitstoShiftBy) { - shiftedBytes[i] = (byte) ((inputBytes[i] << numBitstoShiftBy) | ((inputBytes[i + 1] & getMSBMask(numBitstoShiftBy)) >> (numEndRestBits - numBitstoShiftBy))); - shiftedBytes[i + 1] = (byte) ((inputBytes[i + 1] & getLSBMask(numEndRestBits - - numBitstoShiftBy)) << numBitstoShiftBy); - } else - shiftedBytes[i] = (byte) ((inputBytes[i] << numBitstoShiftBy) | ((inputBytes[i + 1] & getMSBMask(numEndRestBits)) >> (NetUtils.NumBitsInAByte - numEndRestBits))); - } - shiftedBytes[i] = (byte) ((inputBytes[i] << numBitstoShiftBy) | (inputBytes[i + 1] & getMSBMask(numBitstoShiftBy)) >> (NetUtils.NumBitsInAByte - numBitstoShiftBy)); - } - - } - return shiftedBytes; - } - - /** - * It aligns the first numBits bits to the right end of the byte array - * preceding them with numBits % 8 zero bits. - * - * Example: For inputbytes = [01110111][00010000] and numBits = 12 it - * returns: shiftedBytes = [00000111][01110001] - * - * @param byte[] inputBytes - * @param int numBits - number of bits to be right aligned - * @return byte[] - */ - public static byte[] shiftBitsToLSB(byte[] inputBytes, int numBits) { - int numBytes = inputBytes.length; - int numBitstoShift = numBits % NetUtils.NumBitsInAByte; - byte[] shiftedBytes = new byte[numBytes]; - int inputLsb = 0, inputMsb = 0; - - if (numBitstoShift == 0) { - return inputBytes; - } - - for (int i = 1; i < numBytes; i++) { - inputLsb = inputBytes[i - 1] - & getLSBMask(NetUtils.NumBitsInAByte - numBitstoShift); - inputLsb = (inputLsb < 0) ? (inputLsb + 256) : inputLsb; - inputMsb = inputBytes[i] & getMSBMask(numBitstoShift); - inputMsb = (inputBytes[i] < 0) ? (inputBytes[i] + 256) - : inputBytes[i]; - shiftedBytes[i] = (byte) ((inputLsb << numBitstoShift) | (inputMsb >> (NetUtils.NumBitsInAByte - numBitstoShift))); - } - inputMsb = inputBytes[0] & (getMSBMask(numBitstoShift)); - inputMsb = (inputMsb < 0) ? (inputMsb + 256) : inputMsb; - shiftedBytes[0] = (byte) (inputMsb >> (NetUtils.NumBitsInAByte - numBitstoShift)); - return shiftedBytes; - } - - /** - * Insert in the data buffer at position dictated by the offset the number - * of bits specified from the input data byte array. The input byte array - * has the bits stored starting from the LSB - * - * @param byte[] data - * @param byte[] inputdata - * @param int startOffset - * @param int numBits - */ - public static void insertBits(byte[] data, byte[] inputdataLSB, - int startOffset, int numBits) { - byte[] inputdata = shiftBitsToMSB(inputdataLSB, numBits); // Align to - // MSB the - // passed byte - // array - int numBytes = numBits / NetUtils.NumBitsInAByte; - int startByteOffset = startOffset / NetUtils.NumBitsInAByte; - int extraOffsetBits = startOffset % NetUtils.NumBitsInAByte; - int extranumBits = numBits % NetUtils.NumBitsInAByte; - int RestBits = numBits % NetUtils.NumBitsInAByte; - int InputMSBbits = 0, InputLSBbits = 0; - int i; - - if (numBits == 0) { - return; - } - - if (extraOffsetBits == 0) { - if (extranumBits == 0) { - numBytes = numBits / NetUtils.NumBitsInAByte; - System.arraycopy(inputdata, 0, data, startByteOffset, numBytes); - } else { - System.arraycopy(inputdata, 0, data, startByteOffset, numBytes); - data[startByteOffset + numBytes] = (byte) (data[startByteOffset - + numBytes] | (inputdata[numBytes] & getMSBMask(extranumBits))); - } - } else { - for (i = 0; i < numBytes; i++) { - if (i != 0) - InputLSBbits = (inputdata[i - 1] & getLSBMask(extraOffsetBits)); - InputMSBbits = (byte) (inputdata[i] & (getMSBMask(NetUtils.NumBitsInAByte - - extraOffsetBits))); - InputMSBbits = (InputMSBbits >= 0) ? InputMSBbits - : InputMSBbits + 256; - data[startByteOffset + i] = (byte) (data[startByteOffset + i] - | (InputLSBbits << (NetUtils.NumBitsInAByte - extraOffsetBits)) | (InputMSBbits >> extraOffsetBits)); - InputMSBbits = InputLSBbits = 0; - } - if (RestBits < (NetUtils.NumBitsInAByte - extraOffsetBits)) { - if (numBytes != 0) - InputLSBbits = (inputdata[i - 1] & getLSBMask(extraOffsetBits)); - InputMSBbits = (byte) (inputdata[i] & (getMSBMask(RestBits))); - InputMSBbits = (InputMSBbits >= 0) ? InputMSBbits - : InputMSBbits + 256; - data[startByteOffset + i] = (byte) ((data[startByteOffset + i]) - | (InputLSBbits << (NetUtils.NumBitsInAByte - extraOffsetBits)) | (InputMSBbits >> extraOffsetBits)); - } else if (RestBits == (NetUtils.NumBitsInAByte - extraOffsetBits)) { - if (numBytes != 0) - InputLSBbits = (inputdata[i - 1] & getLSBMask(extraOffsetBits)); - InputMSBbits = (byte) (inputdata[i] & (getMSBMask(NetUtils.NumBitsInAByte - - extraOffsetBits))); - InputMSBbits = (InputMSBbits >= 0) ? InputMSBbits - : InputMSBbits + 256; - data[startByteOffset + i] = (byte) (data[startByteOffset + i] - | (InputLSBbits << (NetUtils.NumBitsInAByte - extraOffsetBits)) | (InputMSBbits >> extraOffsetBits)); - } else { - if (numBytes != 0) - InputLSBbits = (inputdata[i - 1] & getLSBMask(extraOffsetBits)); - InputMSBbits = (byte) (inputdata[i] & (getMSBMask(NetUtils.NumBitsInAByte - - extraOffsetBits))); - InputMSBbits = (InputMSBbits >= 0) ? InputMSBbits - : InputMSBbits + 256; - data[startByteOffset + i] = (byte) (data[startByteOffset + i] - | (InputLSBbits << (NetUtils.NumBitsInAByte - extraOffsetBits)) | (InputMSBbits >> extraOffsetBits)); - - InputLSBbits = (inputdata[i] & (getLSBMask(RestBits - - (NetUtils.NumBitsInAByte - extraOffsetBits)) << (NetUtils.NumBitsInAByte - RestBits))); - data[startByteOffset + i + 1] = (byte) (data[startByteOffset - + i + 1] | (InputLSBbits << (NetUtils.NumBitsInAByte - extraOffsetBits))); - } - } - } - - /** - * Checks for overflow and underflow exceptions - * @param data - * @param startOffset - * @param numBits - * @throws PacketException when the startOffset and numBits parameters - * are not congruent with the data buffer's size - */ - public static void checkExceptions(byte[] data, int startOffset, int numBits) - throws BufferException { - int endOffsetByte; - int startByteOffset; - endOffsetByte = startOffset - / NetUtils.NumBitsInAByte - + numBits - / NetUtils.NumBitsInAByte - + ((numBits % NetUtils.NumBitsInAByte != 0) ? 1 : ((startOffset - % NetUtils.NumBitsInAByte != 0) ? 1 : 0)); - startByteOffset = startOffset / NetUtils.NumBitsInAByte; - - if (data == null) { - throw new BufferException("data[] is null\n"); - } - - if ((startOffset < 0) || (startByteOffset >= data.length) - || (endOffsetByte > data.length) || (numBits < 0) - || (numBits > NetUtils.NumBitsInAByte * data.length)) { - throw new BufferException( - "Illegal arguement/out of bound exception - data.length = " - + data.length + " startOffset = " + startOffset - + " numBits " + numBits); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BufferException.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BufferException.java deleted file mode 100644 index 63fd4ec8d1..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/BufferException.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.packet; - -/** - * Describes an exception that is raised during BitBufferHelper operations. - */ -@Deprecated -public class BufferException extends Exception { - private static final long serialVersionUID = 1L; - - public BufferException(String message) { - super(message); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java deleted file mode 100644 index a7ffbe7926..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java +++ /dev/null @@ -1,151 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.NetUtils; - -/** - * Class that represents the Ethernet frame objects - */ -@Deprecated -public class Ethernet extends Packet { - private static final String DMAC = "DestinationMACAddress"; - private static final String SMAC = "SourceMACAddress"; - private static final String ETHT = "EtherType"; - - // TODO: This has to be outside and it should be possible for osgi - // to add new coming packet classes - public static final Map> etherTypeClassMap; - static { - etherTypeClassMap = new HashMap>(); - etherTypeClassMap.put(EtherTypes.ARP.shortValue(), ARP.class); - etherTypeClassMap.put(EtherTypes.IPv4.shortValue(), IPv4.class); - etherTypeClassMap.put(EtherTypes.LLDP.shortValue(), LLDP.class); - etherTypeClassMap.put(EtherTypes.VLANTAGGED.shortValue(), IEEE8021Q.class); - etherTypeClassMap.put(EtherTypes.OLDQINQ.shortValue(), IEEE8021Q.class); - etherTypeClassMap.put(EtherTypes.QINQ.shortValue(), IEEE8021Q.class); - etherTypeClassMap.put(EtherTypes.CISCOQINQ.shortValue(), IEEE8021Q.class); - } - private static Map> fieldCoordinates = new LinkedHashMap>() { - private static final long serialVersionUID = 1L; - { - put(DMAC, new ImmutablePair(0, 48)); - put(SMAC, new ImmutablePair(48, 48)); - put(ETHT, new ImmutablePair(96, 16)); - } - }; - private final Map fieldValues; - - /** - * Default constructor that creates and sets the HashMap - */ - public Ethernet() { - super(); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - } - - /** - * Constructor that sets the access level for the packet and - * creates and sets the HashMap - */ - public Ethernet(boolean writeAccess) { - super(writeAccess); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - } - - @Override - public void setHeaderField(String headerField, byte[] readValue) { - if (headerField.equals(ETHT)) { - payloadClass = etherTypeClassMap.get(BitBufferHelper - .getShort(readValue)); - } - hdrFieldsMap.put(headerField, readValue); - } - - /** - * Gets the destination MAC address stored - * @return byte[] - the destinationMACAddress - */ - public byte[] getDestinationMACAddress() { - return fieldValues.get(DMAC); - } - - /** - * Gets the source MAC address stored - * @return byte[] - the sourceMACAddress - */ - public byte[] getSourceMACAddress() { - return fieldValues.get(SMAC); - } - - /** - * Gets the etherType stored - * @return short - the etherType - */ - public short getEtherType() { - return BitBufferHelper.getShort(fieldValues.get(ETHT)); - } - - public boolean isBroadcast(){ - return NetUtils.isBroadcastMACAddr(getDestinationMACAddress()); - } - - public boolean isMulticast(){ - return NetUtils.isMulticastMACAddr(getDestinationMACAddress()); - } - - /** - * Sets the destination MAC address for the current Ethernet object instance - * @param byte[] - the destinationMACAddress to set - */ - public Ethernet setDestinationMACAddress(byte[] destinationMACAddress) { - fieldValues.put(DMAC, destinationMACAddress); - return this; - } - - /** - * Sets the source MAC address for the current Ethernet object instance - * @param byte[] - the sourceMACAddress to set - */ - public Ethernet setSourceMACAddress(byte[] sourceMACAddress) { - fieldValues.put(SMAC, sourceMACAddress); - return this; - } - - /** - * Sets the etherType for the current Ethernet object instance - * @param short - the etherType to set - */ - public Ethernet setEtherType(short etherType) { - byte[] ethType = BitBufferHelper.toByteArray(etherType); - fieldValues.put(ETHT, ethType); - return this; - } - - @Override - public void populateMatch(Match match) { - match.setField(MatchType.DL_SRC, this.getSourceMACAddress()); - match.setField(MatchType.DL_DST, this.getDestinationMACAddress()); - match.setField(MatchType.DL_TYPE, this.getEtherType()); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ICMP.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ICMP.java deleted file mode 100644 index 79d6f6014f..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ICMP.java +++ /dev/null @@ -1,244 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.opendaylight.controller.sal.utils.NetUtils; - -/** - * Class that represents the ICMP packet objects - */ -@Deprecated -public class ICMP extends Packet { - private static final String TYPE = "Type"; - private static final String CODE = "Code"; - private static final String CHECKSUM = "Checksum"; - private static final String IDENTIFIER = "Identifier"; - private static final String SEQNUMBER = "SequenceNumber"; - - private static Map> fieldCoordinates = new LinkedHashMap>() { - private static final long serialVersionUID = 1L; - { - put(TYPE, new ImmutablePair(0, 8)); - put(CODE, new ImmutablePair(8, 8)); - put(CHECKSUM, new ImmutablePair(16, 16)); - put(IDENTIFIER, new ImmutablePair(32, 16)); - put(SEQNUMBER, new ImmutablePair(48, 16)); - } - }; - - /** - * Default constructor that creates and sets the hash map values - */ - public ICMP() { - super(); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - } - - /** - * Constructor that sets the access level for the packet - */ - public ICMP(boolean writeAccess) { - super(writeAccess); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - } - - private final Map fieldValues; - - @Override - public void setHeaderField(String headerField, byte[] readValue) { - hdrFieldsMap.put(headerField, readValue); - } - - /** - * Sets the type for the current ICMP message - * - * @param type - * The ICMP message type - * @return This ICMP object - */ - public ICMP setType(byte type) { - byte[] icmpType = BitBufferHelper.toByteArray(type); - fieldValues.put(TYPE, icmpType); - return this; - } - - /** - * Returns the type field of the current ICMP packet - * - * @return The type code of the current ICMP packet - */ - public byte getType() { - return BitBufferHelper.getByte(fieldValues.get(TYPE)); - } - - /** - * Sets the ICMP code (type subtype) for the current ICMP object instance - * - * @param code - * The ICMP message type subtype - * @return This ICMP object - */ - public ICMP setCode(byte code) { - byte[] icmpCode = BitBufferHelper.toByteArray(code); - fieldValues.put(CODE, icmpCode); - return this; - } - - /** - * Gets the ICMP code (type subtype) for the current ICMP object instance - * - * @return The ICMP message type subtype - */ - public byte getCode() { - return BitBufferHelper.getByte(fieldValues.get(CODE)); - } - - /** - * Sets the ICMP checksum for the current ICMP object instance - * @param short - checksum - * @return ICMP - */ - public ICMP setChecksum(short checksum) { - byte[] icmpChecksum = BitBufferHelper.toByteArray(checksum); - fieldValues.put(CHECKSUM, icmpChecksum); - return this; - } - - /** - * Sets the ICMP identifier for the current ICMP object instance - * @param short - identifier - * @return ICMP - */ - public ICMP setIdentifier(short identifier) { - byte[] icmpIdentifier = BitBufferHelper.toByteArray(identifier); - fieldValues.put(IDENTIFIER, icmpIdentifier); - return this; - } - - /** - * Gets the ICMP identifier of the current ICMP object instance - * - * @return short - identifier - */ - - public short getIdentifier() { - return BitBufferHelper.getShort(fieldValues.get(IDENTIFIER)); - } - - /** - * Sets the ICMP sequence number for the current ICMP object instance - * @param short - seqNumber - * @return ICMP - */ - public ICMP setSequenceNumber(short seqNumber) { - byte[] icmpSeqNumber = BitBufferHelper.toByteArray(seqNumber); - fieldValues.put(SEQNUMBER, icmpSeqNumber); - return this; - } - - /** - * Gets the ICMP sequence number of the current ICMP object instance - * - * @return short - seqNumber - */ - - public short getSequenceNumber() { - return BitBufferHelper.getShort(fieldValues.get(SEQNUMBER)); - } - - /** - * Gets the header size in bits - * @return The ICMP header size in bits - */ - @Override - public int getHeaderSize() { - return 64; - } - - /** - * Computes the ICMP checksum on the serialized ICMP message - * - * @param serialized - * The data stream - * @param start - * The byte index on the data stream from which the ICMP packet - * starts - * @return The checksum - */ - short computeChecksum(byte[] data, int start) { - int sum = 0, carry = 0, finalSum = 0; - int wordData; - int end = start + this.getHeaderSize() / NetUtils.NumBitsInAByte; - if (rawPayload != null) { - end += rawPayload.length; - } - int checksumStartByte = start + getfieldOffset(CHECKSUM) / NetUtils.NumBitsInAByte; - int even = end & ~1; - - for (int i = start; i < even; i = i + 2) { - // Skip, if the current bytes are checkSum bytes - if (i == checksumStartByte) { - continue; - } - wordData = ((data[i] << 8) & 0xFF00) + (data[i + 1] & 0xFF); - sum = sum + wordData; - } - if (even < end) { - // Add the last octet with zero padding. - wordData = (data[even] << 8) & 0xFF00; - sum = sum + wordData; - } - - carry = sum >>> 16; - finalSum = (sum & 0xFFFF) + carry; - return (short) ~((short) finalSum & 0xFFFF); - } - - @Override - protected void postSerializeCustomOperation(byte[] serializedBytes) - throws PacketException { - byte[] checkSum = BitBufferHelper - .toByteArray(computeChecksum(serializedBytes, 0)); - try { - BitBufferHelper.setBytes(serializedBytes, checkSum, - getfieldOffset(CHECKSUM), getfieldnumBits(CHECKSUM)); - } catch (BufferException e) { - throw new PacketException(e.getMessage()); - } - } - - @Override - protected void postDeserializeCustomOperation(byte[] data, int endBitOffset) { - short computedChecksum = computeChecksum(data, endBitOffset / NetUtils.NumBitsInAByte); - short actualChecksum = BitBufferHelper.getShort(fieldValues.get(CHECKSUM)); - - if (computedChecksum != actualChecksum) { - corrupted = true; - } - } - - /** - * Gets the checksum value stored - * @return the checksum - */ - public short getChecksum() { - return (BitBufferHelper.getShort(fieldValues.get(CHECKSUM))); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IDataPacketService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IDataPacketService.java deleted file mode 100644 index 41937b2537..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IDataPacketService.java +++ /dev/null @@ -1,50 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IDataPacketService.java - * - * @brief SAL exported Data Packet services - * - * Data Packet Services SAL provides to the components - */ -package org.opendaylight.controller.sal.packet; - -/** - * Data Packet Services SAL provides to the components - */ -@Deprecated -public interface IDataPacketService { - /** - * Transmit a data Packet. Transmission will ONLY happen if the - * RawPacket has the OutgoingNodeConnector set else of course - * transmission cannot happen. - * - * @param outPkt Packet to be transmitted out - */ - void transmitDataPacket(RawPacket outPkt); - - /** - * Decode a Data Packet received as a raw stream - * - * @param pkt Raw Packet to be decoded - * - * @return The formatted Data Packet - */ - Packet decodeDataPacket(RawPacket pkt); - - /** - * Encode a Formatted Data Packet in a raw bytestream - * - * @param pkt Formatted Data Packet to be encoded - * - * @return a RawPacket representation, good for transmission purpose - */ - RawPacket encodeDataPacket(Packet pkt); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java deleted file mode 100644 index 196d87f3cd..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; - -/** - * Class that represents the IEEE 802.1Q objects - */ -@Deprecated -public class IEEE8021Q extends Packet { - private static final String PCP = "PriorityCodePoint"; - private static final String CFI = "CanonicalFormatIndicator"; - private static final String VID = "VlanIdentifier"; - private static final String ETHT = "EtherType"; - - private static Map> fieldCoordinates = new LinkedHashMap>() { - private static final long serialVersionUID = 1L; - { - put(PCP, new ImmutablePair(0, 3)); - put(CFI, new ImmutablePair(3, 1)); - put(VID, new ImmutablePair(4, 12)); - put(ETHT, new ImmutablePair(16, 16)); - } - }; - private final Map fieldValues; - - /** - * Default constructor that creates and sets the HashMap - */ - public IEEE8021Q() { - super(); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - } - - /** - * Constructor that sets the access level for the packet and creates and - * sets the HashMap - */ - public IEEE8021Q(boolean writeAccess) { - super(writeAccess); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - } - - @Override - /** - * Store the value read from data stream in hdrFieldMap - */ - public void setHeaderField(String headerField, byte[] readValue) { - if (headerField.equals(ETHT)) { - payloadClass = Ethernet.etherTypeClassMap.get(BitBufferHelper.getShort(readValue)); - } - hdrFieldsMap.put(headerField, readValue); - } - - /** - * Gets the priority code point(PCP) stored - * - * @return byte - the PCP - */ - public byte getPcp() { - return BitBufferHelper.getByte(fieldValues.get(PCP)); - } - - /** - * Gets the canonical format indicator(CFI) stored - * - * @return byte - the CFI - */ - public byte getCfi() { - return BitBufferHelper.getByte(fieldValues.get(CFI)); - } - - /** - * Gets the VLAN identifier(VID) stored - * - * @return short - the VID - */ - public short getVid() { - return BitBufferHelper.getShort(fieldValues.get(VID)); - } - - /** - * Gets the etherType stored - * - * @return short - the etherType - */ - public short getEtherType() { - return BitBufferHelper.getShort(fieldValues.get(ETHT)); - } - - /** - * Sets the priority code point(PCP) for the current IEEE 802.1Q object - * instance - * - * @param byte - the PCP to set - */ - public IEEE8021Q setPcp(byte pcp) { - byte[] priorityCodePoint = BitBufferHelper.toByteArray(pcp); - fieldValues.put(PCP, priorityCodePoint); - return this; - } - - /** - * Sets the canonical format indicator(CFI) for the current IEEE 802.1Q - * object instance - * - * @param byte - the CFI to set - */ - public IEEE8021Q setCfi(byte cfi) { - byte[] canonicalFormatIndicator = BitBufferHelper.toByteArray(cfi); - fieldValues.put(CFI, canonicalFormatIndicator); - return this; - } - - /** - * Sets the VLAN identifier(VID) for the current IEEE 802.1Q instance - * - * @param short - the VID to set - */ - public IEEE8021Q setVid(short vid) { - byte[] vlanIdentifier = BitBufferHelper.toByteArray(vid); - fieldValues.put(VID, vlanIdentifier); - return this; - } - - /** - * Sets the etherType for the current IEEE 802.1Q object instance - * - * @param short - the etherType to set - */ - public IEEE8021Q setEtherType(short etherType) { - byte[] ethType = BitBufferHelper.toByteArray(etherType); - fieldValues.put(ETHT, ethType); - return this; - } - - @Override - public void populateMatch(Match match) { - match.setField(MatchType.DL_VLAN, this.getVid()); - match.setField(MatchType.DL_VLAN_PR, this.getPcp()); - match.setField(MatchType.DL_TYPE, this.getEtherType()); - } - - /** - * Gets the header size in bits - * @return The .1Q header size in bits - */ - @Override - public int getHeaderSize() { - return 32; - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IListenDataPacket.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IListenDataPacket.java deleted file mode 100644 index a64de5b97a..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IListenDataPacket.java +++ /dev/null @@ -1,71 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IListenDataPacket.java - * - * @brief Interface a component will need to implement and export as - * implemented interface in order to get data packet - * - * Interface a component will need to implement and export as - * implemented interface in order to get data packet - */ - -package org.opendaylight.controller.sal.packet; - -/** - * Interface that all the components that want to receive a dataPacket - * need to implement. The interface by itself doesn't specify any - * filtering or sequencing mechanism, but the model supported by Data - * Packet Service is such that the packets can be processed in two - * ways: - * - Serial: When a Data Packet Listener gets a packet after another, - * this case is necessary when the subsequent handler needs some extra - * information that can only be provided by another Data Packet - * Service Handler. If the dependent service is missing, then the one - * with dependencies will not be invoked. In a serial - * processing, a plugin has the the power to prevent the packet to be - * seen but other in the chain, if the return result is CONSUMED, else - * the packet will go through all the elements in the chain. - * - Parallel: When a Data Packet Listener doesn't express any - * dependency then it will get a copy of the packet as anybody - * else. Practical example, let say we have 2 handlers, both didn't - * express any dependency then both will get a copy of any incoming - * packet and they cannot step over each other feet. - * The Processing model is choosen by the properties with which the - * service is registered in the OSGi service registry. - * The properties that will be looked at are: - * salListenerName: Unique identifier of the SAL Data Packet - * Listener - * salListenerDependency: A String containing the - * salListenerName that consitute a dependency for this Listener, for - * now ONLY a SINGLE dependency is supported - * salListenerFilter: A Match class to be used to match a DataPacket, - * processing either parallel or serial will ONLY continue if the - * incoming DataPacket match the filter. If no filter is provided, the - * handler is called for EVERY packet i.e. match All is implied! - */ -@Deprecated -public interface IListenDataPacket { - /** - * Handler for receiving the packet. The application can signal - * back to SAL if the packet has been consumed or no. In case of - * packet consumed SAL will prevent to keep passing to subsequent - * listener in the serial chain, but for handlers without - * dependency things will keep going . - * The packet will received will have the IncomingNodeConnector - * set to understand where the packet is coming from - * - * @param inPkt Packet received - * - * @return An indication if the packet should still be processed - * or we should stop it. - */ - PacketResult receiveDataPacket(RawPacket inPkt); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginInDataPacketService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginInDataPacketService.java deleted file mode 100644 index 863ed68cc9..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginInDataPacketService.java +++ /dev/null @@ -1,36 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IPluginInDataPacketService.java - * - * @brief Data Packet Services exported by SouthBound plugins for SAL usage - * - * Data Packet Services exported by SouthBound plugins for SAL usage - */ -package org.opendaylight.controller.sal.packet; - -/** - * Data Packet Services exported by SouthBound plugins for SAL usage. - * The service will be used by SAL such that for every Protocol Plugin - * there is only one expected, for this reason the service need to be - * registered in the OSGi service registry along with the property: - * - "protocoloPluginType" - * the value of the property will org.opendaylight.controller.sal.core.Node.NodeIDType - */ -@Deprecated -public interface IPluginInDataPacketService { - /** - * Transmit a data Packet. Packet will go out ONLY if the packet - * has property OutgoingNodeConnector set. - * - * @param outPkt Packet to be transmitted out - */ - void transmitDataPacket(RawPacket outPkt); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginOutDataPacketService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginOutDataPacketService.java deleted file mode 100644 index d8852feed6..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPluginOutDataPacketService.java +++ /dev/null @@ -1,43 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file IPluginOutDataPacketService.java - * - * @brief Interface SAL will need to register in order to get some - * packets from the southbound protocol plugins - * - * Interface SAL will need to register in order to get some - * packets from the southbound protocol plugins - */ - -package org.opendaylight.controller.sal.packet; - -/** - * Interface used by SAL to intercept any Data Packet coming from the - * southbound protocol plugins - */ -@Deprecated -public interface IPluginOutDataPacketService { - /** - * Handler for receiving the packet. The SAL layer can signal back - * to the southbound plugin if the packet has been consumed or can - * go for further processing. Usually after SAL processing - * probably there is no other processing to be done, but just in - * case there is chain the return code can be used. - * The protocol plugin is supposed to deliver a packet with the - * IncomingNodeConnector set - * - * @param inPkt Packet received - * - * @return An indication if the packet should still be processed - * or we should stop it. - */ - PacketResult receiveDataPacket(RawPacket inPkt); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java deleted file mode 100644 index 148f3512e8..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java +++ /dev/null @@ -1,600 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * - */ -package org.opendaylight.controller.sal.packet; - -import java.net.InetAddress; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Random; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class that represents the IPv4 packet objects - */ -@Deprecated -public class IPv4 extends Packet { - protected static final Logger logger = LoggerFactory - .getLogger(IPv4.class); - private static final String VERSION = "Version"; - private static final String HEADERLENGTH = "HeaderLength"; - private static final String DIFFSERV = "DiffServ"; - private static final String ECN = "ECN"; - private static final String TOTLENGTH = "TotalLength"; - private static final String IDENTIFICATION = "Identification"; - private static final String FLAGS = "Flags"; - private static final String FRAGOFFSET = "FragmentOffset"; - private static final String TTL = "TTL"; - private static final String PROTOCOL = "Protocol"; - private static final String CHECKSUM = "Checksum"; - private static final String SIP = "SourceIPAddress"; - private static final String DIP = "DestinationIPAddress"; - private static final String OPTIONS = "Options"; - - private static final int UNIT_SIZE_SHIFT = 2; - private static final int UNIT_SIZE = (1 << UNIT_SIZE_SHIFT); - private static final int MIN_HEADER_SIZE = 20; - - public static final Map> protocolClassMap; - static { - protocolClassMap = new HashMap>(); - protocolClassMap.put(IPProtocols.ICMP.byteValue(), ICMP.class); - protocolClassMap.put(IPProtocols.UDP.byteValue(), UDP.class); - protocolClassMap.put(IPProtocols.TCP.byteValue(), TCP.class); - } - private static Map> fieldCoordinates = new LinkedHashMap>() { - private static final long serialVersionUID = 1L; - { - put(VERSION, new ImmutablePair(0, 4)); - put(HEADERLENGTH, new ImmutablePair(4, 4)); - put(DIFFSERV, new ImmutablePair(8, 6)); - put(ECN, new ImmutablePair(14, 2)); - put(TOTLENGTH, new ImmutablePair(16, 16)); - put(IDENTIFICATION, new ImmutablePair(32, 16)); - put(FLAGS, new ImmutablePair(48, 3)); - put(FRAGOFFSET, new ImmutablePair(51, 13)); - put(TTL, new ImmutablePair(64, 8)); - put(PROTOCOL, new ImmutablePair(72, 8)); - put(CHECKSUM, new ImmutablePair(80, 16)); - put(SIP, new ImmutablePair(96, 32)); - put(DIP, new ImmutablePair(128, 32)); - put(OPTIONS, new ImmutablePair(160, 0)); - } - }; - - private final Map fieldValues; - - - /** - * Default constructor that sets the version to 4, headerLength to 5, - * and flags to 2. The default value for the identification is set to a - * random number and the remaining fields are set to 0. - */ - public IPv4() { - super(); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - corrupted = false; - - setVersion((byte) 4); - setHeaderLength((byte) 5); - setDiffServ((byte) 0); - setECN((byte) 0); - setIdentification(generateId()); - setFlags((byte) 2); - setFragmentOffset((short) 0); - } - - /** - * The write access to the packet is set in this constructor. - * Constructor that sets the version to 4, headerLength to 5, - * and flags to 2. The default value for the identification is set to a - * random number and the remaining fields are set to 0. - * @param boolean - */ - public IPv4(boolean writeAccess) { - super(writeAccess); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - corrupted = false; - - setVersion((byte) 4); - setHeaderLength((byte) 5); - setDiffServ((byte) 0); - setECN((byte) 0); - setIdentification(generateId()); - setFlags((byte) 2); - setFragmentOffset((short) 0); - } - - /** - * Gets the IP version stored - * @return the version - */ - public byte getVersion() { - return (BitBufferHelper.getByte(fieldValues.get(VERSION))); - } - - /** - * Gets the IP header length stored - * @return the headerLength in bytes - */ - public int getHeaderLen() { - return (4 * BitBufferHelper.getByte(fieldValues.get(HEADERLENGTH))); - } - - /** - * Gets the header size in bits - * @return The number of bits constituting the header - */ - @Override - public int getHeaderSize() { - int headerLen = this.getHeaderLen(); - if (headerLen == 0) { - headerLen = MIN_HEADER_SIZE; - } - - return headerLen * NetUtils.NumBitsInAByte; - } - - /** - * Gets the differential services value stored - * @return the diffServ - */ - public byte getDiffServ() { - return BitBufferHelper.getByte(fieldValues.get(DIFFSERV)); - } - - /** - * Gets the ecn bits stored - * @return the ecn bits - */ - public byte getECN() { - return BitBufferHelper.getByte(fieldValues.get(ECN)); - } - - /** - * Gets the total length of the IP header in bytes - * @return the totalLength - */ - public short getTotalLength() { - return (BitBufferHelper.getShort(fieldValues.get(TOTLENGTH))); - } - - /** - * Gets the identification value stored - * @return the identification - */ - public short getIdentification() { - return (BitBufferHelper.getShort(fieldValues.get(IDENTIFICATION))); - } - - /** - * Gets the flag values stored - * @return the flags - */ - public byte getFlags() { - return (BitBufferHelper.getByte(fieldValues.get(FLAGS))); - } - - /** - * Gets the TTL value stored - * @return the ttl - */ - public byte getTtl() { - return (BitBufferHelper.getByte(fieldValues.get(TTL))); - } - - /** - * Gets the protocol value stored - * @return the protocol - */ - public byte getProtocol() { - return (BitBufferHelper.getByte(fieldValues.get(PROTOCOL))); - } - - /** - * Gets the checksum value stored - * @return the checksum - */ - public short getChecksum() { - return (BitBufferHelper.getShort(fieldValues.get(CHECKSUM))); - } - - /** - * Gets the fragment offset stored - * @return the fragmentOffset - */ - public short getFragmentOffset() { - return (BitBufferHelper.getShort(fieldValues.get(FRAGOFFSET))); - } - - /** - * Gets the source IP address stored - * @return the sourceAddress - */ - public int getSourceAddress() { - return (BitBufferHelper.getInt(fieldValues.get(SIP))); - } - - /** - * Gets the destination IP address stored - * @return the destinationAddress - */ - public int getDestinationAddress() { - return (BitBufferHelper.getInt(fieldValues.get(DIP))); - } - - /** - * gets the Options stored - * @return the options - */ - public byte[] getOptions() { - return (fieldValues.get(OPTIONS)); - } - - @Override - /** - * Stores the value of fields read from data stream - * Variable header value like payload protocol, is stored here - */ - public void setHeaderField(String headerField, byte[] readValue) { - if (headerField.equals(PROTOCOL)) { - // Don't set payloadClass if framgment offset is not zero. - byte[] fragoff = hdrFieldsMap.get(FRAGOFFSET); - if (fragoff == null || BitBufferHelper.getShort(fragoff) == 0) { - payloadClass = protocolClassMap.get(readValue[0]); - } - } else if (headerField.equals(FRAGOFFSET)) { - if (readValue != null && BitBufferHelper.getShort(readValue) != 0) { - // Clear payloadClass because protocol header is not present - // in this packet. - payloadClass = null; - } - } else if (headerField.equals(OPTIONS) && - (readValue == null || readValue.length == 0)) { - hdrFieldsMap.remove(headerField); - return; - } - hdrFieldsMap.put(headerField, readValue); - } - - /** - * Stores the IP version from the header - * @param version the version to set - * @return @IPv4 - */ - public IPv4 setVersion(byte ipVersion) { - byte[] version = BitBufferHelper.toByteArray(ipVersion); - fieldValues.put(VERSION, version); - return this; - } - - /** - * Stores the length of IP header in words (4 bytes) - * @param headerLength the headerLength to set - * @return IPv4 - */ - public IPv4 setHeaderLength(byte ipheaderLength) { - byte[] headerLength = BitBufferHelper.toByteArray(ipheaderLength); - fieldValues.put(HEADERLENGTH, headerLength); - return this; - } - - /** - * Stores the differential services value from the IP header - * @param diffServ the diffServ to set - * @return IPv4 - */ - public IPv4 setDiffServ(byte ipdiffServ) { - byte[] diffServ = BitBufferHelper.toByteArray(ipdiffServ); - fieldValues.put(DIFFSERV, diffServ); - return this; - } - - /** - * Stores the ECN bits from the header - * @param ECN bits to set - * @return IPv4 - */ - public IPv4 setECN(byte ecn) { - byte[] ecnbytes = BitBufferHelper.toByteArray(ecn); - fieldValues.put(ECN, ecnbytes); - return this; - } - - /** - * Stores the total length of IP header in bytes - * @param totalLength the totalLength to set - * @return IPv4 - */ - public IPv4 setTotalLength(short iptotalLength) { - byte[] totalLength = BitBufferHelper.toByteArray(iptotalLength); - fieldValues.put(TOTLENGTH, totalLength); - return this; - } - - /** - * Stores the identification number from the header - * @param identification the identification to set - * @return IPv4 - */ - public IPv4 setIdentification(short ipIdentification) { - byte[] identification = BitBufferHelper.toByteArray(ipIdentification); - fieldValues.put(IDENTIFICATION, identification); - return this; - } - - /** - * Stores the IP flags value - * @param flags the flags to set - * @return IPv4 - */ - public IPv4 setFlags(byte ipFlags) { - byte[] flags = { ipFlags }; - fieldValues.put(FLAGS, flags); - return this; - } - - /** - * Stores the IP fragmentation offset value - * @param fragmentOffset the fragmentOffset to set - * @return IPv4 - */ - public IPv4 setFragmentOffset(short ipFragmentOffset) { - byte[] fragmentOffset = BitBufferHelper.toByteArray(ipFragmentOffset); - fieldValues.put(FRAGOFFSET, fragmentOffset); - return this; - } - - /** - * Stores the TTL value - * @param ttl the ttl to set - * @return IPv4 - */ - public IPv4 setTtl(byte ipTtl) { - byte[] ttl = BitBufferHelper.toByteArray(ipTtl); - fieldValues.put(TTL, ttl); - return this; - } - - /** - * Stores the protocol value of the IP payload - * @param protocol the protocol to set - * @return IPv4 - */ - public IPv4 setProtocol(byte ipProtocol) { - byte[] protocol = BitBufferHelper.toByteArray(ipProtocol); - fieldValues.put(PROTOCOL, protocol); - return this; - } - - /** - * @param checksum the checksum to set - */ - /*public IPv4 setChecksum() { - short ipChecksum = computeChecksum(); - byte[] checksum = BitBufferHelper.toByteArray(ipChecksum); - fieldValues.put(CHECKSUM, checksum); - return this; - }*/ - - /** - * Stores the IP source address from the header - * @param sourceAddress the sourceAddress to set - * @return IPv4 - */ - public IPv4 setSourceAddress(InetAddress ipSourceAddress) { - byte[] sourceAddress = ipSourceAddress.getAddress(); - fieldValues.put(SIP, sourceAddress); - return this; - } - - /** - * Stores the IP destination address from the header - * @param the destination Address to set - * @return IPv4 - */ - public IPv4 setDestinationAddress(InetAddress ipDestinationAddress) { - byte[] sourceAddress = ipDestinationAddress.getAddress(); - fieldValues.put(DIP, sourceAddress); - return this; - } - - /** - * Stores the IP destination address from the header - * @param destinationAddress the destinationAddress to set - * @return IPv4 - */ - public IPv4 setDestinationAddress(int ipDestinationAddress) { - byte[] destinationAddress = BitBufferHelper - .toByteArray(ipDestinationAddress); - fieldValues.put(DIP, destinationAddress); - return this; - } - - /** - * Generate a random number to set the Identification field - * in IPv4 Header - * @return short - */ - private short generateId() { - Random randomgen = new Random(); - return (short) (randomgen.nextInt(Short.MAX_VALUE + 1)); - } - - /** - * Store the options from IP header - * @param options - byte[] - * @return IPv4 - */ - public IPv4 setOptions(byte[] options) { - byte newIHL = (byte)(MIN_HEADER_SIZE >>> UNIT_SIZE_SHIFT); - if (options == null || options.length == 0) { - fieldValues.remove(OPTIONS); - } else { - int len = options.length; - int rlen = (len + (UNIT_SIZE - 1)) & ~(UNIT_SIZE - 1); - if (rlen > len) { - // Padding is required. - byte[] newopt = new byte[rlen]; - System.arraycopy(options, 0, newopt, 0, len); - options = newopt; - len = rlen; - } - fieldValues.put(OPTIONS, options); - newIHL += (len >>> UNIT_SIZE_SHIFT); - } - - setHeaderLength(newIHL); - - return this; - } - - /** - * Computes the IPv4 header checksum on the passed stream of bytes - * representing the packet - * - * @param data - * The byte stream - * @param offset - * The byte offset from where the IPv4 packet starts - * @return The computed checksum - */ - short computeChecksum(byte[] data, int start) { - int end = start + getHeaderLen(); - short checkSum = (short) 0; - int sum = 0, carry = 0, finalSum = 0; - int wordData; - int checksumStart = start - + (getfieldOffset(CHECKSUM) / NetUtils.NumBitsInAByte); - - for (int i = start; i <= (end - 1); i = i + 2) { - // Skip, if the current bytes are checkSum bytes - if (i == checksumStart) { - continue; - } - wordData = ((data[i] << 8) & 0xFF00) + (data[i + 1] & 0xFF); - sum = sum + wordData; - } - carry = (sum >> 16) & 0xFF; - finalSum = (sum & 0xFFFF) + carry; - checkSum = (short) ~((short) finalSum & 0xFFFF); - - return checkSum; - } - - @Override - /** - * Gets the number of bits for the fieldname specified - * If the fieldname has variable length like "Options", then this value is computed using the header length - * @param fieldname - String - * @return number of bits for fieldname - int - */ - public int getfieldnumBits(String fieldName) { - if (fieldName.equals(OPTIONS)) { - return (getHeaderLen() - MIN_HEADER_SIZE) * NetUtils.NumBitsInAByte; - } - return hdrFieldCoordMap.get(fieldName).getRight(); - } - - @Override - /** - * Method to perform post serialization - like computation of checksum of serialized header - * @param data - * @return void - * @Exception throws PacketException - */ - protected void postSerializeCustomOperation(byte[] data) - throws PacketException { - - // Recompute the total length field here - byte[] totalLength = BitBufferHelper.toByteArray((short) data.length); - try { - BitBufferHelper.setBytes(data, totalLength, getfieldOffset(TOTLENGTH), - getfieldnumBits(TOTLENGTH)); - } catch (BufferException e) { - throw new PacketException(e.getMessage()); - } - - // Now compute the Header Checksum - byte[] checkSum = BitBufferHelper.toByteArray(computeChecksum(data, 0)); - - try { - BitBufferHelper.setBytes(data, checkSum, getfieldOffset(CHECKSUM), - getfieldnumBits(CHECKSUM)); - } catch (BufferException e) { - throw new PacketException(e.getMessage()); - } - } - - @Override - /** - * Stores the payload of IP, serializes it and stores the length of serialized payload - * bytes in Total Length - * @param payload - Packet - */ - /** - * Set the total length field in the IPv4 Object - * Note: this field will get overwritten during serialization phase. - */ - public void setPayload(Packet payload) { - this.payload = payload; - /* - * Deriving the Total Length here - */ - int payloadLength = 0; - if (payload != null) { - try { - payloadLength = payload.serialize().length; - } catch (PacketException e) { - logger.error("", e); - } - } - - this.setTotalLength((short) (this.getHeaderLen() + payloadLength)); - } - - - /** - * Method to perform post deserialization - like compare computed checksum with - * the one obtained from IP header - */ - @Override - protected void postDeserializeCustomOperation(byte[] data, int startBitOffset) { - int start = startBitOffset / NetUtils.NumBitsInAByte; - short computedChecksum = computeChecksum(data, start); - short actualChecksum = BitBufferHelper.getShort(fieldValues.get(CHECKSUM)); - if (computedChecksum != actualChecksum) { - corrupted = true; - } - } - - @Override - public void populateMatch(Match match) { - match.setField(MatchType.NW_SRC, NetUtils.getInetAddress(this.getSourceAddress())); - match.setField(MatchType.NW_DST, NetUtils.getInetAddress(this.getDestinationAddress())); - match.setField(MatchType.NW_PROTO, this.getProtocol()); - match.setField(MatchType.NW_TOS, this.getDiffServ()); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java deleted file mode 100644 index 1f20e85556..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; - -/** - * Class that represents the LLDP frame objects - */ -@Deprecated -public class LLDP extends Packet { - private static final String CHASSISID = "ChassisId"; - private static final String SYSTEMNAMEID = "SystemNameID"; - private static final String PORTID = "PortId"; - private static final String TTL = "TTL"; - private static final int LLDPDefaultTlvs = 4; - private static LLDPTLV emptyTLV = new LLDPTLV().setLength((short) 0) - .setType((byte) 0); - public static final byte[] LLDPMulticastMac = { 1, (byte) 0x80, - (byte) 0xc2, 0, 0, (byte) 0xe }; - private Map tlvList; - - /** - * Default constructor that creates the tlvList LinkedHashMap - */ - public LLDP() { - super(); - tlvList = new LinkedHashMap(LLDPDefaultTlvs); - } - - /** - * Constructor that creates the tlvList LinkedHashMap and sets the write - * access for the same - */ - public LLDP(boolean writeAccess) { - super(writeAccess); - tlvList = new LinkedHashMap(LLDPDefaultTlvs); // Mandatory - // TLVs - } - - /** - * @param String - * - description of the type of TLV - * @return byte - type of TLV - */ - private byte getType(String typeDesc) { - if (typeDesc.equals(CHASSISID)) { - return LLDPTLV.TLVType.ChassisID.getValue(); - } else if (typeDesc.equals(PORTID)) { - return LLDPTLV.TLVType.PortID.getValue(); - } else if (typeDesc.equals(TTL)) { - return LLDPTLV.TLVType.TTL.getValue(); - } else { - return LLDPTLV.TLVType.Unknown.getValue(); - } - } - - /** - * @param String - * - description of the type of TLV - * @return LLDPTLV - full TLV - */ - public LLDPTLV getTLV(String type) { - return tlvList.get(getType(type)); - } - - /** - * @param String - * - description of the type of TLV - * @param LLDPTLV - * - tlv to set - * @return void - */ - public void setTLV(String type, LLDPTLV tlv) { - tlvList.put(getType(type), tlv); - } - - /** - * @return the chassisId TLV - */ - public LLDPTLV getChassisId() { - return getTLV(CHASSISID); - } - - /** - * @param LLDPTLV - * - the chassisId to set - */ - public LLDP setChassisId(LLDPTLV chassisId) { - tlvList.put(getType(CHASSISID), chassisId); - return this; - } - - /** - * @return the SystemName TLV - */ - public LLDPTLV getSystemNameId() { - return getTLV(SYSTEMNAMEID); - } - - /** - * @param LLDPTLV - * - the chassisId to set - */ - public LLDP setSystemNameId(LLDPTLV systemNameId) { - tlvList.put(getType(SYSTEMNAMEID), systemNameId); - return this; - } - - /** - * @return LLDPTLV - the portId TLV - */ - public LLDPTLV getPortId() { - return tlvList.get(getType(PORTID)); - } - - /** - * @param LLDPTLV - * - the portId to set - * @return LLDP - */ - public LLDP setPortId(LLDPTLV portId) { - tlvList.put(getType(PORTID), portId); - return this; - } - - /** - * @return LLDPTLV - the ttl TLV - */ - public LLDPTLV getTtl() { - return tlvList.get(getType(TTL)); - } - - /** - * @param LLDPTLV - * - the ttl to set - * @return LLDP - */ - public LLDP setTtl(LLDPTLV ttl) { - tlvList.put(getType(TTL), ttl); - return this; - } - - /** - * @return the optionalTLVList - */ - public List getOptionalTLVList() { - List list = new ArrayList(); - for (Map.Entry entry : tlvList.entrySet()) { - byte type = entry.getKey(); - if ((type == LLDPTLV.TLVType.ChassisID.getValue()) - || (type == LLDPTLV.TLVType.PortID.getValue()) - || (type == LLDPTLV.TLVType.TTL.getValue())) { - continue; - } else { - list.add(entry.getValue()); - } - } - return list; - } - - /** - * @param optionalTLVList - * the optionalTLVList to set - * @return LLDP - */ - public LLDP setOptionalTLVList(List optionalTLVList) { - for (LLDPTLV tlv : optionalTLVList) { - tlvList.put(tlv.getType(), tlv); - } - return this; - } - - @Override - public Packet deserialize(byte[] data, int bitOffset, int size) - throws PacketException { - int lldpOffset = bitOffset; // LLDP start - int lldpSize = size; // LLDP size - - if (logger.isTraceEnabled()) { - logger.trace("LLDP: {} (offset {} bitsize {})", new Object[] { - HexEncode.bytesToHexString(data), lldpOffset, lldpSize }); - } - /* - * Deserialize the TLVs until we reach the end of the packet - */ - while (lldpSize > 0) { - LLDPTLV tlv = new LLDPTLV(); - tlv.deserialize(data, lldpOffset, lldpSize); - if (tlv.getType() == 0 && tlv.getLength() == 0) { - break; - } - int tlvSize = tlv.getTLVSize(); // Size of current TLV in bits - lldpOffset += tlvSize; - lldpSize -= tlvSize; - this.tlvList.put(tlv.getType(), tlv); - } - return this; - } - - @Override - public byte[] serialize() throws PacketException { - int startOffset = 0; - byte[] serializedBytes = new byte[getLLDPPacketLength()]; - - for (Map.Entry entry : tlvList.entrySet()) { - LLDPTLV tlv = entry.getValue(); - int numBits = tlv.getTLVSize(); - try { - BitBufferHelper.setBytes(serializedBytes, tlv.serialize(), - startOffset, numBits); - } catch (BufferException e) { - throw new PacketException(e.getMessage()); - } - startOffset += numBits; - } - // Now add the empty LLDPTLV at the end - try { - BitBufferHelper.setBytes(serializedBytes, - LLDP.emptyTLV.serialize(), startOffset, - LLDP.emptyTLV.getTLVSize()); - } catch (BufferException e) { - throw new PacketException(e.getMessage()); - } - - if (logger.isTraceEnabled()) { - logger.trace("LLDP: serialized: {}", - HexEncode.bytesToHexString(serializedBytes)); - } - return serializedBytes; - } - - /** - * Returns the size of LLDP packet in bytes - * - * @return int - LLDP Packet size in bytes - */ - private int getLLDPPacketLength() { - int len = 0; - LLDPTLV tlv; - - for (Map.Entry entry : this.tlvList.entrySet()) { - tlv = entry.getValue(); - len += tlv.getTLVSize(); - } - len += LLDP.emptyTLV.getTLVSize(); - - return len / NetUtils.NumBitsInAByte; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java deleted file mode 100644 index f03704caba..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.commons.lang3.tuple.MutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; - -/** - * Class that represents the LLDPTLV objects - */ -@Deprecated -public class LLDPTLV extends Packet { - private static final String TYPE = "Type"; - private static final String LENGTH = "Length"; - private static final String VALUE = "Value"; - private static final int LLDPTLVFields = 3; - public static final byte[] OFOUI = new byte[] { (byte) 0x00, (byte) 0x26, - (byte) 0xe1 }; // OpenFlow OUI - public static final byte[] customTlvSubType = new byte[] { 0 }; - public static final int customTlvOffset = OFOUI.length - + customTlvSubType.length; - public static final byte chassisIDSubType[] = new byte[] { 4 }; // MAC address for the system - public static final byte portIDSubType[] = new byte[] { 7 }; // locally assigned - - public enum TLVType { - Unknown((byte) 0), ChassisID((byte) 1), PortID((byte) 2), TTL((byte) 3), PortDesc( - (byte) 4), SystemName((byte) 5), SystemDesc((byte) 6), Custom( - (byte) 127); - - private byte value; - - private TLVType(byte value) { - this.value = value; - } - - public byte getValue() { - return value; - } - } - - private static Map> fieldCoordinates = new LinkedHashMap>() { - private static final long serialVersionUID = 1L; - - { - put(TYPE, new MutablePair(0, 7)); - put(LENGTH, new MutablePair(7, 9)); - put(VALUE, new MutablePair(16, 0)); - } - }; - - protected Map fieldValues; - - /** - * Default constructor that creates and sets the hash map values and sets - * the payload to null - */ - public LLDPTLV() { - payload = null; - fieldValues = new HashMap(LLDPTLVFields); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - } - - /** - * Constructor that writes the passed LLDPTLV values to the hdrFieldsMap - */ - public LLDPTLV(LLDPTLV other) { - for (Map.Entry entry : other.hdrFieldsMap.entrySet()) { - this.hdrFieldsMap.put(entry.getKey(), entry.getValue()); - } - } - - /** - * @return int - the length of TLV - */ - public int getLength() { - return (int) BitBufferHelper.toNumber(fieldValues.get(LENGTH), - fieldCoordinates.get(LENGTH).getRight().intValue()); - } - - /** - * @return byte - the type of TLV - */ - public byte getType() { - return BitBufferHelper.getByte(fieldValues.get(TYPE)); - } - - /** - * @return byte[] - the value field of TLV - */ - public byte[] getValue() { - return fieldValues.get(VALUE); - } - - /** - * @param byte - the type to set - * @return LLDPTLV - */ - public LLDPTLV setType(byte type) { - byte[] lldpTLVtype = { type }; - fieldValues.put(TYPE, lldpTLVtype); - return this; - } - - /** - * @param short - the length to set - * @return LLDPTLV - */ - public LLDPTLV setLength(short length) { - fieldValues.put(LENGTH, BitBufferHelper.toByteArray(length)); - return this; - } - - /** - * @param byte[] - the value to set - * @return LLDPTLV - */ - public LLDPTLV setValue(byte[] value) { - fieldValues.put(VALUE, value); - return this; - } - - @Override - public void setHeaderField(String headerField, byte[] readValue) { - hdrFieldsMap.put(headerField, readValue); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result - + ((fieldValues == null) ? 0 : fieldValues.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - LLDPTLV other = (LLDPTLV) obj; - if (fieldValues == null) { - if (other.fieldValues != null) { - return false; - } - } else if (!fieldValues.equals(other.fieldValues)) { - return false; - } - return true; - } - - @Override - public int getfieldnumBits(String fieldName) { - if (fieldName.equals(VALUE)) { - return (NetUtils.NumBitsInAByte * BitBufferHelper.getShort( - fieldValues.get(LENGTH), fieldCoordinates.get(LENGTH) - .getRight().intValue())); - } - return fieldCoordinates.get(fieldName).getRight(); - } - - /** - * Returns the size in bits of the whole TLV - * - * @return int - size in bits of full TLV - */ - public int getTLVSize() { - return (LLDPTLV.fieldCoordinates.get(TYPE).getRight() + // static - LLDPTLV.fieldCoordinates.get(LENGTH).getRight() + // static - getfieldnumBits(VALUE)); // variable - } - - /** - * Creates the SystemName TLV value - * - * @param nodeId - * node identifier string - * @return the SystemName TLV value in byte array - */ - static public byte[] createSystemNameTLVValue(String nodeId) { - byte[] nid = nodeId.getBytes(); - return nid; - } - - /** - * Creates the ChassisID TLV value including the subtype and ChassisID - * string - * - * @param nodeId - * node identifier string - * @return the ChassisID TLV value in byte array - */ - static public byte[] createChassisIDTLVValue(String nodeId) { - byte[] nid = HexEncode.bytesFromHexString(nodeId); - byte[] cid = new byte[6]; - int srcPos = 0, dstPos = 0; - - if (nid.length > cid.length) { - srcPos = nid.length - cid.length; - } else { - dstPos = cid.length - nid.length; - } - System.arraycopy(nid, srcPos, cid, dstPos, cid.length); - - byte[] cidValue = new byte[cid.length + chassisIDSubType.length]; - - System.arraycopy(chassisIDSubType, 0, cidValue, 0, - chassisIDSubType.length); - System.arraycopy(cid, 0, cidValue, chassisIDSubType.length, cid.length); - - return cidValue; - } - - /** - * Creates the PortID TLV value including the subtype and PortID string - * - * @param portId - * port identifier string - * @return the PortID TLV value in byte array - */ - static public byte[] createPortIDTLVValue(String portId) { - byte[] pid = portId.getBytes(Charset.defaultCharset()); - byte[] pidValue = new byte[pid.length + portIDSubType.length]; - - System.arraycopy(portIDSubType, 0, pidValue, 0, portIDSubType.length); - System.arraycopy(pid, 0, pidValue, portIDSubType.length, pid.length); - - return pidValue; - } - - /** - * Creates the custom TLV value including OUI, subtype and custom string - * - * @param portId - * port identifier string - * @return the custom TLV value in byte array - */ - static public byte[] createCustomTLVValue(String customString) { - byte[] customArray = customString.getBytes(Charset.defaultCharset()); - byte[] customValue = new byte[customTlvOffset + customArray.length]; - - System.arraycopy(OFOUI, 0, customValue, 0, OFOUI.length); - System.arraycopy(customTlvSubType, 0, customValue, OFOUI.length, - customTlvSubType.length); - System.arraycopy(customArray, 0, customValue, customTlvOffset, - customArray.length); - - return customValue; - } - - /** - * Retrieves the string from TLV value and returns it in HexString format - * - * @param tlvValue - * the TLV value - * @param tlvLen - * the TLV length - * @return the HexString - */ - static public String getHexStringValue(byte[] tlvValue, int tlvLen) { - byte[] cidBytes = new byte[tlvLen - chassisIDSubType.length]; - System.arraycopy(tlvValue, chassisIDSubType.length, cidBytes, 0, - cidBytes.length); - return HexEncode.bytesToHexStringFormat(cidBytes); - } - - /** - * Retrieves the string from TLV value - * - * @param tlvValue - * the TLV value - * @param tlvLen - * the TLV length - * @return the string - */ - static public String getStringValue(byte[] tlvValue, int tlvLen) { - byte[] pidSubType = new byte[portIDSubType.length]; - byte[] pidBytes = new byte[tlvLen - portIDSubType.length]; - System.arraycopy(tlvValue, 0, pidSubType, 0, - pidSubType.length); - System.arraycopy(tlvValue, portIDSubType.length, pidBytes, 0, - pidBytes.length); - if (pidSubType[0] == (byte) 0x3) { - return HexEncode.bytesToHexStringFormat(pidBytes); - } else { - return (new String(pidBytes, Charset.defaultCharset())); - } - } - - /** - * Retrieves the custom string from the Custom TLV value which includes OUI, - * subtype and custom string - * - * @param customTlvValue - * the custom TLV value - * @param customTlvLen - * the custom TLV length - * @return the custom string - */ - static public String getCustomString(byte[] customTlvValue, int customTlvLen) { - String customString = ""; - byte[] vendor = new byte[3]; - System.arraycopy(customTlvValue, 0, vendor, 0, vendor.length); - if (Arrays.equals(vendor, LLDPTLV.OFOUI)) { - int customArrayLength = customTlvLen - customTlvOffset; - byte[] customArray = new byte[customArrayLength]; - System.arraycopy(customTlvValue, customTlvOffset, customArray, 0, - customArrayLength); - try { - customString = new String(customArray, "UTF-8"); - } catch (UnsupportedEncodingException e) { - } - } - - return customString; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LinkEncap.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LinkEncap.java deleted file mode 100644 index 3c75694666..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LinkEncap.java +++ /dev/null @@ -1,25 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file LinkEncap.java - * - * @brief Enum some datalink packet format understood - * - * Enum some datalink packet format understood - */ -package org.opendaylight.controller.sal.packet; - -/** - * Describe a packet data link format - */ -@Deprecated -public enum LinkEncap { - ETHERNET -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java deleted file mode 100644 index 45e3142e98..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java +++ /dev/null @@ -1,395 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.util.Arrays; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.commons.lang3.tuple.Pair; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Abstract class which represents the generic network packet object It provides - * the basic methods which are common for all the packets, like serialize and - * deserialize - */ -@Deprecated -public abstract class Packet { - protected static final Logger logger = LoggerFactory - .getLogger(Packet.class); - // Access level granted to this packet - protected boolean writeAccess; - // When deserialized from wire, packet could result corrupted - protected boolean corrupted; - // The packet that encapsulate this packet - protected Packet parent; - // The packet encapsulated by this packet - protected Packet payload; - // The unparsed raw payload carried by this packet - protected byte[] rawPayload; - // Bit coordinates of packet header fields - protected Map> hdrFieldCoordMap; - // Header fields values: Map - protected Map hdrFieldsMap; - // The class of the encapsulated packet object - protected Class payloadClass; - - public Packet() { - writeAccess = false; - corrupted = false; - } - - public Packet(boolean writeAccess) { - this.writeAccess = writeAccess; - corrupted = false; - } - - public Packet getParent() { - return parent; - } - - public Packet getPayload() { - return payload; - } - - public void setParent(Packet parent) { - this.parent = parent; - } - - public void setPayload(Packet payload) { - this.payload = payload; - } - - public void setHeaderField(String headerField, byte[] readValue) { - hdrFieldsMap.put(headerField, readValue); - } - - /** - * This method deserializes the data bits obtained from the wire into the - * respective header and payload which are of type Packet - * - * @param byte[] data - data from wire to deserialize - * @param int bitOffset bit position where packet header starts in data - * array - * @param int size of packet in bits - * @return Packet - * @throws PacketException - */ - public Packet deserialize(byte[] data, int bitOffset, int size) - throws PacketException { - - // Deserialize the header fields one by one - int startOffset = 0, numBits = 0; - for (Entry> pairs : hdrFieldCoordMap - .entrySet()) { - String hdrField = pairs.getKey(); - startOffset = bitOffset + this.getfieldOffset(hdrField); - numBits = this.getfieldnumBits(hdrField); - - byte[] hdrFieldBytes = null; - try { - hdrFieldBytes = BitBufferHelper.getBits(data, startOffset, - numBits); - } catch (BufferException e) { - throw new PacketException(e.getMessage()); - } - - /* - * Store the raw read value, checks the payload type and set the - * payloadClass accordingly - */ - this.setHeaderField(hdrField, hdrFieldBytes); - - if (logger.isTraceEnabled()) { - logger.trace("{}: {}: {} (offset {} bitsize {})", - new Object[] { this.getClass().getSimpleName(), hdrField, - HexEncode.bytesToHexString(hdrFieldBytes), - startOffset, numBits }); - } - } - - // Deserialize the payload now - int payloadStart = startOffset + numBits; - int payloadSize = data.length * NetUtils.NumBitsInAByte - payloadStart; - - if (payloadClass != null) { - try { - payload = payloadClass.newInstance(); - } catch (Exception e) { - throw new RuntimeException( - "Error parsing payload for Ethernet packet", e); - } - payload.deserialize(data, payloadStart, payloadSize); - payload.setParent(this); - } else { - /* - * The payload class was not set, it means no class for parsing - * this payload is present. Let's store the raw payload if any. - */ - int start = payloadStart / NetUtils.NumBitsInAByte; - int stop = start + payloadSize / NetUtils.NumBitsInAByte; - rawPayload = Arrays.copyOfRange(data, start, stop); - } - - - // Take care of computation that can be done only after deserialization - postDeserializeCustomOperation(data, payloadStart - getHeaderSize()); - - return this; - } - - /** - * This method serializes the header and payload from the respective - * packet class, into a single stream of bytes to be sent on the wire - * - * @return The byte array representing the serialized Packet - * @throws PacketException - */ - public byte[] serialize() throws PacketException { - - // Acquire or compute the serialized payload - byte[] payloadBytes = null; - if (payload != null) { - payloadBytes = payload.serialize(); - } else if (rawPayload != null) { - payloadBytes = rawPayload; - } - int payloadSize = (payloadBytes == null) ? 0 : payloadBytes.length; - - // Allocate the buffer to contain the full (header + payload) packet - int headerSize = this.getHeaderSize() / NetUtils.NumBitsInAByte; - byte packetBytes[] = new byte[headerSize + payloadSize]; - if (payloadBytes != null) { - System.arraycopy(payloadBytes, 0, packetBytes, headerSize, payloadSize); - } - - // Serialize this packet header, field by field - for (Map.Entry> pairs : hdrFieldCoordMap - .entrySet()) { - String field = pairs.getKey(); - byte[] fieldBytes = hdrFieldsMap.get(field); - // Let's skip optional fields when not set - if (fieldBytes != null) { - try { - BitBufferHelper.setBytes(packetBytes, fieldBytes, - getfieldOffset(field), getfieldnumBits(field)); - } catch (BufferException e) { - throw new PacketException(e.getMessage()); - } - } - } - - // Perform post serialize operations (like checksum computation) - postSerializeCustomOperation(packetBytes); - - if (logger.isTraceEnabled()) { - logger.trace("{}: {}", this.getClass().getSimpleName(), - HexEncode.bytesToHexString(packetBytes)); - } - - return packetBytes; - } - - /** - * This method gets called at the end of the serialization process It is - * intended for the child packets to insert some custom data into the output - * byte stream which cannot be done or cannot be done efficiently during the - * normal Packet.serialize() path. An example is the checksum computation - * for IPv4 - * - * @param byte[] - serialized bytes - * @throws PacketException - */ - protected void postSerializeCustomOperation(byte[] myBytes) - throws PacketException { - // no op - } - - /** - * This method re-computes the checksum of the bits received on the wire and - * validates it with the checksum in the bits received Since the computation - * of checksum varies based on the protocol, this method is overridden. - * Currently only IPv4 and ICMP do checksum computation and validation. TCP - * and UDP need to implement these if required. - * - * @param byte[] data The byte stream representing the Ethernet frame - * @param int startBitOffset The bit offset from where the byte array corresponding to this Packet starts in the frame - * @throws PacketException - */ - protected void postDeserializeCustomOperation(byte[] data, int startBitOffset) - throws PacketException { - // no op - } - - /** - * Gets the header length in bits - * - * @return int the header length in bits - */ - public int getHeaderSize() { - int size = 0; - /* - * We need to iterate over the fields that were read in the frame - * (hdrFieldsMap) not all the possible ones described in - * hdrFieldCoordMap. For ex, 802.1Q may or may not be there - */ - for (Map.Entry fieldEntry : hdrFieldsMap.entrySet()) { - if (fieldEntry.getValue() != null) { - String field = fieldEntry.getKey(); - size += getfieldnumBits(field); - } - } - return size; - } - - /** - * This method fetches the start bit offset for header field specified by - * 'fieldname'. The offset is present in the hdrFieldCoordMap of the - * respective packet class - * - * @param String - * fieldName - * @return Integer - startOffset of the requested field - */ - public int getfieldOffset(String fieldName) { - return hdrFieldCoordMap.get(fieldName).getLeft(); - } - - /** - * This method fetches the number of bits for header field specified by - * 'fieldname'. The numBits are present in the hdrFieldCoordMap of the - * respective packet class - * - * @param String - * fieldName - * @return Integer - number of bits of the requested field - */ - public int getfieldnumBits(String fieldName) { - return hdrFieldCoordMap.get(fieldName).getRight(); - } - - @Override - public String toString() { - StringBuilder ret = new StringBuilder(); - ret.append(this.getClass().getSimpleName()); - ret.append(": ["); - for (String field : hdrFieldCoordMap.keySet()) { - byte[] value = hdrFieldsMap.get(field); - ret.append(field); - ret.append(": "); - ret.append(HexEncode.bytesToHexString(value)); - ret.append(", "); - } - ret.replace(ret.length()-2, ret.length()-1, "]"); - return ret.toString(); - } - - /** - * Returns the raw payload carried by this packet in case payload was not - * parsed. Caller can call this function in case the getPaylod() returns null. - * - * @return The raw payload if not parsable as an array of bytes, null otherwise - */ - public byte[] getRawPayload() { - return rawPayload; - } - - /** - * Set a raw payload in the packet class - * - * @param payload The raw payload as byte array - */ - public void setRawPayload(byte[] payload) { - this.rawPayload = Arrays.copyOf(payload, payload.length); - } - - /** - * Return whether the deserialized packet is to be considered corrupted. - * This is the case when the checksum computed after reconstructing the - * packet received from wire is not equal to the checksum read from the - * stream. For the Packet class which do not have a checksum field, this - * function will always return false. - * - * - * @return true if the deserialized packet's recomputed checksum is not - * equal to the packet carried checksum - */ - public boolean isCorrupted() { - return corrupted; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result - + ((this.hdrFieldsMap == null) ? 0 : hdrFieldsMap.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (getClass() != obj.getClass()) { - return false; - } - Packet other = (Packet) obj; - if (hdrFieldsMap == other.hdrFieldsMap) { - return true; - } - if (hdrFieldsMap == null || other.hdrFieldsMap == null) { - return false; - } - if (hdrFieldsMap != null && other.hdrFieldsMap != null) { - for (String field : hdrFieldsMap.keySet()) { - if (!Arrays.equals(hdrFieldsMap.get(field), other.hdrFieldsMap.get(field))) { - return false; - } - } - } else { - return false; - } - return true; - } - - /** - * Adds to the passed Match this packet's header fields - * - * @param match - * The Match object to populate - */ - public void populateMatch(Match match) { - // To be overridden by derived packet classes which have well known - // header fields so that Packet.getMatch would return desired result - } - - /** - * Returns the Match object containing this packet and its payload - * encapsulated packets' header fields - * - * @return The Match containing the header fields of this packet and of its - * payload encapsulated packets - */ - public Match getMatch() { - Match match = new Match(); - Packet packet = this; - while (packet != null) { - packet.populateMatch(match); - packet = packet.getPayload(); - } - return match; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketException.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketException.java deleted file mode 100644 index 14e1bbb678..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketException.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.packet; - -/** - * Describes an exception that is raised when the process of serializing or - * deserializing a network packet/stream fails. This generally happens when the - * packet/stream is malformed. - * - */ -@Deprecated -public class PacketException extends Exception { - private static final long serialVersionUID = 1L; - - public PacketException(String message) { - super(message); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketResult.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketResult.java deleted file mode 100644 index 3583bd1f48..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/PacketResult.java +++ /dev/null @@ -1,41 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file PacketResult.java - * - * @brief Possible results for Data packet processing handler - */ -package org.opendaylight.controller.sal.packet; - -/** - * Possible results for Data packet processing handler - * - */ -@Deprecated -public enum PacketResult { - /** - * Packet has been processed and noone in the chain after us is - * supposed to see it - * - */ - CONSUME, - /** - * Packet has been processed and still further processing is - * possible - * - */ - KEEP_PROCESSING, - /** - * Packet has been ignored so further handler is present in - * the sequence need to still look at it. - * - */ - IGNORED -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/RawPacket.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/RawPacket.java deleted file mode 100644 index 2241774da5..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/RawPacket.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file RawPacket.java - * - * @brief Describe a raw Data Packet, this is how a packet is - * received from the network and how it will be transmitted. It - * essentially wraps the raw bytestream - * - */ -package org.opendaylight.controller.sal.packet; - -import java.util.Map; -import java.util.HashMap; - -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.TimeStamp; - -/** - * - * Describe a raw Data Packet, this is how a packet is received from the network - * and how it will be transmitted. It essentially wraps the raw bytestream - * - */ -@Deprecated -public class RawPacket { - private byte[] packetData; - private final LinkEncap encap; - private final TimeStamp incomingTime; - private final TimeStamp copyTime; - private Map props; - private NodeConnector incomingNodeConnector; - private NodeConnector outgoingNodeConnector; - - /** - * If the packet is being sent this parameter tells where the packet is sent - * toward - * - * - * @return the NodeConnector toward where the packet is being sent - */ - public NodeConnector getOutgoingNodeConnector() { - return outgoingNodeConnector; - } - - /** - * Setter method for OutGoing NodeConnector - * - * @param outgoingNodeConnector - * NodeConnector toward where the packet is travelling - */ - public void setOutgoingNodeConnector(NodeConnector outgoingNodeConnector) { - this.outgoingNodeConnector = outgoingNodeConnector; - } - - /** - * Return the incoming NodeConnector if the packet was received - * - * @return NodeConnector where the packet was received from - */ - public NodeConnector getIncomingNodeConnector() { - return incomingNodeConnector; - } - - /** - * Setter for Incoming NodeConnector - * - * @param incomingNodeConnector - * NodeConnector to be used and incoming one - */ - public void setIncomingNodeConnector(NodeConnector incomingNodeConnector) { - this.incomingNodeConnector = incomingNodeConnector; - } - - /** - * Retrieve a given property attached to the packet, if exits of course - * - * @param key - * Key to retrieve the wanted property attached to the packet - * - * @return The property attached to the packet - */ - public Object getProps(Object key) { - if (this.props != null) { - return this.props.get(key); - } - return null; - } - - /** - * Generic data associated to the data packet - * - * @param key - * key for the association - * @param value - * value associated to the key - */ - public void setProps(Object key, Object value) { - if (this.props == null) { - this.props = new HashMap(); - } - - this.props.put(key, value); - } - - /** - * Constructor for RawPacket - * - * @param data - * content of the packet as bytestream - * @param e - * datalink encapsulation for the packet - * - */ - public RawPacket(byte[] data, LinkEncap e) throws ConstructionException { - if (data == null) { - throw new ConstructionException("Empty data"); - } - if (e == null) { - throw new ConstructionException("Encap not known"); - } - this.packetData = new byte[data.length]; - System.arraycopy(data, 0, this.packetData, 0, data.length); - this.encap = e; - this.incomingTime = new TimeStamp(System.currentTimeMillis(), - "IncomingTime"); - this.copyTime = null; - } - - /** - * Copy Constructor for RawPacket, it performs a copy of the packet so each - * packet can be modified independently without worrying that source packet - * content is touched - * - * @param src - * packet to copy data from - * - */ - public RawPacket(RawPacket src) throws ConstructionException { - if (src == null) { - throw new ConstructionException("null source packet"); - } - if (src.getPacketData() != null) { - this.packetData = new byte[src.getPacketData().length]; - System.arraycopy(src.getPacketData(), 0, this.packetData, 0, - src.getPacketData().length); - } else { - throw new ConstructionException("Empty packetData"); - } - this.encap = src.getEncap(); - this.incomingTime = src.getIncomingTime(); - this.incomingNodeConnector = src.getIncomingNodeConnector(); - this.outgoingNodeConnector = src.getOutgoingNodeConnector(); - this.props = (src.props == null ? null : new HashMap( - src.props)); - this.copyTime = new TimeStamp(System.currentTimeMillis(), "CopyTime"); - } - - /** - * Constructor for RawPacket with Ethernet encapsulation - * - * @param data - * content of the packet as bytestream - * - */ - public RawPacket(byte[] data) throws ConstructionException { - this(data, LinkEncap.ETHERNET); - } - - /** - * Read the time stamp when the packet has entered the system - * - * @return The time stamp when the packet has entered the system - */ - public TimeStamp getIncomingTime() { - return this.incomingTime; - } - - /** - * Read the packet encapsulation - * - * @return The encapsulation for the raw packet, necessary to start parsing - * the packet - */ - public LinkEncap getEncap() { - return this.encap; - } - - /** - * Get bytestream of the packet body - * - * @return The raw bytestream composing the packet - */ - public byte[] getPacketData() { - return this.packetData; - } - - /** - * Returns the time at which the current instance of RawPacket was created - * as a copy of the original one. - * - * @return The time stamp at which this RawPacket instance was created. null - * if this is the original instance. - */ - public TimeStamp getCopyTime() { - return this.copyTime; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java deleted file mode 100644 index 91cd93ee52..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java +++ /dev/null @@ -1,249 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; - -/** - * Class that represents the TCP segment objects - */ -@Deprecated -public class TCP extends Packet { - - public static final String SRCPORT = "SourcePort"; - public static final String DESTPORT = "DestinationPort"; - public static final String SEQNUMBER = "SequenceNumber"; - public static final String ACKNUMBER = "AcknowledgementNumber"; - public static final String DATAOFFSET = "DataOffset"; - public static final String RESERVED = "Reserved"; - public static final String HEADERLENFLAGS = "HeaderLenFlags"; - public static final String WINDOWSIZE = "WindowSize"; - public static final String CHECKSUM = "Checksum"; - public static final String URGENTPOINTER = "UrgentPointer"; - - private static Map> fieldCoordinates = new LinkedHashMap>() { - private static final long serialVersionUID = 1L; - { - put(SRCPORT, new ImmutablePair(0, 16)); - put(DESTPORT, new ImmutablePair(16, 16)); - put(SEQNUMBER, new ImmutablePair(32, 32)); - put(ACKNUMBER, new ImmutablePair(64, 32)); - put(DATAOFFSET, new ImmutablePair(96, 4)); - put(RESERVED, new ImmutablePair(100, 3)); - put(HEADERLENFLAGS, new ImmutablePair(103, 9)); - put(WINDOWSIZE, new ImmutablePair(112, 16)); - put(CHECKSUM, new ImmutablePair(128, 16)); - put(URGENTPOINTER, new ImmutablePair(144, 16)); - } - }; - - private final Map fieldValues; - - /** - * Default constructor that sets all the header fields to zero - */ - public TCP() { - super(); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - /* Setting all remaining header field values to - * default value of 0. These maybe changed as needed - */ - setSourcePort((short) 0); - setDestinationPort((short) 0); - setSequenceNumber(0); - setAckNumber(0); - setDataOffset((byte) 0); - setReserved((byte) 0); - setWindowSize((short) 0); - setUrgentPointer((short) 0); - setChecksum((short) 0); - } - - /** - * Constructor that sets the access level for the packet and - * sets all the header fields to zero. - */ - public TCP(boolean writeAccess) { - super(writeAccess); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - /* Setting all remaining header field values to - * default value of 0. These maybe changed as needed - */ - setSourcePort((short) 0); - setDestinationPort((short) 0); - setSequenceNumber(0); - setAckNumber(0); - setDataOffset((byte) 0); - setReserved((byte) 0); - setWindowSize((short) 0); - setUrgentPointer((short) 0); - setChecksum((short) 0); - } - - @Override - /** - * Stores the value read from data stream - */ - public void setHeaderField(String headerField, byte[] readValue) { - hdrFieldsMap.put(headerField, readValue); - } - - /** - * Sets the TCP source port for the current TCP object instance - * @param short tcpSourcePort - * @return TCP - */ - public TCP setSourcePort(short tcpSourcePort) { - byte[] sourcePort = BitBufferHelper.toByteArray(tcpSourcePort); - fieldValues.put(SRCPORT, sourcePort); - return this; - } - - /** - * Sets the TCP destination port for the current TCP object instance - * @param short tcpDestinationPort - * @return TCP - */ - public TCP setDestinationPort(short tcpDestinationPort) { - byte[] destinationPort = BitBufferHelper - .toByteArray(tcpDestinationPort); - fieldValues.put(DESTPORT, destinationPort); - return this; - } - - /** - * Sets the TCP sequence number for the current TCP object instance - * @param int tcpSequenceNumber - * @return TCP - */ - public TCP setSequenceNumber(int tcpSequenceNumber) { - byte[] sequenceNumber = BitBufferHelper.toByteArray(tcpSequenceNumber); - fieldValues.put(SEQNUMBER, sequenceNumber); - return this; - } - - /** - * Sets the TCP data offset for the current TCP object instance - * @param byte tcpDataOffset - * @return TCP - */ - public TCP setDataOffset(byte tcpDataOffset) { - byte[] offset = BitBufferHelper.toByteArray(tcpDataOffset); - fieldValues.put("DataOffset", offset); - return this; - } - - /** - * Sets the TCP reserved bits for the current TCP object instance - * @param byte tcpReserved - * @return TCP - */ - public TCP setReserved(byte tcpReserved) { - byte[] reserved = BitBufferHelper.toByteArray(tcpReserved); - fieldValues.put("Reserved", reserved); - return this; - } - - /** - * Sets the TCP Ack number for the current TCP object instance - * @param int tcpAckNumber - * @return TCP - */ - public TCP setAckNumber(int tcpAckNumber) { - byte[] ackNumber = BitBufferHelper.toByteArray(tcpAckNumber); - fieldValues.put(ACKNUMBER, ackNumber); - return this; - } - - /** - * Sets the TCP flags for the current TCP object instance - * @param short tcpFlags - * @return TCP - */ - public TCP setHeaderLenFlags(short tcpFlags) { - byte[] headerLenFlags = BitBufferHelper.toByteArray(tcpFlags); - fieldValues.put(HEADERLENFLAGS, headerLenFlags); - return this; - } - - /** - * Sets the TCP window size for the current TCP object instance - * @param short tcpWsize - * @return TCP - */ - public TCP setWindowSize(short tcpWsize) { - byte[] wsize = BitBufferHelper.toByteArray(tcpWsize); - fieldValues.put(WINDOWSIZE, wsize); - return this; - } - - /** - * Sets the TCP checksum for the current TCP object instance - * @param short tcpChecksum - * @return TCP - */ - public TCP setChecksum(short tcpChecksum) { - byte[] checksum = BitBufferHelper.toByteArray(tcpChecksum); - fieldValues.put(CHECKSUM, checksum); - return this; - } - - /** - * Sets the TCP Urgent Pointer for the current TCP object instance - * @param short tcpUrgentPointer - * @return TCP - */ - public TCP setUrgentPointer(short tcpUrgentPointer) { - byte[] urgentPointer = BitBufferHelper.toByteArray(tcpUrgentPointer); - fieldValues.put(URGENTPOINTER, urgentPointer); - return this; - } - - /** - * Gets the stored source port value of TCP header - * @return the sourcePort - */ - public short getSourcePort() { - return (BitBufferHelper.getShort(fieldValues.get(SRCPORT))); - } - - /** - * Gets the stored destination port value of TCP header - * @return the destinationPort - */ - public short getDestinationPort() { - return (BitBufferHelper.getShort(fieldValues.get(DESTPORT))); - } - - /** - * Get the stored checksum value of the TCP header - * @return short - the checksum - */ - public short getChecksum() { - return (BitBufferHelper.getShort(fieldValues.get(CHECKSUM))); - } - - @Override - public void populateMatch(Match match) { - match.setField(MatchType.TP_SRC, this.getSourcePort()); - match.setField(MatchType.TP_DST, this.getDestinationPort()); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java deleted file mode 100644 index 4c7e0ffce8..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java +++ /dev/null @@ -1,167 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; - -/** - * Class that represents the UDP datagram objects - */ -@Deprecated -public class UDP extends Packet { - - private static final String SRCPORT = "SourcePort"; - private static final String DESTPORT = "DestinationPort"; - private static final String LENGTH = "Length"; - private static final String CHECKSUM = "Checksum"; - - private static Map> fieldCoordinates = new LinkedHashMap>() { - private static final long serialVersionUID = 1L; - { - put(SRCPORT, new ImmutablePair(0, 16)); - put(DESTPORT, new ImmutablePair(16, 16)); - put(LENGTH, new ImmutablePair(32, 16)); - put(CHECKSUM, new ImmutablePair(48, 16)); - } - }; - - public UDP() { - super(); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - /* Setting all remaining header field values to - * default value of 0. These maybe changed as needed - */ - setSourcePort((short) 0); - setDestinationPort((short) 0); - setChecksum((short) 0); - } - - public UDP(boolean writeAccess) { - super(writeAccess); - fieldValues = new HashMap(); - hdrFieldCoordMap = fieldCoordinates; - hdrFieldsMap = fieldValues; - /* Setting all remaining header field values to - * default value of 0. These maybe changed as needed - */ - setSourcePort((short) 0); - setDestinationPort((short) 0); - setChecksum((short) 0); - } - - private final Map fieldValues; - - /* public static Map> decodeMap; - - static { - decodeMap = new HashMap>(); - UDP.decodeMap.put((short)67, DHCP.class); - UDP.decodeMap.put((short)68, DHCP.class); - }*/ - /** - * Get the stored source port - * @return short - the sourcePort - */ - public short getSourcePort() { - return (BitBufferHelper.getShort(fieldValues.get(SRCPORT))); - } - - /** - * Get the stored destination port - * @return short - the destinationPort - */ - public short getDestinationPort() { - return (BitBufferHelper.getShort(fieldValues.get(DESTPORT))); - } - - /** - * Gets the stored length of UDP header - * @return short - the length - */ - public short getLength() { - return (BitBufferHelper.getShort(fieldValues.get(LENGTH))); - } - - /** - * Get the stored checksum value of the UDP header - * @return short - the checksum - */ - public short getChecksum() { - return (BitBufferHelper.getShort(fieldValues.get(CHECKSUM))); - } - - @Override - /** - * Store the value read from data stream in hdrFieldMap - */ - public void setHeaderField(String headerField, byte[] readValue) { - hdrFieldsMap.put(headerField, readValue); - } - - /** - * Sets the sourcePort value for the current UDP object instance - * @param short - the sourcePort to set - * @return UDP - */ - public UDP setSourcePort(short udpSourcePort) { - byte[] sourcePort = BitBufferHelper.toByteArray(udpSourcePort); - fieldValues.put(SRCPORT, sourcePort); - return this; - } - - /** - * Sets the destinationPort value for the current UDP object instance - * @param short - the destinationPort to set - * @return UDP - */ - public UDP setDestinationPort(short udpDestinationPort) { - byte[] destinationPort = BitBufferHelper - .toByteArray(udpDestinationPort); - fieldValues.put(DESTPORT, destinationPort); - return this; - } - - /** - * Set the UDP header length value for the current UDP object instance - * @param short - the length to set - * @return UDP - */ - public UDP setLength(short udpLength) { - byte[] length = BitBufferHelper.toByteArray(udpLength); - fieldValues.put(LENGTH, length); - return this; - } - - /** - * Set the checksum for the current UDP object instance - * @param short - the checksum to set - * @return UDP - */ - public UDP setChecksum(short udpChecksum) { - byte[] checksum = BitBufferHelper.toByteArray(udpChecksum); - fieldValues.put(CHECKSUM, checksum); - return this; - } - - @Override - public void populateMatch(Match match) { - match.setField(MatchType.TP_SRC, this.getSourcePort()); - match.setField(MatchType.TP_DST, this.getDestinationPort()); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/DataLinkAddress.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/DataLinkAddress.java deleted file mode 100644 index 3e75993cc8..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/DataLinkAddress.java +++ /dev/null @@ -1,97 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet.address; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @file DataLinkAddress.java - * - * @brief Abstract base class for a Datalink Address - * - */ - -/** - * Abstract base class for a Datalink Address - * - */ -@XmlRootElement -@Deprecated -abstract public class DataLinkAddress implements Serializable { - private static final long serialVersionUID = 1L; - private String name; - - public DataLinkAddress() { - - } - - /** - * Constructor of super class - * - * @param name Create a new DataLink, not for general use but - * available only for sub classes - * - * @return constructed object - */ - protected DataLinkAddress(String name) { - this.name = name; - } - - /** - * Used to copy the DataLinkAddress in a polymorphic way - * - * - * @return A clone of this DataLinkAddress - */ - @Override - abstract public DataLinkAddress clone(); - - /** - * Allow to distinguish among different data link addresses - * - * - * @return Name of the DataLinkAdress we are working on - */ - public String getName() { - return this.name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - DataLinkAddress other = (DataLinkAddress) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - return "DataLinkAddress [name=" + name + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/EthernetAddress.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/EthernetAddress.java deleted file mode 100644 index 731a731bbb..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/packet/address/EthernetAddress.java +++ /dev/null @@ -1,128 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet.address; - -import java.util.Arrays; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.utils.HexEncode; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class EthernetAddress extends DataLinkAddress { - private static final long serialVersionUID = 1L; - @XmlTransient - private byte[] macAddress; - - public static final EthernetAddress BROADCASTMAC = createWellKnownAddress(new byte[] { - (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, - (byte) 0xff }); - - public static final EthernetAddress INVALIDHOST = BROADCASTMAC; - - public static final String addressName = "Ethernet MAC Address"; - public static final int SIZE = 6; - - private static final EthernetAddress createWellKnownAddress(byte[] mac) { - try { - return new EthernetAddress(mac); - } catch (ConstructionException ce) { - return null; - } - } - - /* Private constructor to satisfy JAXB */ - @SuppressWarnings("unused") - private EthernetAddress() { - } - - /** - * Public constructor for an Ethernet MAC address starting from - * the byte constituing the address, the constructor validate the - * size of the arrive to make sure it met the expected size - * - * @param macAddress A byte array in big endian format - * representing the Ethernet MAC Address - * - * @return The constructed object if valid - */ - public EthernetAddress(byte[] macAddress) throws ConstructionException { - super(addressName); - - if (macAddress == null) { - throw new ConstructionException("Null input parameter passed"); - } - - if (macAddress.length != SIZE) { - throw new ConstructionException( - "Wrong size of passed byte array, expected:" + SIZE - + " got:" + macAddress.length); - } - this.macAddress = new byte[SIZE]; - System.arraycopy(macAddress, 0, this.macAddress, 0, SIZE); - } - - public EthernetAddress clone() { - try { - return new EthernetAddress(this.macAddress.clone()); - } catch (ConstructionException ce) { - return null; - } - } - - /** - * Return the Ethernet Mac address in byte array format - * - * @return The Ethernet Mac address in byte array format - */ - public byte[] getValue() { - return this.macAddress; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + Arrays.hashCode(macAddress); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - EthernetAddress other = (EthernetAddress) obj; - if (!Arrays.equals(macAddress, other.macAddress)) - return false; - return true; - } - - @Override - public String toString() { - return "EthernetAddress [macAddress=" + HexEncode.bytesToHexStringFormat(macAddress) - + "]"; - } - - @XmlElement(name = "macAddress") - public String getMacAddress() { - return HexEncode.bytesToHexStringFormat(macAddress); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/FlowOnNode.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/FlowOnNode.java deleted file mode 100644 index bcd404eaed..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/FlowOnNode.java +++ /dev/null @@ -1,175 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.reader; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.flowprogrammer.Flow; - -/** - * Represents the flow that is installed on the network node - * along with the table location, hit counters and timers - */ - -@XmlRootElement (name="FlowStat") -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class FlowOnNode implements Serializable{ - private static final long serialVersionUID = 1L; - - @XmlElement - private Flow flow; // Flow descriptor - @XmlElement - private byte tableId; - @XmlElement - private int durationSeconds; - @XmlElement - private int durationNanoseconds; - @XmlElement - private long packetCount; - @XmlElement - private long byteCount; - - /* Dummy constructor for JAXB */ - @SuppressWarnings("unused") - private FlowOnNode () { - } - - public FlowOnNode(Flow flow) { - this.flow = flow; - } - - /** - * Returns the description of the flow which statistics are about - * @return - */ - public Flow getFlow() { - return flow; - } - - /** - * Set the packet count's value - * @param count - */ - public void setPacketCount(long count) { - packetCount = count; - } - - /** - * Set the byte count's value - * @param count - */ - public void setByteCount(long count) { - byteCount = count; - } - - /** - * Returns the packet count for the flow - * @return - */ - public long getPacketCount() { - return packetCount; - } - - /** - * Return the byte count for the flow - * @return - */ - public long getByteCount() { - return byteCount; - } - - public byte getTableId() { - return tableId; - } - - public void setTableId(byte tableId) { - this.tableId = tableId; - } - - public int getDurationSeconds() { - return durationSeconds; - } - - public void setDurationSeconds(int durationSeconds) { - this.durationSeconds = durationSeconds; - } - - public int getDurationNanoseconds() { - return durationNanoseconds; - } - - public void setDurationNanoseconds(int durationNanoseconds) { - this.durationNanoseconds = durationNanoseconds; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (int) (byteCount ^ (byteCount >>> 32)); - result = prime * result + durationNanoseconds; - result = prime * result + durationSeconds; - result = prime * result + ((flow == null) ? 0 : flow.hashCode()); - result = prime * result + (int) (packetCount ^ (packetCount >>> 32)); - result = prime * result + tableId; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof FlowOnNode)) { - return false; - } - FlowOnNode other = (FlowOnNode) obj; - if (byteCount != other.byteCount) { - return false; - } - if (durationNanoseconds != other.durationNanoseconds) { - return false; - } - if (durationSeconds != other.durationSeconds) { - return false; - } - if (flow == null) { - if (other.flow != null) { - return false; - } - } else if (!flow.equals(other.flow)) { - return false; - } - if (packetCount != other.packetCount) { - return false; - } - if (tableId != other.tableId) { - return false; - } - return true; - } - - @Override - public String toString() { - return "FlowOnNode[flow =" + flow + ", tableId = " + tableId - + ", sec = " + durationSeconds + ", nsec = " - + durationNanoseconds + ", pkt = " + packetCount + ", byte = " - + byteCount + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginInReadService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginInReadService.java deleted file mode 100644 index edaee5f35e..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginInReadService.java +++ /dev/null @@ -1,138 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.reader; - -import java.util.List; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.flowprogrammer.Flow; - -/** - * The interface defines hardware view read methods to be implemented by protocol plugins - */ -@Deprecated -public interface IPluginInReadService { - - /** - * Returns the hardware image for the specified flow on the specified - * network node - * - * @param node - * the network node - * @param flow - * the target flow - * @param cached - * specify if entry has to be queried from the cached hardware - * information maintained locally or directly from the network - * node. - * @return The FlowOnNode object containing the information present in - * hardware for the passed flow on the specified network node - */ - public FlowOnNode readFlow(Node node, Flow flow, boolean cached); - - /** - * Returns the hardware view of all the flow installed on the specified - * network node - * - * @param node - * the network node - * @param cached - * specify if entries have to be queried from the cached hardware - * information maintained locally or directly from the network - * node. - * @return The list of FlowOnNode objects containing the information present - * in hardware on the specified network node for all its flows - */ - public List readAllFlow(Node node, boolean cached); - - /** - * Returns the description of the network node as provided by the node - * itself - * - * @param node - * the network node - * @param cached - * specify if entry has to be queried from the cached hardware - * information maintained locally or directly from the network - * node. - * @return The NodeDescription object containing the description information - * for the specified network node - */ - public NodeDescription readDescription(Node node, boolean cached); - - /** - * Returns the hardware view of the specified network node connector - * - * @param connector - * the target nodeConnector - * @param cached - * specify if entry has to be queried from the cached hardware - * information maintained locally or directly from the - * corresponding network node. - * @return The NodeConnectorStatistics object containing the statistics - * present in hardware for the corresponding network node port - */ - public NodeConnectorStatistics readNodeConnector(NodeConnector connector, - boolean cached); - - /** - * Returns the hardware info for all the node connectors on the specified - * network node - * - * @param node - * the target node - * @param cached - * specify if entries have to be queried from the cached hardware - * information maintained locally or directly from the - * corresponding network node. - * @return The list of NodeConnectorStatistics objects containing the - * statistics present in hardware for all the network node ports - */ - public List readAllNodeConnector(Node node, - boolean cached); - - /** - * Returns the table statistics for the node - * @param table - * the target network node table - * @param cached - * specify if entry has to be queried from the cached hardware - * information maintained locally or directly from - * the corresponding network node. - * @return The NodeTableStatistics object containing the statistics present - * in hardware for the corresponding network node table - */ - public NodeTableStatistics readNodeTable(NodeTable table, boolean cached); - - /** - * Returns all the table statistics for the node - * - * @param node - * the target node - * @param cached - * specify if entries have to be queried from the cached hardware - * information maintained locally or directly from the - * corresponding network node. - * @return The list of NodeTableStatistics objects containing the statistics - * present in hardware for all the network node tables - */ - public List readAllNodeTable(Node node, boolean cached); - - /** - * Returns the averaged transmit rate for the specified node connector - * @param connector - * the target nodeConnector - * @return tx rate [bps] - */ - public long getTransmitRate(NodeConnector connector); - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginOutReadService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginOutReadService.java deleted file mode 100644 index e5baa408b8..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IPluginOutReadService.java +++ /dev/null @@ -1,75 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.reader; - -import java.util.List; - -import org.opendaylight.controller.sal.core.Node; - -/** - * The interface defines hardware statistics updates service to be offered by - * protocol plugins - */ -@Deprecated -public interface IPluginOutReadService { - - /** - * Notifies the hardware view of all the flow installed on the specified - * network node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @param flowStatsList - * the hardware view of all the flow - * {@link org.opendaylight.controller.sal.reader.FlowOnNode} - * installed on the specified network node - */ - public void nodeFlowStatisticsUpdated(Node node, List flowStatsList); - - /** - * Notifies the hardware view of the specified network node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @param ncStatsList - * the statistics - * {@link org.opendaylight.controller.sal.reader.NodeConnectorStatistics} - * for all node connectors in a given node - */ - public void nodeConnectorStatisticsUpdated(Node node, List ncStatsList); - - /** - * Notifies all the table statistics for a node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @param tableStatsList - * the statistics - * {@link org.opendaylight.controller.sal.reader.NodeTableStatistics} - * for all the tables in a given node - */ - public void nodeTableStatisticsUpdated(Node node, List tableStatsList); - - /** - * Notifies the hardware view of node description changes - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @param nodeDescription - * the node description - * {@link org.opendaylight.controller.sal.reader.NodeDescription} - */ - public void descriptionStatisticsUpdated(Node node, NodeDescription nodeDescription ); - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadService.java deleted file mode 100644 index d25a6f62f0..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadService.java +++ /dev/null @@ -1,203 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.reader; - -import java.util.List; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.flowprogrammer.Flow; - -/** - * This interface defines methods for retrieving the network node's - * flow/port/queue hardware view - */ -@Deprecated -public interface IReadService { - /** - * Get the hardware view for the specified flow on the specified network - * node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @param flow - * the given flow - * {@link org.opendaylight.controller.sal.flowprogrammer.Flow} - * @return the flow - * {@link org.opendaylight.controller.sal.reader.FlowOnNode} - * installed on the node - */ - FlowOnNode readFlow(Node node, Flow flow); - - /** - * Get the hardware view for the specified flow on the specified network node - * This call results in a direct polling of the information from the node - * Caller will be blocked until node replies or request times out - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @param flow - * the given flow - * {@link org.opendaylight.controller.sal.flowprogrammer.Flow} - * @return the flow - * {@link org.opendaylight.controller.sal.reader.FlowOnNode} - * installed on the node - */ - FlowOnNode nonCachedReadFlow(Node node, Flow flow); - - /** - * Get the hardware view for all the flows installed on the network node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @return all the flows - * {@link org.opendaylight.controller.sal.reader.FlowOnNode} - * installed on the node - */ - List readAllFlows(Node node); - - /** - * Get the hardware view for all the flows installed on the network node - * This call results in a direct polling of the information from the node - * Caller will be blocked until node replies or request times out - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @return the hardware view of all the flows - * {@link org.opendaylight.controller.sal.reader.FlowOnNode} - * installed on the node - */ - List nonCachedReadAllFlows(Node node); - - /** - * Get the description information for the network node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @return the node description - * {@link org.opendaylight.controller.sal.reader.NodeDescription} - */ - NodeDescription readDescription(Node node); - - /** - * Get the description information for the network node - * This call results in a direct polling of the information from the node - * Caller will be blocked until node replies or request times out - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @return the node description - * {@link org.opendaylight.controller.sal.reader.NodeDescription} - */ - NodeDescription nonCachedReadDescription(Node node); - - /** - * Get the hardware view for the specified node connector - * - * @param connector - * the given node connector - * {@link org.opendaylight.controller.sal.core.NodeConnector} - * @return the node connector statistics - * {@link org.opendaylight.controller.sal.reader.NodeConnectorStatistics} - */ - NodeConnectorStatistics readNodeConnector(NodeConnector connector); - - /** - * Get the hardware view for all the node connectors - * present on the specified network node - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @return the statistics for all the node connectors - * {@link org.opendaylight.controller.sal.reader.NodeConnectorStatistics} - */ - List readNodeConnectors(Node node); - - /** - * Read the Table statistics for the given node table - * - * @param table - * the table - * {@link org.opendaylight.controller.sal.core.NodeTable} - * @return the table statistics - * {@link org.opendaylight.controller.sal.reader.NodeTableStatistics} - */ - NodeTableStatistics readNodeTable(NodeTable table); - - /** - * Read the Table statistics for the given node This is not used. Querying - * all tables on a node is not currently a feature. - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @return the table statistics - * {@link org.opendaylight.controller.sal.reader.NodeTableStatistics} - * for all tables in a given node - */ - List readNodeTable(Node node); - - /** - * Get the table statistics for the given node table - * This call results in a direct polling of the information from the node - * Caller will be blocked until the node replies or request times out - * - * @param table - * the table - * {@link org.opendaylight.controller.sal.core.NodeTable} - * @return the table statistics - * {@link org.opendaylight.controller.sal.reader.NodeTableStatistics} - */ - NodeTableStatistics nonCachedReadNodeTable(NodeTable table); - - /** - * Get the node connectors statistics information for the network node - * This call results in a direct polling of the information from the node - * Caller will be blocked until node replies or request times out - * - * @param node - * the network node - * {@link org.opendaylight.controller.sal.core.Node} - * @return the statistics - * {@link org.opendaylight.controller.sal.reader.NodeConnectorStatistics} - * for all node connectors in a given node - */ - List nonCachedReadNodeConnectors(Node node); - - /** - * Get the node connectors statistics information for the network node - * - * @param connector - * the given node connector - * {@link org.opendaylight.controller.sal.core.NodeConnector} - * @return the node connector statistics - * {@link org.opendaylight.controller.sal.reader.NodeConnectorStatistics} - */ - NodeConnectorStatistics nonCachedReadNodeConnector(NodeConnector connector); - - /** - * Get the transmit rate for the specified node connector - * - * @param connector - * the given node connector - * {@link org.opendaylight.controller.sal.core.NodeConnector} - * @return tx rate [bps] - */ - long getTransmitRate(NodeConnector connector); - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadServiceListener.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadServiceListener.java deleted file mode 100644 index 01eaf1eb37..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/IReadServiceListener.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.reader; - -/** - * The interface describes SAL service to be consumed by functional modules that - * are interested in reader updates - */ -@Deprecated -public interface IReadServiceListener extends IPluginOutReadService { - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeConnectorStatistics.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeConnectorStatistics.java deleted file mode 100644 index 1ef2fd5cb1..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeConnectorStatistics.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.reader; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.NodeConnector; - -/** - * Represents the statistics for a node connector - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class NodeConnectorStatistics implements Serializable { - private static final long serialVersionUID = 1L; - - @XmlElement - private NodeConnector nodeConnector; - @XmlElement - private long receivePackets; - @XmlElement - private long transmitPackets; - @XmlElement - private long receiveBytes; - @XmlElement - private long transmitBytes; - @XmlElement - private long receiveDrops; - @XmlElement - private long transmitDrops; - @XmlElement - private long receiveErrors; - @XmlElement - private long transmitErrors; - @XmlElement - private long receiveFrameError; - @XmlElement - private long receiveOverRunError; - @XmlElement - private long receiveCrcError; - @XmlElement - private long collisionCount; - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (int) (collisionCount ^ (collisionCount >>> 32)); - result = prime * result + ((nodeConnector == null) ? 0 : nodeConnector.hashCode()); - result = prime * result + (int) (receiveBytes ^ (receiveBytes >>> 32)); - result = prime * result + (int) (receiveCrcError ^ (receiveCrcError >>> 32)); - result = prime * result + (int) (receiveDrops ^ (receiveDrops >>> 32)); - result = prime * result + (int) (receiveErrors ^ (receiveErrors >>> 32)); - result = prime * result + (int) (receiveFrameError ^ (receiveFrameError >>> 32)); - result = prime * result + (int) (receiveOverRunError ^ (receiveOverRunError >>> 32)); - result = prime * result + (int) (receivePackets ^ (receivePackets >>> 32)); - result = prime * result + (int) (transmitBytes ^ (transmitBytes >>> 32)); - result = prime * result + (int) (transmitDrops ^ (transmitDrops >>> 32)); - result = prime * result + (int) (transmitErrors ^ (transmitErrors >>> 32)); - result = prime * result + (int) (transmitPackets ^ (transmitPackets >>> 32)); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof NodeConnectorStatistics)) { - return false; - } - NodeConnectorStatistics other = (NodeConnectorStatistics) obj; - if (collisionCount != other.collisionCount) { - return false; - } - if (nodeConnector == null) { - if (other.nodeConnector != null) { - return false; - } - } else if (!nodeConnector.equals(other.nodeConnector)) { - return false; - } - if (receiveBytes != other.receiveBytes) { - return false; - } - if (receiveCrcError != other.receiveCrcError) { - return false; - } - if (receiveDrops != other.receiveDrops) { - return false; - } - if (receiveErrors != other.receiveErrors) { - return false; - } - if (receiveFrameError != other.receiveFrameError) { - return false; - } - if (receiveOverRunError != other.receiveOverRunError) { - return false; - } - if (receivePackets != other.receivePackets) { - return false; - } - if (transmitBytes != other.transmitBytes) { - return false; - } - if (transmitDrops != other.transmitDrops) { - return false; - } - if (transmitErrors != other.transmitErrors) { - return false; - } - if (transmitPackets != other.transmitPackets) { - return false; - } - return true; - } - - // To Satisfy JAXB - public NodeConnectorStatistics() { - - } - - /** - * Set the node connector - * - * @param port - */ - public void setNodeConnector(NodeConnector port) { - this.nodeConnector = port; - } - - /** - * Returns the node connector - * - * @return - */ - public NodeConnector getNodeConnector() { - return nodeConnector; - } - - /** - * Set the rx packet count's value - * - * @param count - */ - public void setReceivePacketCount(long count) { - receivePackets = count; - } - - /** - * Returns the rx packet count for the port - * - * @return - */ - public long getReceivePacketCount() { - return receivePackets; - } - - /** - * Set the tx packet count's value - * - * @param count - */ - public void setTransmitPacketCount(long count) { - transmitPackets = count; - } - - /** - * Returns the tx packet count for the port - * - * @return - */ - public long getTransmitPacketCount() { - return transmitPackets; - } - - /** - * Set the rx byte count's value - * - * @param count - */ - public void setReceiveByteCount(long count) { - receiveBytes = count; - } - - /** - * Return the rx byte count for the port - * - * @return - */ - public long getReceiveByteCount() { - return receiveBytes; - } - - /** - * Set the tx byte count's value - * - * @param count - */ - public void setTransmitByteCount(long count) { - transmitBytes = count; - } - - /** - * Return the tx byte count for the port - * - * @return - */ - public long getTransmitByteCount() { - return transmitBytes; - } - - /** - * Set the rx drop count's value - * - * @param count - */ - public void setReceiveDropCount(long count) { - receiveDrops = count; - } - - /** - * Returns the rx drop count for the port - * - * @return - */ - public long getReceiveDropCount() { - return receiveDrops; - } - - /** - * Set the tx drop count's value - * - * @param count - */ - public void setTransmitDropCount(long count) { - transmitDrops = count; - } - - /** - * Returns the tx drop count for the port - * - * @return - */ - public long getTransmitDropCount() { - return transmitDrops; - } - - /** - * Set the rx error count's value - * - * @param count - */ - public void setReceiveErrorCount(long count) { - receiveErrors = count; - } - - /** - * Return the rx error count for the port - * - * @return - */ - public long getReceiveErrorCount() { - return receiveErrors; - } - - /** - * Set the tx error count's value - * - * @param count - */ - public void setTransmitErrorCount(long count) { - transmitErrors = count; - } - - /** - * Return the tx error count for the port - * - * @return - */ - public long getTransmitErrorCount() { - return transmitErrors; - } - - /** - * Set the rx frame error value - * - * @param count - */ - public void setReceiveFrameErrorCount(long count) { - receiveFrameError = count; - } - - /** - * Returns the rx frame error for the port - * - * @return - */ - public long getReceiveFrameErrorCount() { - return receiveFrameError; - } - - /** - * Set the rx overrun error value - * - * @param count - */ - public void setReceiveOverRunErrorCount(long count) { - receiveOverRunError = count; - } - - /** - * Return the rx overrun error for the port - * - * @return - */ - public long getReceiveOverRunErrorCount() { - return receiveOverRunError; - } - - /** - * Set the rx CRC Error value - * - * @param count - */ - public void setReceiveCRCErrorCount(long count) { - receiveCrcError = count; - } - - /** - * Return the rx CRC error for the port - * - * @return - */ - public long getReceiveCRCErrorCount() { - return receiveCrcError; - } - - /** - * Set the collisionCount count's value - * - * @param count - */ - public void setCollisionCount(long count) { - collisionCount = count; - } - - /** - * Return the collisionCount count for the port - * - * @return - */ - public long getCollisionCount() { - return collisionCount; - } - - @Override - public String toString() { - return "NodeConnectorStats[portNumber = " + nodeConnector - + ", receivePackets = " + receivePackets - + ", transmitPackets = " + transmitPackets - + ", receiveBytes = " + receiveBytes + ", transmitBytes = " - + transmitBytes + ", receiveDrops = " + receiveDrops - + ", transmitDrops = " + transmitDrops + ", receiveErrors = " - + receiveErrors + ", transmitErrors = " + transmitErrors - + ", receiveFrameError = " + receiveFrameError - + ", receiveOverRunError = " + receiveOverRunError - + ", receiveCrcError = " + receiveCrcError - + ", collisionCount = " + collisionCount + "]"; - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeDescription.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeDescription.java deleted file mode 100644 index afcd02ece9..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeDescription.java +++ /dev/null @@ -1,151 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.reader; - -import java.io.Serializable; - - -/** - * Represents the network node description information - */ -@Deprecated -public class NodeDescription implements Serializable, Cloneable{ - private static final long serialVersionUID = 1L; - - private String manufacturer; - private String hardware; - private String software; - private String serialNumber; - private String description; - - public NodeDescription() { - - } - - public String getManufacturer() { - return manufacturer; - } - - public void setManufacturer(String manufacturer) { - this.manufacturer = manufacturer; - } - - public String getHardware() { - return hardware; - } - - public void setHardware(String hardware) { - this.hardware = hardware; - } - - public String getSoftware() { - return software; - } - - public void setSoftware(String software) { - this.software = software; - } - - public String getSerialNumber() { - return serialNumber; - } - - public void setSerialNumber(String serialNumber) { - this.serialNumber = serialNumber; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((hardware == null) ? 0 : hardware.hashCode()); - result = prime * result + ((manufacturer == null) ? 0 : manufacturer.hashCode()); - result = prime * result + ((serialNumber == null) ? 0 : serialNumber.hashCode()); - result = prime * result + ((software == null) ? 0 : software.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof NodeDescription)) { - return false; - } - NodeDescription other = (NodeDescription) obj; - if (description == null) { - if (other.description != null) { - return false; - } - } else if (!description.equals(other.description)) { - return false; - } - if (hardware == null) { - if (other.hardware != null) { - return false; - } - } else if (!hardware.equals(other.hardware)) { - return false; - } - if (manufacturer == null) { - if (other.manufacturer != null) { - return false; - } - } else if (!manufacturer.equals(other.manufacturer)) { - return false; - } - if (serialNumber == null) { - if (other.serialNumber != null) { - return false; - } - } else if (!serialNumber.equals(other.serialNumber)) { - return false; - } - if (software == null) { - if (other.software != null) { - return false; - } - } else if (!software.equals(other.software)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "HwDescription[manufacturer=" + manufacturer + ", hardware=" - + hardware + ", software=" + software + ", serialNumber=" - + serialNumber + ", description=" + description + "]"; - } - @Override - public NodeDescription clone() { - NodeDescription nd = new NodeDescription(); - nd.setDescription(description); - nd.setHardware(hardware); - nd.setManufacturer(manufacturer); - nd.setSerialNumber(serialNumber); - nd.setSoftware(software); - - return nd; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeTableStatistics.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeTableStatistics.java deleted file mode 100644 index e85bfd4da7..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/reader/NodeTableStatistics.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.reader; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.sal.core.NodeTable; - -/** - * @author Aditya Prakash Vaja - * Represents the Table statistics for the node - * - */ - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -@Deprecated -public class NodeTableStatistics implements Serializable { - private static final long serialVersionUID = 1L; - - @XmlElement - private NodeTable nodeTable; - @XmlElement - private String name; - @XmlElement - private int activeCount; - @XmlElement - private long lookupCount; - @XmlElement - private long matchedCount; - @XmlElement - private int maximumEntries; - - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + activeCount; - result = prime * result + (int) (lookupCount ^ (lookupCount >>> 32)); - result = prime * result + (int) (matchedCount ^ (matchedCount >>> 32)); - result = prime * result + maximumEntries; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((nodeTable == null) ? 0 : nodeTable.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof NodeTableStatistics)) { - return false; - } - NodeTableStatistics other = (NodeTableStatistics) obj; - if (activeCount != other.activeCount) { - return false; - } - if (lookupCount != other.lookupCount) { - return false; - } - if (matchedCount != other.matchedCount) { - return false; - } - if (maximumEntries != other.maximumEntries) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (nodeTable == null) { - if (other.nodeTable != null) { - return false; - } - } else if (!nodeTable.equals(other.nodeTable)) { - return false; - } - return true; - } - - //To Satisfy JAXB - public NodeTableStatistics() { - - } - - /** - * @return the node table - */ - public NodeTable getNodeTable() { - return nodeTable; - } - - /** - * @param table of the node - */ - public void setNodeTable(NodeTable table) { - this.nodeTable = table; - } - - /** - * @return name of the table - */ - public String getName() { - return name; - } - - /** - * @param name - set the table name to name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the activeCount - */ - public int getActiveCount() { - return activeCount; - } - - /** - * @param activeCount the activeCount to set - */ - public void setActiveCount(int activeCount) { - this.activeCount = activeCount; - } - - /** - * @return the lookupCount - */ - public long getLookupCount() { - return lookupCount; - } - - /** - * @param lookupCount the lookupCount to set - */ - public void setLookupCount(long lookupCount) { - this.lookupCount = lookupCount; - } - - /** - * @return the matchedCount - */ - public long getMatchedCount() { - return matchedCount; - } - - /** - * @param matchedCount the matchedCount to set - */ - public void setMatchedCount(long matchedCount) { - this.matchedCount = matchedCount; - } - - /** - * @return the maximumEntries - */ - public int getMaximumEntries() { - return maximumEntries; - } - - /** - * @param maximumEntries the maximumEntries to set - */ - public void setMaximumEntries(int maximumEntries) { - this.maximumEntries = maximumEntries; - } - - @Override - public String toString() { - return "NodeTableStats[tableId = " + nodeTable - + ", activeCount = " + activeCount - + ", lookupCount = " + lookupCount - + ", matchedCount = " + matchedCount - + ", maximumEntries = " + maximumEntries + "]"; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IListenRoutingUpdates.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IListenRoutingUpdates.java deleted file mode 100644 index dd2262b2be..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IListenRoutingUpdates.java +++ /dev/null @@ -1,26 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.routing; - -/** - * Interface that will be implemented by the modules that wants to - * know events published by the routing engine - * - */ -@Deprecated -public interface IListenRoutingUpdates { - /** - * Method invoked when the recalculation of the all shortest path - * tree is done - * - */ - public void recalculateDone(); - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IRouting.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IRouting.java deleted file mode 100644 index b50f616908..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/routing/IRouting.java +++ /dev/null @@ -1,87 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.routing; - -import java.util.Map; - -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.Path; - -/** - * This interface provides APIs to manage and query the routing information - * - */ -@Deprecated -public interface IRouting { - - /** - * Returns a Path leading from the source to the destination - * - * @param src - * source {@link org.opendaylight.controller.sal.core.Node} - * - * @param dst - * destination - * {@link org.opendaylight.controller.sal.core.Node} - * @return: the {@link org.opendaylight.controller.sal.core.Path} - */ - public Path getRoute(Node src, Node dst); - - /** - * Returns a Max ThroughPut Path leading from the source to the destination - * - * @param src - * source {@link org.opendaylight.controller.sal.core.Node} - * - * @param dst - * destination - * {@link org.opendaylight.controller.sal.core.Node} - * @return: the max throughput {@link org.opendaylight.controller.sal.core.Path} - */ - public Path getMaxThroughputRoute(Node src, Node dst); - - /** - * Returns a Path leading from the source to the destination that meets the - * specified bandwidth - * - * @param src - * source {@link org.opendaylight.controller.sal.core.Node} - * - * @param dst - * destination {@link org.opendaylight.controller.sal.core.Node} - * @param Bw - * the bandwidth - * @return: the {@link org.opendaylight.controller.sal.core.Path} - */ - public Path getRoute(Node src, Node dst, Short Bw); - - /** - * Remove all routes and reset all state. USE CAREFULLY! - */ - public void clear(); - - /** - * Remove all Max Throughput Routes and reset all state. USE CAREFULLY! - */ - public void clearMaxThroughput(); - - /** - * Initialization For Max Throughput - * - * @param EdgeWeightMap - * Map containing - * {@link org.opendaylight.controller.sal.core.Edge} and - * Corresponding Weight. Optional Param - if null, implementation - * specific weight calculation will be used. - */ - public void initMaxThroughput(Map EdgeWeightMap); - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IListenTopoUpdates.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IListenTopoUpdates.java deleted file mode 100644 index 3895993be5..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IListenTopoUpdates.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.topology; - -import java.util.List; - -import org.opendaylight.controller.sal.core.Edge; - -/** - * This interface defines the methods for topology notifications provided by SAL - * toward the application. For example an application that wants to keep up to - * date with the updates coming from SAL it will register in the OSGi service - * registry. This interface (on a per-container base) and SAL will call it - * providing the update. - */ -@Deprecated -public interface IListenTopoUpdates { - /** - * Called to update on Edge in the topology graph - * - * @param topoedgeupdateList - * List of topoedgeupdates Each topoedgeupdate includes edge, its - * Properties ( BandWidth and/or Latency etc) and update type. - */ - public void edgeUpdate(List topoedgeupdateList); - - /** - * Called when an Edge utilization is above the safety threshold configured - * on the controller - * - * @param edge - * The edge which bandwidth usage is above the safety level - */ - public void edgeOverUtilized(Edge edge); - - /** - * Called when the Edge utilization is back to normal, below the safety - * threshold level configured on the controller - * - * @param edge - * The edge which bandwidth usage is back to normal - */ - public void edgeUtilBackToNormal(Edge edge); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginInTopologyService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginInTopologyService.java deleted file mode 100644 index 35e0872b01..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginInTopologyService.java +++ /dev/null @@ -1,37 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.topology; - -/** - * @file IPluginInTopologyService.java - * - * @brief Methods that are invoked from SAL toward the protocol - * plugin. - * - * For example if SAL startup late in respect to a protocol plugin, or - * restarts, we need away to sollicit the push of older updates from - * Protocol Plugins this interface serve the purpose. This a practical - * example of the type of service provided by this interface - */ - -/** - * Methods that are invoked from SAL toward the protocol - * plugin to sollicit Topoloy updates - * - */ -@Deprecated -public interface IPluginInTopologyService { - /** - * Tell to protocol plugin that is time to send the updates of the - * current topology because someone joined late the game - * - */ - public void sollicitRefresh(); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginOutTopologyService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginOutTopologyService.java deleted file mode 100644 index 42d1a5e2c6..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/IPluginOutTopologyService.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.topology; - -import java.util.List; -import org.opendaylight.controller.sal.core.Edge; - -/** - * This interface defines the methods that are invoked from Protocol Plugin - * toward SAL. Every time a protocol plugin update the topology, it will call - * this service provided by SAL so the update can migrate upward toward the - * applications. - */ -@Deprecated -public interface IPluginOutTopologyService { - - /** - * Called to update on Edge in the topology graph - * - * @param topoedgeupdateList - * List of topoedgeupdates Each topoedgeupdate includes edge, its - * Properties ( BandWidth and/or Latency etc) and update type. - */ - public void edgeUpdate(List topoedgeupdateList); - - /** - * Called when an Edge utilization is above the safety threshold configured - * on the controller - * - * @param edge - * The edge which bandwidth usage is above the safety level - */ - public void edgeOverUtilized(Edge edge); - - /** - * Called when the Edge utilization is back to normal, below the safety - * threshold level configured on the controller - * - * @param edge - * The edge which bandwidth usage is back to normal - */ - public void edgeUtilBackToNormal(Edge edge); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/ITopologyService.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/ITopologyService.java deleted file mode 100644 index ffad2378dd..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/ITopologyService.java +++ /dev/null @@ -1,33 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.topology; - -/** - * @file ITopologyService.java - * - * @brief Topology methods provided by SAL toward the applications - * - * For example An application that startup late in the game or restart - * for example, wants to know the current status of SAL, so can use - * this interface to get a bunlk sync of the topology status. - */ - -/** - * Topology methods provided by SAL toward the applications - */ -@Deprecated -public interface ITopologyService { - /** - * Tell to SAL that is time to send the updates of the - * current topology because someone joined late the game - * - */ - public void sollicitRefresh(); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/TopoEdgeUpdate.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/TopoEdgeUpdate.java deleted file mode 100644 index 90596bdb6b..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/topology/TopoEdgeUpdate.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.topology; - -import java.util.Set; - -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; - -/** - * The class represents an Edge, the Edge's Property Set and its UpdateType. - * If update is on new properties added to an existing edge, appropriate type is CHANGED. - */ -@Deprecated -public class TopoEdgeUpdate { - private Edge edge; - private Set props; - private UpdateType type; - private boolean isLocal; - - /** - * Constructor for a topology element update. A TopologyElementUpdate is an - * object that summarize what has happened on an Edge and if the update is - * generated locally to this controller or no - * - * @param e - * Edge being updated - * @param p - * Set of Properties attached to the edge - * @param t - * Type of update - */ - public TopoEdgeUpdate(Edge e, Set p, UpdateType t) { - edge = e; - props = p; - type = t; - setLocal(true); - } - - public Edge getEdge() { - return edge; - } - - public Set getProperty() { - return props; - } - - public UpdateType getUpdateType() { - return type; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + ((edge == null) ? 0 : edge.hashCode()); - result = (prime * result) + ((type == null) ? 0 : type.hashCode()); - return result; - } - - @Override - public String toString() { - return "TopoEdgeUpdate [edge=" + edge + ", props=" + props + ", type=" + type + ", isLocal=" + isLocal + "]"; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - TopoEdgeUpdate other = (TopoEdgeUpdate) obj; - if (edge == null) { - if (other.edge != null) { - return false; - } - } else if (!edge.equals(other.edge)) { - return false; - } - if (type != other.type) { - return false; - } - return true; - } - - public boolean isLocal() { - return isLocal; - } - - public void setLocal(boolean isLocal) { - this.isLocal = isLocal; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ConfigurationObject.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ConfigurationObject.java deleted file mode 100644 index 8f482283c0..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ConfigurationObject.java +++ /dev/null @@ -1,19 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -/** - * This interface defines the methods for configuration object - * - */ -@Deprecated -public interface ConfigurationObject { - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Direction.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Direction.java deleted file mode 100644 index 095997156a..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Direction.java +++ /dev/null @@ -1,32 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.io.Serializable; - -/** - * Direction enum - * - * - * - */ -@Deprecated -public enum Direction implements Serializable { - FORWARD("forward"), REVERSE("reverse"); - private Direction(String name) { - this.name = name; - } - - private String name; - - public String toString() { - return name; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/EtherTypes.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/EtherTypes.java deleted file mode 100644 index 7f1955d84c..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/EtherTypes.java +++ /dev/null @@ -1,118 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.util.ArrayList; -import java.util.List; - -/** - * The enum contains the most common 802.3 ethernet types and 802.2 + SNAP protocol ids - * - * - * - */ -@Deprecated -public enum EtherTypes { - PVSTP("PVSTP", 0x010B), // 802.2 + SNAP (Spanning Tree) - CDP("CDP", 0x2000), // 802.2 + SNAP - VTP("VTP", 0x2003), // 802.2 + SNAP - IPv4("IPv4", 0x800), ARP("ARP", 0x806), RARP("Reverse ARP", 0x8035), VLANTAGGED( - "VLAN Tagged", 0x8100), // 802.1Q - IPv6("IPv6", 0x86DD), MPLSUCAST("MPLS Unicast", 0x8847), MPLSMCAST( - "MPLS Multicast", 0x8848), QINQ("QINQ", 0x88A8), // Standard 802.1ad QinQ - LLDP("LLDP", 0x88CC), OLDQINQ("Old QINQ", 0x9100), // Old non-standard QinQ - CISCOQINQ("Cisco QINQ", 0x9200); // Cisco non-standard QinQ - - private static final String regexNumberString = "^[0-9]+$"; - private String description; - private int number; - - private EtherTypes(String description, int number) { - this.description = description; - this.number = number; - } - - public String toString() { - return description; - } - - public int intValue() { - return number; - } - - public short shortValue() { - return ((Integer) number).shortValue(); - } - - public static String getEtherTypeName(int number) { - return getEtherTypeInternal(number); - } - - public static String getEtherTypeName(short number) { - return getEtherTypeInternal((int) number & 0xffff); - } - - public static String getEtherTypeName(byte number) { - return getEtherTypeInternal((int) number & 0xff); - } - - private static String getEtherTypeInternal(int number) { - for (EtherTypes type : EtherTypes.values()) { - if (type.number == number) { - return type.toString(); - } - } - return "0x" + Integer.toHexString(number); - } - - public static short getEtherTypeNumberShort(String name) { - if (name.matches(regexNumberString)) { - return Short.valueOf(name); - } - for (EtherTypes type : EtherTypes.values()) { - if (type.description.equalsIgnoreCase(name)) { - return type.shortValue(); - } - } - return 0; - } - - public static int getEtherTypeNumberInt(String name) { - if (name.matches(regexNumberString)) { - return Integer.valueOf(name); - } - for (EtherTypes type : EtherTypes.values()) { - if (type.description.equalsIgnoreCase(name)) { - return type.intValue(); - } - } - return 0; - } - - public static List getEtherTypesNameList() { - List ethertypesList = new ArrayList(); - for (EtherTypes type : EtherTypes.values()) { - ethertypesList.add(type.toString()); - } - return ethertypesList; - } - - public static EtherTypes loadFromString(String string) { - int intType = Integer.parseInt(string); - - for (EtherTypes type : EtherTypes.values()) { - if (type.number == intType) { - return type; - } - } - return null; - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/FilterIterator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/FilterIterator.java deleted file mode 100644 index d0de0be048..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/FilterIterator.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.sal.utils; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * An iterator that will filter values from an iterator and return only those - * values that match the predicate. - */ -@Deprecated -public abstract class FilterIterator implements Iterator { - protected Iterator subIterator; - protected T next; - - /** - * Construct a filter iterator from the given sub iterator - * - * @param subIterator - * the sub iterator over which we'll filter - */ - public FilterIterator(Iterator subIterator) { - super(); - this.subIterator = subIterator; - } - - /** - * Check whether the given value should be returned by the filter - * - * @param value - * the value to check - * @return true if the value should be included - */ - protected abstract boolean matches(T value); - - // *********** - // Iterator - // *********** - - @Override - public boolean hasNext() { - if (next != null) - return true; - - while (subIterator.hasNext()) { - next = subIterator.next(); - if (matches(next)) - return true; - } - next = null; - return false; - } - - @Override - public T next() { - if (hasNext()) { - T cur = next; - next = null; - return cur; - } - throw new NoSuchElementException(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GUIField.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GUIField.java deleted file mode 100644 index 6d69a27a8a..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GUIField.java +++ /dev/null @@ -1,49 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -/** - * GUI field constants - * - * - * - */ -@Deprecated -public enum GUIField { - USER("User"), PASSWORD("Password"), ROLE("Role"), SERVERIP("Server address"), SERVERSECRET( - "Server secret"), SERVERPROTOCOL("Server protocol"), NAME("Name"), CONTAINER( - "Container"), SUBNET("Subnet"), GATEWAYIP("Gateway IP Address/Mask"), NODE( - "Node"), NODEID("Node ID"), NODEMAC("Node MAC Address"), NODENAME( - "Node Name"), SRCNODE("Source Node"), DSTNODE("Destination Node"), SRCPORT( - "Source Port"), DSTPORT("Destination Port"), PORTS("Ports"), NODEPORTS( - "Node/Ports"), SPANPORTS("Span Ports"), TIER("Tier"), MODE("Mode"), INPUTPORT( - "Input Port"), ETHERTYPE("Ether Type"), DLSRCADDRESS("Source MAC"), DLDSTADDRESS( - "Dest MAC"), VLANID("Vlan Id"), VLANPRIO("Vlan Priority"), NWSRCADDRESS( - "Source IP"), NWDSTADDRESS("Dest IP"), NWPROTOCOL("Protocol"), NWPROTOCOLSHORT( - "Proto"), NWTOSBITS("TOS"), TPSRCPORT("Transport Source Port"), TPDSTPORT( - "Transport Dest Port"), TPSRCPORTSHORT("Source L4 Port"), TPDSTPORTSHORT( - "Dest L4 Port"), METRIC("Metric"), STATUS("Status"), TAG("Tag"), TAGS( - "Tags"), STATICVLAN("Static Vlan"), PRIORITY("Priority"), PORTGROUP( - "Port Group"), COOKIE("Cookie"), ACTIONS("Actions"), ACTIVE( - "Active"), IDLETIMEOUT("Idle Time Out"), HARDTIMEOUT( - "Hard Time Out"), INHARDWARE("Install on Switch"), STATICROUTE( - "Static Route"), NEXTHOPTYPE("NextHop Type"), NEXTHOP( - "NextHop address"); - - private GUIField(String name) { - this.name = name; - } - - private String name; - - public String toString() { - return name; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GlobalConstants.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GlobalConstants.java deleted file mode 100644 index 342a99b2d6..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/GlobalConstants.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -/** - * Global Constants - * - */ -@Deprecated -public enum GlobalConstants { - DEFAULT("default"), - CONTAINERMANAGER("containermanager"), - CONTAINERNAME("name"), - STATICVLAN("staticvlan"), - CLUSTERINGSERVICES("clusteringservices"), - STARTUPHOME("configuration/startup/"), - PROTOCOLPLUGINTYPE("protocolPluginType"), - PROTOCOLPLUGINPRIORITY("protocolPluginPriority"); - - private GlobalConstants(String name) { - this.name = name; - } - - private String name; - - public String toString() { - return name; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/HexEncode.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/HexEncode.java deleted file mode 100644 index 4e6b59ed1c..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/HexEncode.java +++ /dev/null @@ -1,115 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.math.BigInteger; - -/** - * The class provides methods to convert hex encode strings - * - * - */ -@Deprecated -public class HexEncode { - /** - * This method converts byte array into String format without ":" inserted. - * - * @param bytes - * The byte array to convert to string - * @return The hexadecimal representation of the byte array. If bytes is - * null, "null" string is returned - */ - public static String bytesToHexString(byte[] bytes) { - - if (bytes == null) { - return "null"; - } - - String ret = ""; - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < bytes.length; i++) { - if (i > 0) { - ret += ":"; - } - short u8byte = (short) (bytes[i] & 0xff); - String tmp = Integer.toHexString(u8byte); - if (tmp.length() == 1) { - buf.append("0"); - } - buf.append(tmp); - } - ret = buf.toString(); - return ret; - } - - public static String longToHexString(long val) { - char arr[] = Long.toHexString(val).toCharArray(); - StringBuffer buf = new StringBuffer(); - // prepend the right number of leading zeros - int i = 0; - for (; i < (16 - arr.length); i++) { - buf.append("0"); - if ((i & 0x01) == 1) { - buf.append(":"); - } - } - for (int j = 0; j < arr.length; j++) { - buf.append(arr[j]); - if ((((i + j) & 0x01) == 1) && (j < (arr.length - 1))) { - buf.append(":"); - } - } - return buf.toString(); - } - - - public static byte[] bytesFromHexString(String values) { - String target = ""; - if (values != null) { - target = values; - } - String[] octets = target.split(":"); - - byte[] ret = new byte[octets.length]; - for (int i = 0; i < octets.length; i++) { - ret[i] = Integer.valueOf(octets[i], 16).byteValue(); - } - return ret; - } - - public static long stringToLong(String values) { - long value = new BigInteger(values.replaceAll(":", ""), 16).longValue(); - return value; - } - - /** - * This method converts byte array into HexString format with ":" inserted. - */ - public static String bytesToHexStringFormat(byte[] bytes) { - if (bytes == null) { - return "null"; - } - String ret = ""; - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < bytes.length; i++) { - if (i > 0) { - buf.append(":"); - } - short u8byte = (short) (bytes[i] & 0xff); - String tmp = Integer.toHexString(u8byte); - if (tmp.length() == 1) { - buf.append("0"); - } - buf.append(tmp); - } - ret = buf.toString(); - return ret; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IListener.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IListener.java deleted file mode 100644 index ae72643ff6..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IListener.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2011 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.sal.utils; - -/** - * This interface defines the methods for callback ordering - * - */ -@Deprecated -public interface IListener { - public enum Command { - CONTINUE, STOP - } - - /** - * The name assigned to this listener - * - * @return the name string - */ - public String getName(); - - /** - * Check if the module called name is a callback ordering prerequisite for - * this module. In other words, if this function returns true for the given - * name, then this listener will be called after that message listener. - * - * @param type - * the object type to which this applies - * @param name - * the name of the module - * @return whether name is a prerequisite. - */ - public boolean isCallbackOrderingPrereq(T type, String name); - - /** - * Check if the module called name is a callback ordering post-requisite for - * this module. In other words, if this function returns true for the given - * name, then this listener will be called before that message listener. - * - * @param type - * the object type to which this applies - * @param name - * the name of the module - * @return whether name is a post-requisite. - */ - public boolean isCallbackOrderingPostreq(T type, String name); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeConnectorFactory.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeConnectorFactory.java deleted file mode 100644 index 5c8076b491..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeConnectorFactory.java +++ /dev/null @@ -1,36 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; - -/** - * This interface defines the methods to be called when looking up custom node types - * - */ -@Deprecated -public interface INodeConnectorFactory { - /** - * Method to get custom NodeConnector types from protocol plugins - * - * @param typeStr - * {@Link - * org.opendaylight.controller.sal.core.NodeConnector} type - * string - * @param IDStr - * {@Link - * org.opendaylight.controller.sal.core.NodeConnector} ID string - * @return the custom {@Link - * org.opendaylight.controller.sal.core.NodeConnector} - */ - public NodeConnector fromStringNoNode(String typeStr, String IDStr, - Node n); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeFactory.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeFactory.java deleted file mode 100644 index 09339f87ce..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/INodeFactory.java +++ /dev/null @@ -1,33 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import org.opendaylight.controller.sal.core.Node; - -/** - * This interface defines the methods to be called when looking up custom node types - * - */ -@Deprecated -public interface INodeFactory { - /** - * Method to get custom node types from protocol plugins - * - * @param nodeType - * {@Link org.opendaylight.controller.sal.core.Node} type - * string - * @param nodeId - * {@Link org.opendaylight.controller.sal.core.Node} ID - * string - * @return the custom {@Link - * org.opendaylight.controller.sal.core.Node} - */ - public Node fromString(String nodeType, String nodeId); -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IObjectReader.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IObjectReader.java deleted file mode 100644 index 4cd1c9f21d..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IObjectReader.java +++ /dev/null @@ -1,30 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.ObjectInputStream; - -/** - * This interface is needed to allow object reconstruction when reading serialized objects from - * inside a package other than the one where ObjectReader is defined (otherwise you hit the - * java.lang.ClassNotFoundException). This interface will allow to deserialize a class from inside - * the package where the class is defined. All the exception handling can still happen in - * ObjectReader and the implementer of IObjectReader only need to throws such exceptions - * - * - * - */ -@Deprecated -public interface IObjectReader { - public Object readObject(ObjectInputStream ois) - throws FileNotFoundException, IOException, ClassNotFoundException; -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IPProtocols.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IPProtocols.java deleted file mode 100644 index dbe74efe1b..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IPProtocols.java +++ /dev/null @@ -1,304 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.util.ArrayList; -import java.util.List; - -/** - * Enum represents the most common IP protocols numbers It provides the binding - * between IP protocol names and numbers and provides APIs to read and parse - * them in either of the two forms - * - * NOTE: Openflow 1.0 supports the IP Proto match only for ICMP, TCP and UDP - * - * references: - * http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml - */ -@Deprecated -public enum IPProtocols { - ANY("any", -1), - HOPOPT("HOPOPT",0), - ICMP("ICMP", 1), - IGMP("IGMP",2), - GGP("GGP",3), - IPV4("IPv4",4), - ST("ST",5), - TCP("TCP", 6), - CBT("CBT",7), - EGP("EGP",8), - IGP("IGP",9), - BBNRCCMON("BBN-RCC-MON",10), - NVPII("NVP-II",11), - PUP("PUP",12), - ARGUS("ARGUS",13), - EMCON("EMCON",14), - XNET("XNET",15), - CHAOS("CHAOS",16), - UDP("UDP", 17), - MUX("MUX",18), - DCNMEAS("DCN-MEAS",19), - HMP("HMP",20), - PRM("PRM",21), - XNSIDP("XNS-IDP",22), - TRUNK1("TRUNK-1",23), - TRUNK2("TRUNK-2",24), - LEAF1("LEAF-1",25), - LEAF2("LEAF-2",26), - RDP("RDP",27), - IRTP("IRTP",28), - ISOTP4("ISO-TP4",29), - NETBLT("NETBLT",30), - MFENSP("MFE-NSP",31), - MERITINP("MERIT-INP",32), - DCCP("DCCP",33), - THREEPC("3PC",34), - IDPR("IDPR",35), - XTP("XTP",36), - DDP("DDP",37), - IDPRCMTP("IDPR-CMTP",38), - TPPLUSPLUS("TP++",39), - IL("IL",40), - IPV6("IPv6",41), - SDRP("SDRP",42), - IPV6Route("IPv6-Route",43), - IPV6Frag("IPv6-Frag",44), - IDRP("IDRP",45), - RSVP("RSVP",46), - GRE("GRE",47), - DSR("DSR",48), - BNA("BNA",49), - ESP("ESP",50), - AH("AH",51), - INLSP("I-NLSP",52), - SWIPE("SWIPE",53), - NARP("NARP",54), - MOBILE("MOBILE",55), - TLSP("TLSP",56), - SKIP("SKIP",57), - IPV6ICMP("IPv6-ICMP", 58), - IPV6NoNxt("IPv6-NoNxt",59), - IPV6Opts("IPv6-Opts",60), - ANYHOST("ANY-HOST",61), - CFTP("CFTP",62), - ANYNETWORK("ANY-NETWORK",63), - SATEXPAK("SAT-EXPAK",64), - KRYPTOLAN("KRYPTOLAN",65), - RVD("RVD",66), - IPPC("IPPC",67), - ANYDISTFS("ANY-DIST-FS",68), - SATMON("SAT-MON",69), - VISA("VISA",70), - IPCV("IPCV",71), - CPNX("CPNX",72), - CPHB("CPHB",73), - WSN("WSN",74), - PVP("PVP",75), - BRSATMON("BR-SAT-MON",76), - SUNND("SUN-ND",77), - WBMON("WB-MON",78), - WBEXPAK("WB-EXPAK",79), - ISOIP("ISO-IP",80), - VMTP("VMTP",81), - SECUREVMTP("SECURE-VMTP",82), - VINES("VINES",83), - TTP("TTP",84), - IPTM("IPTM",84), - NSFNETIGP("NSFNET-IGP",85), - DGP("DGP",86), - TCF("TCF",87), - EIGRP("EIGRP",88), - OSPFIGP("OSPFIGP",89), - SPRITERPC("Sprite-RPC",90), - LARP("LARP",91), - MTP("MTP",92), - AX25("AX.25",93), - IPIP("IPIP",94), - MICP("MICP",95), - SCCSP("SCC-SP",96), - ETHERIP("ETHERIP",97), - ENCAP("ENCAP",98), - ANYENC("ANY-ENC",99), - GMTP("GMTP",100), - IFMP("IFMP",101), - PNNI("PNNI",102), - PIM("PIM",103), - ARIS("ARIS",104), - SCPS("SCPS",105), - QNX("QNX",106), - AN("A/N",107), - IPComp("IPComp",108), - SNP("SNP",109), - COMPAQPEER("Compaq-Peer",110), - IPXINIP("IPX-in-IP",111), - VRRP("VRRP",112), - PGM("PGM",113), - ANY0HOP("ANY-0-HOP",114), - L2TP("L2TP",115), - DDX("DDX",116), - IATP("IATP",117), - STP("STP",118), - SRP("SRP",119), - UTI("UTI",120), - SMP("SMP",121), - SM("SM",122), - PTP("PTP",123), - ISIS("ISIS",124), - FIRE("FIRE",125), - CRTP("CRTP",126), - CRUDP("CRUDP",127), - SSCOPMCE("SSCOPMCE",128), - IPLT("IPLT",129), - SPS("SPS",130), - PIPE("PIPE",131), - SCTP("SCTP",132), - FC("FC",133), - RSVPE2EIGNORE("RSVP-E2E-IGNORE",134), - MOBILITYHEADER("Mobility Header",135), - UDPLITE("UDPLite",136), - MPLSINIP("MPLS-in-IP",137), - MANET("MANET",138), - HIP("HIP",139), - SHIM6("Shim6",140), - WESP("WESP",141), - ROHC("ROHC",142), - /*143-252 Unassigned by IANA*/ - - //Experimebtal protocol numbers (http://tools.ietf.org/html/rfc3692) - EXP1("Experimental1", 253), - EXP2("Experimental2", 254), - - RESERVED("RESERVED",255); - - private String protocolName; - private int protocolNumber; - - private IPProtocols(String name, int number) { - protocolName = name; - protocolNumber = number; - } - - public int intValue() { - return protocolNumber; - } - - public short shortValue() { - return ((Integer) protocolNumber).shortValue(); - } - - public byte byteValue() { - return ((Integer) protocolNumber).byteValue(); - } - - @Override - public String toString() { - return protocolName; - } - - public static String getProtocolName(int number) { - return getProtocolNameInternal(number); - } - - public static String getProtocolName(short number) { - return getProtocolNameInternal(number & 0xffff); - } - - public static String getProtocolName(byte number) { - return getProtocolNameInternal(number & 0xff); - } - - private static String getProtocolNameInternal(int number) { - for (IPProtocols proto : IPProtocols.values()) { - if (proto.protocolNumber == number) { - return proto.toString(); - } - } - //TODO: this is for backwards compatibility - return "0x" + Integer.toHexString(number); - } - - public static short getProtocolNumberShort(String name) { - IPProtocols p = fromString(name); - if (p != null) { - return p.shortValue(); - } - //This method should be called after validation only - throw new IllegalArgumentException("Illegal IP protocol value: " + name); - } - - public static int getProtocolNumberInt(String name) { - IPProtocols p = fromString(name); - if (p != null) { - return p.intValue(); - } - //This method should be called after validation only - throw new IllegalArgumentException("Illegal IP protocol value: " + name); - } - - public static byte getProtocolNumberByte(String name) { - IPProtocols p = fromString(name); - if (p != null) { - return p.byteValue(); - } - //This method should be called after validation only - throw new IllegalArgumentException("Illegal IP protocol value: " + name); - } - - public static List getProtocolNameList() { - List protoList = new ArrayList(); - for (IPProtocols proto : IPProtocols.values()) { - protoList.add(proto.toString()); - } - return protoList; - } - - /** - * Method to parse an IPProtocol from a numeric string - * (see: {@link Java.Lang.Integer.decode(java.lang.String)} for parsable strings), - * or this enum's name string. - * - * @param s - * The IP protocol string to be parsed - * @return The IP protocol Enum, or null if invalid protocol string is passed - */ - public static IPProtocols fromString(String s) { - // null/empty/any/* evaluates to ANY - if (s == null || s.isEmpty() || s.equalsIgnoreCase("any") || s.equals("*")) { - return IPProtocols.ANY; - } - - // Try parsing numeric and find the related ENUM - try { - int protoNum = Integer.decode(s); - for (IPProtocols protoEnum : IPProtocols.values()) { - if (protoEnum.protocolNumber == protoNum) { - return protoEnum; - } - } - // At this point it's an invalid number (i.e. out of range or not a valid proto num) - return null; - } catch (NumberFormatException nfe) { - // numeric failed try by NAME - try { - return valueOf(s); - } catch(IllegalArgumentException e) { - // Neither numeric nor enum NAME, attempt human readable name - for (IPProtocols protoEnum : IPProtocols.values()) { - if (protoEnum.toString().equalsIgnoreCase(s)) { - return protoEnum; - } - } - //couldn't parse, signifies an invalid proto field! - return null; - } - - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IterableIterator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IterableIterator.java deleted file mode 100644 index 8a72028917..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/IterableIterator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.sal.utils; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * Iterator over all values in an iterator of iterators - * - * @param - * the type of elements returned by this iterator - */ -@Deprecated -public class IterableIterator implements Iterator { - Iterator> subIterator; - Iterator current = null; - - public IterableIterator(Iterator> subIterator) { - super(); - this.subIterator = subIterator; - } - - @Override - public boolean hasNext() { - if (current == null) { - if (subIterator.hasNext()) { - current = subIterator.next().iterator(); - } else { - return false; - } - } - while (!current.hasNext() && subIterator.hasNext()) { - current = subIterator.next().iterator(); - } - - return current.hasNext(); - } - - @Override - public T next() { - if (hasNext()) - return current.next(); - throw new NoSuchElementException(); - } - - @Override - public void remove() { - if (hasNext()) - current.remove(); - throw new NoSuchElementException(); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ListenerDispatcher.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ListenerDispatcher.java deleted file mode 100644 index 2a4ea3da60..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ListenerDispatcher.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2011 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.sal.utils; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Maintain lists of listeners ordered by dependency. - * - * @author readams - * - */ -@Deprecated -public class ListenerDispatcher> { - protected static Logger logger = LoggerFactory - .getLogger(ListenerDispatcher.class); - volatile List listeners = new ArrayList(); - - private void visit(List newlisteners, U type, HashSet visited, - List ordering, T listener) { - if (!visited.contains(listener)) { - visited.add(listener); - - for (T i : newlisteners) { - if (ispre(type, i, listener)) { - visit(newlisteners, type, visited, ordering, i); - } - } - ordering.add(listener); - } - } - - private boolean ispre(U type, T l1, T l2) { - return (l2.isCallbackOrderingPrereq(type, l1.getName()) || l1 - .isCallbackOrderingPostreq(type, l2.getName())); - } - - /** - * Add a listener to the list of listeners - * - * @param listener - */ - public void addListener(U type, T listener) { - List newlisteners = new ArrayList(); - if (listeners != null) - newlisteners.addAll(listeners); - - newlisteners.add(listener); - // Find nodes without outgoing edges - List terminals = new ArrayList(); - for (T i : newlisteners) { - boolean isterm = true; - for (T j : newlisteners) { - if (ispre(type, i, j)) { - isterm = false; - break; - } - } - if (isterm) { - terminals.add(i); - } - } - - if (terminals.size() == 0) { - logger.error("No listener dependency solution: " - + "No listeners without incoming dependencies"); - listeners = newlisteners; - return; - } - - // visit depth-first traversing in the opposite order from - // the dependencies. Note we will not generally detect cycles - HashSet visited = new HashSet(); - List ordering = new ArrayList(); - for (T term : terminals) { - visit(newlisteners, type, visited, ordering, term); - } - listeners = ordering; - } - - /** - * Remove the given listener - * - * @param listener - * the listener to remove - */ - public void removeListener(T listener) { - if (listeners != null) { - List newlisteners = new ArrayList(); - newlisteners.addAll(listeners); - newlisteners.remove(listener); - listeners = newlisteners; - } - } - - /** - * Clear all listeners - */ - public void clearListeners() { - listeners = new ArrayList(); - } - - /** - * Get the ordered list of listeners ordered by dependencies - * - * @return - */ - public List getOrderedListeners() { - return listeners; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/MultiIterator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/MultiIterator.java deleted file mode 100644 index fbb40882da..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/MultiIterator.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2012 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.sal.utils; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * Iterator over all values in an iterator of iterators - * - * @param - * the type of elements returned by this iterator - */ -@Deprecated -public class MultiIterator implements Iterator { - Iterator> subIterator; - Iterator current = null; - - public MultiIterator(Iterator> subIterator) { - super(); - this.subIterator = subIterator; - } - - @Override - public boolean hasNext() { - if (current == null) { - if (subIterator.hasNext()) { - current = subIterator.next(); - } else { - return false; - } - } - while (!current.hasNext() && subIterator.hasNext()) { - current = subIterator.next(); - } - - return current.hasNext(); - } - - @Override - public T next() { - if (hasNext()) - return current.next(); - throw new NoSuchElementException(); - } - - @Override - public void remove() { - if (hasNext()) - current.remove(); - throw new NoSuchElementException(); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NetUtils.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NetUtils.java deleted file mode 100644 index 79b17785fa..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NetUtils.java +++ /dev/null @@ -1,522 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Utility class containing the common utility functions needed for operating on - * networking data structures - */ -@Deprecated -public abstract class NetUtils { - protected static final Logger logger = LoggerFactory.getLogger(NetUtils.class); - /** - * Constant holding the number of bits in a byte - */ - public static final int NumBitsInAByte = 8; - - /** - * Constant holding the number of bytes in MAC Address - */ - public static final int MACAddrLengthInBytes = 6; - - /** - * Constant holding the number of words in MAC Address - */ - public static final int MACAddrLengthInWords = 3; - - /** - * Constant holding the broadcast MAC address - */ - private static final byte[] BroadcastMACAddr = {-1, -1, -1, -1, -1, -1}; - - /** - * Converts a 4 bytes array into an integer number - * - * @param ba - * the 4 bytes long byte array - * @return the integer number - */ - public static int byteArray4ToInt(byte[] ba) { - if (ba == null || ba.length != 4) { - return 0; - } - return (0xff & ba[0]) << 24 | (0xff & ba[1]) << 16 | (0xff & ba[2]) << 8 | (0xff & ba[3]); - } - - /** - * Converts a 6 bytes array into a long number MAC addresses. - * - * @param ba - * The 6 bytes long byte array. - * @return The long number. - * Zero is returned if {@code ba} is {@code null} or - * the length of it is not six. - */ - public static long byteArray6ToLong(byte[] ba) { - if (ba == null || ba.length != MACAddrLengthInBytes) { - return 0L; - } - long num = 0L; - int i = 0; - do { - num <<= NumBitsInAByte; - num |= 0xff & ba[i]; - i++; - } while (i < MACAddrLengthInBytes); - return num; - } - - /** - * Converts a long number to a 6 bytes array for MAC addresses. - * - * @param addr - * The long number. - * @return The byte array. - */ - public static byte[] longToByteArray6(long addr){ - byte[] mac = new byte[MACAddrLengthInBytes]; - int i = MACAddrLengthInBytes - 1; - do { - mac[i] = (byte) addr; - addr >>>= NumBitsInAByte; - i--; - } while (i >= 0); - return mac; - } - - /** - * Converts an integer number into a 4 bytes array - * - * @param i - * the integer number - * @return the byte array - */ - public static byte[] intToByteArray4(int i) { - return new byte[] { (byte) ((i >> 24) & 0xff), (byte) ((i >> 16) & 0xff), (byte) ((i >> 8) & 0xff), - (byte) (i & 0xff) }; - } - - /** - * Converts an IP address passed as integer value into the respective - * InetAddress object - * - * @param address - * the IP address in integer form - * @return the IP address in InetAddress form - */ - public static InetAddress getInetAddress(int address) { - InetAddress ip = null; - try { - ip = InetAddress.getByAddress(NetUtils.intToByteArray4(address)); - } catch (UnknownHostException e) { - logger.error("", e); - } - return ip; - } - - /** - * Return the InetAddress Network Mask given the length of the prefix bit - * mask. The prefix bit mask indicates the contiguous leading bits that are - * NOT masked out. Example: A prefix bit mask length of 8 will give an - * InetAddress Network Mask of 255.0.0.0 - * - * @param prefixMaskLength - * integer representing the length of the prefix network mask - * @param isV6 - * boolean representing the IP version of the returned address - * @return - */ - public static InetAddress getInetNetworkMask(int prefixMaskLength, boolean isV6) { - if (prefixMaskLength < 0 || (!isV6 && prefixMaskLength > 32) || (isV6 && prefixMaskLength > 128)) { - return null; - } - byte v4Address[] = { 0, 0, 0, 0 }; - byte v6Address[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - byte address[] = (isV6) ? v6Address : v4Address; - int numBytes = prefixMaskLength / 8; - int numBits = prefixMaskLength % 8; - int i = 0; - for (; i < numBytes; i++) { - address[i] = (byte) 0xff; - } - if (numBits > 0) { - int rem = 0; - for (int j = 0; j < numBits; j++) { - rem |= 1 << (7 - j); - } - address[i] = (byte) rem; - } - - try { - return InetAddress.getByAddress(address); - } catch (UnknownHostException e) { - logger.error("", e); - } - return null; - } - - /** - * Returns the prefix size in bits of the specified subnet mask. Example: - * For the subnet mask ff.ff.ff.e0 it returns 25 while for ff.00.00.00 it - * returns 8. If the passed subnetMask array is null, 0 is returned. - * - * @param subnetMask - * the subnet mask as byte array - * @return the prefix length as number of bits - */ - public static int getSubnetMaskLength(byte[] subnetMask) { - int maskLength = 0; - if (subnetMask != null && (subnetMask.length == 4 || subnetMask.length == 16)) { - int index = 0; - while (index < subnetMask.length && subnetMask[index] == (byte) 0xFF) { - maskLength += NetUtils.NumBitsInAByte; - index++; - } - if (index != subnetMask.length) { - int bits = NetUtils.NumBitsInAByte - 1; - while (bits >= 0 && (subnetMask[index] & 1 << bits) != 0) { - bits--; - maskLength++; - } - } - } - return maskLength; - } - - /** - * Returns the prefix size in bits of the specified subnet mask. Example: - * For the subnet mask 255.255.255.128 it returns 25 while for 255.0.0.0 it - * returns 8. If the passed subnetMask object is null, 0 is returned - * - * @param subnetMask - * the subnet mask as InetAddress - * @return the prefix length as number of bits - */ - public static int getSubnetMaskLength(InetAddress subnetMask) { - return subnetMask == null ? 0 : NetUtils.getSubnetMaskLength(subnetMask.getAddress()); - } - - /** - * Given an IP address and a prefix network mask length, it returns the - * equivalent subnet prefix IP address Example: for ip = "172.28.30.254" and - * maskLen = 25 it will return "172.28.30.128" - * - * @param ip - * the IP address in InetAddress form - * @param maskLen - * the length of the prefix network mask - * @return the subnet prefix IP address in InetAddress form - */ - public static InetAddress getSubnetPrefix(InetAddress ip, int maskLen) { - int bytes = maskLen / 8; - int bits = maskLen % 8; - byte modifiedByte; - byte[] sn = ip.getAddress(); - if (bits > 0) { - modifiedByte = (byte) (sn[bytes] >> (8 - bits)); - sn[bytes] = (byte) (modifiedByte << (8 - bits)); - bytes++; - } - for (; bytes < sn.length; bytes++) { - sn[bytes] = (byte) (0); - } - try { - return InetAddress.getByAddress(sn); - } catch (UnknownHostException e) { - return null; - } - } - - /** - * Checks if the test address and mask conflicts with the filter address and - * mask - * - * For example: - * testAddress: 172.28.2.23 - * testMask: 255.255.255.0 - * filterAddress: 172.28.1.10 - * testMask: 255.255.255.0 - * do conflict - * - * testAddress: 172.28.2.23 - * testMask: 255.255.255.0 - * filterAddress: 172.28.1.10 - * testMask: 255.255.0.0 - * do not conflict - * - * Null parameters are permitted - * - * @param testAddress - * @param filterAddress - * @param testMask - * @param filterMask - * @return - */ - public static boolean inetAddressConflict(InetAddress testAddress, InetAddress filterAddress, InetAddress testMask, - InetAddress filterMask) { - // Sanity check - if ((testAddress == null) || (filterAddress == null)) { - return false; - } - - // Presence check - if (isAny(testAddress) || isAny(filterAddress)) { - return false; - } - - int testMaskLen = (testMask == null) ? ((testAddress instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength(testMask); - int filterMaskLen = (filterMask == null) ? ((testAddress instanceof Inet4Address) ? 32 : 128) : NetUtils - .getSubnetMaskLength(filterMask); - - // Mask length check. Test mask has to be more specific than filter one - if (testMaskLen < filterMaskLen) { - return true; - } - - // Subnet Prefix on filter mask length must be the same - InetAddress prefix1 = getSubnetPrefix(testAddress, filterMaskLen); - InetAddress prefix2 = getSubnetPrefix(filterAddress, filterMaskLen); - return (!prefix1.equals(prefix2)); - } - - /** - * Returns true if the passed MAC address is all zero - * - * @param mac - * the byte array representing the MAC address - * @return true if all MAC bytes are zero - */ - public static boolean isZeroMAC(byte[] mac) { - for (short i = 0; i < 6; i++) { - if (mac[i] != 0) { - return false; - } - } - return true; - } - - /** - * Returns true if the MAC address is the broadcast MAC address and false - * otherwise. - * - * @param MACAddress - * @return - */ - public static boolean isBroadcastMACAddr(byte[] MACAddress) { - if (MACAddress.length == MACAddrLengthInBytes) { - for (int i = 0; i < 6; i++) { - if (MACAddress[i] != BroadcastMACAddr[i]) { - return false; - } - } - return true; - } - - return false; - } - /** - * Returns true if the MAC address is a unicast MAC address and false - * otherwise. - * - * @param MACAddress - * @return - */ - public static boolean isUnicastMACAddr(byte[] MACAddress) { - if (MACAddress.length == MACAddrLengthInBytes) { - return (MACAddress[0] & 1) == 0; - } - return false; - } - - /** - * Returns true if the MAC address is a multicast MAC address and false - * otherwise. Note that this explicitly returns false for the broadcast MAC - * address. - * - * @param MACAddress - * @return - */ - public static boolean isMulticastMACAddr(byte[] MACAddress) { - if (MACAddress.length == MACAddrLengthInBytes && !isBroadcastMACAddr(MACAddress)) { - return (MACAddress[0] & 1) != 0; - } - return false; - } - - /** - * Returns true if the passed InetAddress contains all zero - * - * @param ip - * the IP address to test - * @return true if the address is all zero - */ - public static boolean isAny(InetAddress ip) { - for (byte b : ip.getAddress()) { - if (b != 0) { - return false; - } - } - return true; - } - - public static boolean fieldsConflict(int field1, int field2) { - if ((field1 == 0) || (field2 == 0) || (field1 == field2)) { - return false; - } - return true; - } - - public static InetAddress parseInetAddress(String addressString) { - InetAddress address = null; - try { - address = InetAddress.getByName(addressString); - } catch (UnknownHostException e) { - logger.error("", e); - } - return address; - } - - /** - * Checks if the passed IP v4 address in string form is valid The address - * may specify a mask at the end as "/MM" - * - * @param cidr - * the v4 address as A.B.C.D/MM - * @return - */ - public static boolean isIPv4AddressValid(String cidr) { - if (cidr == null) { - return false; - } - - String values[] = cidr.split("/"); - Pattern ipv4Pattern = Pattern - .compile("(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])"); - Matcher mm = ipv4Pattern.matcher(values[0]); - if (!mm.matches()) { - return false; - } - if (values.length >= 2) { - int prefix = Integer.valueOf(values[1]); - if ((prefix < 0) || (prefix > 32)) { - return false; - } - } - return true; - } - - /** - * Checks if the passed IP v6 address in string form is valid The address - * may specify a mask at the end as "/MMM" - * - * @param cidr - * the v6 address as A::1/MMM - * @return - */ - public static boolean isIPv6AddressValid(String cidr) { - if (cidr == null) { - return false; - } - - String values[] = cidr.split("/"); - try { - // when given an IP address, InetAddress.getByName validates the ip - // address - InetAddress addr = InetAddress.getByName(values[0]); - if (!(addr instanceof Inet6Address)) { - return false; - } - } catch (UnknownHostException ex) { - return false; - } - - if (values.length >= 2) { - int prefix = Integer.valueOf(values[1]); - if ((prefix < 0) || (prefix > 128)) { - return false; - } - } - return true; - } - - /** - * Checks if the passed IP address in string form is a valid v4 or v6 - * address. The address may specify a mask at the end as "/MMM" - * - * @param cidr - * the v4 or v6 address as IP/MMM - * @return - */ - public static boolean isIPAddressValid(String cidr) { - return NetUtils.isIPv4AddressValid(cidr) || NetUtils.isIPv6AddressValid(cidr); - } - - /* - * Following utilities are useful when you need to compare or bit shift java - * primitive type variable which are inherently signed - */ - /** - * Returns the unsigned value of the passed byte variable - * - * @param b - * the byte value - * @return the int variable containing the unsigned byte value - */ - public static int getUnsignedByte(byte b) { - return b & 0xFF; - } - - /** - * Return the unsigned value of the passed short variable - * - * @param s - * the short value - * @return the int variable containing the unsigned short value - */ - public static int getUnsignedShort(short s) { - return s & 0xFFFF; - } - - /** - * Returns the highest v4 or v6 InetAddress - * - * @param v6 - * true for IPv6, false for Ipv4 - * @return The highest IPv4 or IPv6 address - */ - public static InetAddress gethighestIP(boolean v6) { - try { - return (v6) ? InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") : InetAddress - .getByName("255.255.255.255"); - } catch (UnknownHostException e) { - return null; - } - } - - /** - * Returns Broadcast MAC Address - * - * @return the byte array containing broadcast mac address - */ - public static byte[] getBroadcastMACAddr() { - return Arrays.copyOf(BroadcastMACAddr, BroadcastMACAddr.length); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeConnectorCreator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeConnectorCreator.java deleted file mode 100644 index df57e0e170..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeConnectorCreator.java +++ /dev/null @@ -1,113 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.util.HashSet; -import java.util.Set; - -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Node.NodeIDType; -import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class provides helper functions to create a node connector - * - * - */ -@Deprecated -public abstract class NodeConnectorCreator { - protected static final Logger logger = LoggerFactory - .getLogger(NodeConnectorCreator.class); - /** - * Generic NodeConnector creator - * The nodeConnector type is inferred from the node type - * - * @param portId - * @param node - * @return - */ - public static NodeConnector createNodeConnector(Object portId, Node node) { - if (node.getType().equals(NodeIDType.OPENFLOW)) { - try { - return new NodeConnector(NodeConnectorIDType.OPENFLOW, - portId, node); - } catch (ConstructionException e1) { - logger.error("",e1); - return null; - } - } - return null; - } - - /** - * Generic NodeConnector creator - * The nodeConnector type is inferred from the node type - * - * @param portId The string representing the port id - * @param node The network node as {@link org.opendaylight.controller.sal.core.Node Node} object - * @return The corresponding {@link org.opendaylight.controller.sal.core.NodeConnector NodeConnector} object - */ - public static NodeConnector createNodeConnector(String portId, Node node) { - return NodeConnector.fromString(String.format("%s|%s@%s", node.getType(), portId, node.toString())); - } - - /** - * NodeConnector creator where NodeConnector type can be specified - * Needed to create special internal node connectors (like software stack) - * - * @param nodeConnectorType - * @param portId - * @param node - * @return - */ - public static NodeConnector createNodeConnector( - String nodeConnectorType, Object portId, Node node) { - try { - if (nodeConnectorType.equals(Node.NodeIDType.OPENFLOW) && (portId.getClass() == String.class)) { - return new NodeConnector(nodeConnectorType, Short.parseShort((String) portId), node); - } else { - return new NodeConnector(nodeConnectorType, portId, node); - } - } catch (ConstructionException e1) { - logger.error("",e1); - return null; - } - } - - public static NodeConnector createOFNodeConnector(Short portId, Node node) { - try { - return new NodeConnector(NodeConnectorIDType.OPENFLOW, portId, node); - } catch (ConstructionException e1) { - logger.error("",e1); - return null; - } - } - - public static Set createOFNodeConnectorSet( - Set portIds, Node n) { - try { - Set nodeConnectors = new HashSet(); - for (Short ofPortID : portIds) { - NodeConnector p = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, Short - .valueOf(ofPortID), n); - nodeConnectors.add(p); - } - return nodeConnectors; - } catch (ConstructionException e1) { - logger.error("",e1); - return null; - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeCreator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeCreator.java deleted file mode 100644 index 3e4339a4f2..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeCreator.java +++ /dev/null @@ -1,36 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.Node.NodeIDType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Utility class for creating a Node object - * - * - * - */ -@Deprecated -public abstract class NodeCreator { - protected static final Logger logger = LoggerFactory.getLogger(NodeCreator.class); - - public static Node createOFNode(Long switchId) { - try { - return new Node(NodeIDType.OPENFLOW, switchId); - } catch (ConstructionException e1) { - logger.error("",e1); - return null; - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeTableCreator.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeTableCreator.java deleted file mode 100644 index d6793d78f4..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/NodeTableCreator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.utils; - -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.core.NodeTable.NodeTableIDType; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -@Deprecated -public class NodeTableCreator { - protected static final Logger logger = LoggerFactory - .getLogger(NodeTableCreator.class); - - /** - * Generic NodeTable creator - * The nodeTable type is OPENFLOW only for the time being - * - * @param portId - * @param node - * @return - */ - public static NodeTable createNodeTable(byte tableId, Node node) { - try { - return new NodeTable(NodeTableIDType.OPENFLOW, tableId, node); - } catch (ConstructionException e1) { - logger.error("",e1); - return null; - } - } - - public static NodeTable createOFNodeTable(byte tableId, Node node) { - try { - return new NodeTable(NodeTableIDType.OPENFLOW, tableId, node); - } catch (ConstructionException e1) { - logger.error("",e1); - return null; - } - } - -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectReader.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectReader.java deleted file mode 100644 index 042e71e8e3..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectReader.java +++ /dev/null @@ -1,69 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.ObjectInputStream; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Read object to read from file stream - * - * - * - */ -@Deprecated -public class ObjectReader { - private static Logger logger = LoggerFactory.getLogger(ObjectReader.class); - private FileInputStream fis; - public ObjectInputStream ois; - - public ObjectReader() { - fis = null; - ois = null; - } - - public Object read(IObjectReader reader, String file) { - Object obj = null; - try { - fis = new FileInputStream(file); - ois = new ObjectInputStream(fis); - obj = reader.readObject(ois); - } catch (FileNotFoundException fnfex) { - //logger.info("Cannot find {} for reading", file); - } catch (IOException ioex) { - logger.error("Failed to read from {}", file); - } catch (ClassNotFoundException cnfex) { - logger.error("Failed to interpret content of {}", file); - } catch (Exception e) { - - } finally { - if (ois != null) { - try { - ois.close(); - } catch (IOException ioex) { - logger.error("Failed to close object input stream: {}", - file); - } - } - if (fis != null) { - try { - fis.close(); - } catch (IOException ioex) { - logger.error("Failed to close input file stream: {}", file); - } - } - } - return obj; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectWriter.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectWriter.java deleted file mode 100644 index 22a83caa5a..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ObjectWriter.java +++ /dev/null @@ -1,67 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Write object to write to file stream - * - */ -@Deprecated -public class ObjectWriter { - private static Logger logger = LoggerFactory.getLogger(ObjectWriter.class); - private FileOutputStream fos; - private ObjectOutputStream oos; - - public ObjectWriter() { - fos = null; - oos = null; - } - - public Status write(Object obj, String file) { - try { - fos = new FileOutputStream(file); - oos = new ObjectOutputStream(fos); - oos.writeObject(obj); - } catch (FileNotFoundException fex) { - logger.error("Cannot create {} for writing", file); - return new Status(StatusCode.INTERNALERROR, "IO Error"); - } catch (IOException ioex) { - logger.error("Failed to write to {}", file); - return new Status(StatusCode.INTERNALERROR, "IO Error"); - } finally { - if (oos != null) { - try { - oos.close(); - } catch (IOException ioex) { - logger.error("Failed to close object output stream: {}", - file); - } - } - if (fos != null) { - try { - fos.close(); - } catch (IOException ioex) { - logger - .error("Failed to close output file stream: {}", - file); - } - } - } - return new Status(StatusCode.SUCCESS); - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ReadFromFile.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ReadFromFile.java deleted file mode 100644 index 8ec3f8a3d8..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ReadFromFile.java +++ /dev/null @@ -1,58 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.io.BufferedReader; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; - -/** - * Convenience object for reading from file - * - * - * - */ -@Deprecated -public class ReadFromFile { - private FileInputStream fileStream; - private File filePointer; - - public ReadFromFile(String fileName) throws FileNotFoundException { - fileStream = new FileInputStream(fileName); - filePointer = new File(fileName); //needed to allow file deletion - } - - public ArrayList readFile() throws IOException { - DataInputStream dataInput = new DataInputStream(this.fileStream); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInput)); - - ArrayList lineList = new ArrayList(); - String line; - while ((line = bufferedReader.readLine()) != null) { - lineList.add(line); - } - bufferedReader.close(); - dataInput.close(); - fileStream.close(); - return lineList; - } - - public boolean delete() { - if (filePointer == null) { - return true; - } - return filePointer.delete(); - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ServiceHelper.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ServiceHelper.java deleted file mode 100644 index 95aa6830c3..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/ServiceHelper.java +++ /dev/null @@ -1,262 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file ServiceHelper.java - * - * @brief The class helps to register and retrieve OSGi service registry - */ -package org.opendaylight.controller.sal.utils; - -import java.util.Hashtable; -import org.osgi.framework.ServiceRegistration; -import java.util.Dictionary; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class helps to register and retrieve OSGi service registry - * - * - */ -@Deprecated -public class ServiceHelper { - private static final Logger logger = LoggerFactory - .getLogger(ServiceHelper.class); - - /** - * Register a Service in the OSGi service registry - * - * @param clazz The target class - * @param containerName The container name - * @param instance of the object exporting the service, be careful - * the object must implement/extend clazz else the registration - * will fail unless a ServiceFactory is passed as parameter - * @param properties The properties to be attached to the service - * registration - * @return true if registration happened, false otherwise - */ - public static boolean registerService(Class clazz, String containerName, - Object instance, Dictionary properties) { - if (properties == null) { - properties = (Dictionary) new Hashtable(); - } - properties.put("containerName", containerName); - return registerGlobalService(clazz, instance, properties); - } - - /** - * Register a Global Service in the OSGi service registry - * - * @param clazz The target class - * @param instance of the object exporting the service, be careful - * the object must implement/extend clazz else the registration - * will fail unless a ServiceFactory is passed as parameter - * @param properties The properties to be attached to the service - * registration - * @return true if registration happened, false otherwise - */ - public static boolean registerGlobalService(Class clazz, - Object instance, - Dictionary properties) { - ServiceRegistration registration = registerGlobalServiceWReg(clazz, instance, properties); - if (registration == null) { - logger.error("Failed to register {} for instance {}", clazz, instance); - return false; - } - return true; - } - - /** - * Register a Service in the OSGi service registry and return the ServiceRegistration - * - * @param clazz The target class - * @param containerName The container name - * @param instance of the object exporting the service, be careful - * the object must implement/extend clazz else the registration - * will fail unless a ServiceFactory is passed as parameter - * @param properties The properties to be attached to the service - * registration - * @return the ServiceRegistration if registration happened, null otherwise - */ - public static ServiceRegistration registerServiceWReg(Class clazz, String containerName, - Object instance, Dictionary properties) { - if (properties == null) { - properties = (Dictionary) new Hashtable(); - } - properties.put("containerName", containerName); - return registerGlobalServiceWReg(clazz, instance, properties); - } - - /** - * Register a Global Service in the OSGi service registry - * - * @param clazz The target class - * @param instance of the object exporting the service, be careful - * the object must implement/extend clazz else the registration - * will fail unless a ServiceFactory is passed as parameter - * @param properties The properties to be attached to the service - * registration - * @return the ServiceRegistration if registration happened, null otherwise - */ - public static ServiceRegistration registerGlobalServiceWReg(Class clazz, - Object instance, - Dictionary properties) { - try { - BundleContext bCtx = FrameworkUtil.getBundle(instance.getClass()).getBundleContext(); - if (bCtx == null) { - logger.error("Could not retrieve the BundleContext"); - return null; - } - - ServiceRegistration registration = bCtx.registerService(clazz.getName(), instance, properties); - return registration; - } catch (Exception e) { - logger.error("Exception {} while registering the service {}", - e.getMessage(), instance.toString()); - } - return null; - } - - /** - * Retrieve instance of a class via OSGI registry, if there - * are many only the first is returned. - * - * @param clazz The target class - * @param containerName The container name - * @param bundle The caller - */ - public static Object getInstance(Class clazz, String containerName, - Object bundle) { - // Back-end convention: Container id in lower case. Let's enforce it here - return getInstance(clazz, containerName.toLowerCase(), bundle, null); - } - - /** - * Retrieve global instance of a class via OSGI registry, if - * there are many only the first is returned. - * - * @param clazz The target class - * @param bundle The caller - */ - public static Object getGlobalInstance(Class clazz, Object bundle) { - return getGlobalInstance(clazz, bundle, null); - } - - /** - * Retrieve instance of a class via OSGI registry, if there - * are many only the first is returned. On this version an LDAP - * type of filter is applied - * - * @param clazz The target class - * @param containerName The container name - * @param bundle The caller - * @param serviceFilter LDAP filter to be applied in the search - */ - public static Object getInstance(Class clazz, String containerName, - Object bundle, String serviceFilter) { - Object[] instances = getInstances(clazz, containerName, bundle, - serviceFilter); - if (instances != null) { - return instances[0]; - } - return null; - } - - /** - * Retrieve global instance of a class via OSGI registry, if - * there are many only the first is returned. On this version an LDAP - * type of filter is applied - * - * @param clazz The target class - * @param bundle The caller - * @param serviceFilter LDAP filter to be applied in the search - */ - public static Object getGlobalInstance(Class clazz, Object bundle, - String serviceFilter) { - Object[] instances = getGlobalInstances(clazz, bundle, serviceFilter); - if (instances != null) { - return instances[0]; - } - return null; - } - - /** - * Retrieve all the Instances of a Service, optionally - * filtered via serviceFilter if non-null else all the results are - * returned if null - * - * @param clazz The target class - * @param containerName The container name - * @param bundle The caller - * @param serviceFilter LDAP filter to be applied in the search - */ - public static Object[] getInstances(Class clazz, String containerName, - Object bundle, String serviceFilter) { - Object instances[] = null; - try { - BundleContext bCtx = FrameworkUtil.getBundle(bundle.getClass()) - .getBundleContext(); - - ServiceReference[] services = null; - if (serviceFilter != null) { - services = bCtx.getServiceReferences(clazz.getName(), - "(&(containerName=" + containerName + ")" - + serviceFilter + ")"); - } else { - services = bCtx.getServiceReferences(clazz.getName(), - "(containerName=" + containerName + ")"); - } - - if (services != null) { - instances = new Object[services.length]; - for (int i = 0; i < services.length; i++) { - instances[i] = bCtx.getService(services[i]); - } - } - } catch (Exception e) { - logger.error("Instance reference is NULL"); - } - return instances; - } - - /** - * Retrieve all the Instances of a Service, optionally - * filtered via serviceFilter if non-null else all the results are - * returned if null - * - * @param clazz The target class - * @param bundle The caller - * @param serviceFilter LDAP filter to be applied in the search - */ - public static Object[] getGlobalInstances(Class clazz, Object bundle, - String serviceFilter) { - Object instances[] = null; - try { - BundleContext bCtx = FrameworkUtil.getBundle(bundle.getClass()) - .getBundleContext(); - - ServiceReference[] services = bCtx.getServiceReferences(clazz - .getName(), serviceFilter); - - if (services != null) { - instances = new Object[services.length]; - for (int i = 0; i < services.length; i++) { - instances[i] = bCtx.getService(services[i]); - } - } - } catch (Exception e) { - logger.error("Instance reference is NULL"); - } - return instances; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/SingletonTask.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/SingletonTask.java deleted file mode 100644 index 664beff460..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/SingletonTask.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (c) 2011,2013 Big Switch Networks, Inc. - * - * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html - * - * 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. - * - * This file incorporates work covered by the following copyright and - * permission notice: - * - * Originally created by David Erickson, Stanford University - * - * Licensed 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.opendaylight.controller.sal.utils; - -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This allows you to represent a task that should be queued for future - * execution but where you only want the task to complete once in response to - * some sequence of events. For example, if you get a change notification and - * want to reload state, you only want to reload the state once, at the end, and - * don't want to queue an update for every notification that might come in. - * - * The semantics are as follows: * If the task hasn't begun yet, do not queue a - * new task * If the task has begun, set a bit to restart it after the current - * task finishes - */ -@Deprecated -public class SingletonTask { - protected static Logger logger = LoggerFactory - .getLogger(SingletonTask.class); - - protected static class SingletonTaskContext { - protected boolean taskShouldRun = false; - protected boolean taskRunning = false; - - protected SingletonTaskWorker waitingTask = null; - } - - protected static class SingletonTaskWorker implements Runnable { - SingletonTask parent; - boolean canceled = false; - long nextschedule = 0; - - public SingletonTaskWorker(SingletonTask parent) { - super(); - this.parent = parent; - } - - @Override - public void run() { - synchronized (parent.context) { - if (canceled || !parent.context.taskShouldRun) - return; - - parent.context.taskRunning = true; - parent.context.taskShouldRun = false; - } - - try { - parent.task.run(); - } catch (Exception e) { - logger.error("Exception while executing task", e); - } - - synchronized (parent.context) { - parent.context.taskRunning = false; - - if (parent.context.taskShouldRun) { - long now = System.nanoTime(); - if ((nextschedule <= 0 || (nextschedule - now) <= 0)) { - parent.ses.execute(this); - } else { - parent.ses.schedule(this, nextschedule - now, - TimeUnit.NANOSECONDS); - } - } - } - } - } - - protected SingletonTaskContext context = new SingletonTaskContext(); - protected Runnable task; - protected ScheduledExecutorService ses; - - /** - * Construct a new SingletonTask for the given runnable. The context is used - * to manage the state of the task execution and can be shared by more than - * one instance of the runnable. - * - * @param context - * @param Task - */ - public SingletonTask(ScheduledExecutorService ses, Runnable task) { - super(); - this.task = task; - this.ses = ses; - } - - /** - * Schedule the task to run if there's not already a task scheduled If there - * is such a task waiting that has not already started, it cancel that task - * and reschedule it to run at the given time. If the task is already - * started, it will cause the task to be rescheduled once it completes to - * run after delay from the time of reschedule. - * - * @param delay - * the delay in scheduling - * @param unit - * the timeunit of the delay - */ - public void reschedule(long delay, TimeUnit unit) { - boolean needQueue = true; - SingletonTaskWorker stw = null; - - synchronized (context) { - if (context.taskRunning || context.taskShouldRun) { - if (context.taskRunning) { - // schedule to restart at the right time - if (delay > 0) { - long now = System.nanoTime(); - long then = now - + TimeUnit.NANOSECONDS.convert(delay, unit); - context.waitingTask.nextschedule = then; - } else { - context.waitingTask.nextschedule = 0; - } - needQueue = false; - } else { - // cancel and requeue - context.waitingTask.canceled = true; - context.waitingTask = null; - } - } - - context.taskShouldRun = true; - - if (needQueue) { - stw = context.waitingTask = new SingletonTaskWorker(this); - } - } - - if (needQueue) { - if (delay <= 0) { - ses.execute(stw); - } - else { - ses.schedule(stw, delay, unit); - } - } - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Status.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Status.java deleted file mode 100644 index 44d1c5736a..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/Status.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.io.Serializable; - -/** - * Represents the return object of the osgi service interfaces function calls. - * It contains a code {@code StatusCode} representing the result of the call and - * a string which describes a failure reason (if any) in human readable form. - */ -@Deprecated -public class Status implements Serializable { - private static final long serialVersionUID = 0L; - private StatusCode code; - private String description; - private long requestId; - - /** - * Generates an instance of the Status class. This is used as return code - * for internal API2 function calls. This constructor allows to specify, - * beside the Status Code, a custom human readable description to add more - * information about the status. - * - * @param errorCode - * The status code. If passed as null, code will be stored as - * {@code StatusCode.UNDEFINED} - * @param description - * The human readable description of the status. If passed as - * null, description will be inferred by the code - */ - public Status(StatusCode errorCode, String description) { - this.code = (errorCode != null) ? errorCode : StatusCode.UNDEFINED; - this.description = (description != null) ? description : this.code - .toString(); - this.requestId = 0; - } - - /** - * Generates an instance of the Status class based on the passed StatusCode - * only. The description field of the Status object will be inferred by the - * status code. - * - * @param errorCode - * The status code. If passed as null, code will be stored as - * {@code StatusCode.UNDEFINED} - */ - public Status(StatusCode errorCode) { - this.code = (errorCode != null) ? errorCode : StatusCode.UNDEFINED; - this.description = (description != null) ? description : this.code - .toString(); - this.requestId = 0; - } - - /** - * Generates an instance of the Status class to be used in case of - * asynchronous call. It is supposed to be created by the underlying - * infrastructure only when it was successful in allocating the asynchronous - * request id, hence caller should expect StatusCode to be successful. - * - * @param errorCode - * The status code. If passed as null, code will be stored as - * {@code StatusCode.UNDEFINED} - * @param requestId - * The request id set by underlying infrastructure for this - * request - */ - public Status(StatusCode errorCode, long requestId) { - this.code = (errorCode != null) ? errorCode : StatusCode.UNDEFINED; - this.description = (description != null) ? description : this.code - .toString(); - this.requestId = requestId; - } - - /** - * Returns the status code - * - * @return the {@code StatusCode} representing the status code - */ - public StatusCode getCode() { - return code; - } - - /** - * Returns a human readable description of the failure if any - * - * @return a string representing the reason of failure - */ - public String getDescription() { - return description; - } - - /** - * Tells whether the status is successful - * - * @return true if the Status code is {@code StatusCode.SUCCESS} - */ - public boolean isSuccess() { - return code == StatusCode.SUCCESS || code == StatusCode.CREATED; - } - - /** - * Return the request id assigned by underlying infrastructure in case of - * asynchronous request. In case of synchronous requests, the returned id - * is expected to be 0 - * - * @return The request id assigned for this asynchronous request - */ - public long getRequestId() { - return requestId; - } - - @Override - public String toString() { - return code + ": " + description + " (" + requestId + ")"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((code == null) ? 0 : code.calculateConsistentHashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Status other = (Status) obj; - if (code != other.code) { - return false; - } - return true; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/StatusCode.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/StatusCode.java deleted file mode 100644 index 81f0b76b95..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/StatusCode.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -/** - * The enum which describes the generic error conditions. - * Each enum value is associated with a minimal description string. - * - */ -@Deprecated -public enum StatusCode { - SUCCESS("Success"), - CREATED("Created"), - - BADREQUEST("Bad Request"), - UNAUTHORIZED("UnAuthorized"), - FORBIDDEN("Forbidden"), - NOTFOUND("Not Found"), - NOTALLOWED("Method Not Allowed"), - NOTACCEPTABLE("Request Not Acceptable"), - TIMEOUT("Request Timeout"), - CONFLICT("Resource Conflict"), - GONE("Resource Gone"), - UNSUPPORTED("Unsupported"), - - INTERNALERROR("Internal Error"), - NOTIMPLEMENTED("Not Implemented"), - NOSERVICE("Service Not Available"), - - UNDEFINED("Undefined Error"); - - private String description; - private StatusCode(String description) { - this.description = description; - } - - /** - * Prints the description associated to the code value - */ - @Override - public String toString() { - return description; - } - - public int calculateConsistentHashCode() { - if (this.description != null) { - return this.description.hashCode(); - } else { - return 0; - } - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/TierHelper.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/TierHelper.java deleted file mode 100644 index c1ce6f49f0..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/TierHelper.java +++ /dev/null @@ -1,51 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.util.ArrayList; -import java.util.List; -@Deprecated -public final class TierHelper { - private static TierHelper tierHelper; - public static final int unknownTierNumber = 0; - private List tierNames; - - static { - tierHelper = new TierHelper(); - } - - private TierHelper() { - tierNames = new ArrayList(); - tierNames.add("Unknown"); - tierNames.add("Access"); - tierNames.add("Distribution"); - tierNames.add("Core"); - } - - public static void setTierName(int tier, String name) { - if (tier > tierHelper.tierNames.size() - 1) { - for (int i = tierHelper.tierNames.size() - 1; i < tier; i++) { - tierHelper.tierNames.add("Unknown"); - } - } - tierHelper.tierNames.set(tier, name); - } - - public static String getTierName(int tier) { - if ((tier < 0) || (tier > tierHelper.tierNames.size() - 1)) { - return "Unknown"; - } - return tierHelper.tierNames.get(tier); - } - - public static List getTiers() { - return tierHelper.tierNames; - } -} diff --git a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/WriteToFile.java b/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/WriteToFile.java deleted file mode 100644 index 6b109bab8d..0000000000 --- a/opendaylight/adsal/sal/api/src/main/java/org/opendaylight/controller/sal/utils/WriteToFile.java +++ /dev/null @@ -1,59 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.io.BufferedWriter; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Convenience object to write a file - * - * - * - */ -@Deprecated -public class WriteToFile { - protected static final Logger logger = LoggerFactory - .getLogger(WriteToFile.class); - private FileWriter fstream; - private BufferedWriter bufferOut; - - public WriteToFile(String fileName) throws IOException { - fstream = new FileWriter(fileName); - bufferOut = new BufferedWriter(fstream); - } - - public void save(ArrayList entryList) throws IOException { - for (String entry : entryList) { - bufferOut.write(entry); - bufferOut.append('\n'); - } - try { - this.bufferOut.flush(); - } catch (IOException e) { - logger.error("",e); - } - } - - public boolean close() { - try { - bufferOut.close(); - fstream.close(); - } catch (IOException e) { - return false; - } - return true; - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/action/ActionTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/action/ActionTest.java deleted file mode 100644 index edcb3e2761..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/action/ActionTest.java +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.action; - -import org.opendaylight.controller.sal.core.ConstructionException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; -import org.junit.Assert; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.Tables; -import org.opendaylight.controller.sal.core.Tier; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ActionTest { - protected static final Logger logger = LoggerFactory - .getLogger(ActionTest.class); - @Test - public void tesActionCreationValidation() { - Action action = new PopVlan(); - Assert.assertTrue(action.isValid()); - - byte mac[] = { (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0x11, - (byte) 0x22, (byte) 0x33 }; - - action = new SetDlSrc(mac); - Assert.assertTrue(action.isValid()); - - action = new SetDlSrc(mac); - Assert.assertTrue(action.isValid()); - } - - @Test - public void testSetVlanActionCreation() { - Action action = null; - - action = new SetVlanId(2); - Assert.assertTrue(action.isValid()); - - action = new SetVlanId(4095); - Assert.assertTrue(action.isValid()); - - action = new SetVlanId(0); - Assert.assertFalse(action.isValid()); - - action = new SetVlanId(1); - Assert.assertTrue(action.isValid()); - - action = new SetVlanId(4096); - Assert.assertFalse(action.isValid()); - } - - @Test - public void testPushVlanActionCreation() { - Action action = null; - - action = new PushVlan(EtherTypes.QINQ, 0x4, 0x1, 2000); - Assert.assertTrue(action.isValid()); - - action = new PushVlan(EtherTypes.QINQ.intValue(), 0x4, 0x1, 2000); - Assert.assertTrue(action.isValid()); - - action = new PushVlan(EtherTypes.OLDQINQ, 0x4, 2, 2000); - Assert.assertFalse(action.isValid()); - - action = new PushVlan(EtherTypes.VLANTAGGED, 0x4, 0, 2000); - Assert.assertTrue(action.isValid()); - - action = new PushVlan(EtherTypes.QINQ.intValue(), 0x4, 0x1, 5000); - Assert.assertFalse(action.isValid()); - - action = new PushVlan(EtherTypes.LLDP, 0x4, 0x1, 2000); - Assert.assertFalse(action.isValid()); - - action = new PushVlan(EtherTypes.PVSTP, 0x4, 2, 2000); - Assert.assertFalse(action.isValid()); - - action = new PushVlan(EtherTypes.QINQ, 0x4, -1, 2000); - Assert.assertFalse(action.isValid()); - - // OF 1.3 PUSH_VLAN test. - for (EtherTypes tag: EtherTypes.values()) { - int t = tag.intValue(); - boolean valid = - (tag == EtherTypes.VLANTAGGED || tag == EtherTypes.QINQ); - PushVlan pv = new PushVlan(tag); - Assert.assertEquals(valid, pv.isValid()); - if (valid) { - Assert.assertEquals(t, pv.getTag()); - } - - pv = new PushVlan(t); - Assert.assertEquals(valid, pv.isValid()); - if (valid) { - Assert.assertEquals(t, pv.getTag()); - } - } - } - - @Test - public void testSetVlanPcpActionCreation() { - Action action = null; - - action = new SetVlanPcp(0x4); - Assert.assertTrue(action.isValid()); - - action = new SetVlanPcp(0x8); - Assert.assertFalse(action.isValid()); - - action = new SetVlanPcp(-1); - Assert.assertFalse(action.isValid()); - } - - @Test - public void testSetVlanCfiActionCreation() { - Action action = null; - - action = new SetVlanCfi(0x0); - Assert.assertTrue(action.isValid()); - - action = new SetVlanCfi(0x1); - Assert.assertTrue(action.isValid()); - - action = new SetVlanCfi(0x2); - Assert.assertFalse(action.isValid()); - - action = new SetVlanCfi(-1); - Assert.assertFalse(action.isValid()); - } - - @Test - public void testNetworkSetActionCreation() { - Action action = null; - - InetAddress ip = null; - try { - ip = InetAddress.getByName("171.71.9.52"); - } catch (UnknownHostException e) { - logger.error("",e); - } - - action = new SetNwSrc(ip); - Assert.assertTrue(action.isValid()); - - action = new SetNwDst(ip); - Assert.assertTrue(action.isValid()); - - try { - ip = InetAddress.getByName("2001:420:281:1003:f2de:f1ff:fe71:728d"); - } catch (UnknownHostException e) { - logger.error("", e); - } - action = new SetNwSrc(ip); - Assert.assertTrue(action.isValid()); - - action = new SetNwDst(ip); - Assert.assertTrue(action.isValid()); - - action = new SetNwTos(0xf); - Assert.assertTrue(action.isValid()); - - action = new SetNwTos(0x3f); - Assert.assertTrue(action.isValid()); - - action = new SetNwTos(0x40); - Assert.assertFalse(action.isValid()); - - action = new SetNwTos(0xff1); - Assert.assertFalse(action.isValid()); - - action = new SetNwTos(-1); - Assert.assertFalse(action.isValid()); - } - - @Test - public void testTransportSetActionCreation() { - Action action = null; - - action = new SetTpSrc(50000); - Assert.assertTrue(action.isValid()); - - action = new SetTpDst(65535); - Assert.assertTrue(action.isValid()); - - action = new SetTpSrc(0); - Assert.assertTrue(action.isValid()); - - action = new SetTpDst(0); - Assert.assertTrue(action.isValid()); - - action = new SetTpSrc(-1); - Assert.assertFalse(action.isValid()); - - action = new SetTpDst(-1); - Assert.assertFalse(action.isValid()); - - action = new SetTpSrc(65536); - Assert.assertFalse(action.isValid()); - - action = new SetTpDst(65536); - Assert.assertFalse(action.isValid()); - } - - @Test - public void testNextHopActionCreation() { - SetNextHop action = null; - - InetAddress ip = null; - try { - ip = InetAddress.getByName("171.71.9.52"); - } catch (UnknownHostException e) { - logger.error("", e); - } - - action = new SetNextHop(ip); - Assert.assertTrue(action.getAddress().equals(ip)); - - try { - ip = InetAddress.getByName("2001:420:281:1003:f2de:f1ff:fe71:728d"); - } catch (UnknownHostException e) { - logger.error("", e); - } - action = new SetNextHop(ip); - Assert.assertTrue(action.getAddress().equals(ip)); - } - - @Test - public void testActionList() { - List actions = new ArrayList(); - short portId = (short) 9; - Node node = null; - try { - node = new Node(Node.NodeIDType.OPENFLOW, new Long(0x55667788L)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - NodeConnector nc = NodeConnectorCreator.createNodeConnector(portId, - node); - byte mac[] = { (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0x11, - (byte) 0x22, (byte) 0x33 }; - InetAddress ip = null; - try { - ip = InetAddress.getByName("1.1.1.1"); - } catch (UnknownHostException e) { - logger.error("",e); - } - - actions.add(new SetDlSrc(mac)); - actions.add(new SetNwSrc(ip)); - actions.add(new Output(nc)); - Assert.assertTrue(actions.size() == 3); - Assert.assertTrue(actions.get(0).isValid()); - - Action probe = new Output(nc); - Assert.assertTrue(actions.contains(probe)); - Assert.assertFalse(actions.contains(new Output(NodeConnectorCreator - .createNodeConnector((short) 5, node)))); - Assert.assertFalse(actions.contains(new Controller())); - } - - @Test - public void testMetadata() { - Property tier1 = new Tier(1); - Property tier2 = new Tier(2); - Property table1 = new Tables((byte)0x7f); - Action a1 = new PopVlan(); - List resprops = null; - resprops = a1.getMetadatas(); - // This should be an empty list - Assert.assertTrue(resprops.isEmpty()); - a1.setMetadata("tier1", tier1); - a1.setMetadata("tier2", tier2); - a1.setMetadata("table1", table1); - resprops = a1.getMetadatas(); - // Check for the number of elements in it - Assert.assertTrue(resprops.size() == 3); - // Check if the elements are in it - Assert.assertTrue(resprops.contains(tier1)); - Assert.assertTrue(resprops.contains(tier2)); - Assert.assertTrue(resprops.contains(table1)); - // Check for single elements retrieve - Assert.assertTrue(a1.getMetadata("tier1").equals(tier1)); - Assert.assertTrue(a1.getMetadata("tier2").equals(tier2)); - Assert.assertTrue(a1.getMetadata("table1").equals(table1)); - // Now remove an element and make sure the remaining are - // correct - a1.removeMetadata("tier1"); - - resprops = a1.getMetadatas(); - // Check for the number of elements in it - Assert.assertTrue(resprops.size() == 2); - // Check if the elements are in it - Assert.assertFalse(resprops.contains(tier1)); - Assert.assertTrue(resprops.contains(tier2)); - Assert.assertTrue(resprops.contains(table1)); - // Check for single elements retrieve - Assert.assertTrue(a1.getMetadata("table1").equals(table1)); - Assert.assertTrue(a1.getMetadata("tier2").equals(tier2)); - Assert.assertNull(a1.getMetadata("tier1")); - - // Check for an element never existed - Assert.assertNull(a1.getMetadata("table100")); - - // Remove them all - a1.removeMetadata("tier2"); - a1.removeMetadata("table1"); - - // Remove also a non-existent one - a1.removeMetadata("table100"); - - resprops = a1.getMetadatas(); - // Check there are no elements left - Assert.assertTrue(resprops.size() == 0); - - // Now check for exception on setting null values - try { - a1.setMetadata("foo", null); - // The line below should never be reached - Assert.assertTrue(false); - } catch (NullPointerException nue) { - // NPE should be raised for null value - Assert.assertTrue(true); - } - - // Now check on using null key - try { - a1.setMetadata(null, table1); - // The line below should never be reached - Assert.assertTrue(false); - } catch (NullPointerException nue) { - // NPE should be raised for null value - Assert.assertTrue(true); - } - - // Now check on using null key and null value - try { - a1.setMetadata(null, null); - // The line below should never be reached - Assert.assertTrue(false); - } catch (NullPointerException nue) { - // NPE should be raised for null value - Assert.assertTrue(true); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/authorization/AuthorizationTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/authorization/AuthorizationTest.java deleted file mode 100644 index 869d7ff520..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/authorization/AuthorizationTest.java +++ /dev/null @@ -1,77 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.authorization; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import org.junit.Assert; -import org.junit.Test; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.NodeCreator; - - public class AuthorizationTest { - - @Test - public void testResources () { - Privilege p = Privilege.WRITE; - ResourceGroup resourceGroup = new ResourceGroup("NodeGroup", p); - Map> resourceMap = new HashMap>(); - ArrayList resourceList = new ArrayList(); - - for (int i = 0; i < 5; i++) { - Node node = NodeCreator.createOFNode((long)i); - Resource resource = new Resource (node, p); - resourceList.add(resource); - } - - resourceMap.put(resourceGroup, resourceList); - - ArrayList retrievedResourceList = resourceMap.get(resourceGroup); - for (Entry> entry : resourceMap.entrySet()) { - ResourceGroup rGroup = entry.getKey(); - Assert.assertTrue(rGroup.getGroupName().equals(resourceGroup.getGroupName())); - for (int i = 0; i < 5; i++) { - Resource resource = retrievedResourceList.get(i); - Assert.assertTrue(resource.getPrivilege().equals(Privilege.WRITE)); - Assert.assertTrue(((Long)((Node)resource.getResource()).getID()).equals((long)i)); - } - } - } - - @Test - public void testAppRoleLevel() { - AppRoleLevel appRoleLevel = AppRoleLevel.APPOPERATOR; - Assert.assertTrue(appRoleLevel.toString().equals("App-Operator")); - Assert.assertTrue(appRoleLevel.toNumber() == 2); - Assert.assertTrue(appRoleLevel.toStringPretty().equals("Application Operator")); - } - - @Test - public void testUserLevel() { - UserLevel userLevel = UserLevel.SYSTEMADMIN; - Assert.assertTrue(userLevel.toString().equals("System-Admin")); - Assert.assertTrue(userLevel.toNumber() == 0); - Assert.assertTrue(userLevel.toStringPretty().equals("System Administrator")); - } - - @Test - public void testAppRoleLevelFromString() { - Assert.assertTrue(AppRoleLevel.fromString("App-Admin") == AppRoleLevel.APPADMIN); - Assert.assertTrue(AppRoleLevel.fromString("App-User") == AppRoleLevel.APPUSER); - Assert.assertTrue(AppRoleLevel.fromString("App-Operator") == AppRoleLevel.APPOPERATOR); - Assert.assertTrue(AppRoleLevel.fromString(" ") == null); - Assert.assertTrue(AppRoleLevel.fromString("") == null); - Assert.assertTrue(AppRoleLevel.fromString("App-Admini") == null); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/EdgeTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/EdgeTest.java deleted file mode 100644 index 7c36d09682..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/EdgeTest.java +++ /dev/null @@ -1,186 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file EdgeTest.java - * - * @brief Unit Tests for Edge element - * - * Unit Tests for Edge element - */ -package org.opendaylight.controller.sal.core; - -import org.junit.Assert; -import org.junit.Test; - -public class EdgeTest { - @Test - public void testEdgeEquals() { - try { - Node n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - NodeConnector c0 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x4), n0); - - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector c1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x1), n1); - - Node n2 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - NodeConnector c2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x4), n2); - - Node n3 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector c3 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x1), n3); - - Edge e0 = new Edge(c0, c1); - Edge e1 = new Edge(c2, c3); - // e0 must be equal to e1 to pass the test - Assert.assertTrue(e0.equals(e1)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - } - - @Test - public void testEdgeDifferents() { - Node n0, n1, n2, n3; - NodeConnector c0, c1, c2, c3; - Edge e0, e1; - try { - // Difference in the tail node - n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - c0 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x4), n0); - - n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - c1 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x1), n1); - - e0 = new Edge(c0, c1); - - n2 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - c2 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x4), n2); - - n3 = new Node(Node.NodeIDType.OPENFLOW, new Long(111L)); - c3 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x1), n3); - - e0 = new Edge(c0, c1); - e1 = new Edge(c2, c3); - // e0 must be different from e1 to pass the test - Assert.assertTrue(!e0.equals(e1)); - - // Difference in the head node - n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - c0 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x4), n0); - - n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - c1 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x1), n1); - - e0 = new Edge(c0, c1); - - n2 = new Node(Node.NodeIDType.OPENFLOW, new Long(41L)); - c2 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x4), n2); - - n3 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - c3 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x1), n3); - - e0 = new Edge(c0, c1); - e1 = new Edge(c2, c3); - // e0 must be different from e1 to pass the test - Assert.assertTrue(!e0.equals(e1)); - - // Difference in the head nodeconnetor - n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - c0 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x4), n0); - - n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - c1 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x1), n1); - - e0 = new Edge(c0, c1); - - n2 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - c2 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x5), n2); - - n3 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - c3 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x1), n3); - - e0 = new Edge(c0, c1); - e1 = new Edge(c2, c3); - // e0 must be different from e1 to pass the test - Assert.assertTrue(!e0.equals(e1)); - - // Difference in the tail nodeconnetor - n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - c0 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x4), n0); - - n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - c1 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x1), n1); - - e0 = new Edge(c0, c1); - - n2 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - c2 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x4), n2); - - n3 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - c3 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x2), n3); - - e0 = new Edge(c0, c1); - e1 = new Edge(c2, c3); - // e0 must be different from e1 to pass the test - Assert.assertTrue(!e0.equals(e1)); - - // Difference in the both nodeconnetor/node - n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - c0 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x4), n0); - - n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - c1 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x1), n1); - - e0 = new Edge(c0, c1); - - n2 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - c2 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x4), n2); - - n3 = new Node(Node.NodeIDType.OPENFLOW, new Long(111L)); - c3 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, - new Short((short) 0x2), n3); - - e0 = new Edge(c0, c1); - e1 = new Edge(c2, c3); - // e0 must be different from e1 to pass the test - Assert.assertTrue(!e0.equals(e1)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeConnectorTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeConnectorTest.java deleted file mode 100644 index f85b7b4b01..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeConnectorTest.java +++ /dev/null @@ -1,1281 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file NodeConnectorTest.java - * - * @brief Unit Tests for NodeConnector element - * - * Unit Tests for NodeConnector element - */ -package org.opendaylight.controller.sal.core; - -import java.util.UUID; - -import org.junit.Assert; -import org.junit.Test; - -public class NodeConnectorTest { - @Test - public void testNodeConnectorOpenFlowOfWrongType() { - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - @SuppressWarnings("unused") - NodeConnector of1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new String( - "0xDEADBEEFCAFE0001L"), n1); - - // If we reach this point the exception was not raised - // which should have been the case - Assert.assertTrue(false); - } catch (ConstructionException e) { - // If we reach this point the exception has been raised - // and so test passed - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(true); - } - } - - @Test - public void testNodeConnectorONEPKOfWrongType() { - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - @SuppressWarnings("unused") - NodeConnector onepk1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new Long( - 0xDEADBEEFCAFE0001L), n1); - - // If we reach this point the exception was not raised - // which should have been the case - Assert.assertTrue(false); - } catch (ConstructionException e) { - // If we reach this point the exception has been raised - // and so test passed - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(true); - } - } - - @Test - public void testNodeConnectorPCEPOfWrongType() { - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - @SuppressWarnings("unused") - NodeConnector pcep1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Long( - 0xDEADBEEFCAFE0001L), n1); - - // If we reach this point the exception was not raised - // which should have been the case - Assert.assertTrue(false); - } catch (ConstructionException e) { - // If we reach this point the exception has been raised - // and so test passed - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(true); - } - } - - @Test - public void testNodeConnectorOpenFlowOfCorrectType() { - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector of1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0xCAFE), n1); - - // If we reach this point the exception has not been - // raised so we passed the test - System.out.println("Got node:" + of1); - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testNodeConnectorONEPKOfCorrectType() { - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector onepk1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n1); - - // If we reach this point the exception has not been - // raised so we passed the test - System.out.println("Got node:" + onepk1); - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testNodeConnectorPCEPOfCorrectType() { - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector pcep1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer( - 0xDEADBEEF), n1); - - // If we reach this point the exception has not been - // raised so we passed the test - System.out.println("Got node:" + pcep1); - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoOpenFlowNodeConnectorEquals() { - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector of1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0xCAFE), n1); - NodeConnector of2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0xCAFE), n1); - - Assert.assertTrue(of1.equals(of2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoONEPKNodeConnectorEquals() { - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector onepk1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n1); - NodeConnector onepk2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n1); - - Assert.assertTrue(onepk1.equals(onepk2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoPCEPNodeConnectorEquals() { - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector pcep1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer( - 0xDEADBEEF), n1); - NodeConnector pcep2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer( - 0xDEADBEEF), n1); - - Assert.assertTrue(pcep1.equals(pcep2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoOpenFlowNodeConnectorDifferents() { - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector of1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0xCAFE), n1); - NodeConnector of2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0xBEEF), n1); - - Assert.assertTrue(!of1.equals(of2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoONEPKNodeConnectorDifferents() { - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector onepk1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n1); - NodeConnector onepk2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/2"), n1); - - Assert.assertTrue(!onepk1.equals(onepk2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoPCEPNodeConnectorDifferents() { - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector pcep1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer( - 0xDEADBEEF), n1); - NodeConnector pcep2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer( - 0xCAFECAFE), n1); - - Assert.assertTrue(!pcep1.equals(pcep2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoOpenFlowNodeConnectorDifferentsNodes() { - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - Node n2 = new Node(Node.NodeIDType.OPENFLOW, new Long(111L)); - NodeConnector of1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0xCAFE), n1); - NodeConnector of2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0xCAFE), n2); - - Assert.assertTrue(!of1.equals(of2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoONEPKNodeConnectorDifferentsNodes() { - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - Node n2 = new Node(Node.NodeIDType.ONEPK, new String("Router2")); - NodeConnector onepk1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n1); - NodeConnector onepk2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n2); - - Assert.assertTrue(!onepk1.equals(onepk2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoPCEPNodeConnectorDifferentsNodes() { - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - Node n2 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 1L)); - NodeConnector pcep1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer( - 0xDEADBEEF), n1); - NodeConnector pcep2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer( - 0xDEADBEEF), n2); - - Assert.assertTrue(!pcep1.equals(pcep2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @SuppressWarnings("unused") - @Test - public void testIncompatibleNodes() { - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2PCEP, new Short( - (short) 0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2ONEPK, - new Short((short) 0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2PCEP, new String( - "towardPCEP1"), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2OPENFLOW, - new String("towardPCEP1"), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer(0), n1); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP2ONEPK, - new Integer(0), n1); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP2OPENFLOW, - new Integer(0), n1); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2PCEP, new Short( - (short) 0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2ONEPK, - new Short((short) 0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2PCEP, new String( - "towardPCEP1"), n1); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2OPENFLOW, - new String("towardPCEP1"), n1); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n1); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer(0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP2ONEPK, - new Integer(0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP2OPENFLOW, - new Integer(0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0), n1); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2PCEP, new Short( - (short) 0), n1); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2ONEPK, - new Short((short) 0), n1); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2PCEP, new String( - "towardPCEP1"), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2OPENFLOW, - new String("towardPCEP1"), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer(0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP2ONEPK, - new Integer(0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP2OPENFLOW, - new Integer(0), n1); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - } - - @Test - public void testConversionToStringAndBack() { - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID( - 0xDEADBEEFCAFE0001L, 0xDEADBEEFCAFE0002L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP2ONEPK, new Integer( - 0xDEADBEEF), n1); - String nc1Str = nc1.toString(); - System.out.println("NodeConnector String = " + nc1Str); - NodeConnector nc1FromStr = NodeConnector.fromString(nc1Str); - - // Make sure we got a nodeconnector - Assert.assertTrue(nc1FromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc1.equals(nc1FromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID( - 0xDEADBEEFCAFE0001L, 0xDEADBEEFCAFE0002L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP2OPENFLOW, - new Integer(0x10), n1); - String nc1Str = nc1.toString(); - System.out.println("NodeConnector String = " + nc1Str); - NodeConnector nc1FromStr = NodeConnector.fromString(nc1Str); - - // Make sure we got a nodeconnector - Assert.assertTrue(nc1FromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc1.equals(nc1FromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.PCEP, new UUID( - 0xDEADBEEFCAFE0001L, 0xDEADBEEFCAFE0002L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.PCEP, new Integer(0x10), - n1); - String nc1Str = nc1.toString(); - System.out.println("NodeConnector String = " + nc1Str); - NodeConnector nc1FromStr = NodeConnector.fromString(nc1Str); - - // Make sure we got a nodeconnector - Assert.assertTrue(nc1FromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc1.equals(nc1FromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2PCEP, new String( - "towardPCEP1"), n1); - - String nc1Str = nc1.toString(); - System.out.println("NodeConnector String = " + nc1Str); - NodeConnector nc1FromStr = NodeConnector.fromString(nc1Str); - - // Make sure we got a nodeconnector - Assert.assertTrue(nc1FromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc1.equals(nc1FromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2OPENFLOW, - new String("towardOPENFLOW1"), n1); - - String nc1Str = nc1.toString(); - System.out.println("NodeConnector String = " + nc1Str); - NodeConnector nc1FromStr = NodeConnector.fromString(nc1Str); - - // Make sure we got a nodeconnector - Assert.assertTrue(nc1FromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc1.equals(nc1FromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n1); - - String nc1Str = nc1.toString(); - System.out.println("NodeConnector String = " + nc1Str); - NodeConnector nc1FromStr = NodeConnector.fromString(nc1Str); - - // Make sure we got a nodeconnector - Assert.assertTrue(nc1FromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc1.equals(nc1FromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long( - 0xDEADBEEFCAFE0001L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0xCAFE), n1); - - String nc1Str = nc1.toString(); - System.out.println("NodeConnector String = " + nc1Str); - NodeConnector nc1FromStr = NodeConnector.fromString(nc1Str); - - // Make sure we got a nodeconnector - Assert.assertTrue(nc1FromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc1.equals(nc1FromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(0x100L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2PCEP, new Short( - (short) 0x10), n1); - - String nc1Str = nc1.toString(); - System.out.println("NodeConnector String = " + nc1Str); - NodeConnector nc1FromStr = NodeConnector.fromString(nc1Str); - - // Make sure we got a nodeconnector - Assert.assertTrue(nc1FromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc1.equals(nc1FromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(0x100L)); - NodeConnector nc1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2ONEPK, - new Short((short) 0x11), n1); - - String nc1Str = nc1.toString(); - System.out.println("NodeConnector String = " + nc1Str); - NodeConnector nc1FromStr = NodeConnector.fromString(nc1Str); - - // Make sure we got a nodeconnector - Assert.assertTrue(nc1FromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc1.equals(nc1FromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - } - - @Test - public void testNodeConnectorSpecialType() { - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.CONTROLLER, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.ALL, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.SWSTACK, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.HWPATH, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.CONTROLLER, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.ALL, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.SWSTACK, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.HWPATH, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.CONTROLLER, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.ALL, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.SWSTACK, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.HWPATH, - NodeConnector.SPECIALNODECONNECTORID, n); - System.out.println("Special NC = " + specialNc); - // We expect to reach this point succesfully - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - } - - @Test - public void testToStringConversionForOpenFlow() { - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x2AB), n); - - NodeConnector ofFromStr = null; - - ofFromStr = NodeConnector.fromStringNoNode("0x2ab", n); - - // Make sure we got a nodeconnector - Assert.assertTrue(ofFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc.equals(ofFromStr)); - - ofFromStr = NodeConnector.fromStringNoNode("0x2AB", n); - - // Make sure we got a nodeconnector - Assert.assertTrue(ofFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc.equals(ofFromStr)); - - ofFromStr = NodeConnector.fromStringNoNode("683", n); - - // Make sure we got a nodeconnector - Assert.assertTrue(ofFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc.equals(ofFromStr)); - } catch (Exception e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector nc = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0xcafe), n); - - NodeConnector ofFromStr = null; - - ofFromStr = NodeConnector.fromStringNoNode("-13570", n); - - // Make sure we got a nodeconnector - Assert.assertTrue(ofFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(nc.equals(ofFromStr)); - } catch (Exception e) { - // If this expection is raised the test is failing - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(false); - } - } - - @Test - public void testConversionToStringAndBackSpecialPorts() { - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.CONTROLLER, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.ALL, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.HWPATH, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.SWSTACK, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.CONTROLLER, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.ALL, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.HWPATH, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.SWSTACK, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.CONTROLLER, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.ALL, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.HWPATH, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - - try { - Node n = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector specialNc = new NodeConnector( - NodeConnector.NodeConnectorIDType.SWSTACK, - NodeConnector.SPECIALNODECONNECTORID, n); - - String specialNcStr = specialNc.toString(); - System.out.println("NodeConnector String obtained= " + specialNc); - NodeConnector specialNcFromStr = NodeConnector - .fromString(specialNcStr); - - // Make sure we got a nodeconnector - Assert.assertTrue(specialNcFromStr != null); - - // Now the converted nodeconnector need to be the same of the - // original one - Assert.assertTrue(specialNc.equals(specialNcFromStr)); - } catch (ConstructionException e) { - // Fail if exception raised - Assert.assertTrue(false); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTableTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTableTest.java deleted file mode 100644 index d018823698..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTableTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.core; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.utils.NodeCreator; - -public class NodeTableTest { - @Test - public void testNodeTableOpenFlowOfWrongType() { - try { - Node node = NodeCreator.createOFNode((long) 20); - @SuppressWarnings("unused") - NodeTable of1 = new NodeTable(NodeTable.NodeTableIDType.OPENFLOW, "name", node); - - // If we reach this point the exception was not raised - // which should have been the case - Assert.assertTrue(false); - } catch (ConstructionException e) { - // If we reach this point the exception has been raised - // and so test passed - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(true); - } - } - - @Test - public void testNodeTableOpenFlowOfCorrectType() { - try { - Node node = NodeCreator.createOFNode((long) 20); - NodeTable of1 = new NodeTable(NodeTable.NodeTableIDType.OPENFLOW, Byte.valueOf("10"), node); - - // If we reach this point the exception has not been - // raised so we passed the test - System.out.println("Got node table:" + of1); - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoOpenFlowNodeTableEquals() { - try { - Node node1 = NodeCreator.createOFNode((long) 20); - NodeTable of1 = new NodeTable(NodeTable.NodeTableIDType.OPENFLOW, Byte.valueOf("10"), node1); - NodeTable of2 = new NodeTable(NodeTable.NodeTableIDType.OPENFLOW, Byte.valueOf("10"), node1); - - Assert.assertTrue(of1.equals(of2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoOpenFlowNodeTableDifferents() { - try { - Node node1 = NodeCreator.createOFNode((long) 20); - NodeTable of1 = new NodeTable(NodeTable.NodeTableIDType.OPENFLOW, Byte.valueOf("10"), node1); - Node node2 = NodeCreator.createOFNode((long) 40); - NodeTable of2 = new NodeTable(NodeTable.NodeTableIDType.OPENFLOW, Byte.valueOf("20"), node2); - - Assert.assertTrue(!of1.equals(of2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTest.java deleted file mode 100644 index 0b394bf9ec..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/NodeTest.java +++ /dev/null @@ -1,429 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file NodeTest.java - * - * @brief Unit Tests for Node element - * - * Unit Tests for Node element - */ -package org.opendaylight.controller.sal.core; - -import java.util.UUID; -import org.junit.Assert; -import org.junit.Test; - -public class NodeTest { - @Test - public void testNodeOpenFlowOfWrongType() { - try { - @SuppressWarnings("unused") - Node of1 = new Node(Node.NodeIDType.OPENFLOW, new String( - "0xDEADBEEFCAFE0001L")); - - // If we reach this point the exception was not raised - // which should have been the case - Assert.assertTrue(false); - } catch (ConstructionException e) { - // If we reach this point the exception has been raised - // and so test passed - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(true); - } - } - - @Test - public void testNodeONEPKOfWrongType() { - try { - @SuppressWarnings("unused") - Node onepk1 = new Node(Node.NodeIDType.ONEPK, new Long( - 0xDEADBEEFCAFE0001L)); - - // If we reach this point the exception was not raised - // which should have been the case - Assert.assertTrue(false); - } catch (ConstructionException e) { - // If we reach this point the exception has been raised - // and so test passed - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(true); - } - } - - @Test - public void testNodePCEPOfWrongType() { - try { - @SuppressWarnings("unused") - Node pcep1 = new Node(Node.NodeIDType.PCEP, new Long( - 0xDEADBEEFCAFE0001L)); - - // If we reach this point the exception was not raised - // which should have been the case - Assert.assertTrue(false); - } catch (ConstructionException e) { - // If we reach this point the exception has been raised - // and so test passed - System.out.println("Got exception as expected!:" + e); - Assert.assertTrue(true); - } - } - - @Test - public void testNodeOpenFlowOfCorrectType() { - try { - Node of1 = new Node(Node.NodeIDType.OPENFLOW, new Long( - 0xDEADBEEFCAFE0001L)); - - // If we reach this point the exception has not been - // raised so we passed the test - System.out.println("Got node:" + of1); - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testNodeONEPKOfCorrectType() { - try { - Node onepk1 = new Node(Node.NodeIDType.ONEPK, new String( - "0xDEADBEEFCAFE0001L")); - - // If we reach this point the exception has not been - // raised so we passed the test - System.out.println("Got node:" + onepk1); - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testNodePCEPOfCorrectType() { - try { - Node pcep1 = new Node(Node.NodeIDType.PCEP, new UUID(0L, 0L)); - - // If we reach this point the exception has not been - // raised so we passed the test - System.out.println("Got node:" + pcep1); - Assert.assertTrue(true); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoOpenFlowNodeEquals() { - try { - Node of1 = new Node(Node.NodeIDType.OPENFLOW, new Long( - 0xDEADBEEFCAFE0001L)); - Node of2 = new Node(Node.NodeIDType.OPENFLOW, new Long( - 0xDEADBEEFCAFE0001L)); - - Assert.assertTrue(of1.equals(of2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoONEPKNodeEquals() { - try { - Node onepk1 = new Node(Node.NodeIDType.ONEPK, new String( - "0xDEADBEEFCAFE0001L")); - Node onepk2 = new Node(Node.NodeIDType.ONEPK, new String( - "0xDEADBEEFCAFE0001L")); - - Assert.assertTrue(onepk1.equals(onepk2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoPCEPNodeEquals() { - try { - Node pcep1 = new Node(Node.NodeIDType.PCEP, new UUID( - 0xDEADBEEFCAFE0001L, 0L)); - Node pcep2 = new Node(Node.NodeIDType.PCEP, new UUID( - 0xDEADBEEFCAFE0001L, 0L)); - - Assert.assertTrue(pcep1.equals(pcep2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoOpenFlowNodeDifferents() { - try { - Node of1 = new Node(Node.NodeIDType.OPENFLOW, new Long( - 0xDEADBEEFCAFE0001L)); - Node of2 = new Node(Node.NodeIDType.OPENFLOW, new Long( - 0xDEADBEEFCAFE0002L)); - - Assert.assertTrue(!of1.equals(of2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoONEPKNodeDifferents() { - try { - Node onepk1 = new Node(Node.NodeIDType.ONEPK, new String( - "0xDEADBEEFCAFE0001L")); - Node onepk2 = new Node(Node.NodeIDType.ONEPK, new String( - "0xDEADBEEFCAFE0002L")); - - Assert.assertTrue(!onepk1.equals(onepk2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testTwoPCEPNodeDifferents() { - try { - Node pcep1 = new Node(Node.NodeIDType.PCEP, new UUID( - 0xDEADBEEFCAFE0001L, 0L)); - Node pcep2 = new Node(Node.NodeIDType.PCEP, new UUID( - 0xDEADBEEFCAFE0001L, 1L)); - - Assert.assertTrue(!pcep1.equals(pcep2)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testToStringConversionAndBack() { - // Test PCEP - try { - Node pcep = new Node(Node.NodeIDType.PCEP, new UUID( - 0xDEADBEEFCAFE0001L, 0L)); - - String pcepToStr = pcep.toString(); - System.out.println("Got String from PCEP=(" + pcepToStr + ")"); - - Node pcepFromStr = Node.fromString(pcepToStr); - - // Make sure we got a node - Assert.assertTrue(pcepFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(pcep.equals(pcepFromStr)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - - // Test ONEPK - try { - Node onepk = new Node(Node.NodeIDType.ONEPK, new String( - "0xDEADBEEFCAFE0001L")); - - String onepkToStr = onepk.toString(); - System.out.println("Got String from ONEPK=(" + onepkToStr + ")"); - - Node onepkFromStr = Node.fromString(onepkToStr); - - // Make sure we got a node - Assert.assertTrue(onepkFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(onepk.equals(onepkFromStr)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - - // Test OPENFLOW short string - try { - Node of = new Node(Node.NodeIDType.OPENFLOW, new Long(0x10L)); - - String ofToStr = of.toString(); - System.out.println("Got String from OPENFLOW=(" + ofToStr + ")"); - - Node ofFromStr = Node.fromString(ofToStr); - - // Make sure we got a node - Assert.assertTrue(ofFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(of.equals(ofFromStr)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - - // Test OPENFLOW longer string - try { - Node of = new Node(Node.NodeIDType.OPENFLOW, new Long( - 0xDEADBEEFCAFE0001L)); - - String ofToStr = of.toString(); - System.out.println("Got String from OPENFLOW=(" + ofToStr + ")"); - - Node ofFromStr = Node.fromString(ofToStr); - - // Make sure we got a node - Assert.assertTrue(ofFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(of.equals(ofFromStr)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testToStringConversionForOpenFlow() { - // Test OPENFLOW longer string - try { - Node of = new Node(Node.NodeIDType.OPENFLOW, new Long( - 0xDEADBEEFCAFE0001L)); - Node ofFromStr = null; - - // Decimal value for deadbeefcafe0001 - ofFromStr = Node.fromString("-2401053089206501375"); - - // Make sure we got a node - Assert.assertTrue(ofFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(of.equals(ofFromStr)); - - ofFromStr = Node.fromString("deadbeefcafe0001"); - - // Make sure we got a node - Assert.assertTrue(ofFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(of.equals(ofFromStr)); - - ofFromStr = Node.fromString("DEADBEEFCAFE0001"); - - // Make sure we got a node - Assert.assertTrue(ofFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(of.equals(ofFromStr)); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(of.equals(ofFromStr)); - - ofFromStr = Node.fromString("0xdeadbeefcafe0001"); - - // Make sure we got a node - Assert.assertTrue(ofFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(of.equals(ofFromStr)); - - ofFromStr = Node.fromString("0xDEADBEEFCAFE0001"); - - // Make sure we got a node - Assert.assertTrue(ofFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(of.equals(ofFromStr)); - - ofFromStr = Node.fromString("DE:AD:BE:EF:CA:FE:00:01"); - - // Make sure we got a node - Assert.assertTrue(ofFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(of.equals(ofFromStr)); - - ofFromStr = Node.fromString("de:ad:be:ef:ca:fe:00:01"); - - // Make sure we got a node - Assert.assertTrue(ofFromStr != null); - - // Now the converted node need to be the same of the - // original one - Assert.assertTrue(of.equals(ofFromStr)); - } catch (ConstructionException e) { - // If we reach this point the exception was raised - // which is not expected - Assert.assertTrue(false); - } - } - - @Test - public void testExtensibleNode() { - // Add a new ID type - Assert.assertTrue(Node.NodeIDType.registerIDType("FOO", Integer.class)); - - // Trying to re-register the node must fail - Assert.assertFalse(Node.NodeIDType.registerIDType("FOO", - Integer.class)); - try { - Node n = new Node("FOO", new Integer(0xCAFE)); - - System.out.println("Got Extended node:" + n); - } catch (ConstructionException e) { - // Got an unexpected exception - Assert.assertTrue(false); - } - - // Now unregister the type and make sure the node doesn't get - // created - Node.NodeIDType.unRegisterIDType("FOO"); - try { - @SuppressWarnings("unused") - Node n = new Node("FOO", new Integer(0xCAFE)); - - // If we reach here, something didn't go fine, an - // exception should have been raised - Assert.assertTrue(false); - } catch (ConstructionException e) { - // Got an expected exception, do nothing! - } - - Assert.assertTrue(true); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/PathTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/PathTest.java deleted file mode 100644 index 0ea88558de..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/PathTest.java +++ /dev/null @@ -1,341 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file PathTest.java - * - * @brief Unit Tests for Path element - * - * Unit Tests for Path element - */ -package org.opendaylight.controller.sal.core; - -import java.util.LinkedList; -import java.util.List; -import java.util.Arrays; -import org.junit.Assert; -import org.junit.Test; - -public class PathTest { - @Test - public void testPathValid() { - List edges = null; - try { - Node n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - NodeConnector c0 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x4), n0); - - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector c1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x1), n1); - NodeConnector c2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2ONEPK, - new Short((short) 0xCAFE), n1); - - Node n2 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector c3 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2OPENFLOW, - new String("towardOF1"), n2); - NodeConnector c4 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n2); - - Node n3 = new Node(Node.NodeIDType.ONEPK, new String("Router2")); - NodeConnector c5 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n3); - - Edge e0 = new Edge(c0, c1); - Edge e1 = new Edge(c1, c2); - Edge e2 = new Edge(c2, c3); - Edge e3 = new Edge(c3, c4); - Edge e4 = new Edge(c4, c5); - // actually need a LinkedList because we're going to .remove() - edges = new LinkedList(Arrays.asList(e0, e1, e2, e3, e4)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - @SuppressWarnings("unused") - Path res = new Path(edges); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - // Now lets disconnect on edge so to create a disconnected - // path, the constructor should catch that and should not - // create the path - edges.remove(2); - - try { - @SuppressWarnings("unused") - Path res = new Path(edges); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - } - - @Test - public void testPathComparison() { - List edges1 = null; - Path path1 = null; - List edges2 = null; - Path path2 = null; - List edges3 = null; - Path path3 = null; - - try { - Node n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - NodeConnector c0 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x4), n0); - - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector c1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x1), n1); - NodeConnector c2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2ONEPK, - new Short((short) 0xCAFE), n1); - - Node n2 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector c3 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2OPENFLOW, - new String("towardOF1"), n2); - NodeConnector c4 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n2); - - Node n3 = new Node(Node.NodeIDType.ONEPK, new String("Router2")); - NodeConnector c5 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n3); - - Edge e0 = new Edge(c0, c1); - Edge e1 = new Edge(c1, c2); - Edge e2 = new Edge(c2, c3); - Edge e3 = new Edge(c3, c4); - Edge e4 = new Edge(c4, c5); - edges1 = Arrays.asList(e0, e1, e2, e3, e4); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - Node n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - NodeConnector c0 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x4), n0); - - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector c1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x1), n1); - NodeConnector c2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2ONEPK, - new Short((short) 0xCAFE), n1); - - Node n2 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector c3 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2OPENFLOW, - new String("towardOF1"), n2); - NodeConnector c4 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n2); - - Node n3 = new Node(Node.NodeIDType.ONEPK, new String("Router2")); - NodeConnector c5 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n3); - - Edge e0 = new Edge(c0, c1); - Edge e1 = new Edge(c1, c2); - Edge e2 = new Edge(c2, c3); - Edge e3 = new Edge(c3, c4); - Edge e4 = new Edge(c4, c5); - edges2 = Arrays.asList(e0, e1, e2, e3, e4); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - Node n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - NodeConnector c0 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x5), n0); - - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector c1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x1), n1); - NodeConnector c2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2ONEPK, - new Short((short) 0xCAFE), n1); - - Node n2 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector c3 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2OPENFLOW, - new String("towardOF1"), n2); - NodeConnector c4 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n2); - - Node n3 = new Node(Node.NodeIDType.ONEPK, new String("Router2")); - NodeConnector c5 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n3); - - Edge e0 = new Edge(c0, c1); - Edge e1 = new Edge(c1, c2); - Edge e2 = new Edge(c2, c3); - Edge e3 = new Edge(c3, c4); - Edge e4 = new Edge(c4, c5); - edges3 = Arrays.asList(e0, e1, e2, e3, e4); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - path1 = new Path(edges1); - path2 = new Path(edges2); - path3 = new Path(edges3); - - System.out.println("Path1: " + path1); - System.out.println("Path2: " + path2); - System.out.println("Path3: " + path3); - - // Make sure the path are equals - Assert.assertTrue(path1.equals(path2)); - - // Make sure the path are marked as different - Assert.assertTrue(!path1.equals(path3)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - } - - @Test - public void testPathEmpty() { - try { - @SuppressWarnings("unused") - Path path = new Path(new LinkedList()); - // Exception is expected if not raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - } - - @Test - public void testPathOneElement() { - try { - Node n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - NodeConnector c0 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x5), n0); - - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector c1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x1), n1); - - Edge e0 = new Edge(c0, c1); - - @SuppressWarnings("unused") - Path path = new Path(Arrays.asList(e0)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - } - - @Test - public void testPathGetNodes() { - // Test on >2 edges paths - try { - Node n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - NodeConnector c0 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x4), n0); - - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector c1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x1), n1); - NodeConnector c2 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW2ONEPK, - new Short((short) 0xCAFE), n1); - - Node n2 = new Node(Node.NodeIDType.ONEPK, new String("Router1")); - NodeConnector c3 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK2OPENFLOW, - new String("towardOF1"), n2); - NodeConnector c4 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n2); - - Node n3 = new Node(Node.NodeIDType.ONEPK, new String("Router2")); - NodeConnector c5 = new NodeConnector( - NodeConnector.NodeConnectorIDType.ONEPK, new String( - "Gi1/0/1"), n3); - - Edge e0 = new Edge(c0, c1); - Edge e1 = new Edge(c1, c2); - Edge e2 = new Edge(c2, c3); - Edge e3 = new Edge(c3, c4); - Edge e4 = new Edge(c4, c5); - List edges = Arrays.asList(e0, e1, e2, e3, e4); - Path path = new Path(edges); - - // Test start node - Assert.assertTrue(path.getStartNode().equals(n0)); - - // Test end node - Assert.assertTrue(path.getEndNode().equals(n3)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - // Test on 1 edge path - try { - Node n0 = new Node(Node.NodeIDType.OPENFLOW, new Long(40L)); - NodeConnector c0 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x4), n0); - - Node n1 = new Node(Node.NodeIDType.OPENFLOW, new Long(110L)); - NodeConnector c1 = new NodeConnector( - NodeConnector.NodeConnectorIDType.OPENFLOW, new Short( - (short) 0x1), n1); - - Edge e0 = new Edge(c0, c1); - List edges = Arrays.asList(e0); - Path path = new Path(edges); - - // Test start node - Assert.assertTrue(path.getStartNode().equals(n0)); - - // Test end node - Assert.assertTrue(path.getEndNode().equals(n1)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/PropertyTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/PropertyTest.java deleted file mode 100644 index 0828268cc9..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/core/PropertyTest.java +++ /dev/null @@ -1,92 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file PropertyTest.java - * - * @brief Test for properties - * - */ - -package org.opendaylight.controller.sal.core; - -import org.junit.Assert; -import org.junit.Test; - -public class PropertyTest { - @Test - public void testBandWidthStr() { - Property b; - - b = new Bandwidth(Bandwidth.BWUNK); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[UnKnown]")); - - b = new Bandwidth(100L); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[100bps]")); - - b = new Bandwidth(Bandwidth.BW10Mbps); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[10Mbps]")); - - b = new Bandwidth(Bandwidth.BW100Mbps); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[100Mbps]")); - - b = new Bandwidth(Bandwidth.BW100Mbps); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[100Mbps]")); - - b = new Bandwidth(Bandwidth.BW1Gbps); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[1Gbps]")); - - b = new Bandwidth(Bandwidth.BW10Gbps); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[10Gbps]")); - - b = new Bandwidth(Bandwidth.BW40Gbps); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[40Gbps]")); - - b = new Bandwidth(Bandwidth.BW100Gbps); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[100Gbps]")); - - b = new Bandwidth(Bandwidth.BW100Gbps + 15L); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[100Gbps]")); - - b = new Bandwidth(Bandwidth.BW1Tbps); - System.out.println("b = " + b); - Assert.assertTrue(b.toString().equals("BandWidth[1Tbps]")); - } - - @Test - public void testLatencyStr() { - Property l; - - l = new Latency(Latency.LATENCYUNK); - System.out.println("l = " + l); - Assert.assertTrue(l.toString().equals("Latency[UnKnown]")); - - l = new Latency(Latency.LATENCY1ns); - System.out.println("l = " + l); - Assert.assertTrue(l.toString().equals("Latency[1nsec]")); - - l = new Latency(Latency.LATENCY1us); - System.out.println("l = " + l); - Assert.assertTrue(l.toString().equals("Latency[1usec]")); - - l = new Latency(Latency.LATENCY1ms); - System.out.println("l = " + l); - Assert.assertTrue(l.toString().equals("Latency[1msec]")); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/flowprogrammer/FlowTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/flowprogrammer/FlowTest.java deleted file mode 100644 index e644b0d834..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/flowprogrammer/FlowTest.java +++ /dev/null @@ -1,220 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.flowprogrammer; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.Controller; -import org.opendaylight.controller.sal.action.Flood; -import org.opendaylight.controller.sal.action.Loopback; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.action.PopVlan; -import org.opendaylight.controller.sal.action.PushVlan; -import org.opendaylight.controller.sal.action.SetDlDst; -import org.opendaylight.controller.sal.action.SetNwDst; -import org.opendaylight.controller.sal.action.SetVlanId; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -public class FlowTest { - - @Test - public void testFlowEquality() throws Exception { - Node node = NodeCreator.createOFNode(1055L); - Flow flow1 = getSampleFlowV6(node); - Flow flow2 = getSampleFlowV6(node); - Flow flow3 = getSampleFlow(node); - - // Check Match equality - Assert.assertTrue(flow1.getMatch().equals(flow2.getMatch())); - - // Check Actions equality - for (int i = 0; i < flow1.getActions().size(); i++) { - Action a = flow1.getActions().get(i); - Action b = flow2.getActions().get(i); - Assert.assertTrue(a != b); - Assert.assertTrue(a.equals(b)); - } - - Assert.assertTrue(flow1.equals(flow2)); - Assert.assertFalse(flow2.equals(flow3)); - - // Check Flow equality where Flow has null action list (pure match) - List emptyList = new ArrayList(1); - Flow x = flow1.clone(); - x.setActions(emptyList); - Assert.assertFalse(flow1.equals(x)); - flow1.setActions(emptyList); - Assert.assertTrue(flow1.equals(x)); - } - - @Test - public void testFlowCloning() throws UnknownHostException { - Node node = NodeCreator.createOFNode(55L); - Flow flow1 = getSampleFlowV6(node); - Flow flow2 = flow1.clone(); - - Assert.assertTrue(flow1.equals(flow2)); - Assert.assertTrue(flow1.getMatch().equals(flow2.getMatch())); - Assert.assertTrue(flow1.getActions() != flow2.getActions()); - Assert.assertTrue(flow1.getActions().equals(flow2.getActions())); - } - - @Test - public void testFlowActions() throws UnknownHostException { - Node node = NodeCreator.createOFNode(55L); - Flow flow = getSampleFlowV6(node); - - List actions = flow.getActions(); - actions.add(new Loopback()); - - Assert.assertTrue(flow.getActions() != actions); - Assert.assertTrue(!flow.getActions().equals(actions)); - - flow.addAction(new Loopback()); - Assert.assertTrue(flow.getActions().equals(actions)); - - actions.remove(new Loopback()); - flow.removeAction(new Loopback()); - Assert.assertTrue(flow.getActions().equals(actions)); - - // Add a malformed action - Assert.assertFalse(flow.addAction(new PushVlan(EtherTypes.CISCOQINQ, 3, - 3, 8000))); - } - - private Flow getSampleFlow(Node node) throws UnknownHostException { - NodeConnector port = NodeConnectorCreator.createOFNodeConnector( - (short) 24, node); - NodeConnector oport = NodeConnectorCreator.createOFNodeConnector( - (short) 30, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, - (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, - (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress.getByName("172.28.30.50"); - InetAddress dstIP = InetAddress.getByName("171.71.9.52"); - InetAddress newIP = InetAddress.getByName("200.200.100.1"); - InetAddress ipMask = InetAddress.getByName("255.255.255.0"); - InetAddress ipMask2 = InetAddress.getByName("255.240.0.0"); - short ethertype = EtherTypes.IPv4.shortValue(); - short vlan = (short) 27; - byte vlanPr = 3; - Byte tos = 4; - byte proto = IPProtocols.TCP.byteValue(); - short src = (short) 55000; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(MatchType.IN_PORT, port); - match.setField(MatchType.DL_SRC, srcMac); - match.setField(MatchType.DL_DST, dstMac); - match.setField(MatchType.DL_TYPE, ethertype); - match.setField(MatchType.DL_VLAN, vlan); - match.setField(MatchType.DL_VLAN_PR, vlanPr); - match.setField(MatchType.NW_SRC, srcIP, ipMask); - match.setField(MatchType.NW_DST, dstIP, ipMask2); - match.setField(MatchType.NW_TOS, tos); - match.setField(MatchType.NW_PROTO, proto); - match.setField(MatchType.TP_SRC, src); - match.setField(MatchType.TP_DST, dst); - - List actions = new ArrayList(); - actions.add(new SetNwDst(newIP)); - actions.add(new Output(oport)); - actions.add(new PopVlan()); - actions.add(new Flood()); - actions.add(new Controller()); - - Flow flow = new Flow(match, actions); - flow.setPriority((short) 100); - flow.setHardTimeout((short) 360); - - return flow; - } - - private Flow getSampleFlowV6(Node node) throws UnknownHostException { - NodeConnector port = NodeConnectorCreator.createOFNodeConnector( - (short) 24, node); - NodeConnector oport = NodeConnectorCreator.createOFNodeConnector( - (short) 30, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, - (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, - (byte) 0x5e, (byte) 0x6f }; - byte newMac[] = { (byte) 0x11, (byte) 0xaa, (byte) 0xbb, (byte) 0x34, - (byte) 0x9a, (byte) 0xee }; - InetAddress srcIP = InetAddress - .getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress - .getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMask = InetAddress - .getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - InetAddress ipMask2 = InetAddress - .getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - InetAddress newIP = InetAddress.getByName("2056:650::a1b0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27; - byte vlanPr = (byte) 3; - Byte tos = 4; - byte proto = IPProtocols.UDP.byteValue(); - short src = (short) 5500; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(MatchType.IN_PORT, port); - match.setField(MatchType.DL_SRC, srcMac); - match.setField(MatchType.DL_DST, dstMac); - match.setField(MatchType.DL_TYPE, ethertype); - match.setField(MatchType.DL_VLAN, vlan); - match.setField(MatchType.DL_VLAN_PR, vlanPr); - match.setField(MatchType.NW_SRC, srcIP, ipMask); - match.setField(MatchType.NW_DST, dstIP, ipMask2); - match.setField(MatchType.NW_TOS, tos); - match.setField(MatchType.NW_PROTO, proto); - match.setField(MatchType.TP_SRC, src); - match.setField(MatchType.TP_DST, dst); - - List actions = new ArrayList(); - actions.add(new Controller()); - actions.add(new SetVlanId(5)); - actions.add(new SetDlDst(newMac)); - actions.add(new SetNwDst(newIP)); - actions.add(new Output(oport)); - actions.add(new PopVlan()); - actions.add(new Flood()); - - actions.add(new Controller()); - - Flow flow = new Flow(match, actions); - flow.setPriority((short) 300); - flow.setHardTimeout((short) 240); - - return flow; - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchExtensibleTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchExtensibleTest.java deleted file mode 100644 index 0f49f421d2..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchExtensibleTest.java +++ /dev/null @@ -1,589 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.match; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.match.extensible.DlDst; -import org.opendaylight.controller.sal.match.extensible.DlSrc; -import org.opendaylight.controller.sal.match.extensible.DlType; -import org.opendaylight.controller.sal.match.extensible.DlVlan; -import org.opendaylight.controller.sal.match.extensible.DlVlanPriority; -import org.opendaylight.controller.sal.match.extensible.InPort; -import org.opendaylight.controller.sal.match.extensible.Match; -import org.opendaylight.controller.sal.match.extensible.MatchField; -import org.opendaylight.controller.sal.match.extensible.NwDst; -import org.opendaylight.controller.sal.match.extensible.NwProtocol; -import org.opendaylight.controller.sal.match.extensible.NwSrc; -import org.opendaylight.controller.sal.match.extensible.NwTos; -import org.opendaylight.controller.sal.match.extensible.TpDst; -import org.opendaylight.controller.sal.match.extensible.TpSrc; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -public class MatchExtensibleTest { - @Test - public void testMatchCreation() { - Node node = NodeCreator.createOFNode(7L); - NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 6, node); - MatchField field = new InPort(port); - - Assert.assertTrue(field != null); - Assert.assertEquals(field.getType(), InPort.TYPE); - Assert.assertEquals(field.getValue(), port); - Assert.assertTrue(field.isValid()); - - - byte mac[] = { (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 11, (byte) 22 }; - field = null; - field = new DlSrc(mac); - Assert.assertNotNull(field.getValue()); - - field = null; - field = new NwTos((byte) 0x22); - Assert.assertNotNull(field.getValue()); - } - - @Test - public void testMatchSetGet() { - Match x = new Match(); - short val = 2346; - NodeConnector inPort = NodeConnectorCreator.createOFNodeConnector(val, NodeCreator.createOFNode(1L)); - x.setField(new InPort(inPort)); - Assert.assertEquals(x.getField(InPort.TYPE).getValue(), inPort); - Assert.assertTrue((Short) ((NodeConnector) x.getField(InPort.TYPE).getValue()).getID() == val); - } - - @Test - public void testMatchSetGetMAC() { - Match x = new Match(); - byte mac[] = { (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 11, (byte) 22 }; - byte mac2[] = { (byte) 0xaa, (byte) 0xbb, 0, 0, 0, (byte) 0xbb }; - - x.setField(new DlSrc(mac)); - x.setField(new DlDst(mac2)); - Assert.assertArrayEquals(mac, (byte[]) x.getField(DlSrc.TYPE).getValue()); - Assert.assertFalse(Arrays.equals((byte[]) x.getField(DlSrc.TYPE).getValue(), (byte[]) x.getField(DlDst.TYPE) - .getValue())); - - x.setField(new DlDst(mac.clone())); - Assert.assertArrayEquals((byte[]) x.getField(DlSrc.TYPE).getValue(), (byte[]) x.getField(DlDst.TYPE).getValue()); - } - - @Test - public void testMatchSetGetNWAddr() throws UnknownHostException { - Match x = new Match(); - String ip = "172.20.231.23"; - InetAddress address = InetAddress.getByName(ip); - InetAddress mask = InetAddress.getByName("255.255.0.0"); - - x.setField(new NwSrc(address, mask)); - Assert.assertEquals(address, x.getField(NwSrc.TYPE).getValue()); - Assert.assertEquals(x.getField(NwSrc.TYPE).getMask(), mask); - } - - @Test - public void testMatchSetGetEtherType() throws UnknownHostException { - Match x = new Match(); - - x.setField(new DlType(EtherTypes.QINQ.shortValue())); - Assert.assertEquals(x.getField(DlType.TYPE).getValue(), EtherTypes.QINQ.shortValue()); - - x.setField(new DlType(EtherTypes.LLDP.shortValue())); - Assert.assertEquals(x.getField(DlType.TYPE).getValue(), EtherTypes.LLDP.shortValue()); - Assert.assertFalse(x.getField(DlType.TYPE).equals(EtherTypes.LLDP.intValue())); - } - - @Test - public void testSetGetNwTos() { - Match x = new Match(); - x.setField(new NwTos((byte) 0xb)); - - Byte t = new Byte((byte) 0xb); - - Object o = x.getField(NwTos.TYPE).getValue(); - Assert.assertEquals(o, t); - Assert.assertEquals(o, Byte.valueOf((byte)0xb)); - } - - @Test - public void testSetGetNwProto() { - Match x = new Match(); - Byte proto = (byte) 199; - x.setField(new NwProtocol(proto)); - - Byte o = (Byte) x.getField(NwProtocol.TYPE).getValue(); - Assert.assertEquals(o, proto); - } - - @Test - public void testSetTpSrc() { - // Minimum value validation. - Match match = new Match(); - short tp_src = 0; - match.setField(new TpSrc(tp_src)); - - Object o = match.getField(TpSrc.TYPE).getValue(); - Assert.assertEquals(o, tp_src); - - // Maximum value validation. - match = new Match(); - tp_src = (short) 0xffff; - match.setField(new TpSrc(tp_src)); - - o = match.getField(TpSrc.TYPE).getValue(); - Assert.assertEquals(o, tp_src); - } - - @Test - public void testSetTpDst() { - // Minimum value validation. - Match match = new Match(); - short tp_dst = 0; - match.setField(new TpDst(tp_dst)); - - Object o = match.getField(TpDst.TYPE).getValue(); - Assert.assertTrue(o.equals(tp_dst)); - - // Maximum value validation. - match = new Match(); - tp_dst = (short) 0xffff; - match.setField(new TpDst(tp_dst)); - - o = match.getField(TpDst.TYPE).getValue(); - Assert.assertEquals(o, tp_dst); - } - - @Test - public void testEquality() throws Exception { - Node node = NodeCreator.createOFNode(7L); - NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node); - NodeConnector port2 = NodeConnectorCreator.createOFNodeConnector((short) 24, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - byte srcMac2[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac2[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMask = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - InetAddress ipMaskd = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - InetAddress ipMask2 = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - InetAddress ipMaskd2 = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short ethertype2 = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27, vlan2 = (short) 27; - byte vlanPr = (byte) 3, vlanPr2 = (byte) 3; - Byte tos = 4, tos2 = 4; - byte proto = IPProtocols.UDP.byteValue(), proto2 = IPProtocols.UDP.byteValue(); - short src = (short) 5500, src2 = (short) 5500; - short dst = 80, dst2 = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match1 = new Match(); - Match match2 = new Match(); - match1.setField(new InPort(port)); - match1.setField(new DlSrc(srcMac)); - match1.setField(new DlDst(dstMac)); - match1.setField(new DlType(ethertype)); - match1.setField(new DlVlan(vlan)); - match1.setField(new DlVlanPriority(vlanPr)); - match1.setField(new NwSrc(srcIP, ipMask)); - match1.setField(new NwDst(dstIP, ipMaskd)); - match1.setField(new NwTos(tos)); - match1.setField(new NwProtocol(proto)); - match1.setField(new TpSrc(src)); - match1.setField(new TpDst(dst)); - - match2.setField(new InPort(port2)); - match2.setField(new DlSrc(srcMac2)); - match2.setField(new DlDst(dstMac2)); - match2.setField(new DlType(ethertype2)); - match2.setField(new DlVlan(vlan2)); - match2.setField(new DlVlanPriority(vlanPr2)); - match2.setField(new NwSrc(srcIP, ipMask2)); - match2.setField(new NwDst(dstIP, ipMaskd2)); - match2.setField(new NwTos(tos2)); - match2.setField(new NwProtocol(proto2)); - match2.setField(new TpSrc(src2)); - match2.setField(new TpDst(dst2)); - - Assert.assertTrue(match1.equals(match2)); - - Set allFields = new HashSet(match1.getMatchesList()); - allFields.addAll(match2.getMatchesList()); - // Make sure all values are equals - for (String type : allFields) { - if (match1.isPresent(type)) { - Assert.assertEquals(match1.getField(type), match2.getField(type)); - } - } - - // Make none of the fields couples are pointing to the same reference - MatchField a = null, b = null; - for (String type : allFields) { - a = match1.getField(type); - b = match2.getField(type); - if (a != null && b != null) { - Assert.assertFalse(a == b); - } - } - } - - @Test - public void testEqualityNetMask() throws Exception { - - InetAddress srcIP = InetAddress.getByName("1.1.1.1"); - InetAddress ipMask = InetAddress.getByName("255.255.255.255"); - InetAddress srcIP2 = InetAddress.getByName("1.1.1.1"); - InetAddress ipMask2 = null; - short ethertype = EtherTypes.IPv4.shortValue(); - short ethertype2 = EtherTypes.IPv4.shortValue(); - - /* - * Create a SAL Flow aFlow - */ - Match match1 = new Match(); - Match match2 = new Match(); - - match1.setField(new DlType(ethertype)); - match1.setField(new NwSrc(srcIP, ipMask)); - - match2.setField(new DlType(ethertype2)); - match2.setField(new NwSrc(srcIP2, ipMask2)); - - Assert.assertTrue(match1.equals(match2)); - - ipMask2 = InetAddress.getByName("255.255.255.255"); - match2.setField(new NwSrc(srcIP2, ipMask2)); - - srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - srcIP2 = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - ipMask = null; - ipMask2 = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); - ethertype = EtherTypes.IPv6.shortValue(); - ethertype2 = EtherTypes.IPv6.shortValue(); - - match1.setField(new DlType(ethertype)); - match1.setField(new NwSrc(srcIP, ipMask)); - - match2.setField(new DlType(ethertype2)); - match2.setField(new NwSrc(srcIP2, ipMask2)); - - Assert.assertEquals(match1, match2); - } - - @Test - public void testHashCodeWithReverseMatch() throws Exception { - InetAddress srcIP1 = InetAddress.getByName("1.1.1.1"); - InetAddress ipMask1 = InetAddress.getByName("255.255.255.255"); - InetAddress srcIP2 = InetAddress.getByName("2.2.2.2"); - InetAddress ipMask2 = InetAddress.getByName("255.255.255.255"); - MatchField field1 = new NwSrc(srcIP1, ipMask1); - MatchField field2 = new NwDst(srcIP2, ipMask2); - Match match1 = new Match(); - match1.setField(field1); - match1.setField(field2); - Match match2 = match1.reverse(); - Assert.assertFalse(match1.hashCode() == match2.hashCode()); - } - - @Test - public void testHashCode() throws Exception { - byte srcMac1[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte srcMac2[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac1[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - byte dstMac2[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - short ethertype = EtherTypes.IPv4.shortValue(); - short ethertype2 = EtherTypes.IPv4.shortValue(); - InetAddress srcIP1 = InetAddress.getByName("1.1.1.1"); - InetAddress ipMask1 = InetAddress.getByName("255.255.255.255"); - InetAddress srcIP2 = InetAddress.getByName("1.1.1.1"); - InetAddress ipMask2 = InetAddress.getByName("255.255.255.255"); - - Match match1 = new Match(); - Match match2 = new Match(); - - MatchField field1 = new DlSrc(srcMac1); - MatchField field2 = new DlSrc(srcMac2); - Assert.assertTrue(field1.hashCode() == field2.hashCode()); - - match1.setField(field1); - match2.setField(field2); - Assert.assertTrue(match1.hashCode() == match2.hashCode()); - - MatchField field3 = new DlDst(dstMac1); - MatchField field4 = new DlDst(dstMac2); - Assert.assertTrue(field3.hashCode() == field4.hashCode()); - - match1.setField(field3); - match2.setField(field4); - Assert.assertTrue(match1.hashCode() == match2.hashCode()); - - MatchField field5 = new DlType(ethertype); - MatchField field6 = new DlType(ethertype2); - Assert.assertTrue(field5.hashCode() == field6.hashCode()); - - match1.setField(field5); - match2.setField(field6); - Assert.assertTrue(match1.hashCode() == match2 .hashCode()); - - MatchField field7 = new NwSrc(srcIP1, ipMask1); - MatchField field8 = new NwSrc(srcIP2, ipMask2); - Assert.assertTrue(field7.hashCode() == field8.hashCode()); - - match1.setField(field7); - match2.setField(field8); - Assert.assertTrue(match1.hashCode() == match2.hashCode()); - - } - - @Test - public void testCloning() throws Exception { - Node node = NodeCreator.createOFNode(7L); - NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMasks = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - InetAddress ipMaskd = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27; - byte vlanPr = (byte) 3; - Byte tos = 4; - byte proto = IPProtocols.UDP.byteValue(); - short src = (short) 5500; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(new InPort(port)); - match.setField(new DlSrc(srcMac)); - match.setField(new DlDst(dstMac)); - match.setField(new DlType(ethertype)); - match.setField(new DlVlan(vlan)); - match.setField(new DlVlanPriority(vlanPr)); - match.setField(new NwSrc(srcIP, ipMasks)); - match.setField(new NwDst(dstIP, ipMaskd)); - match.setField(new NwTos(tos)); - match.setField(new NwProtocol(proto)); - match.setField(new TpSrc(src)); - match.setField(new TpDst(dst)); - - Match cloned = match.clone(); - - // Make sure all values are equals - for (String type : match.getMatchesList()) { - if (match.isPresent(type)) { - if (!match.getField(type).equals(cloned.getField(type))) { - Assert.assertEquals(match.getField(type), cloned.getField(type)); - } - } - } - - // Make sure none of the fields couples are pointing to the same - // reference - MatchField a = null, b = null; - for (String type : match.getMatchesList()) { - a = match.getField(type); - b = cloned.getField(type); - if (a != null && b != null) { - Assert.assertFalse(a == b); - } - } - - Assert.assertTrue(match.equals(cloned)); - - Assert.assertEquals(match.getField(DlSrc.TYPE), cloned.getField(DlSrc.TYPE)); - Assert.assertEquals(match.getField(NwDst.TYPE), cloned.getField(NwDst.TYPE)); - Assert.assertEquals(match.getField(NwDst.TYPE).getMask(), cloned.getField(NwDst.TYPE).getMask()); - Assert.assertEquals(match.hashCode(), cloned.hashCode()); - } - - @Test - public void testFlip() throws Exception { - Node node = NodeCreator.createOFNode(7L); - NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMasks = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - InetAddress ipMaskd = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27; - byte vlanPr = (byte) 3; - Byte tos = 4; - byte proto = IPProtocols.UDP.byteValue(); - short src = (short) 5500; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(new InPort(port)); - match.setField(new DlSrc(srcMac)); - match.setField(new DlDst(dstMac)); - match.setField(new DlType(ethertype)); - match.setField(new DlVlan(vlan)); - match.setField(new DlVlanPriority(vlanPr)); - match.setField(new NwSrc(srcIP, ipMasks)); - match.setField(new NwDst(dstIP, ipMaskd)); - match.setField(new NwTos(tos)); - match.setField(new NwProtocol(proto)); - match.setField(new TpSrc(src)); - match.setField(new TpDst(dst)); - - Match flipped = match.reverse(); - - Assert.assertEquals(match.getField(DlType.TYPE), flipped.getField(DlType.TYPE)); - Assert.assertEquals(match.getField(DlVlan.TYPE), flipped.getField(DlVlan.TYPE)); - - Assert.assertArrayEquals((byte[]) match.getField(DlDst.TYPE).getValue(), (byte[]) flipped.getField(DlSrc.TYPE) - .getValue()); - - Assert.assertEquals(match.getField(NwDst.TYPE).getValue(), flipped.getField(NwSrc.TYPE).getValue()); - - Assert.assertEquals(match.getField(TpDst.TYPE).getValue(), flipped.getField(TpSrc.TYPE).getValue()); - - Match flipflip = flipped.reverse().reverse(); - Assert.assertEquals(flipflip, flipped); - - } - - @Test - public void testVlanNone() throws Exception { - // The value 0 is used to indicate that no VLAN ID is set - short vlan = (short) 0; - MatchField field = new DlVlan(vlan); - - Assert.assertTrue(field != null); - Assert.assertEquals(field.getValue(), new Short(vlan)); - Assert.assertTrue(field.isValid()); - } - - @Test - public void testIntersection() throws UnknownHostException { - Short ethType = Short.valueOf((short)0x800); - InetAddress ip1 = InetAddress.getByName("1.1.1.1"); - InetAddress ip2 = InetAddress.getByName("1.1.1.0"); - InetAddress ipm2 = InetAddress.getByName("255.255.255.0"); - InetAddress ip3 = InetAddress.getByName("1.3.0.0"); - InetAddress ipm3 = InetAddress.getByName("255.255.0.0"); - InetAddress ip4 = InetAddress.getByName("1.3.4.4"); - InetAddress ipm4 = InetAddress.getByName("255.255.255.0"); - - Match m1 = new Match(); - m1.setField(new DlType(ethType)); - m1.setField(new NwSrc(ip1)); - - Match m2 = new Match(); - m2.setField(new DlType(ethType)); - m2.setField(new NwSrc(ip2, ipm2)); - - Match m3 = new Match(); - m3.setField(new DlType(ethType)); - m3.setField(new NwSrc(ip3, ipm3)); - m3.setField(new NwProtocol(IPProtocols.TCP.byteValue())); - - Match m3r = m3.reverse(); - Assert.assertTrue(m3.intersetcs(m3r)); - - Assert.assertTrue(m1.intersetcs(m2)); - Assert.assertTrue(m2.intersetcs(m1)); - Assert.assertFalse(m1.intersetcs(m3)); - Assert.assertTrue(m1.intersetcs(m3r)); - Assert.assertFalse(m3.intersetcs(m1)); - Assert.assertTrue(m3.intersetcs(m1.reverse())); - Assert.assertFalse(m2.intersetcs(m3)); - Assert.assertFalse(m3.intersetcs(m2)); - Assert.assertTrue(m2.intersetcs(m3r)); - - - Match i = m1.getIntersection(m2); - Assert.assertTrue(((Short)i.getField(DlType.TYPE).getValue()).equals(ethType)); - // Verify intersection of IP addresses is correct - Assert.assertTrue(((InetAddress)i.getField(NwSrc.TYPE).getValue()).equals(ip1)); - Assert.assertNull(i.getField(NwSrc.TYPE).getMask()); - - // Empty set - i = m2.getIntersection(m3); - Assert.assertNull(i); - - Match m4 = new Match(); - m4.setField(new DlType(ethType)); - m4.setField(new NwProtocol(IPProtocols.TCP.byteValue())); - m3.setField(new NwSrc(ip4, ipm4)); - Assert.assertTrue(m4.intersetcs(m3)); - - // Verify intersection of IP and IP mask addresses is correct - Match ii = m3.getIntersection(m4); - Assert.assertTrue(((InetAddress)ii.getField(NwSrc.TYPE).getValue()).equals(ip4)); - Assert.assertTrue(((InetAddress)ii.getField(NwSrc.TYPE).getMask()).equals(ipm4)); - - Match m5 = new Match(); - m5.setField(new DlType(ethType)); - m3.setField(new NwSrc(ip3, ipm3)); - m5.setField(new NwProtocol(IPProtocols.UDP.byteValue())); - Assert.assertFalse(m5.intersetcs(m3)); - Assert.assertFalse(m5.intersetcs(m4)); - Assert.assertTrue(m5.intersetcs(m5)); - Assert.assertFalse(m3.intersetcs(m5)); - Assert.assertFalse(m4.intersetcs(m5)); - - - Match i2 = m4.getIntersection(m3); - Assert.assertFalse(i2.isEmpty()); - Assert.assertFalse(i2.getMatchesList().isEmpty()); - Assert.assertTrue(((InetAddress)i2.getField(NwSrc.TYPE).getValue()).equals(ip3)); - Assert.assertTrue(((InetAddress)i2.getField(NwSrc.TYPE).getMask()).equals(ipm3)); - Assert.assertTrue(((Byte)i2.getField(NwProtocol.TYPE).getValue()).equals(IPProtocols.TCP.byteValue())); - - byte src[] = {(byte)0, (byte)0xab,(byte)0xbc,(byte)0xcd,(byte)0xde,(byte)0xef}; - byte dst[] = {(byte)0x10, (byte)0x11,(byte)0x12,(byte)0x13,(byte)0x14,(byte)0x15}; - Short srcPort = (short)1024; - Short dstPort = (short)80; - - // Check identity - Match m6 = new Match(); - m6.setField(new DlSrc(src)); - m6.setField(new DlDst(dst)); - m6.setField(new NwSrc(ip2, ipm2)); - m6.setField(new NwDst(ip3, ipm3)); - m6.setField(new NwProtocol(IPProtocols.UDP.byteValue())); - m6.setField(new TpSrc(srcPort)); - m6.setField(new TpDst(dstPort)); - Assert.assertTrue(m6.intersetcs(m6)); - Assert.assertTrue(m6.getIntersection(m6).equals(m6)); - - // Empty match, represents the universal set (all packets) - Match u = new Match(); - Assert.assertEquals(m6.getIntersection(u), m6); - Assert.assertEquals(u.getIntersection(m6), m6); - - // No intersection with null match, empty set - Assert.assertNull(m6.getIntersection(null)); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchTest.java deleted file mode 100644 index b89b27ffe0..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/match/MatchTest.java +++ /dev/null @@ -1,730 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.match; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.Tables; -import org.opendaylight.controller.sal.core.Tier; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -public class MatchTest { - @Test - public void testMatchCreation() { - Node node = NodeCreator.createOFNode(7L); - NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 6, node); - MatchField field = new MatchField(MatchType.IN_PORT, port); - - Assert.assertTrue(field != null); - Assert.assertTrue(field.getType() == MatchType.IN_PORT); - Assert.assertTrue((NodeConnector) field.getValue() == port); - Assert.assertTrue(field.isValid()); - - field = null; - field = new MatchField(MatchType.TP_SRC, Long.valueOf(23)); - Assert.assertFalse(field.isValid()); - - field = null; - field = new MatchField(MatchType.TP_SRC, (long) 45); - Assert.assertFalse(field.isValid()); - - field = null; - field = new MatchField(MatchType.TP_SRC, 120000); - Assert.assertFalse(field.isValid()); - - byte mac[] = { (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 11, (byte) 22 }; - byte mask[] = { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff }; - field = null; - field = new MatchField(MatchType.DL_SRC, mac, mask); - Assert.assertFalse(field.getValue() == null); - - field = null; - field = new MatchField(MatchType.NW_TOS, (byte) 0x22, (byte) 0x3); - Assert.assertFalse(field.getValue() == null); - } - - @Test - public void testMatchSetGet() { - Match x = new Match(); - short val = 2346; - NodeConnector inPort = NodeConnectorCreator.createOFNodeConnector(val, NodeCreator.createOFNode(1L)); - x.setField(MatchType.IN_PORT, inPort); - Assert.assertTrue(((NodeConnector) x.getField(MatchType.IN_PORT).getValue()).equals(inPort)); - Assert.assertTrue((Short) ((NodeConnector) x.getField(MatchType.IN_PORT).getValue()).getID() == val); - } - - @Test - public void testMatchSetGetMAC() { - Match x = new Match(); - byte mac[] = { (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 11, (byte) 22 }; - byte mac2[] = { (byte) 0xaa, (byte) 0xbb, 0, 0, 0, (byte) 0xbb }; - byte mask1[] = { (byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, (byte) 0x55, (byte) 0x66 }; - byte mask2[] = { (byte) 0xff, (byte) 0xff, (byte) 0, (byte) 0, (byte) 0, (byte) 0xff }; - - x.setField(MatchType.DL_SRC, mac.clone(), mask1); - x.setField(MatchType.DL_DST, mac2.clone(), mask2); - Assert.assertTrue(Arrays.equals(mac, (byte[]) x.getField(MatchType.DL_SRC).getValue())); - Assert.assertFalse(Arrays.equals((byte[]) x.getField(MatchType.DL_SRC).getValue(), - (byte[]) x.getField(MatchType.DL_DST).getValue())); - Assert.assertFalse(x.getField(MatchType.DL_SRC).getBitMask() == x.getField(MatchType.DL_DST).getBitMask()); - - x.setField(new MatchField(MatchType.DL_DST, mac.clone(), mask1)); - Assert.assertTrue(Arrays.equals((byte[]) x.getField(MatchType.DL_SRC).getValue(), - (byte[]) x.getField(MatchType.DL_DST).getValue())); - } - - @Test - public void testMatchSetGetNWAddr() throws UnknownHostException { - Match x = new Match(); - String ip = "172.20.231.23"; - InetAddress address = InetAddress.getByName(ip); - InetAddress mask = InetAddress.getByName("255.255.0.0"); - - x.setField(MatchType.NW_SRC, address, mask); - Assert.assertTrue(ip.equals(((InetAddress) x.getField(MatchType.NW_SRC).getValue()).getHostAddress())); - Assert.assertTrue(x.getField(MatchType.NW_SRC).getMask().equals(mask)); - } - - @Test - public void testMatchSetGetEtherType() throws UnknownHostException { - Match x = new Match(); - - x.setField(MatchType.DL_TYPE, EtherTypes.QINQ.shortValue(), (short) 0xffff); - Assert.assertTrue(((Short) x.getField(MatchType.DL_TYPE).getValue()).equals(EtherTypes.QINQ.shortValue())); - Assert.assertFalse(x.getField(MatchType.DL_TYPE).getValue() == EtherTypes.QINQ); - Assert.assertFalse(x.getField(MatchType.DL_TYPE).getValue().equals(EtherTypes.QINQ)); - - x.setField(MatchType.DL_TYPE, EtherTypes.LLDP.shortValue(), (short) 0xffff); - Assert.assertTrue(((Short) x.getField(MatchType.DL_TYPE).getValue()).equals(EtherTypes.LLDP.shortValue())); - Assert.assertFalse(x.getField(MatchType.DL_TYPE).equals(EtherTypes.LLDP.intValue())); - } - - @Test - public void testSetGetNwTos() { - Match x = new Match(); - x.setField(MatchType.NW_TOS, (byte) 0xb, (byte) 0xf); - - Byte t = new Byte((byte) 0xb); - - Object o = x.getField(MatchType.NW_TOS).getValue(); - Assert.assertTrue(o.equals(t)); - Assert.assertTrue(o.equals((byte) 0xb)); - } - - @Test - public void testSetGetNwProto() { - Match x = new Match(); - byte proto = (byte) 199; - x.setField(MatchType.NW_PROTO, proto, (byte) 0xff); - - Object o = x.getField(MatchType.NW_PROTO).getValue(); - Assert.assertTrue(o.equals(proto)); - } - - @Test - public void testSetTpSrc() { - // Minimum value validation. - Match match = new Match(); - short tp_src = 0; - match.setField(MatchType.TP_SRC, tp_src); - - Object o = match.getField(MatchType.TP_SRC).getValue(); - Assert.assertTrue(o.equals(tp_src)); - - // Maximum value validation. - match = new Match(); - tp_src = (short) 0xffff; - match.setField(MatchType.TP_SRC, tp_src); - - o = match.getField(MatchType.TP_SRC).getValue(); - Assert.assertTrue(o.equals(tp_src)); - } - - @Test - public void testSetTpDst() { - // Minimum value validation. - Match match = new Match(); - short tp_dst = 0; - match.setField(MatchType.TP_DST, tp_dst); - - Object o = match.getField(MatchType.TP_DST).getValue(); - Assert.assertTrue(o.equals(tp_dst)); - - // Maximum value validation. - match = new Match(); - tp_dst = (short) 0xffff; - match.setField(MatchType.TP_DST, tp_dst); - - o = match.getField(MatchType.TP_DST).getValue(); - Assert.assertTrue(o.equals(tp_dst)); - } - - @Test - public void testMatchMask() { - Match x = new Match(); - NodeConnector inPort = NodeConnectorCreator.createOFNodeConnector((short) 6, NodeCreator.createOFNode(3L)); - x.setField(MatchType.IN_PORT, inPort); - x.setField(MatchType.DL_VLAN, (short) 28, (short) 0xfff); - Assert.assertFalse(x.getMatches() == 0); - Assert.assertTrue(x.getMatches() == (MatchType.IN_PORT.getIndex() | MatchType.DL_VLAN.getIndex())); - } - - @Test - public void testMatchBitMask() { - byte mac[] = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 22, (byte) 12 }; - byte mask[] = { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0 }; - NodeConnector inPort = NodeConnectorCreator.createOFNodeConnector((short) 4095, NodeCreator.createOFNode(7L)); - - MatchField x = new MatchField(MatchType.IN_PORT, inPort); - Assert.assertTrue((x.getMask()) == null); - - x = new MatchField(MatchType.DL_VLAN, (short) 255, (short) 0xff); - Assert.assertTrue(x.getBitMask() == 0xff); - - x = new MatchField(MatchType.DL_SRC, mac, mask); - Assert.assertTrue(x.getMask().equals(mask)); - Assert.assertTrue(x.getBitMask() == 0xffffffffff00L); - } - - @Test - public void testNullMask() { - byte mac[] = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 22, (byte) 12 }; - NodeConnector inPort = NodeConnectorCreator.createOFNodeConnector((short) 2000, NodeCreator.createOFNode(7L)); - - MatchField x = new MatchField(MatchType.IN_PORT, inPort); - Assert.assertTrue(x.getBitMask() == 0); - - x = new MatchField(MatchType.NW_PROTO, (byte) 17); - Assert.assertTrue(x.getBitMask() == 0xff); - - x = new MatchField(MatchType.DL_VLAN, (short) 255); - Assert.assertTrue(x.getBitMask() == 0xfff); - - x = new MatchField(MatchType.DL_SRC, mac); - Assert.assertTrue(x.getBitMask() == 0xffffffffffffL); - } - - @Test - public void testEquality() throws Exception { - Node node = NodeCreator.createOFNode(7L); - NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node); - NodeConnector port2 = NodeConnectorCreator.createOFNodeConnector((short) 24, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - byte srcMac2[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac2[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMask = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - InetAddress ipMaskd = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - InetAddress srcIP2 = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP2 = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMask2 = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - InetAddress ipMaskd2 = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short ethertype2 = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27, vlan2 = (short) 27; - byte vlanPr = (byte) 3, vlanPr2 = (byte) 3; - Byte tos = 4, tos2 = 4; - byte proto = IPProtocols.UDP.byteValue(), proto2 = IPProtocols.UDP.byteValue(); - short src = (short) 5500, src2 = (short) 5500; - short dst = 80, dst2 = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match1 = new Match(); - Match match2 = new Match(); - match1.setField(MatchType.IN_PORT, port); - match1.setField(MatchType.DL_SRC, srcMac); - match1.setField(MatchType.DL_DST, dstMac); - match1.setField(MatchType.DL_TYPE, ethertype); - match1.setField(MatchType.DL_VLAN, vlan); - match1.setField(MatchType.DL_VLAN_PR, vlanPr); - match1.setField(MatchType.NW_SRC, srcIP, ipMask); - match1.setField(MatchType.NW_DST, dstIP, ipMaskd); - match1.setField(MatchType.NW_TOS, tos); - match1.setField(MatchType.NW_PROTO, proto); - match1.setField(MatchType.TP_SRC, src); - match1.setField(MatchType.TP_DST, dst); - - match2.setField(MatchType.IN_PORT, port2); - match2.setField(MatchType.DL_SRC, srcMac2); - match2.setField(MatchType.DL_DST, dstMac2); - match2.setField(MatchType.DL_TYPE, ethertype2); - match2.setField(MatchType.DL_VLAN, vlan2); - match2.setField(MatchType.DL_VLAN_PR, vlanPr2); - match2.setField(MatchType.NW_SRC, srcIP2, ipMask2); - match2.setField(MatchType.NW_DST, dstIP2, ipMaskd2); - match2.setField(MatchType.NW_TOS, tos2); - match2.setField(MatchType.NW_PROTO, proto2); - match2.setField(MatchType.TP_SRC, src2); - match2.setField(MatchType.TP_DST, dst2); - - Assert.assertTrue(match1.equals(match2)); - - // Make sure all values are equals - for (MatchType type : MatchType.values()) { - if (match1.isPresent(type)) { - Assert.assertTrue(match1.getField(type).equals(match2.getField(type))); - } - } - - // Make none of the fields couples are pointing to the same reference - MatchField a = null, b = null; - for (MatchType type : MatchType.values()) { - a = match1.getField(type); - b = match2.getField(type); - if (a != null && b != null) { - Assert.assertFalse(a == b); - } - } - } - - @Test - public void testEqualityNetMask() throws Exception { - - InetAddress srcIP = InetAddress.getByName("1.1.1.1"); - InetAddress ipMask = InetAddress.getByName("255.255.255.255"); - InetAddress srcIP2 = InetAddress.getByName("1.1.1.1"); - InetAddress ipMask2 = null; - short ethertype = EtherTypes.IPv4.shortValue(); - short ethertype2 = EtherTypes.IPv4.shortValue(); - - /* - * Create a SAL Flow aFlow - */ - Match match1 = new Match(); - Match match2 = new Match(); - - match1.setField(MatchType.DL_TYPE, ethertype); - match1.setField(MatchType.NW_SRC, srcIP, ipMask); - - match2.setField(MatchType.DL_TYPE, ethertype2); - match2.setField(MatchType.NW_SRC, srcIP2, ipMask2); - - Assert.assertTrue(match1.equals(match2)); - - ipMask2 = InetAddress.getByName("255.255.255.255"); - match2.setField(MatchType.NW_SRC, srcIP2, ipMask2); - - srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - srcIP2 = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - ipMask = null; - ipMask2 = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); - ethertype = EtherTypes.IPv6.shortValue(); - ethertype2 = EtherTypes.IPv6.shortValue(); - - match1.setField(MatchType.DL_TYPE, ethertype); - match1.setField(MatchType.NW_SRC, srcIP, ipMask); - - match2.setField(MatchType.DL_TYPE, ethertype2); - match2.setField(MatchType.NW_SRC, srcIP2, ipMask2); - - Assert.assertTrue(match1.equals(match2)); - } - - @Test - public void testHashCodeWithReverseMatch() throws Exception { - InetAddress srcIP1 = InetAddress.getByName("1.1.1.1"); - InetAddress ipMask1 = InetAddress.getByName("255.255.255.255"); - InetAddress srcIP2 = InetAddress.getByName("2.2.2.2"); - InetAddress ipMask2 = InetAddress.getByName("255.255.255.255"); - MatchField field1 = new MatchField(MatchType.NW_SRC, srcIP1, ipMask1); - MatchField field2 = new MatchField(MatchType.NW_DST, srcIP2, ipMask2); - Match match1 = new Match(); - match1.setField(field1); - match1.setField(field2); - Match match2 = match1.reverse(); - Assert.assertFalse(match1.hashCode() == match2.hashCode()); - } - - @Test - public void testHashCode() throws Exception { - byte srcMac1[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte srcMac2[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac1[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - byte dstMac2[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - short ethertype = EtherTypes.IPv4.shortValue(); - short ethertype2 = EtherTypes.IPv4.shortValue(); - InetAddress srcIP1 = InetAddress.getByName("1.1.1.1"); - InetAddress ipMask1 = InetAddress.getByName("255.255.255.255"); - InetAddress srcIP2 = InetAddress.getByName("1.1.1.1"); - InetAddress ipMask2 = InetAddress.getByName("255.255.255.255"); - - Match match1 = new Match(); - Match match2 = new Match(); - - MatchField field1 = new MatchField(MatchType.DL_SRC, srcMac1); - MatchField field2 = new MatchField(MatchType.DL_SRC, srcMac2); - Assert.assertTrue(field1.hashCode() == field2.hashCode()); - - match1.setField(field1); - match2.setField(field2); - Assert.assertTrue(match1.hashCode() == match2.hashCode()); - - MatchField field3 = new MatchField(MatchType.DL_DST, dstMac1); - MatchField field4 = new MatchField(MatchType.DL_DST, dstMac2); - Assert.assertTrue(field3.hashCode() == field4.hashCode()); - - match1.setField(field3); - match2.setField(field4); - Assert.assertTrue(match1.hashCode() == match2.hashCode()); - - MatchField field5 = new MatchField(MatchType.DL_TYPE, ethertype); - MatchField field6 = new MatchField(MatchType.DL_TYPE, ethertype2); - Assert.assertTrue(field5.hashCode() == field6.hashCode()); - - match1.setField(field5); - match2.setField(field6); - Assert.assertTrue(match1.hashCode() == match2 .hashCode()); - - MatchField field7 = new MatchField(MatchType.NW_SRC, srcIP1, ipMask1); - MatchField field8 = new MatchField(MatchType.NW_SRC, srcIP2, ipMask2); - Assert.assertTrue(field7.hashCode() == field8.hashCode()); - - match1.setField(field7); - match2.setField(field8); - Assert.assertTrue(match1.hashCode() == match2.hashCode()); - - } - - @Test - public void testCloning() throws Exception { - Node node = NodeCreator.createOFNode(7L); - NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMasks = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - InetAddress ipMaskd = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27; - byte vlanPr = (byte) 3; - Byte tos = 4; - byte proto = IPProtocols.UDP.byteValue(); - short src = (short) 5500; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(MatchType.IN_PORT, port); - match.setField(MatchType.DL_SRC, srcMac); - match.setField(MatchType.DL_DST, dstMac); - match.setField(MatchType.DL_TYPE, ethertype); - match.setField(MatchType.DL_VLAN, vlan); - match.setField(MatchType.DL_VLAN_PR, vlanPr); - match.setField(MatchType.NW_SRC, srcIP, ipMasks); - match.setField(MatchType.NW_DST, dstIP, ipMaskd); - match.setField(MatchType.NW_TOS, tos); - match.setField(MatchType.NW_PROTO, proto); - match.setField(MatchType.TP_SRC, src); - match.setField(MatchType.TP_DST, dst); - - Match cloned = match.clone(); - - // Make sure all values are equals - for (MatchType type : MatchType.values()) { - if (match.isPresent(type)) { - if (!match.getField(type).equals(cloned.getField(type))) { - Assert.assertTrue(match.getField(type).equals(cloned.getField(type))); - } - } - } - - // Make sure none of the fields couples are pointing to the same - // reference - MatchField a = null, b = null; - for (MatchType type : MatchType.values()) { - a = match.getField(type); - b = cloned.getField(type); - if (a != null && b != null) { - Assert.assertFalse(a == b); - } - } - - Assert.assertTrue(match.equals(cloned)); - - Assert.assertFalse(match.getField(MatchType.DL_SRC) == cloned.getField(MatchType.DL_SRC)); - Assert.assertFalse(match.getField(MatchType.NW_DST) == cloned.getField(MatchType.NW_DST)); - Assert.assertTrue(match.getField(MatchType.NW_DST).getMask() - .equals(cloned.getField(MatchType.NW_DST).getMask())); - Assert.assertTrue(match.hashCode() == cloned.hashCode()); - } - - @Test - public void testFlip() throws Exception { - Node node = NodeCreator.createOFNode(7L); - NodeConnector port = NodeConnectorCreator.createOFNodeConnector((short) 24, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress.getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress.getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMasks = InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - InetAddress ipMaskd = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27; - byte vlanPr = (byte) 3; - Byte tos = 4; - byte proto = IPProtocols.UDP.byteValue(); - short src = (short) 5500; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(MatchType.IN_PORT, port); - match.setField(MatchType.DL_SRC, srcMac); - match.setField(MatchType.DL_DST, dstMac); - match.setField(MatchType.DL_TYPE, ethertype); - match.setField(MatchType.DL_VLAN, vlan); - match.setField(MatchType.DL_VLAN_PR, vlanPr); - match.setField(MatchType.NW_SRC, srcIP, ipMasks); - match.setField(MatchType.NW_DST, dstIP, ipMaskd); - match.setField(MatchType.NW_TOS, tos); - match.setField(MatchType.NW_PROTO, proto); - match.setField(MatchType.TP_SRC, src); - match.setField(MatchType.TP_DST, dst); - - Match flipped = match.reverse(); - - Assert.assertTrue(match.getField(MatchType.DL_TYPE).equals(flipped.getField(MatchType.DL_TYPE))); - Assert.assertTrue(match.getField(MatchType.DL_VLAN).equals(flipped.getField(MatchType.DL_VLAN))); - - Assert.assertTrue(match.getField(MatchType.DL_DST).getValue() - .equals(flipped.getField(MatchType.DL_SRC).getValue())); - Assert.assertTrue(match.getField(MatchType.DL_DST).getMask() == flipped.getField(MatchType.DL_SRC).getMask()); - - Assert.assertTrue(match.getField(MatchType.NW_DST).getValue() - .equals(flipped.getField(MatchType.NW_SRC).getValue())); - Assert.assertTrue(match.getField(MatchType.NW_DST).getMask() == flipped.getField(MatchType.NW_SRC).getMask()); - - Assert.assertTrue(match.getField(MatchType.TP_DST).getValue() - .equals(flipped.getField(MatchType.TP_SRC).getValue())); - Assert.assertTrue(match.getField(MatchType.TP_DST).getMask() == flipped.getField(MatchType.TP_SRC).getMask()); - - Match flipflip = flipped.reverse().reverse(); - Assert.assertTrue(flipflip.equals(flipped)); - - } - - @Test - public void testVlanNone() throws Exception { - // The value 0 is used to indicate that no VLAN ID is set - short vlan = (short) 0; - MatchField field = new MatchField(MatchType.DL_VLAN, vlan); - - Assert.assertTrue(field != null); - Assert.assertTrue(field.getValue().equals(new Short(vlan))); - Assert.assertTrue(field.isValid()); - } - - @Test - public void testIntersection() throws UnknownHostException { - Short ethType = Short.valueOf((short)0x800); - InetAddress ip1 = InetAddress.getByName("1.1.1.1"); - InetAddress ip2 = InetAddress.getByName("1.1.1.0"); - InetAddress ipm2 = InetAddress.getByName("255.255.255.0"); - InetAddress ip3 = InetAddress.getByName("1.3.0.0"); - InetAddress ipm3 = InetAddress.getByName("255.255.0.0"); - InetAddress ip4 = InetAddress.getByName("1.3.4.4"); - InetAddress ipm4 = InetAddress.getByName("255.255.255.0"); - - Match m1 = new Match(); - m1.setField(MatchType.DL_TYPE, ethType); - m1.setField(MatchType.NW_SRC, ip1); - - Match m2 = new Match(); - m2.setField(MatchType.DL_TYPE, ethType); - m2.setField(MatchType.NW_SRC, ip2, ipm2); - - Match m3 = new Match(); - m3.setField(MatchType.DL_TYPE, ethType); - m3.setField(MatchType.NW_SRC, ip3, ipm3); - m3.setField(MatchType.NW_PROTO, IPProtocols.TCP.byteValue()); - - Match m3r = m3.reverse(); - Assert.assertTrue(m3.intersetcs(m3r)); - - Assert.assertTrue(m1.intersetcs(m2)); - Assert.assertTrue(m2.intersetcs(m1)); - Assert.assertFalse(m1.intersetcs(m3)); - Assert.assertTrue(m1.intersetcs(m3r)); - Assert.assertFalse(m3.intersetcs(m1)); - Assert.assertTrue(m3.intersetcs(m1.reverse())); - Assert.assertFalse(m2.intersetcs(m3)); - Assert.assertFalse(m3.intersetcs(m2)); - Assert.assertTrue(m2.intersetcs(m3r)); - - - Match i = m1.getIntersection(m2); - Assert.assertTrue(((Short)i.getField(MatchType.DL_TYPE).getValue()).equals(ethType)); - // Verify intersection of IP addresses is correct - Assert.assertTrue(((InetAddress)i.getField(MatchType.NW_SRC).getValue()).equals(ip1)); - Assert.assertNull(i.getField(MatchType.NW_SRC).getMask()); - - // Empty set - i = m2.getIntersection(m3); - Assert.assertNull(i); - - Match m4 = new Match(); - m4.setField(MatchType.DL_TYPE, ethType); - m4.setField(MatchType.NW_PROTO, IPProtocols.TCP.byteValue()); - m3.setField(MatchType.NW_SRC, ip4, ipm4); - Assert.assertTrue(m4.intersetcs(m3)); - - // Verify intersection of IP and IP mask addresses is correct - Match ii = m3.getIntersection(m4); - Assert.assertTrue(((InetAddress)ii.getField(MatchType.NW_SRC).getValue()).equals(ip4)); - Assert.assertTrue(((InetAddress)ii.getField(MatchType.NW_SRC).getMask()).equals(ipm4)); - - Match m5 = new Match(); - m5.setField(MatchType.DL_TYPE, ethType); - m3.setField(MatchType.NW_SRC, ip3, ipm3); - m5.setField(MatchType.NW_PROTO, IPProtocols.UDP.byteValue()); - Assert.assertFalse(m5.intersetcs(m3)); - Assert.assertFalse(m5.intersetcs(m4)); - Assert.assertTrue(m5.intersetcs(m5)); - Assert.assertFalse(m3.intersetcs(m5)); - Assert.assertFalse(m4.intersetcs(m5)); - - - Match i2 = m4.getIntersection(m3); - Assert.assertFalse(i2.getMatches() == 0); - Assert.assertFalse(i2.getMatchesList().isEmpty()); - Assert.assertTrue(((InetAddress)i2.getField(MatchType.NW_SRC).getValue()).equals(ip3)); - Assert.assertTrue(((InetAddress)i2.getField(MatchType.NW_SRC).getMask()).equals(ipm3)); - Assert.assertTrue(((Byte)i2.getField(MatchType.NW_PROTO).getValue()).equals(IPProtocols.TCP.byteValue())); - - byte src[] = {(byte)0, (byte)0xab,(byte)0xbc,(byte)0xcd,(byte)0xde,(byte)0xef}; - byte dst[] = {(byte)0x10, (byte)0x11,(byte)0x12,(byte)0x13,(byte)0x14,(byte)0x15}; - Short srcPort = (short)1024; - Short dstPort = (short)80; - - // Check identity - Match m6 = new Match(); - m6.setField(MatchType.DL_SRC, src); - m6.setField(MatchType.DL_DST, dst); - m6.setField(MatchType.NW_SRC, ip2, ipm2); - m6.setField(MatchType.NW_DST, ip3, ipm3); - m6.setField(MatchType.NW_PROTO, IPProtocols.UDP.byteValue()); - m6.setField(MatchType.TP_SRC, srcPort); - m6.setField(MatchType.TP_DST, dstPort); - Assert.assertTrue(m6.intersetcs(m6)); - Assert.assertTrue(m6.getIntersection(m6).equals(m6)); - - // Empty match, represents the universal set (all packets) - Match u = new Match(); - Assert.assertTrue(m6.getIntersection(u).equals(m6)); - Assert.assertTrue(u.getIntersection(m6).equals(m6)); - - // No intersection with null match, empty set - Assert.assertNull(m6.getIntersection(null)); - } - - @Test - public void testMetadata() { - Property tier1 = new Tier(1); - Property tier2 = new Tier(2); - Property table1 = new Tables((byte)0x7f); - Match m1 = new Match(); - List resprops = null; - resprops = m1.getMetadatas(); - // This should be null - Assert.assertTrue(resprops.isEmpty()); - m1.setMetadata("tier1", tier1); - m1.setMetadata("tier2", tier2); - m1.setMetadata("table1", table1); - resprops = m1.getMetadatas(); - // Check for the number of elements in it - Assert.assertTrue(resprops.size() == 3); - // Check if the elements are in it - Assert.assertTrue(resprops.contains(tier1)); - Assert.assertTrue(resprops.contains(tier2)); - Assert.assertTrue(resprops.contains(table1)); - // Check for single elements retrieve - Assert.assertTrue(m1.getMetadata("tier1").equals(tier1)); - Assert.assertTrue(m1.getMetadata("tier2").equals(tier2)); - Assert.assertTrue(m1.getMetadata("table1").equals(table1)); - // Now remove an element and make sure the remaining are - // correct - m1.removeMetadata("tier1"); - - resprops = m1.getMetadatas(); - // Check for the number of elements in it - Assert.assertTrue(resprops.size() == 2); - // Check if the elements are in it - Assert.assertFalse(resprops.contains(tier1)); - Assert.assertTrue(resprops.contains(tier2)); - Assert.assertTrue(resprops.contains(table1)); - // Check for single elements retrieve - Assert.assertTrue(m1.getMetadata("table1").equals(table1)); - Assert.assertTrue(m1.getMetadata("tier2").equals(tier2)); - Assert.assertNull(m1.getMetadata("tier1")); - - // Check for an element never existed - Assert.assertNull(m1.getMetadata("table100")); - - // Remove them all - m1.removeMetadata("tier2"); - m1.removeMetadata("table1"); - - // Remove also a non-existent one - m1.removeMetadata("table100"); - - resprops = m1.getMetadatas(); - // Check there are no elements left - Assert.assertTrue(resprops.size() == 0); - - // Now check for exception on setting null values - try { - m1.setMetadata("foo", null); - // The line below should never be reached - Assert.assertTrue(false); - } catch (NullPointerException nue) { - // NPE should be raised for null value - Assert.assertTrue(true); - } - - // Now check on using null key - try { - m1.setMetadata(null, table1); - // The line below should never be reached - Assert.assertTrue(false); - } catch (NullPointerException nue) { - // NPE should be raised for null value - Assert.assertTrue(true); - } - - // Now check on using null key and null value - try { - m1.setMetadata(null, null); - // The line below should never be reached - Assert.assertTrue(false); - } catch (NullPointerException nue) { - // NPE should be raised for null value - Assert.assertTrue(true); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java deleted file mode 100644 index 792772a15c..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java +++ /dev/null @@ -1,226 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import org.junit.Test; - -import org.junit.Assert; - -public class ARPTest { - - @Test - public void testGetHardwareType() { - ARP arp = new ARP(); - byte[] hardwaretype = { 8, 6 }; - arp.hdrFieldsMap.put("HardwareType", hardwaretype); - short hwtype = arp.getHardwareType(); - Assert.assertTrue(hwtype == 2054); - } - - @Test - public void testGetProtocolType() { - ARP arp = new ARP(); - byte[] protocoltype = { 8, 0 }; - arp.hdrFieldsMap.put("ProtocolType", protocoltype); - short ptype = arp.getProtocolType(); - Assert.assertTrue(ptype == 2048); - } - - @Test - public void testGetHardwareAddressLength() { - ARP arp = new ARP(); - byte[] hardwareaddresslength = { 48 }; - arp.hdrFieldsMap.put("HardwareAddressLength", hardwareaddresslength); - byte hwaddrlength = arp.getHardwareAddressLength(); - Assert.assertTrue(hwaddrlength == 48); - } - - @Test - public void testGetProtocolAddressLength() { - ARP arp = new ARP(); - byte[] protocoladdresslength = { 32 }; - arp.hdrFieldsMap.put("ProtocolAddressLength", protocoladdresslength); - byte paddrlength = arp.getProtocolAddressLength(); - Assert.assertTrue(paddrlength == 32); - } - - @Test - public void testGetOpCode() { - ARP arp = new ARP(); - byte[] opcode = { 0, 2 }; - arp.hdrFieldsMap.put("OpCode", opcode); - short opCode = arp.getOpCode(); - Assert.assertTrue(opCode == 2); - } - - @Test - public void testGetSenderHardwareAddress() { - ARP arp = new ARP(); - byte[] hardwareaddress = { 48, 50, 120, 15, 66, 80 }; - arp.hdrFieldsMap.put("SenderHardwareAddress", hardwareaddress); - byte[] hwAddress = arp.getSenderHardwareAddress(); - Assert.assertTrue(hwAddress[0] == 48); - Assert.assertTrue(hwAddress[1] == 50); - Assert.assertTrue(hwAddress[2] == 120); - Assert.assertTrue(hwAddress[3] == 15); - Assert.assertTrue(hwAddress[4] == 66); - Assert.assertTrue(hwAddress[5] == 80); - } - - @Test - public void testGetSenderProtocolAddress() { - ARP arp = new ARP(); - byte[] protocoladdress = { 50, 100, 10, 20, 40, 80 }; - arp.hdrFieldsMap.put("SenderProtocolAddress", protocoladdress); - byte[] pAddress = arp.getSenderProtocolAddress(); - Assert.assertTrue(pAddress[0] == 50); - Assert.assertTrue(pAddress[1] == 100); - Assert.assertTrue(pAddress[2] == 10); - Assert.assertTrue(pAddress[3] == 20); - Assert.assertTrue(pAddress[4] == 40); - Assert.assertTrue(pAddress[5] == 80); - } - - @Test - public void testGetTargetHardwareAddress() { - ARP arp = new ARP(); - byte[] hardwareaddress = { 48, 50, 120, 15, 66, 80 }; - arp.hdrFieldsMap.put("TargetHardwareAddress", hardwareaddress); - byte[] hwAddress = arp.getTargetHardwareAddress(); - Assert.assertTrue(hwAddress[0] == 48); - Assert.assertTrue(hwAddress[1] == 50); - Assert.assertTrue(hwAddress[2] == 120); - Assert.assertTrue(hwAddress[3] == 15); - Assert.assertTrue(hwAddress[4] == 66); - Assert.assertTrue(hwAddress[5] == 80); - } - - @Test - public void testGetTargetProtocolAddress() { - ARP arp = new ARP(); - byte[] protocoladdress = { 50, 100, 10, 20, 40, 80 }; - arp.hdrFieldsMap.put("TargetProtocolAddress", protocoladdress); - byte[] pAddress = arp.getTargetProtocolAddress(); - Assert.assertTrue(pAddress[0] == 50); - Assert.assertTrue(pAddress[1] == 100); - Assert.assertTrue(pAddress[2] == 10); - Assert.assertTrue(pAddress[3] == 20); - Assert.assertTrue(pAddress[4] == 40); - Assert.assertTrue(pAddress[5] == 80); - } - - @Test - public void testSetHardwareType() { - ARP arp = new ARP(); - short hwtype = 2054; - arp.setHardwareType(hwtype); - byte[] hardwaretype = arp.hdrFieldsMap.get("HardwareType"); - Assert.assertTrue(hardwaretype[0] == 8); - Assert.assertTrue(hardwaretype[1] == 6); - } - - @Test - public void testSetProtocolType() { - ARP arp = new ARP(); - short ptype = 2048; - arp.setProtocolType(ptype); - byte[] protocoltype = arp.hdrFieldsMap.get("ProtocolType"); - Assert.assertTrue(protocoltype[0] == 8); - Assert.assertTrue(protocoltype[1] == 0); - } - - @Test - public void testSetHardwareAddressLength() { - ARP arp = new ARP(); - byte hwaddrlength = 48; - arp.setHardwareAddressLength(hwaddrlength); - byte[] hardwareaddresslength = arp.hdrFieldsMap - .get("HardwareAddressLength"); - Assert.assertTrue(hardwareaddresslength[0] == 48); - } - - @Test - public void testSetProtocolAddressLength() { - ARP arp = new ARP(); - byte PAddrlength = 32; - arp.setProtocolAddressLength(PAddrlength); - byte[] protocoladdresslength = arp.hdrFieldsMap - .get("ProtocolAddressLength"); - Assert.assertTrue(protocoladdresslength[0] == 32); - } - - @Test - public void testSetOpCode() { - ARP arp = new ARP(); - short opCode = (short) 2; - arp.setOpCode(opCode); - byte[] opcode = arp.hdrFieldsMap.get("OpCode"); - //System.out.println(opCode); - Assert.assertTrue(opcode[0] == 0); - Assert.assertTrue(opcode[1] == 2); - } - - @Test - public void testSetSenderHardwareAddress() { - ARP arp = new ARP(); - byte[] hardwareaddress = { 48, 50, 120, 15, 66, 80 }; - arp.setSenderHardwareAddress(hardwareaddress); - byte[] hwAddress = arp.hdrFieldsMap.get("SenderHardwareAddress"); - Assert.assertTrue(hwAddress[0] == 48); - Assert.assertTrue(hwAddress[1] == 50); - Assert.assertTrue(hwAddress[2] == 120); - Assert.assertTrue(hwAddress[3] == 15); - Assert.assertTrue(hwAddress[4] == 66); - Assert.assertTrue(hwAddress[5] == 80); - } - - @Test - public void testSetSenderProtocolAddress() { - ARP arp = new ARP(); - byte[] protocoladdress = { 50, 100, 10, 20, 40, 80 }; - arp.setSenderProtocolAddress(protocoladdress); - byte[] pAddress = arp.hdrFieldsMap.get("SenderProtocolAddress"); - Assert.assertTrue(pAddress[0] == 50); - Assert.assertTrue(pAddress[1] == 100); - Assert.assertTrue(pAddress[2] == 10); - Assert.assertTrue(pAddress[3] == 20); - Assert.assertTrue(pAddress[4] == 40); - Assert.assertTrue(pAddress[5] == 80); - } - - @Test - public void testSetTargetHardwareAddress() { - ARP arp = new ARP(); - byte[] hardwareaddress = { 48, 50, 120, 15, 66, 80 }; - arp.setTargetHardwareAddress(hardwareaddress); - byte[] hwAddress = arp.hdrFieldsMap.get("TargetHardwareAddress"); - Assert.assertTrue(hwAddress[0] == 48); - Assert.assertTrue(hwAddress[1] == 50); - Assert.assertTrue(hwAddress[2] == 120); - Assert.assertTrue(hwAddress[3] == 15); - Assert.assertTrue(hwAddress[4] == 66); - Assert.assertTrue(hwAddress[5] == 80); - } - - @Test - public void testSetTargetProtocolAddress() { - ARP arp = new ARP(); - byte[] protocoladdress = { 50, 100, 10, 20, 40, 80 }; - arp.setTargetProtocolAddress(protocoladdress); - byte[] pAddress = arp.hdrFieldsMap.get("TargetProtocolAddress"); - Assert.assertTrue(pAddress[0] == 50); - Assert.assertTrue(pAddress[1] == 100); - Assert.assertTrue(pAddress[2] == 10); - Assert.assertTrue(pAddress[3] == 20); - Assert.assertTrue(pAddress[4] == 40); - Assert.assertTrue(pAddress[5] == 80); - } - -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/BitBufferHelperTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/BitBufferHelperTest.java deleted file mode 100644 index 98e8c45250..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/BitBufferHelperTest.java +++ /dev/null @@ -1,692 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import org.junit.Assert; - -import org.junit.Test; - -public class BitBufferHelperTest { - - @Test - public void testGetByte() { - byte[] data = { 100 }; - Assert.assertTrue(BitBufferHelper.getByte(data) == 100); - } - - @Test - public void testGetBits() throws Exception { - byte[] data = { 10, 12, 14, 20, 55, 69, 82, 97, 109, 117, 127, -50 }; - byte[] bits; - - bits = BitBufferHelper.getBits(data, 88, 8); //BYTE extraOffsetBits = extranumBits = 0 - Assert.assertTrue(bits[0] == -50); - - bits = BitBufferHelper.getBits(data, 8, 16); //Short - Assert.assertTrue(bits[0] == 12); - Assert.assertTrue(bits[1] == 14); - - bits = BitBufferHelper.getBits(data, 32, 32); //Int - Assert.assertTrue(bits[0] == 55); - Assert.assertTrue(bits[1] == 69); - Assert.assertTrue(bits[2] == 82); - Assert.assertTrue(bits[3] == 97); - - bits = BitBufferHelper.getBits(data, 16, 48); //Long - Assert.assertTrue(bits[0] == 14); - Assert.assertTrue(bits[1] == 20); - Assert.assertTrue(bits[2] == 55); - Assert.assertTrue(bits[3] == 69); - Assert.assertTrue(bits[4] == 82); - Assert.assertTrue(bits[5] == 97); - - bits = BitBufferHelper.getBits(data, 40, 7); //BYTE extraOffsetBits = extranumBits != 0 - Assert.assertTrue(bits[0] == 34); - - bits = BitBufferHelper.getBits(data, 8, 13); //Short - Assert.assertTrue(bits[0] == 1); - Assert.assertTrue(bits[1] == -127); - - bits = BitBufferHelper.getBits(data, 32, 28); //Int - Assert.assertTrue(bits[0] == 3); - Assert.assertTrue(bits[1] == 116); - Assert.assertTrue(bits[2] == 85); - Assert.assertTrue(bits[3] == 38); - - bits = BitBufferHelper.getBits(data, 16, 41); //Long - Assert.assertTrue(bits[0] == 0); - Assert.assertTrue(bits[1] == 28); - Assert.assertTrue(bits[2] == 40); - Assert.assertTrue(bits[3] == 110); - Assert.assertTrue(bits[4] == -118); - Assert.assertTrue(bits[5] == -92); - - bits = BitBufferHelper.getBits(data, 3, 7); //BYTE extraOffsetBits != 0; extranumBits == 0 - Assert.assertTrue(bits[0] == 40); - - bits = BitBufferHelper.getBits(data, 13, 16); //Short - Assert.assertTrue(bits[0] == -127); - Assert.assertTrue(bits[1] == -62); - - bits = BitBufferHelper.getBits(data, 5, 32); //Int - Assert.assertTrue(bits[0] == 65); - Assert.assertTrue(bits[1] == -127); - Assert.assertTrue(bits[2] == -62); - Assert.assertTrue(bits[3] == -122); - - bits = BitBufferHelper.getBits(data, 23, 48); //Long - Assert.assertTrue(bits[0] == 10); - Assert.assertTrue(bits[1] == 27); - Assert.assertTrue(bits[2] == -94); - Assert.assertTrue(bits[3] == -87); - Assert.assertTrue(bits[4] == 48); - Assert.assertTrue(bits[5] == -74); - - bits = BitBufferHelper.getBits(data, 66, 9); //BYTE extraOffsetBits != 0; extranumBits != 0 - Assert.assertTrue(bits[0] == 1); - Assert.assertTrue(bits[1] == 107); - - bits = BitBufferHelper.getBits(data, 13, 15); //Short - Assert.assertTrue(bits[0] == 64); - Assert.assertTrue(bits[1] == -31); - - bits = BitBufferHelper.getBits(data, 5, 29); //Int - Assert.assertTrue(bits[0] == 8); - Assert.assertTrue(bits[1] == 48); - Assert.assertTrue(bits[2] == 56); - Assert.assertTrue(bits[3] == 80); - - bits = BitBufferHelper.getBits(data, 31, 43); //Long - Assert.assertTrue(bits[0] == 0); - Assert.assertTrue(bits[1] == -35); - Assert.assertTrue(bits[2] == 21); - Assert.assertTrue(bits[3] == 73); - Assert.assertTrue(bits[4] == -123); - Assert.assertTrue(bits[5] == -75); - - bits = BitBufferHelper.getBits(data, 4, 12); //Short - Assert.assertTrue(bits[0] == 10); - Assert.assertTrue(bits[1] == 12); - - byte[] data1 = { 0, 8 }; - bits = BitBufferHelper.getBits(data1, 7, 9); //Short - Assert.assertTrue(bits[0] == 0); - Assert.assertTrue(bits[1] == 8); - - byte[] data2 = { 2, 8 }; - bits = BitBufferHelper.getBits(data2, 0, 7); //Short - Assert.assertTrue(bits[0] == 1); - - bits = BitBufferHelper.getBits(data2, 7, 9); //Short - Assert.assertTrue(bits[0] == 0); - Assert.assertTrue(bits[1] == 8); - } - - // [01101100][01100000] - // [01100011] - @Test - public void testGetBytes() throws Exception { - byte data[] = { 108, 96, 125, -112, 5, 6, 108, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, 22 }; - byte[] x; - - Assert.assertTrue(BitBufferHelper.getBits(data, 0, 8)[0] == 108); - Assert.assertTrue(BitBufferHelper.getBits(data, 8, 8)[0] == 96); - - x = BitBufferHelper.getBits(data, 0, 10); - Assert.assertTrue(x[0] == 1); - Assert.assertTrue(x[1] == -79); - - x = BitBufferHelper.getBits(data, 3, 8); - Assert.assertTrue(x[0] == 99); - //Assert.assertTrue(x[1] == 97); - - } - - @Test - public void testMSBMask() { - int numBits = 1; //MSB - int mask = BitBufferHelper.getMSBMask(numBits); - Assert.assertTrue(mask == 128); - - numBits = 8; - mask = BitBufferHelper.getMSBMask(numBits); - Assert.assertTrue(mask == 255); - - numBits = 2; - mask = BitBufferHelper.getMSBMask(numBits); - Assert.assertTrue(mask == 192); - } - - @Test - public void testLSBMask() { - int numBits = 1; //LSB - int mask = BitBufferHelper.getLSBMask(numBits); - Assert.assertTrue(mask == 1); - - numBits = 3; - mask = BitBufferHelper.getLSBMask(numBits); - Assert.assertTrue(mask == 7); - - numBits = 8; - mask = BitBufferHelper.getLSBMask(numBits); - Assert.assertTrue(mask == 255); - } - - @Test - public void testToByteArray() { - short sh = Short.MAX_VALUE; - byte[] data_sh = new byte[Byte.SIZE / 8]; - data_sh = BitBufferHelper.toByteArray(sh); - Assert.assertTrue(data_sh[0] == 127); - Assert.assertTrue(data_sh[1] == -1); - - short sh2 = Short.MIN_VALUE; - byte[] data_sh2 = new byte[Byte.SIZE / 8]; - data_sh2 = BitBufferHelper.toByteArray(sh2); - Assert.assertTrue(data_sh2[0] == -128); - Assert.assertTrue(data_sh2[1] == 0); - - short sh3 = 16384; - byte[] data_sh3 = new byte[Byte.SIZE / 8]; - data_sh3 = BitBufferHelper.toByteArray(sh3); - Assert.assertTrue(data_sh3[0] == 64); - Assert.assertTrue(data_sh3[1] == 0); - - short sh4 = 146; //TCP headerlenflags - startoffset = 103 - byte[] data_sh4 = new byte[Byte.SIZE / 8]; - data_sh4 = BitBufferHelper.toByteArray(sh4); - Assert.assertTrue(data_sh4[0] == 0); - Assert.assertTrue(data_sh4[1] == -110); - - short sh4_2 = 5000; //IPv4 Offset - startOffset = 51 (to 63) - byte[] data_sh4_2 = new byte[Byte.SIZE / 8]; - data_sh4_2 = BitBufferHelper.toByteArray(sh4_2); - Assert.assertTrue(data_sh4_2[0] == 19); - Assert.assertTrue(data_sh4_2[1] == -120); - - short sh4_3 = 5312; //numEndRestBits < numBitstoShiftBy - byte[] data_sh4_3 = new byte[Byte.SIZE / 8]; - data_sh4_3 = BitBufferHelper.toByteArray(sh4_3); - Assert.assertTrue(data_sh4_3[0] == 20); - Assert.assertTrue(data_sh4_3[1] == -64); - - int Int = Integer.MAX_VALUE; - byte[] data_Int = new byte[Integer.SIZE / 8]; - data_Int = BitBufferHelper.toByteArray(Int); - Assert.assertTrue(data_Int[0] == 127); - Assert.assertTrue(data_Int[1] == -1); - Assert.assertTrue(data_Int[2] == -1); - Assert.assertTrue(data_Int[3] == -1); - - int Int2 = Integer.MIN_VALUE; - byte[] data_Int2 = new byte[Integer.SIZE / 8]; - data_Int2 = BitBufferHelper.toByteArray(Int2); - Assert.assertTrue(data_Int2[0] == -128); - Assert.assertTrue(data_Int2[1] == 0); - Assert.assertTrue(data_Int2[2] == 0); - Assert.assertTrue(data_Int2[3] == 0); - - int Int3 = 1077952576; - byte[] data_Int3 = new byte[Integer.SIZE / 8]; - data_Int3 = BitBufferHelper.toByteArray(Int3); - Assert.assertTrue(data_Int3[0] == 64); - Assert.assertTrue(data_Int3[1] == 64); - Assert.assertTrue(data_Int3[2] == 64); - Assert.assertTrue(data_Int3[3] == 64); - - long Lng = Long.MAX_VALUE; - byte[] data_lng = new byte[Long.SIZE / 8]; - data_lng = BitBufferHelper.toByteArray(Lng); - Assert.assertTrue(data_lng[0] == 127); - Assert.assertTrue(data_lng[1] == -1); - Assert.assertTrue(data_lng[2] == -1); - Assert.assertTrue(data_lng[3] == -1); - Assert.assertTrue(data_lng[4] == -1); - Assert.assertTrue(data_lng[5] == -1); - Assert.assertTrue(data_lng[6] == -1); - Assert.assertTrue(data_lng[7] == -1); - - long Lng2 = Long.MIN_VALUE; - byte[] data_lng2 = new byte[Long.SIZE / 8]; - data_lng2 = BitBufferHelper.toByteArray(Lng2); - Assert.assertTrue(data_lng2[0] == -128); - Assert.assertTrue(data_lng2[1] == 0); - Assert.assertTrue(data_lng2[2] == 0); - Assert.assertTrue(data_lng2[3] == 0); - Assert.assertTrue(data_lng2[4] == 0); - Assert.assertTrue(data_lng2[5] == 0); - Assert.assertTrue(data_lng2[6] == 0); - Assert.assertTrue(data_lng2[7] == 0); - - byte B = Byte.MAX_VALUE; - byte[] data_B = new byte[Byte.SIZE / 8]; - data_B = BitBufferHelper.toByteArray(B); - Assert.assertTrue(data_B[0] == 127); - - byte B1 = Byte.MIN_VALUE; - byte[] data_B1 = new byte[Byte.SIZE / 8]; - data_B1 = BitBufferHelper.toByteArray(B1); - Assert.assertTrue(data_B1[0] == -128); - - byte B2 = 64; - byte[] data_B2 = new byte[Byte.SIZE / 8]; - data_B2 = BitBufferHelper.toByteArray(B2); - Assert.assertTrue(data_B2[0] == 64); - - byte B3 = 32; - byte[] data_B3 = new byte[Byte.SIZE / 8]; - data_B3 = BitBufferHelper.toByteArray(B3); - Assert.assertTrue(data_B3[0] == 32); - - } - - @Test - public void testToByteArrayVariable() { - int len = 9; - byte[] data_sh; - data_sh = BitBufferHelper.toByteArray(511, len); - Assert.assertTrue(data_sh[0] == (byte) 255); - Assert.assertTrue(data_sh[1] == (byte) 128); - - data_sh = BitBufferHelper.toByteArray((int) 511, len); - Assert.assertTrue(data_sh[0] == (byte) 255); - Assert.assertTrue(data_sh[1] == (byte) 128); - - data_sh = BitBufferHelper.toByteArray((long) 511, len); - Assert.assertTrue(data_sh[0] == (byte) 255); - Assert.assertTrue(data_sh[1] == (byte) 128); - } - - @Test - public void testToInt() { - byte data[] = { 1 }; - Assert.assertTrue(BitBufferHelper.toNumber(data) == 1); - - byte data2[] = { 1, 1 }; - Assert.assertTrue(BitBufferHelper.toNumber(data2) == 257); - - byte data3[] = { 1, 1, 1 }; - Assert.assertTrue(BitBufferHelper.toNumber(data3) == 65793); - } - - @Test - public void testToLongGetter() { - byte data[] = { 1, 1 }; - Assert.assertTrue(BitBufferHelper.getLong(data) == 257L); - } - - @Test - public void testSetByte() throws Exception { - byte input; - byte[] data = new byte[20]; - - input = 125; - BitBufferHelper.setByte(data, input, 0, Byte.SIZE); - Assert.assertTrue(data[0] == 125); - - input = 109; - BitBufferHelper.setByte(data, input, 152, Byte.SIZE); - Assert.assertTrue(data[19] == 109); - } - - @Test - public void testSetBytes() throws Exception { - byte[] input = { 0, 1 }; - byte[] data = { 6, 0 }; - - BitBufferHelper.setBytes(data, input, 7, 9); - Assert.assertTrue(data[0] == 6); - Assert.assertTrue(data[1] == 1); - } - - //@Test - //INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001]*/ - public void testInsertBits() throws Exception { - //CASE 1: startOffset%8 == 0 && numBits%8 == 0 - byte inputdata[] = { 75, 110, 107, 80, 10, 12, 35, 100, 125, 65 }; - int startOffset = 0; - int numBits = 8; - - byte data1[] = new byte[2]; - startOffset = 0; - numBits = 16; - BitBufferHelper.insertBits(data1, inputdata, startOffset, numBits); - Assert.assertTrue(data1[0] == 75); - Assert.assertTrue(data1[1] == 110); - - byte data2[] = new byte[4]; - startOffset = 0; - numBits = 32; - BitBufferHelper.insertBits(data2, inputdata, startOffset, numBits); - Assert.assertTrue(data2[0] == 75); - Assert.assertTrue(data2[1] == 110); - Assert.assertTrue(data2[2] == 107); - Assert.assertTrue(data2[3] == 80); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] // OUTPUT: [01001011] [01101000] = {75, 104} - byte data10[] = new byte[2]; - startOffset = 0; - numBits = 13; - BitBufferHelper.insertBits(data10, inputdata, startOffset, numBits); - Assert.assertTrue(data10[0] == 75); - Assert.assertTrue(data10[1] == 104); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] // OUTPUT: [01001000] = {72} - byte data11[] = new byte[4]; - startOffset = 8; - numBits = 6; - BitBufferHelper.insertBits(data11, inputdata, startOffset, numBits); - Assert.assertTrue(data11[1] == 72); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [01001011] [01101110] [01101000] = {75, 110, 105} - byte data12[] = new byte[4]; - startOffset = 0; - numBits = 23; - BitBufferHelper.insertBits(data12, inputdata, startOffset, numBits); - Assert.assertTrue(data12[0] == 75); - Assert.assertTrue(data12[1] == 110); - Assert.assertTrue(data12[2] == 106); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [01001011] [01101110] [01100000] = {75, 110, 96} - byte data13[] = new byte[4]; - startOffset = 8; - numBits = 20; - BitBufferHelper.insertBits(data13, inputdata, startOffset, numBits); - Assert.assertTrue(data13[1] == 75); - Assert.assertTrue(data13[2] == 110); - Assert.assertTrue(data13[3] == 96); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [01001011] [01101110] [01101011] [10100000]= {75, 110, 107, 80} - byte data14[] = new byte[4]; - startOffset = 0; - numBits = 30; - BitBufferHelper.insertBits(data14, inputdata, startOffset, numBits); - Assert.assertTrue(data14[0] == 75); - Assert.assertTrue(data14[1] == 110); - Assert.assertTrue(data14[2] == 107); - Assert.assertTrue(data14[3] == 80); - - //CASE 3: startOffset%8 != 0, numBits%8 = 0 - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [10100000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00001001] [11000000] = {72, 96} - byte data16[] = new byte[5]; - startOffset = 3; - numBits = 8; - BitBufferHelper.insertBits(data16, inputdata, startOffset, numBits); - Assert.assertTrue(data16[0] == 9); - Assert.assertTrue(data16[1] == 96); - Assert.assertTrue(data16[2] == 0); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: [00000100] [1011 0110] [1110 0000] = {4, -54, -96} - - startOffset = 3; - numBits = 16; - byte data17[] = new byte[5]; - BitBufferHelper.insertBits(data17, inputdata, startOffset, numBits); - Assert.assertTrue(data17[0] == 9); - Assert.assertTrue(data17[1] == 109); - Assert.assertTrue(data17[2] == -64); - Assert.assertTrue(data17[3] == 0); - - // INPUT: {79, 110, 111} - // = [01001111] [01101110] [01101111] - //OUTPUT: [0000 1001] [1110 1101] [110 00000] = {9, -19, -64} - byte data18[] = new byte[5]; - byte inputdata3[] = { 79, 110, 111 }; - startOffset = 3; - numBits = 16; - BitBufferHelper.insertBits(data18, inputdata3, startOffset, numBits); - Assert.assertTrue(data18[0] == 9); - Assert.assertTrue(data18[1] == -19); - Assert.assertTrue(data18[2] == -64); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: [0000 1001] [0110 1101] [1100 1101] [0110 1010] [0000 0001] = {9, 109, -51, 106, 0} - - startOffset = 3; - numBits = 32; - byte data19[] = new byte[5]; - BitBufferHelper.insertBits(data19, inputdata, startOffset, numBits); - Assert.assertTrue(data19[0] == 9); - Assert.assertTrue(data19[1] == 109); - Assert.assertTrue(data19[2] == -51); - Assert.assertTrue(data19[3] == 106); - Assert.assertTrue(data19[4] == 0); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: data[4, 5, 6] = [0 010 0101] [1 011 0111] [0 000 0000] = {37, -73, 0} - startOffset = 33; - numBits = 16; - byte data20[] = new byte[7]; - BitBufferHelper.insertBits(data20, inputdata, startOffset, numBits); - Assert.assertTrue(data20[4] == 37); - Assert.assertTrue(data20[5] == -73); - Assert.assertTrue(data20[6] == 0); - - //CASE 4: extranumBits != 0 AND extraOffsetBits != 0 - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: [0000 1001] [0100 0000] = {9, 96} - startOffset = 3; - numBits = 7; - byte data21[] = new byte[7]; - BitBufferHelper.insertBits(data21, inputdata, startOffset, numBits); - Assert.assertTrue(data21[0] == 9); - Assert.assertTrue(data21[1] == 64); - Assert.assertTrue(data21[2] == 0); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: data = [00000 010] [01011 011] [01110 000] = {37, -73, 0} - startOffset = 5; - numBits = 17; - byte data22[] = new byte[7]; - BitBufferHelper.insertBits(data22, inputdata, startOffset, numBits); - Assert.assertTrue(data22[0] == 2); - Assert.assertTrue(data22[1] == 91); - Assert.assertTrue(data22[2] == 112); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: [0000 1001] [0110 1101] [110 01101] [01 00000] = {9, 109, -51, 64} - startOffset = 3; - numBits = 23; - byte data23[] = new byte[7]; - BitBufferHelper.insertBits(data23, inputdata, startOffset, numBits); - Assert.assertTrue(data23[0] == 9); - Assert.assertTrue(data23[1] == 109); - Assert.assertTrue(data23[2] == -51); - Assert.assertTrue(data23[3] == 64); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: [0000 1001] [0110 1101] = {9, 109} - startOffset = 3; - numBits = 13; - byte data24[] = new byte[7]; - BitBufferHelper.insertBits(data24, inputdata, startOffset, numBits); - Assert.assertTrue(data24[0] == 9); - Assert.assertTrue(data24[1] == 109); - Assert.assertTrue(data24[2] == 0); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: [0000 0100] [1011 0110] [1110 0110] = {4, -74, -26} - startOffset = 4; - numBits = 20; - byte data25[] = new byte[7]; - BitBufferHelper.insertBits(data25, inputdata, startOffset, numBits); - Assert.assertTrue(data25[0] == 4); - Assert.assertTrue(data25[1] == -74); - Assert.assertTrue(data25[2] == -26); - Assert.assertTrue(data25[3] == -0); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: [0000 0010] [0101 1011] = {0, 2, 91, 0} - startOffset = 13; - numBits = 11; - byte data26[] = new byte[7]; - BitBufferHelper.insertBits(data26, inputdata, startOffset, numBits); - Assert.assertTrue(data26[0] == 0); - Assert.assertTrue(data26[1] == 2); - Assert.assertTrue(data26[2] == 91); - Assert.assertTrue(data26[3] == 0); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: [000 01001] [011 01101] [110 0 0000] = {9, 109, -64, 0} - startOffset = 3; - numBits = 17; - byte data27[] = new byte[7]; - BitBufferHelper.insertBits(data27, inputdata, startOffset, numBits); - Assert.assertTrue(data27[0] == 9); - Assert.assertTrue(data27[1] == 109); - Assert.assertTrue(data27[2] == -64); - Assert.assertTrue(data27[3] == 0); - - // INPUT: {75, 110, 107, 80, 10, 12, 35, 100, 125, 65} = - // [01001011] [01101110] [01101011] [01010000] [00001010] [00001100] [00100011] [01100100] [11111101] [01000001] //OUTPUT: [00000000] [00000100] [10110110] [11100000]= {0, 4, -54, -96} - // OUTPUT: [00 000000] [00 000000] [00 010010] [11 011011] [10 011010] [11 010100] [0000 0000] = {0, 0, 18, -37,-102,-44,0} - startOffset = 18; - numBits = 34; - byte data28[] = new byte[7]; - BitBufferHelper.insertBits(data28, inputdata, startOffset, numBits); - Assert.assertTrue(data28[0] == 0); - Assert.assertTrue(data28[1] == 0); - Assert.assertTrue(data28[2] == 18); - Assert.assertTrue(data28[3] == -37); - Assert.assertTrue(data28[4] == -102); - Assert.assertTrue(data28[5] == -44); - Assert.assertTrue(data28[6] == 0); - - } - - @Test - public void testGetShort() throws Exception { - byte data[] = new byte[2]; - data[0] = 7; - data[1] = 8; - int length = 9; // num bits - Assert.assertTrue(BitBufferHelper.getShort(data, length) == 264); - - data[0] = 6; - data[1] = 8; - short result = BitBufferHelper.getShort(data, length); - Assert.assertTrue(result == 8); - - data[0] = 8; - data[1] = 47; - result = BitBufferHelper.getShort(data, length); - Assert.assertTrue(result == 47); - - //[0000 0001] [0001 0100] [0110 0100] - byte[] data1 = new byte[2]; - data1[0] = 1; - data1[1] = 20; //data1[2] = 100; - length = 15; - result = BitBufferHelper.getShort(data1, length); - Assert.assertTrue(result == 276); - - byte[] data2 = new byte[2]; - data2[0] = 64; - data2[1] = 99; //data2[2] = 100; - length = 13; - result = BitBufferHelper.getShort(data2, length); - Assert.assertTrue(result == 99); - - byte[] data3 = { 100, 50 }; - result = BitBufferHelper.getShort(data3); - Assert.assertTrue(result == 25650); - } - - @Test - public void testToIntVarLength() throws Exception { - byte data[] = { (byte) 255, (byte) 128 }; - int length = 9; // num bits - Assert.assertTrue(BitBufferHelper.getInt(data, length) == 384); - - byte data2[] = { 0, 8 }; - Assert.assertTrue(BitBufferHelper.getInt(data2, 9) == 8); - - byte data3[] = { 1, 1, 1 }; - Assert.assertTrue(BitBufferHelper.getInt(data3) == 65793); - - byte data4[] = { 1, 1, 1 }; - Assert.assertTrue(BitBufferHelper.getInt(data4) == 65793); - - byte data5[] = { 1, 1 }; - Assert.assertTrue(BitBufferHelper.getInt(data5) == 257); - - } - - @Test - public void testShiftBitstoLSB() { - byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - - byte[] data2 = { 8, 9, 10 }; - byte[] shiftedBytes2 = BitBufferHelper.shiftBitsToLSB(data2, 11); - - Assert.assertTrue(shiftedBytes2[0] == 0); - Assert.assertTrue(shiftedBytes2[1] == 64); - Assert.assertTrue(shiftedBytes2[2] == 72); - - byte[] shiftedBytes = BitBufferHelper.shiftBitsToLSB(data, 49); - - Assert.assertTrue(shiftedBytes[0] == 0); - Assert.assertTrue(shiftedBytes[1] == 2); - Assert.assertTrue(shiftedBytes[2] == 4); - Assert.assertTrue(shiftedBytes[3] == 6); - Assert.assertTrue(shiftedBytes[4] == 8); - Assert.assertTrue(shiftedBytes[5] == 10); - Assert.assertTrue(shiftedBytes[6] == 12); - Assert.assertTrue(shiftedBytes[7] == 14); - Assert.assertTrue(shiftedBytes[8] == 16); - Assert.assertTrue(shiftedBytes[9] == 18); - - byte[] data1 = { 1, 2, 3 }; - byte[] shiftedBytes1 = BitBufferHelper.shiftBitsToLSB(data1, 18); - Assert.assertTrue(shiftedBytes1[0] == 0); - Assert.assertTrue(shiftedBytes1[1] == 4); - Assert.assertTrue(shiftedBytes1[2] == 8); - - } - - @Test - public void testShiftBitstoLSBMSB() { - byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; - - byte[] clone = BitBufferHelper.shiftBitsToMSB(BitBufferHelper - .shiftBitsToLSB(data, 72), 72); - - Assert.assertTrue(clone[0] == 1); - Assert.assertTrue(clone[1] == 2); - Assert.assertTrue(clone[2] == 3); - Assert.assertTrue(clone[3] == 4); - Assert.assertTrue(clone[4] == 5); - Assert.assertTrue(clone[5] == 6); - Assert.assertTrue(clone[6] == 7); - Assert.assertTrue(clone[7] == 8); - Assert.assertTrue(clone[8] == 9); - Assert.assertTrue(clone[9] == 0); - } - -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java deleted file mode 100644 index 5176bd6cbc..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java +++ /dev/null @@ -1,121 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.util.Arrays; - -import org.junit.Assert; - -import org.junit.Test; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; - -public class EthernetTest { - - @Test - public void testGetDestinationMACAddress() { - Ethernet eth = new Ethernet(); - byte mac[] = { 10, 12, 14, 20, 55, 69 }; - eth.hdrFieldsMap.put("DestinationMACAddress", mac); - byte[] dMAC = eth.getDestinationMACAddress(); - Assert.assertTrue(dMAC[0] == 10); - Assert.assertTrue(dMAC[1] == 12); - Assert.assertTrue(dMAC[2] == 14); - Assert.assertTrue(dMAC[3] == 20); - Assert.assertTrue(dMAC[4] == 55); - Assert.assertTrue(dMAC[5] == 69); - - } - - @Test - public void testSourceMACAddress() { - Ethernet eth = new Ethernet(); - byte mac[] = { 120, 30, 25, 80, 66, 99 }; - eth.hdrFieldsMap.put("SourceMACAddress", mac); - byte[] sMAC = eth.getSourceMACAddress(); - Assert.assertTrue(sMAC[0] == 120); - Assert.assertTrue(sMAC[1] == 30); - Assert.assertTrue(sMAC[2] == 25); - Assert.assertTrue(sMAC[3] == 80); - Assert.assertTrue(sMAC[4] == 66); - Assert.assertTrue(sMAC[5] == 99); - - } - - @Test - public void testGetEthertype() throws Exception { - Ethernet eth = new Ethernet(); - byte ethType[] = { 8, 6 }; - eth.hdrFieldsMap.put("EtherType", ethType); - short etherType = eth.getEtherType(); - Assert.assertTrue(etherType == 2054); - } - - @Test - public void testSetDestinationMACAddress() { - Ethernet eth = new Ethernet(); - byte mac[] = { 10, 12, 14, 20, 55, 69 }; - eth.setDestinationMACAddress(mac); - byte[] dMAC = eth.hdrFieldsMap.get("DestinationMACAddress"); - Assert.assertTrue(dMAC[0] == 10); - Assert.assertTrue(dMAC[1] == 12); - Assert.assertTrue(dMAC[2] == 14); - Assert.assertTrue(dMAC[3] == 20); - Assert.assertTrue(dMAC[4] == 55); - Assert.assertTrue(dMAC[5] == 69); - - } - - @Test - public void testSetSourceMACAddress() { - Ethernet eth = new Ethernet(); - byte mac[] = { 120, 30, 25, 80, 66, 99 }; - eth.setSourceMACAddress(mac); - byte[] sMAC = eth.hdrFieldsMap.get("SourceMACAddress"); - Assert.assertTrue(sMAC[0] == 120); - Assert.assertTrue(sMAC[1] == 30); - Assert.assertTrue(sMAC[2] == 25); - Assert.assertTrue(sMAC[3] == 80); - Assert.assertTrue(sMAC[4] == 66); - Assert.assertTrue(sMAC[5] == 99); - - } - - @Test - public void testSetEthertype() throws Exception { - Ethernet eth = new Ethernet(); - short ethType = 2054; - eth.setEtherType(ethType); - byte[] etherType = eth.hdrFieldsMap.get("EtherType"); - Assert.assertTrue(etherType[0] == 8); - Assert.assertTrue(etherType[1] == 6); - - } - - @Test - public void testGetMatch() throws Exception { - Ethernet eth = new Ethernet(); - byte smac[] = { (byte) 0xf0, (byte) 0xde, (byte) 0xf1, (byte) 0x71, (byte) 0x72, (byte) 0x8d }; - byte dmac[] = { (byte) 0xde, (byte) 0x28, (byte) 0xdb, (byte) 0xb3, (byte) 0x7c, (byte) 0xf8 }; - short ethType = EtherTypes.IPv4.shortValue(); - eth.setDestinationMACAddress(dmac); - eth.setSourceMACAddress(smac); - eth.setEtherType(ethType); - - Match match = eth.getMatch(); - - Assert.assertTrue(Arrays.equals(smac, (byte[]) match.getField(MatchType.DL_SRC).getValue())); - Assert.assertTrue(Arrays.equals(dmac, (byte[]) match.getField(MatchType.DL_DST).getValue())); - Assert.assertEquals(ethType, (short) match.getField(MatchType.DL_TYPE).getValue()); - - } - -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ICMPTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ICMPTest.java deleted file mode 100644 index f591fb1952..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ICMPTest.java +++ /dev/null @@ -1,133 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.util.Arrays; - -import org.junit.Assert; - -import org.junit.Test; - -public class ICMPTest { - - @Test - public void testSetTypeCode() { - ICMP icmp = new ICMP(); - byte icmpType = 2; - icmp.setType(icmpType); - byte[] typeCode = icmp.hdrFieldsMap.get("Type"); - Assert.assertTrue(typeCode[0] == 2); - - } - - @Test - public void testSetChecksum() { - ICMP icmp = new ICMP(); - short icmpChecksum = 200; - icmp.setChecksum(icmpChecksum); - byte[] checksum = icmp.hdrFieldsMap.get("Checksum"); - Assert.assertTrue(checksum[0] == 0); - Assert.assertTrue(checksum[1] == -56); - - } - - @Test - public void testSetIdentifier() { - ICMP icmp = new ICMP(); - short icmpIdentifier = 1201; - icmp.setIdentifier(icmpIdentifier); - byte[] identifier = icmp.hdrFieldsMap.get("Identifier"); - Assert.assertTrue(identifier[0] == 4); - Assert.assertTrue(identifier[1] == -79); - - } - - @Test - public void testSetSequenceNumber() { - ICMP icmp = new ICMP(); - short icmpSequenceNumber = 5000; - icmp.setSequenceNumber(icmpSequenceNumber); - byte[] sequenceNumber = icmp.hdrFieldsMap.get("SequenceNumber"); - Assert.assertTrue(sequenceNumber[0] == 19); - Assert.assertTrue(sequenceNumber[1] == -120); - - } - - @Test - public void testSerialization() throws PacketException { - byte icmpRawPayload[] = { (byte) 0x38, (byte) 0x26, (byte) 0x9e, - (byte) 0x51, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x2e, (byte) 0x6a, (byte) 0x08, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x10, (byte) 0x11, (byte) 0x12, - (byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16, - (byte) 0x17, (byte) 0x18, (byte) 0x19, (byte) 0x1a, - (byte) 0x1b, (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, - (byte) 0x1f, (byte) 0x20, (byte) 0x21, (byte) 0x22, - (byte) 0x23, (byte) 0x24, (byte) 0x25, (byte) 0x26, - (byte) 0x27, (byte) 0x28, (byte) 0x29, (byte) 0x2a, - (byte) 0x2b, (byte) 0x2c, (byte) 0x2d, (byte) 0x2e, - (byte) 0x2f, (byte) 0x30, (byte) 0x31, (byte) 0x32, - (byte) 0x33, (byte) 0x34, (byte) 0x35, (byte) 0x36, (byte) 0x37 }; - serializeTest(icmpRawPayload, (short)0xe553); - - serializeTest(null, (short)0xb108); - serializeTest(new byte[0], (short)0xb108); - - byte[] odd = { - (byte)0xba, (byte)0xd4, (byte)0xc7, (byte)0x53, - (byte)0xf8, (byte)0x59, (byte)0x68, (byte)0x77, - (byte)0xfd, (byte)0x27, (byte)0xe0, (byte)0x5b, - (byte)0xd0, (byte)0x2e, (byte)0x28, (byte)0x41, - (byte)0xa3, (byte)0x48, (byte)0x5d, (byte)0x2e, - (byte)0x7d, (byte)0x5b, (byte)0xd3, (byte)0x60, - (byte)0xb3, (byte)0x88, (byte)0x8d, (byte)0x0f, - (byte)0x1d, (byte)0x87, (byte)0x51, (byte)0x0f, - (byte)0x6a, (byte)0xff, (byte)0xf7, (byte)0xd4, - (byte)0x40, (byte)0x35, (byte)0x4e, (byte)0x01, - (byte)0x36, - }; - serializeTest(odd, (short)0xd0ad); - - // Large payload that causes 16-bit checksum overflow more than - // 255 times. - byte[] largeEven = new byte[1024]; - Arrays.fill(largeEven, (byte)0xff); - serializeTest(largeEven, (short)0xb108); - - byte[] largeOdd = new byte[1021]; - Arrays.fill(largeOdd, (byte)0xff); - serializeTest(largeOdd, (short)0xb207); - } - - private void serializeTest(byte[] payload, short checksum) - throws PacketException { - ICMP icmp = new ICMP(); - icmp.setType((byte)8).setCode((byte)0). - setIdentifier((short)0x46f5).setSequenceNumber((short)2); - int payloadSize = 0; - if (payload != null) { - icmp.setRawPayload(payload); - payloadSize = payload.length; - } - - // Serialize - byte[] data = icmp.serialize(); - Assert.assertEquals(payloadSize + 8, data.length); - - // Deserialize - ICMP icmpDes = new ICMP(); - icmpDes.deserialize(data, 0, data.length); - - Assert.assertFalse(icmpDes.isCorrupted()); - Assert.assertEquals(checksum, icmpDes.getChecksum()); - Assert.assertEquals(icmp, icmpDes); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java deleted file mode 100644 index 99da52adfb..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import org.junit.Assert; - -import org.junit.Test; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.NetUtils; - -public class IEEE8021QTest { - - @Test - public void testGetPcp() throws Exception { - IEEE8021Q vlan = new IEEE8021Q(); - byte pcp[] = { 5 }; - vlan.hdrFieldsMap.put("PriorityCodePoint", pcp); - byte spcp = vlan.getPcp(); - Assert.assertTrue(spcp == 5); - } - - @Test - public void testGetCfi() throws Exception { - IEEE8021Q vlan = new IEEE8021Q(); - byte cfi[] = { 0 }; - vlan.hdrFieldsMap.put("CanonicalFormatIndicator", cfi); - byte scfi = vlan.getCfi(); - Assert.assertTrue(scfi == 0); - } - - @Test - public void testGetVid() throws Exception { - IEEE8021Q vlan = new IEEE8021Q(); - byte vid[] = { (byte) 0xF, (byte) 0xFE }; // 4094 - vlan.hdrFieldsMap.put("VlanIdentifier", vid); - short svid = vlan.getVid(); - Assert.assertTrue(svid == 4094); - } - - @Test - public void testGetEthertype() throws Exception { - IEEE8021Q vlan = new IEEE8021Q(); - byte ethType[] = { 8, 6 }; - vlan.hdrFieldsMap.put("EtherType", ethType); - short etherType = vlan.getEtherType(); - Assert.assertTrue(etherType == 2054); - } - - @Test - public void testSetPcp() throws Exception { - IEEE8021Q vlan = new IEEE8021Q(); - byte pcp = 5; - vlan.setPcp(pcp); - byte[] bpcp = vlan.hdrFieldsMap.get("PriorityCodePoint"); - Assert.assertTrue(bpcp[0] == 5); - } - - @Test - public void testSetCfi() throws Exception { - IEEE8021Q vlan = new IEEE8021Q(); - byte cfi = 0; - vlan.setCfi(cfi); - byte[] bcfi = vlan.hdrFieldsMap.get("CanonicalFormatIndicator"); - Assert.assertTrue(bcfi[0] == 0); - } - - @Test - public void testSetVid() throws Exception { - IEEE8021Q vlan = new IEEE8021Q(); - short vid = 4094; // 0xFFE - vlan.setVid(vid); - byte[] bvid = vlan.hdrFieldsMap.get("VlanIdentifier"); - Assert.assertTrue(bvid[0] == (byte) 0xF); - Assert.assertTrue(bvid[1] == (byte) 0xFE); - } - - @Test - public void testSetEthertype() throws Exception { - Ethernet eth = new Ethernet(); - short ethType = 2054; // 0x806 - eth.setEtherType(ethType); - byte[] etherType = eth.hdrFieldsMap.get("EtherType"); - Assert.assertTrue(etherType[0] == 8); - Assert.assertTrue(etherType[1] == 6); - } - - @Test - public void testDeserialize() throws Exception { - short startOffset, numBits; - Ethernet eth = new Ethernet(); - byte[] data = { - (byte) 0xA, (byte) 0xC, (byte) 0xE, (byte) 0x14, (byte) 0x37, (byte) 0x45, // Destination MAC - (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F, // Source MAC - (byte) 0x81, (byte) 0x00, // EtherType - (byte) 0xAF, (byte) 0xFE, // PCP, CFI, VLAN ID - 8, 6, // EtherType - 0, 1, // Hardware Type - 8, 0, // Protocol Type - 6, // Hardware Address Length - 4, // Protocol Address Length - 0, 1, // opCode - (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F, // Sender Hardware Address - (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0x1, // Sender Protocol Address - (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, // Target Hardware Address - (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0xFE }; // Target Protocol Address - - startOffset = 0; - numBits = (short) (data.length * 8); - eth.deserialize(data, startOffset, numBits); - - short etherType = eth.getEtherType(); - Assert.assertTrue(NetUtils.getUnsignedShort(etherType) == 0x8100); - - IEEE8021Q vlanPacket = (IEEE8021Q) eth.getPayload(); - Assert.assertTrue(vlanPacket.getCfi() == 0); - Assert.assertTrue(vlanPacket.getPcp() == 5); - Assert.assertTrue(vlanPacket.getVid() == 4094); - Assert.assertTrue(vlanPacket.getEtherType() == 2054); // 0x806 - - Packet arpPkt = (vlanPacket).getPayload(); - Assert.assertTrue(arpPkt instanceof ARP); - } - - @Test - public void testSerialize() throws Exception { - Ethernet eth = new Ethernet(); - - byte[] dMac = { (byte) 0xA, (byte) 0xC, (byte) 0xE, (byte) 0x14, (byte) 0x37, (byte) 0x45 }; - byte[] sMac = { (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F }; - eth.setDestinationMACAddress(dMac); - eth.setSourceMACAddress(sMac); - eth.setEtherType((short) 33024); - - IEEE8021Q vlan = new IEEE8021Q(); - vlan.setCfi((byte) 0x0); - vlan.setPcp((byte) 0x5); - vlan.setVid((short) 4094); - vlan.setEtherType((short) 2054); - - vlan.setParent(eth); - eth.setPayload(vlan); - - ARP arp = new ARP(); - arp.setHardwareType((short) 1); - arp.setProtocolType((short) 2048); - arp.setHardwareAddressLength((byte) 0x6); - arp.setProtocolAddressLength((byte) 0x4); - arp.setOpCode((byte) 0x1); - - byte[] senderHardwareAddress = { (byte) 0xA6, (byte) 0xEC, (byte) 0x9C, (byte) 0xAE, (byte) 0xB2, (byte) 0x9F }; - byte[] senderProtocolAddress = { (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0x1 }; - byte[] targetProtocolAddress = { (byte) 0x9, (byte) 0x9, (byte) 0x9, (byte) 0xFE }; - byte[] targetHardwareAddress = { (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0 }; - arp.setSenderHardwareAddress(senderHardwareAddress); - arp.setSenderProtocolAddress(senderProtocolAddress); - arp.setTargetHardwareAddress(targetHardwareAddress); - arp.setTargetProtocolAddress(targetProtocolAddress); - - arp.setParent(vlan); - vlan.setPayload(arp); - - byte[] data = eth.serialize(); - - Assert.assertTrue(data[0] == (byte) 0x0A); // Destination MAC - Assert.assertTrue(data[1] == (byte) 0x0C); - Assert.assertTrue(data[2] == (byte) 0x0E); - Assert.assertTrue(data[3] == (byte) 0x14); - Assert.assertTrue(data[4] == (byte) 0x37); - Assert.assertTrue(data[5] == (byte) 0x45); - Assert.assertTrue(data[6] == (byte) 0xA6); // Source MAC - Assert.assertTrue(data[7] == (byte) 0xEC); - Assert.assertTrue(data[8] == (byte) 0x9C); - Assert.assertTrue(data[9] == (byte) 0xAE); - Assert.assertTrue(data[10] == (byte) 0xB2); - Assert.assertTrue(data[11] == (byte) 0x9F); - Assert.assertTrue(data[12] == (byte) 0x81); // EtherType - Assert.assertTrue(data[13] == (byte) 0x00); - Assert.assertTrue(data[14] == (byte) 0xAF); // PCP, CFI, VLAN ID - Assert.assertTrue(data[15] == (byte) 0xFE); - Assert.assertTrue(data[16] == (byte) 0x08); // EtherType - Assert.assertTrue(data[17] == (byte) 0x06); - Assert.assertTrue(data[18] == (byte) 0x00); // Hardware Type - Assert.assertTrue(data[19] == (byte) 0x01); - Assert.assertTrue(data[20] == (byte) 0x08); // Protocol Type - Assert.assertTrue(data[21] == (byte) 0x0); - Assert.assertTrue(data[22] == (byte) 0x6); // Hardware Address Length - Assert.assertTrue(data[23] == (byte) 0x4); // Protocol Address Length - Assert.assertTrue(data[24] == (byte) 0x0); // opCode - Assert.assertTrue(data[25] == (byte) 0x1); // opCode - Assert.assertTrue(data[26] == (byte) 0xA6); // Source MAC - Assert.assertTrue(data[27] == (byte) 0xEC); - Assert.assertTrue(data[28] == (byte) 0x9C); - Assert.assertTrue(data[29] == (byte) 0xAE); - Assert.assertTrue(data[30] == (byte) 0xB2); - Assert.assertTrue(data[31] == (byte) 0x9F); - Assert.assertTrue(data[32] == (byte) 0x09); // Sender Protocol Address - Assert.assertTrue(data[33] == (byte) 0x09); - Assert.assertTrue(data[34] == (byte) 0x09); - Assert.assertTrue(data[35] == (byte) 0x01); // Target Hardware Address - Assert.assertTrue(data[36] == (byte) 0x00); - Assert.assertTrue(data[37] == (byte) 0x00); - Assert.assertTrue(data[38] == (byte) 0x00); - Assert.assertTrue(data[39] == (byte) 0x00); - Assert.assertTrue(data[40] == (byte) 0x00); - Assert.assertTrue(data[41] == (byte) 0x00); - Assert.assertTrue(data[42] == (byte) 0x09); // Target Protocol Address - Assert.assertTrue(data[43] == (byte) 0x09); - Assert.assertTrue(data[44] == (byte) 0x09); - Assert.assertTrue(data[45] == (byte) 0xFE); - } - - @Test - public void testGetMatchFullPacket() throws Exception { - IEEE8021Q dot1q = new IEEE8021Q(); - byte priority = 4; - short vlanId = 59; - short ethType = EtherTypes.IPv4.shortValue(); - dot1q.setPcp(priority); - dot1q.setVid(vlanId); - dot1q.setEtherType(ethType); - - Match match = dot1q.getMatch(); - - Assert.assertEquals(priority, (byte) match.getField(MatchType.DL_VLAN_PR).getValue()); - Assert.assertEquals(vlanId, (short) match.getField(MatchType.DL_VLAN).getValue()); - Assert.assertEquals(ethType, (short) match.getField(MatchType.DL_TYPE).getValue()); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java deleted file mode 100644 index b98342831c..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java +++ /dev/null @@ -1,680 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; - -import org.junit.Assert; -import org.junit.Test; - -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NetUtils; - -public class IPv4Test { - - @Test - public void testGetVersion() { - IPv4 ip = new IPv4(); - byte[] ipVersion = { (byte) 4 }; - ip.hdrFieldsMap.put("Version", ipVersion); - byte version = ip.getVersion(); - Assert.assertTrue(version == (byte) 4); - } - - @Test - public void testGetHeaderLength() { - IPv4 ip = new IPv4(); - byte[] ipHeaderLength = { 5 }; - ip.hdrFieldsMap.put("HeaderLength", ipHeaderLength); - byte headerLength = (byte) ip.getHeaderLen(); - Assert.assertTrue(headerLength == 20); - } - - @Test - public void testGetDiffServ() { - IPv4 ip = new IPv4(); - byte[] ipDiffServ = { 20 }; - ip.hdrFieldsMap.put("DiffServ", ipDiffServ); - byte diffServ = ip.getDiffServ(); - Assert.assertTrue(diffServ == 20); - } - - @Test - public void testGetTotalLength() { - IPv4 ip = new IPv4(); - byte[] iptotLength = { 3, -24 }; - ip.hdrFieldsMap.put("TotalLength", iptotLength); - short totalLength = ip.getTotalLength(); - Assert.assertTrue(totalLength == 1000); - } - - @Test - public void testGetIdentification() { - IPv4 ip = new IPv4(); - byte[] ipIdentification = { 7, -48 }; - ip.hdrFieldsMap.put("Identification", ipIdentification); - short identification = ip.getIdentification(); - Assert.assertTrue(identification == 2000); - } - - @Test - public void testGetFlags() { - IPv4 ip = new IPv4(); - byte[] ipFlags = { 7 }; - ip.hdrFieldsMap.put("Flags", ipFlags); - byte flags = ip.getFlags(); - Assert.assertTrue(flags == 7); - } - - @Test - public void testGetTtl() { - IPv4 ip = new IPv4(); - byte[] ipTtl = { 100 }; - ip.hdrFieldsMap.put("TTL", ipTtl); - byte ttl = ip.getTtl(); - Assert.assertTrue(ttl == 100); - } - - @Test - public void testGetProtocol() { - IPv4 ip = new IPv4(); - byte[] ipProtocol = { 1 }; - ip.hdrFieldsMap.put("Protocol", ipProtocol); - byte protocol = ip.getProtocol(); - Assert.assertTrue(protocol == 1); - - Class clazz = IPv4.protocolClassMap.get(protocol); - Assert.assertTrue(clazz == ICMP.class); - } - - @Test - public void testGetFragmentOffset() { - IPv4 ip = new IPv4(); - byte[] ipFragmentOffset = { 6, -35 }; - ip.hdrFieldsMap.put("FragmentOffset", ipFragmentOffset); - short fragmentOffset = ip.getFragmentOffset(); - Assert.assertTrue(fragmentOffset == 1757); - } - - @Test - public void testGetSourceAddress() { - IPv4 ip = new IPv4(); - byte[] ipSourceAddress = { 10, 110, 31, 55 }; - ip.hdrFieldsMap.put("SourceIPAddress", ipSourceAddress); - int sourceAddress = ip.getSourceAddress(); - Assert.assertTrue(sourceAddress == 174989111); - } - - @Test - public void testGetDestinationAddress() { - IPv4 ip = new IPv4(); - byte[] ipDestinationAddress = { 20, 55, 62, 110 }; - ip.hdrFieldsMap.put("DestinationIPAddress", ipDestinationAddress); - int destinationAddress = ip.getDestinationAddress(); - Assert.assertTrue(destinationAddress == 339164782); - } - - @Test - public void testSetVersion() { - IPv4 ip = new IPv4(); - byte ipVersion = (byte) 4; - ip.setVersion(ipVersion); - byte[] version = ip.hdrFieldsMap.get("Version"); - Assert.assertTrue(version[0] == (byte) 4); - } - - @Test - public void testSetHeaderLength() { - IPv4 ip = new IPv4(); - byte ipHeaderLength = 5; - ip.setHeaderLength(ipHeaderLength); - byte[] headerLength = ip.hdrFieldsMap.get("HeaderLength"); - Assert.assertTrue(headerLength[0] == 5); - } - - @Test - public void testSetDiffServ() { - IPv4 ip = new IPv4(); - byte ipDiffServ = 20; - ip.setDiffServ(ipDiffServ); - byte[] diffServ = ip.hdrFieldsMap.get("DiffServ"); - Assert.assertTrue(diffServ[0] == 20); - } - - @Test - public void testSetTotalLength() { - IPv4 ip = new IPv4(); - short iptotLength = 1000; - ip.setTotalLength(iptotLength); - byte[] totalLength = ip.hdrFieldsMap.get("TotalLength"); - Assert.assertTrue(totalLength[0] == 3); - Assert.assertTrue(totalLength[1] == -24); - - ip.setTotalLength((short)84); - totalLength = ip.hdrFieldsMap.get("TotalLength"); - Assert.assertTrue(totalLength[0] == 0); - Assert.assertTrue(totalLength[1] == 84); - } - - @Test - public void testSetIdentification() { - IPv4 ip = new IPv4(); - short ipIdentification = 2000; - ip.setIdentification(ipIdentification); - byte[] identification = ip.hdrFieldsMap.get("Identification"); - Assert.assertTrue(identification[0] == 7); - Assert.assertTrue(identification[1] == -48); - } - - @Test - public void testSetFlags() { - IPv4 ip = new IPv4(); - byte ipFlags = 7; - ip.setFlags(ipFlags); - byte[] flags = ip.hdrFieldsMap.get("Flags"); - Assert.assertTrue(flags[0] == 7); - } - - @Test - public void testSetTtl() { - IPv4 ip = new IPv4(); - byte ipTtl = 100; - ip.setTtl(ipTtl); - byte[] ttl = ip.hdrFieldsMap.get("TTL"); - Assert.assertTrue(ttl[0] == 100); - } - - @Test - public void testSetProtocol() { - IPv4 ip = new IPv4(); - byte ipProtocol = 11; - ip.setProtocol(ipProtocol); - byte[] protocol = ip.hdrFieldsMap.get("Protocol"); - Assert.assertTrue(protocol[0] == 11); - } - - @Test - public void testSetFragmentOffset() { - IPv4 ip = new IPv4(); - short ipFragmentOffset = 1757; - ip.setFragmentOffset(ipFragmentOffset); - byte[] fragmentOffset = ip.hdrFieldsMap.get("FragmentOffset"); - Assert.assertTrue(fragmentOffset[0] == 6); - Assert.assertTrue(fragmentOffset[1] == -35); - } - - @Test - public void testSetDestinationAddress() { - IPv4 ip = new IPv4(); - int ipDestinationAddress = 339164782; - ip.setDestinationAddress(ipDestinationAddress); - byte[] destinationAddress = ip.hdrFieldsMap.get("DestinationIPAddress"); - Assert.assertTrue(destinationAddress[0] == 20); - Assert.assertTrue(destinationAddress[1] == 55); - Assert.assertTrue(destinationAddress[2] == 62); - Assert.assertTrue(destinationAddress[3] == 110); - } - - @Test - public void testOptions() throws Exception { - IPv4 ip = new IPv4(); - Assert.assertEquals(20, ip.getHeaderLen()); - Assert.assertEquals(160, ip.getHeaderSize()); - Assert.assertEquals(0, ip.getfieldnumBits("Options")); - - byte[][] options = { - new byte[] { - (byte)0x01, - }, - new byte[] { - (byte)0x01, (byte)0x02, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, - }, - null, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, - (byte)0x05, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, - (byte)0x05, (byte)0x06, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, - (byte)0x05, (byte)0x06, (byte)0x07, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, - (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, - }, - new byte[0], - }; - - byte[][] expected = { - new byte[] { - (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x00, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x00, (byte)0x00, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x00, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, - }, - null, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, - (byte)0x05, (byte)0x00, (byte)0x00, (byte)0x00, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, - (byte)0x05, (byte)0x06, (byte)0x00, (byte)0x00, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, - (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x00, - }, - new byte[] { - (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04, - (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08, - }, - null, - }; - - byte[] echo = { - (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, - (byte)0x55, (byte)0x66, (byte)0x77, (byte)0x88, - (byte)0x99, (byte)0xaa, - }; - ICMP icmp = new ICMP(); - icmp.setType((byte)8); - icmp.setCode((byte)0); - icmp.setIdentifier((short)0xabcd); - icmp.setSequenceNumber((short)7777); - icmp.setRawPayload(echo); - - ip.setSourceAddress(InetAddress.getByName("192.168.10.20")); - ip.setDestinationAddress(InetAddress.getByName("192.168.30.40")); - ip.setProtocol(IPProtocols.ICMP.byteValue()); - - for (int i = 0; i < options.length; i++) { - byte[] opts = options[i]; - byte[] exp = expected[i]; - - // Set IPv4 options. - int hlen = 20; - int optlen; - if (exp != null) { - optlen = exp.length; - hlen += optlen; - } else { - optlen = 0; - } - ip.setOptions(opts); - Assert.assertTrue(Arrays.equals(exp, ip.getOptions())); - Assert.assertEquals(hlen, ip.getHeaderLen()); - Assert.assertEquals(hlen * 8, ip.getHeaderSize()); - Assert.assertEquals(optlen * 8, ip.getfieldnumBits("Options")); - - // Serialize/Deserialize test. - ip.setPayload(icmp); - - byte[] raw = ip.serialize(); - IPv4 newip = new IPv4(); - newip.deserialize(raw, 0, raw.length * 8); - Assert.assertEquals(ip, newip); - Assert.assertEquals(icmp, newip.getPayload()); - Assert.assertTrue(Arrays.equals(exp, newip.getOptions())); - } - } - - @Test - public void testChecksum() { - byte header[] = { (byte) 0x45, 00, 00, (byte) 0x3c, (byte) 0x1c, - (byte) 0x46, (byte) 0x40, 00, (byte) 0x40, 06, (byte) 0xb1, - (byte) 0xe6, (byte) 0xac, (byte) 0x10, (byte) 0x0a, - (byte) 0x63, (byte) 0xac, (byte) 0x10, (byte) 0x0a, (byte) 0x0c }; - byte header2[] = { (byte) 0x45, 00, 00, (byte) 0x73, 00, 00, - (byte) 0x40, 00, (byte) 0x40, (byte) 0x11, (byte) 0xb8, - (byte) 0x61, (byte) 0xc0, (byte) 0xa8, 00, 01, (byte) 0xc0, - (byte) 0xa8, 00, (byte) 0xc7 }; - byte header3[] = { (byte) 0x45, 00, 00, (byte) 0x47, (byte) 0x73, - (byte) 0x88, (byte) 0x40, 00, (byte) 0x40, 06, (byte) 0xA2, - (byte) 0xC4, (byte) 0x83, (byte) 0x9F, (byte) 0x0E, - (byte) 0x85, (byte) 0x83, (byte) 0x9F, (byte) 0x0E, (byte) 0xA1 }; - byte header4[] = { (byte) 0x45, 00, 00, (byte) 0x54, 00, 00, - (byte) 0x40, 00, (byte) 0x40, 01, (byte) 0xf0, (byte) 0x8e, - (byte) 0xc0, (byte) 0xa8, (byte) 0x64, (byte) 0x65, - (byte) 0xc0, (byte) 0xa8, (byte) 0x64, (byte) 0x64 }; - byte header5[] = { (byte) 0x45, 00, 00, (byte) 0x54, 00, 00, - (byte) 0x40, 00, (byte) 0x40, 01, (byte) 0xef, (byte) 0x8d, - (byte) 0xc0, (byte) 0xa8, (byte) 0x64, (byte) 0x65, - (byte) 0xc0, (byte) 0xa8, (byte) 0x65, (byte) 0x65 }; - byte header6[] = { (byte) 0x45, 00, 00, (byte) 0x54, 00, 00, - (byte) 0x40, 00, (byte) 0x40, 01, (byte) 0x0b, (byte) 0x92, - (byte) 0xc0, (byte) 0xa8, (byte) 0x64, (byte) 0x65, (byte) 0x9, - (byte) 0x9, (byte) 0x1, (byte) 0x1 }; - byte header7[] = { (byte) 0x45, 00, 00, (byte) 0x54, 00, 00, - (byte) 0x40, 00, (byte) 0x40, 01, (byte) 0, (byte) 0, - (byte) 0xc0, (byte) 0xa8, (byte) 0x64, (byte) 0x65, (byte) 0x9, - (byte) 0x9, (byte) 0x2, (byte) 0x2 }; - - IPv4 ip = new IPv4(); - - Assert.assertTrue(NetUtils.getUnsignedShort(ip.computeChecksum(header, - 0)) == 0xB1E6); - Assert.assertTrue(NetUtils.getUnsignedShort(ip.computeChecksum(header2, - 0)) == 0xb861); - Assert.assertTrue(NetUtils.getUnsignedShort(ip.computeChecksum(header3, - 0)) == 0xa2c4); - Assert.assertTrue(NetUtils.getUnsignedShort(ip.computeChecksum(header4, - 0)) == 0xf08e); - Assert.assertTrue(NetUtils.getUnsignedShort(ip.computeChecksum(header5, - 0)) == 0xef8d); - Assert.assertTrue(NetUtils.getUnsignedShort(ip.computeChecksum(header6, - 0)) == 0x0b92); - Assert.assertTrue(NetUtils.getUnsignedShort(ip.computeChecksum(header7, - 0)) == 0x0a91); - } - - @Test - public void testFullIP() throws UnknownHostException, PacketException { - byte[] icmpRawPayload = new byte[] { (byte) 0x38, (byte) 0x26, - (byte) 0x9e, (byte) 0x51, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x2e, (byte) 0x6a, - (byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x11, - (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15, - (byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19, - (byte) 0x1a, (byte) 0x1b, (byte) 0x1c, (byte) 0x1d, - (byte) 0x1e, (byte) 0x1f, (byte) 0x20, (byte) 0x21, - (byte) 0x22, (byte) 0x23, (byte) 0x24, (byte) 0x25, - (byte) 0x26, (byte) 0x27, (byte) 0x28, (byte) 0x29, - (byte) 0x2a, (byte) 0x2b, (byte) 0x2c, (byte) 0x2d, - (byte) 0x2e, (byte) 0x2f, (byte) 0x30, (byte) 0x31, - (byte) 0x32, (byte) 0x33, (byte) 0x34, (byte) 0x35, - (byte) 0x36, (byte) 0x37 }; - ICMP icmp = new ICMP(); - icmp.setType((byte) 8); - icmp.setCode((byte) 0); - icmp.setIdentifier((short) 0x46f5); - icmp.setSequenceNumber((short) 2); - icmp.setRawPayload(icmpRawPayload); - - IPv4 ip = new IPv4(); - ip.setVersion((byte) 4); - ip.setIdentification((short) 5); - ip.setDiffServ((byte) 0); - ip.setECN((byte) 0); - ip.setTotalLength((short) 84); - ip.setFlags((byte) 2); - ip.setFragmentOffset((short) 0); - ip.setTtl((byte) 64); - ip.setProtocol(IPProtocols.ICMP.byteValue()); - ip.setDestinationAddress(InetAddress.getByName("192.168.100.100")); - ip.setSourceAddress(InetAddress.getByName("192.168.100.101")); - ip.setPayload(icmp); - - Ethernet eth = new Ethernet(); - eth.setDestinationMACAddress(new byte[] { (byte) 0x98, (byte) 0xfc, - (byte) 0x11, (byte) 0x93, (byte) 0x5c, (byte) 0xb8 }); - eth.setSourceMACAddress(new byte[] { (byte) 0x00, (byte) 0x24, - (byte) 0xd7, (byte) 0xa9, (byte) 0xa3, (byte) 0x50 }); - eth.setEtherType(EtherTypes.IPv4.shortValue()); - eth.setPayload(ip); - - byte[] stream = eth.serialize(); - - Ethernet decEth = new Ethernet(); - decEth.deserialize(stream, 0, stream.length * NetUtils.NumBitsInAByte); - - IPv4 decIp = (IPv4) decEth.getPayload(); - Assert.assertFalse(decIp.isCorrupted()); - Assert.assertTrue(ip.equals(decIp)); - - ICMP decIcmp = (ICMP) decIp.getPayload(); - Assert.assertFalse(decIcmp.isCorrupted()); - Assert.assertTrue(Arrays.equals(icmpRawPayload, decIcmp.getRawPayload())); - } - - @Test - public void testGetMatch() throws Exception { - IPv4 ip = new IPv4(); - InetAddress sourceAddress = InetAddress.getByName("172.168.190.15"); - InetAddress destintationAddress = InetAddress.getByName("23.128.0.11"); - byte protocol = IPProtocols.TCP.byteValue(); - byte tos = 7; - ip.setVersion((byte) 4); - ip.setIdentification((short) 5); - ip.setDiffServ(tos); - ip.setECN((byte) 0); - ip.setTotalLength((short) 84); - ip.setFlags((byte) 2); - ip.setFragmentOffset((short) 0); - ip.setTtl((byte) 64); - ip.setProtocol(protocol); - ip.setDestinationAddress(destintationAddress); - ip.setSourceAddress(sourceAddress); - - Match match = ip.getMatch(); - - Assert.assertEquals(sourceAddress, match.getField(MatchType.NW_SRC).getValue()); - Assert.assertEquals(destintationAddress, match.getField(MatchType.NW_DST).getValue()); - Assert.assertEquals(protocol, (byte) match.getField(MatchType.NW_PROTO).getValue()); - Assert.assertEquals(tos, (byte) match.getField(MatchType.NW_TOS).getValue()); - } - - @Test - public void testFragment() throws Exception { - byte[] payload1 = new byte[0]; - byte[] payload2 = { - (byte)0x61, (byte)0xd1, (byte)0x3d, (byte)0x51, - (byte)0x1b, (byte)0x75, (byte)0xa7, (byte)0x83, - }; - byte[] payload3 = { - (byte)0xe7, (byte)0x0f, (byte)0x2d, (byte)0x7e, - (byte)0x15, (byte)0xba, (byte)0xe7, (byte)0x6d, - (byte)0xb5, (byte)0xc5, (byte)0xb5, (byte)0x37, - (byte)0x59, (byte)0xbc, (byte)0x91, (byte)0x43, - (byte)0xb5, (byte)0xb7, (byte)0xe4, (byte)0x28, - (byte)0xec, (byte)0x62, (byte)0x6b, (byte)0x6a, - (byte)0xd1, (byte)0xcb, (byte)0x79, (byte)0x1e, - (byte)0xfc, (byte)0x82, (byte)0xf5, (byte)0xb4, - }; - - // Ensure that the payload is not deserialized if the fragment offset - // is not zero. - byte proto = IPProtocols.TCP.byteValue(); - fragmentTest(payload1, proto, (short)0xf250); - fragmentTest(payload2, proto, (short)0xf248); - fragmentTest(payload3, proto, (short)0xf230); - - proto = IPProtocols.UDP.byteValue(); - fragmentTest(payload1, proto, (short)0xf245); - fragmentTest(payload2, proto, (short)0xf23d); - fragmentTest(payload3, proto, (short)0xf225); - - proto = IPProtocols.ICMP.byteValue(); - fragmentTest(payload1, proto, (short)0xf255); - fragmentTest(payload2, proto, (short)0xf24d); - fragmentTest(payload3, proto, (short)0xf235); - - // Ensure that the protocol header in the first fragment is - // deserialized. - proto = IPProtocols.TCP.byteValue(); - TCP tcp = new TCP(); - tcp.setSourcePort((short)1234).setDestinationPort((short)32000). - setSequenceNumber((int)0xd541f5f8).setAckNumber((int)0x58da787d). - setDataOffset((byte)5).setReserved((byte)0). - setHeaderLenFlags((short)0x18).setWindowSize((short)0x40e8). - setUrgentPointer((short)0x15f7).setChecksum((short)0x0d4e); - firstFragmentTest(tcp, payload1, proto, (short)0xdfe6); - tcp.setChecksum((short)0xab2a); - firstFragmentTest(tcp, payload2, proto, (short)0xdfde); - tcp.setChecksum((short)0x1c75); - firstFragmentTest(tcp, payload3, proto, (short)0xdfc6); - - proto = IPProtocols.UDP.byteValue(); - UDP udp = new UDP(); - udp.setSourcePort((short)53).setDestinationPort((short)45383). - setLength((short)(payload1.length + 8)).setChecksum((short)0); - firstFragmentTest(udp, payload1, proto, (short)0xdfe7); - udp.setLength((short)(payload2.length + 8)); - firstFragmentTest(udp, payload2, proto, (short)0xdfdf); - udp.setLength((short)(payload3.length + 8)); - firstFragmentTest(udp, payload3, proto, (short)0xdfc7); - - proto = IPProtocols.ICMP.byteValue(); - ICMP icmp = new ICMP(); - icmp.setType((byte)8).setCode((byte)0).setIdentifier((short)0x3d1e). - setSequenceNumber((short)1); - firstFragmentTest(icmp, payload1, proto, (short)0xdff7); - firstFragmentTest(icmp, payload2, proto, (short)0xdfef); - firstFragmentTest(icmp, payload3, proto, (short)0xdfd7); - } - - private void fragmentTest(byte[] payload, byte proto, short checksum) - throws Exception { - // Construct a fragmented raw IPv4 packet. - int ipv4Len = 20; - byte[] rawIp = new byte[ipv4Len + payload.length]; - - byte ipVersion = 4; - byte dscp = 35; - byte ecn = 2; - byte tos = (byte)((dscp << 2) | ecn); - short totalLen = (short)rawIp.length; - short id = 22143; - short offset = 0xb9; - byte ttl = 64; - byte[] srcIp = {(byte)0x0a, (byte)0x00, (byte)0x00, (byte)0x01}; - byte[] dstIp = {(byte)0xc0, (byte)0xa9, (byte)0x66, (byte)0x23}; - - rawIp[0] = (byte)((ipVersion << 4) | (ipv4Len >> 2)); - rawIp[1] = tos; - rawIp[2] = (byte)(totalLen >>> Byte.SIZE); - rawIp[3] = (byte)totalLen; - rawIp[4] = (byte)(id >>> Byte.SIZE); - rawIp[5] = (byte)id; - rawIp[6] = (byte)(offset >>> Byte.SIZE); - rawIp[7] = (byte)offset; - rawIp[8] = ttl; - rawIp[9] = proto; - rawIp[10] = (byte)(checksum >>> Byte.SIZE); - rawIp[11] = (byte)checksum; - System.arraycopy(srcIp, 0, rawIp, 12, srcIp.length); - System.arraycopy(dstIp, 0, rawIp, 16, srcIp.length); - System.arraycopy(payload, 0, rawIp, ipv4Len, payload.length); - - // Deserialize. - IPv4 ipv4 = new IPv4(); - ipv4.deserialize(rawIp, 0, rawIp.length * Byte.SIZE); - - Assert.assertEquals(ipVersion, ipv4.getVersion()); - Assert.assertEquals(ipv4Len, ipv4.getHeaderLen()); - Assert.assertEquals(dscp, ipv4.getDiffServ()); - Assert.assertEquals(ecn, ipv4.getECN()); - Assert.assertEquals(totalLen, ipv4.getTotalLength()); - Assert.assertEquals(id, ipv4.getIdentification()); - Assert.assertEquals((byte)0, ipv4.getFlags()); - Assert.assertEquals(offset, ipv4.getFragmentOffset()); - Assert.assertEquals(ttl, ipv4.getTtl()); - Assert.assertEquals(proto, ipv4.getProtocol()); - Assert.assertEquals(checksum, ipv4.getChecksum()); - Assert.assertEquals(NetUtils.byteArray4ToInt(srcIp), - ipv4.getSourceAddress()); - Assert.assertEquals(NetUtils.byteArray4ToInt(dstIp), - ipv4.getDestinationAddress()); - Assert.assertFalse(ipv4.isCorrupted()); - - // payloadClass should not be set if fragment offset is not zero. - Assert.assertEquals(null, ipv4.getPayload()); - Assert.assertArrayEquals(payload, ipv4.getRawPayload()); - } - - private void firstFragmentTest(Packet payload, byte[] rawPayload, - byte proto, short checksum) - throws Exception { - // Construct a raw IPv4 packet with MF flag. - int ipv4Len = 20; - payload.setRawPayload(rawPayload); - byte[] payloadBytes = payload.serialize(); - byte[] rawIp = new byte[ipv4Len + payloadBytes.length]; - - byte ipVersion = 4; - byte dscp = 13; - byte ecn = 1; - byte tos = (byte)((dscp << 2) | ecn); - short totalLen = (short)rawIp.length; - short id = 19834; - byte flags = 0x1; - short offset = 0; - short off = (short)(((short)flags << 13) | offset); - byte ttl = 64; - byte[] srcIp = {(byte)0xac, (byte)0x23, (byte)0x5b, (byte)0xfd}; - byte[] dstIp = {(byte)0xc0, (byte)0xa8, (byte)0x64, (byte)0x71}; - - rawIp[0] = (byte)((ipVersion << 4) | (ipv4Len >> 2)); - rawIp[1] = tos; - rawIp[2] = (byte)(totalLen >>> Byte.SIZE); - rawIp[3] = (byte)totalLen; - rawIp[4] = (byte)(id >>> Byte.SIZE); - rawIp[5] = (byte)id; - rawIp[6] = (byte)(off >>> Byte.SIZE); - rawIp[7] = (byte)off; - rawIp[8] = ttl; - rawIp[9] = proto; - rawIp[10] = (byte)(checksum >>> Byte.SIZE); - rawIp[11] = (byte)checksum; - System.arraycopy(srcIp, 0, rawIp, 12, srcIp.length); - System.arraycopy(dstIp, 0, rawIp, 16, srcIp.length); - System.arraycopy(payloadBytes, 0, rawIp, ipv4Len, payloadBytes.length); - - // Deserialize. - IPv4 ipv4 = new IPv4(); - ipv4.deserialize(rawIp, 0, rawIp.length * Byte.SIZE); - - Assert.assertEquals(ipVersion, ipv4.getVersion()); - Assert.assertEquals(ipv4Len, ipv4.getHeaderLen()); - Assert.assertEquals(dscp, ipv4.getDiffServ()); - Assert.assertEquals(ecn, ipv4.getECN()); - Assert.assertEquals(totalLen, ipv4.getTotalLength()); - Assert.assertEquals(id, ipv4.getIdentification()); - Assert.assertEquals(flags, ipv4.getFlags()); - Assert.assertEquals(offset, ipv4.getFragmentOffset()); - Assert.assertEquals(ttl, ipv4.getTtl()); - Assert.assertEquals(proto, ipv4.getProtocol()); - Assert.assertEquals(checksum, ipv4.getChecksum()); - Assert.assertEquals(NetUtils.byteArray4ToInt(srcIp), - ipv4.getSourceAddress()); - Assert.assertEquals(NetUtils.byteArray4ToInt(dstIp), - ipv4.getDestinationAddress()); - Assert.assertFalse(ipv4.isCorrupted()); - - // Protocol header in the first fragment should be deserialized. - Assert.assertEquals(null, ipv4.getRawPayload()); - - Packet desPayload = ipv4.getPayload(); - Assert.assertEquals(payload, desPayload); - Assert.assertFalse(desPayload.isCorrupted()); - Assert.assertArrayEquals(rawPayload, desPayload.getRawPayload()); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java deleted file mode 100644 index 00b0feecd8..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java +++ /dev/null @@ -1,227 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import java.net.InetAddress; -import java.util.Arrays; -import java.util.Map; - -import org.junit.Assert; - -import org.junit.Test; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.IPProtocols; - -public class PacketTest { - - @Test - public void testDeserialize() throws NoSuchFieldException, Exception { - short startOffset, numBits; - - Ethernet eth = new Ethernet(); - byte[] data = { 10, 12, 14, 20, 55, 69, //DMAC - -90, -20, -100, -82, -78, -97, //SMAC - 8, 6, //ethype - 0, 1, // hw type - 8, 0, // proto (ip) - 6, // hw addr len - 4, // proto addr len - 0, 1, // op codes - -90, -20, -100, -82, -78, -97, //src hw addr - 9, 9, 9, 1, // src proto - 0, 0, 0, 0, 0, 0, // target hw addr - 9, 9, 9, -2 }; // target proto - - startOffset = 0; - numBits = 42 * 8; - eth.deserialize(data, startOffset, numBits); - - byte[] dMAC = eth.getDestinationMACAddress(); - byte[] sMAC = eth.getSourceMACAddress(); - short etherType = eth.getEtherType(); - - Assert.assertTrue(dMAC[0] == 10); - Assert.assertTrue(dMAC[1] == 12); - Assert.assertTrue(dMAC[2] == 14); - Assert.assertTrue(dMAC[3] == 20); - Assert.assertTrue(dMAC[4] == 55); - Assert.assertTrue(dMAC[5] == 69); - - Assert.assertTrue(sMAC[0] == -90); - Assert.assertTrue(sMAC[1] == -20); - Assert.assertTrue(sMAC[2] == -100); - Assert.assertTrue(sMAC[3] == -82); - Assert.assertTrue(sMAC[4] == -78); - Assert.assertTrue(sMAC[5] == -97); - - Assert.assertTrue(etherType == 0x806); - - ARP arpPacket = (ARP) eth.getPayload(); - - Assert.assertTrue(arpPacket.getHardwareType() == (byte)0x1); - Assert.assertTrue(arpPacket.getProtocolType() == 2048); - Assert.assertTrue(arpPacket.getHardwareAddressLength() == (byte)0x6); - Assert.assertTrue(arpPacket.getProtocolAddressLength() == (byte)0x4); - Assert.assertTrue(arpPacket.getOpCode() == 1); - - byte[] senderHwAddress = arpPacket.getSenderHardwareAddress(); - byte[] senderProtocolAddress = arpPacket.getSenderProtocolAddress(); - - byte[] targetHwAddress = arpPacket.getTargetHardwareAddress(); - byte[] targetProtocolAddress = arpPacket.getTargetProtocolAddress(); - - - Assert.assertTrue(senderHwAddress[0] == (byte)0xA6); - Assert.assertTrue(senderHwAddress[1] == (byte)0xEC); - Assert.assertTrue(senderHwAddress[2] == (byte)0x9C); - Assert.assertTrue(senderHwAddress[3] == (byte)0xAE); - Assert.assertTrue(senderHwAddress[4] == (byte)0xB2); - Assert.assertTrue(senderHwAddress[5] == (byte)0x9F); - - Assert.assertTrue(senderProtocolAddress[0] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[1] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[2] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[3] == (byte)0x1); - - Assert.assertTrue(targetHwAddress[0] == (byte)0x0); - Assert.assertTrue(targetHwAddress[1] == (byte)0x0); - Assert.assertTrue(targetHwAddress[2] == (byte)0x0); - Assert.assertTrue(targetHwAddress[3] == (byte)0x0); - Assert.assertTrue(targetHwAddress[4] == (byte)0x0); - Assert.assertTrue(targetHwAddress[5] == (byte)0x0); - - Assert.assertTrue(senderProtocolAddress[0] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[1] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[2] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[3] == (byte)0x1); - - Assert.assertTrue(targetProtocolAddress[0] == (byte)0x9); - Assert.assertTrue(targetProtocolAddress[1] == (byte)0x9); - Assert.assertTrue(targetProtocolAddress[2] == (byte)0x9); - Assert.assertTrue(targetProtocolAddress[3] == (byte)0xFE); - } - - @Test - public void testSerialize() throws NoSuchFieldException, Exception { - Ethernet eth = new Ethernet(); - Map fCValues = eth.hdrFieldsMap; - - byte[] dMAC = { 10, 12, 14, 20, 55, 69 }; - byte[] sMAC = { 82, 97, 109, 117, 127, -50 }; - short etherType = 2054; - - byte[] dMACdata, sMACdata, etherTypedata; - byte[] data = new byte[20]; - - eth.setDestinationMACAddress(dMAC); - eth.setSourceMACAddress(sMAC); - eth.setEtherType(etherType); - - dMACdata = fCValues.get("DestinationMACAddress"); - sMACdata = fCValues.get("SourceMACAddress"); - etherTypedata = fCValues.get("EtherType"); - - Assert.assertTrue(dMACdata[0] == 10); - Assert.assertTrue(dMACdata[1] == 12); - Assert.assertTrue(dMACdata[2] == 14); - Assert.assertTrue(dMACdata[3] == 20); - Assert.assertTrue(dMACdata[4] == 55); - Assert.assertTrue(dMACdata[5] == 69); - - Assert.assertTrue(sMACdata[0] == 82); - Assert.assertTrue(sMACdata[1] == 97); - Assert.assertTrue(sMACdata[2] == 109); - Assert.assertTrue(sMACdata[3] == 117); - Assert.assertTrue(sMACdata[4] == 127); - Assert.assertTrue(sMACdata[5] == -50); - - Assert.assertTrue(etherTypedata[0] == 8); - Assert.assertTrue(etherTypedata[1] == 6); - data = eth.serialize(); - - Assert.assertTrue(data[0] == 10); - Assert.assertTrue(data[1] == 12); - Assert.assertTrue(data[2] == 14); - Assert.assertTrue(data[3] == 20); - Assert.assertTrue(data[4] == 55); - Assert.assertTrue(data[5] == 69); - - Assert.assertTrue(data[6] == 82); - Assert.assertTrue(data[7] == 97); - Assert.assertTrue(data[8] == 109); - Assert.assertTrue(data[9] == 117); - Assert.assertTrue(data[10] == 127); - Assert.assertTrue(data[11] == -50); - - Assert.assertTrue(data[12] == 8); - Assert.assertTrue(data[13] == 6); - - } - - @Test - public void testGetMatch() throws Exception { - TCP tcp = new TCP(); - short sport = (short) 11093; - short dport = (short) 23; - tcp.setSourcePort(sport); - tcp.setDestinationPort(dport); - - IPv4 ip = new IPv4(); - InetAddress sourceAddress = InetAddress.getByName("192.168.100.100"); - InetAddress destintationAddress = InetAddress.getByName("192.168.100.101"); - byte protocol = IPProtocols.TCP.byteValue(); - byte tos = 5; - ip.setVersion((byte) 4); - ip.setIdentification((short) 5); - ip.setDiffServ(tos); - ip.setECN((byte) 0); - ip.setTotalLength((short) 84); - ip.setFlags((byte) 2); - ip.setFragmentOffset((short) 0); - ip.setTtl((byte) 64); - ip.setProtocol(protocol); - ip.setDestinationAddress(destintationAddress); - ip.setSourceAddress(sourceAddress); - ip.setPayload(tcp); - - IEEE8021Q dot1q = new IEEE8021Q(); - byte priority = 4; - short vlanId = 59; - short ethType = EtherTypes.IPv4.shortValue(); - dot1q.setPcp(priority); - dot1q.setVid(vlanId); - dot1q.setEtherType(ethType); - dot1q.setPayload(ip); - - Ethernet eth = new Ethernet(); - byte smac[] = { (byte) 0xf0, (byte) 0xde, (byte) 0xf1, (byte) 0x71, (byte) 0x72, (byte) 0x8d }; - byte dmac[] = { (byte) 0xde, (byte) 0x28, (byte) 0xdb, (byte) 0xb3, (byte) 0x7c, (byte) 0xf8 }; - eth.setDestinationMACAddress(dmac); - eth.setSourceMACAddress(smac); - eth.setEtherType(EtherTypes.VLANTAGGED.shortValue()); - eth.setPayload(dot1q); - - Match match = eth.getMatch(); - - Assert.assertTrue(Arrays.equals(smac, (byte[]) match.getField(MatchType.DL_SRC).getValue())); - Assert.assertTrue(Arrays.equals(dmac, (byte[]) match.getField(MatchType.DL_DST).getValue())); - Assert.assertEquals(priority, (byte) match.getField(MatchType.DL_VLAN_PR).getValue()); - Assert.assertEquals(vlanId, (short) match.getField(MatchType.DL_VLAN).getValue()); - Assert.assertEquals(ethType, (short) match.getField(MatchType.DL_TYPE).getValue()); - Assert.assertEquals(sourceAddress, match.getField(MatchType.NW_SRC).getValue()); - Assert.assertEquals(destintationAddress, match.getField(MatchType.NW_DST).getValue()); - Assert.assertEquals(protocol, (byte) match.getField(MatchType.NW_PROTO).getValue()); - Assert.assertEquals(tos, (byte) match.getField(MatchType.NW_TOS).getValue()); - Assert.assertEquals(sport, (short) match.getField(MatchType.TP_SRC).getValue()); - Assert.assertEquals(dport, (short) match.getField(MatchType.TP_DST).getValue()); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java deleted file mode 100644 index c5f69518a1..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java +++ /dev/null @@ -1,132 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import org.junit.Assert; - -import org.junit.Test; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; - -public class TCPTest { - - @Test - public void testSetSourcePort() { - TCP tcp = new TCP(); - short tcpSourcePort = 118; - tcp.setSourcePort(tcpSourcePort); - byte[] sourcePort = tcp.hdrFieldsMap.get(TCP.SRCPORT); - Assert.assertTrue(sourcePort[0] == 0); - Assert.assertTrue(sourcePort[1] == 118); - - } - - @Test - public void testSetDestinationPort() { - TCP tcp = new TCP(); - short tcpDestinationPort = 443; - tcp.setDestinationPort(tcpDestinationPort); - byte[] destinationPort = tcp.hdrFieldsMap.get(TCP.DESTPORT); - Assert.assertTrue(destinationPort[0] == 1); - Assert.assertTrue(destinationPort[1] == -69); - - } - - @Test - public void testSetSequenceNumber() { - TCP tcp = new TCP(); - short tcpSequenceNumber = 700; - tcp.setSequenceNumber(tcpSequenceNumber); - byte[] sequenceNumber = tcp.hdrFieldsMap.get(TCP.SEQNUMBER); - Assert.assertTrue(sequenceNumber[0] == 0); - Assert.assertTrue(sequenceNumber[1] == 0); - Assert.assertTrue(sequenceNumber[2] == 2); - Assert.assertTrue(sequenceNumber[3] == -68); - } - - @Test - public void testSetAckNumber() { - TCP tcp = new TCP(); - short tcpAckNumber = 697; - tcp.setAckNumber(tcpAckNumber); - byte[] ackNumber = tcp.hdrFieldsMap.get(TCP.ACKNUMBER); - Assert.assertTrue(ackNumber[0] == 0); - Assert.assertTrue(ackNumber[1] == 0); - Assert.assertTrue(ackNumber[2] == 2); - Assert.assertTrue(ackNumber[3] == -71); - } - - @Test - public void testSetHeaderLenFlags() { - TCP tcp = new TCP(); - short tcpFlags = 26; - tcp.setHeaderLenFlags(tcpFlags); - byte[] headerLenFlags = tcp.hdrFieldsMap.get(TCP.HEADERLENFLAGS); - Assert.assertTrue(headerLenFlags[0] == 0); - Assert.assertTrue(headerLenFlags[1] == 26); - - } - - @Test - public void testSetWindowSize() { - TCP tcp = new TCP(); - short tcpWindowSize = 100; - tcp.setWindowSize(tcpWindowSize); - byte[] windowSize = tcp.hdrFieldsMap.get(TCP.WINDOWSIZE); - Assert.assertTrue(windowSize[0] == 0); - Assert.assertTrue(windowSize[1] == 100); - - } - - @Test - public void testSetChecksum() { - TCP tcp = new TCP(); - short tcpChecksum = 134; - tcp.setChecksum(tcpChecksum); - byte[] checksum = tcp.hdrFieldsMap.get(TCP.CHECKSUM); - Assert.assertTrue(checksum[0] == 0); - Assert.assertTrue(checksum[1] == -122); - - } - - @Test - public void testSetUrgentPointer() { - TCP tcp = new TCP(); - short tcpUrgentPointer = 25098; - tcp.setUrgentPointer(tcpUrgentPointer); - byte[] urgentPointer = tcp.hdrFieldsMap.get(TCP.URGENTPOINTER); - Assert.assertTrue(urgentPointer[0] == 98); - Assert.assertTrue(urgentPointer[1] == 10); - - } - - @Test - public void testGetChecksum() { - TCP tcp = new TCP(); - byte[] udpChecksum = { 0, -56 }; - tcp.hdrFieldsMap.put("Checksum", udpChecksum); - short checksum = tcp.getChecksum(); - Assert.assertTrue(checksum == 200); - } - - @Test - public void testGetMatch() throws Exception { - TCP tcp = new TCP(); - short sport = (short) 52012; - short dport = (short) 40345; - tcp.setSourcePort(sport); - tcp.setDestinationPort(dport); - - Match match = tcp.getMatch(); - - Assert.assertEquals(sport, (short) match.getField(MatchType.TP_SRC).getValue()); - Assert.assertEquals(dport, (short) match.getField(MatchType.TP_DST).getValue()); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java deleted file mode 100644 index ddb6acb0a1..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java +++ /dev/null @@ -1,115 +0,0 @@ - -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.packet; - -import org.junit.Assert; - -import org.junit.Test; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; - -public class UDPTest { - - @Test - public void testGetSourcePort() { - UDP udp = new UDP(); - byte[] udpSourcePort = { 0, 118 }; - udp.hdrFieldsMap.put("SourcePort", udpSourcePort); - short sourcePort = udp.getSourcePort(); - Assert.assertTrue(sourcePort == 118); - } - - @Test - public void testGetDestinationPort() { - UDP udp = new UDP(); - byte[] udpDestinationPort = { 1, -69 }; - udp.hdrFieldsMap.put("DestinationPort", udpDestinationPort); - short destinationPort = udp.getDestinationPort(); - Assert.assertTrue(destinationPort == 443); - } - - @Test - public void testGetLength() { - UDP udp = new UDP(); - byte[] udpLength = { 0, 20 }; - udp.hdrFieldsMap.put("Length", udpLength); - short length = udp.getLength(); - Assert.assertTrue(length == 20); - } - - @Test - public void testGetChecksum() { - UDP udp = new UDP(); - byte[] udpChecksum = { 0, -56 }; - udp.hdrFieldsMap.put("Checksum", udpChecksum); - short checksum = udp.getChecksum(); - Assert.assertTrue(checksum == 200); - } - - @Test - public void testSetSourcePort() { - UDP udp = new UDP(); - short tcpSourcePort = 118; - udp.setSourcePort(tcpSourcePort); - byte[] sourcePort = udp.hdrFieldsMap.get("SourcePort"); - Assert.assertTrue(sourcePort[0] == 0); - Assert.assertTrue(sourcePort[1] == 118); - - } - - @Test - public void testSetDestinationPort() { - UDP udp = new UDP(); - short tcpDestinationPort = 443; - udp.setDestinationPort(tcpDestinationPort); - byte[] destinationPort = udp.hdrFieldsMap.get("DestinationPort"); - Assert.assertTrue(destinationPort[0] == 1); - Assert.assertTrue(destinationPort[1] == -69); - - } - - @Test - public void testSetLength() { - UDP udp = new UDP(); - short udpLength = 20; - udp.setLength(udpLength); - byte[] length = udp.hdrFieldsMap.get("Length"); - Assert.assertTrue(length[0] == 0); - Assert.assertTrue(length[1] == 20); - - } - - @Test - public void testSetChecksum() { - UDP udp = new UDP(); - short udpChecksum = 200; - udp.setChecksum(udpChecksum); - byte[] checksum = udp.hdrFieldsMap.get("Checksum"); - Assert.assertTrue(checksum[0] == 0); - Assert.assertTrue(checksum[1] == -56); - - } - - @Test - public void testGetMatch() throws Exception { - UDP udp = new UDP(); - short sport = (short) 33000; - short dport = (short) 843; - udp.setSourcePort(sport); - udp.setDestinationPort(dport); - - Match match = udp.getMatch(); - - Assert.assertEquals(sport, (short) match.getField(MatchType.TP_SRC).getValue()); - Assert.assertEquals(dport, (short) match.getField(MatchType.TP_DST).getValue()); - - } - -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/address/EthernetAddressTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/address/EthernetAddressTest.java deleted file mode 100644 index e20e22a181..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/packet/address/EthernetAddressTest.java +++ /dev/null @@ -1,113 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file EthernetAddressTest.java - * - * @brief Unit Tests for EthernetAddress class - * - * Unit Tests for EthernetAddress class - */ -package org.opendaylight.controller.sal.packet.address; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.ConstructionException; - -public class EthernetAddressTest { - @Test - public void testNonValidConstructor() { - @SuppressWarnings("unused") - EthernetAddress ea1; - // Null input array - try { - ea1 = new EthernetAddress((byte[]) null); - - // Exception is expected if NOT raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - // Array too short - try { - ea1 = new EthernetAddress(new byte[] { (byte) 0x0, (byte) 0x0 }); - - // Exception is expected if NOT raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - - // Array too long - try { - ea1 = new EthernetAddress(new byte[] { (byte) 0x0, (byte) 0x0, - (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, - (byte) 0x0 }); - - // Exception is expected if NOT raised test will fail - Assert.assertTrue(false); - } catch (ConstructionException e) { - } - } - - @Test - public void testEquality() { - EthernetAddress ea1; - EthernetAddress ea2; - try { - ea1 = new EthernetAddress(new byte[] { (byte) 0x0, (byte) 0x0, - (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x1 }); - - ea2 = new EthernetAddress(new byte[] { (byte) 0x0, (byte) 0x0, - (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x1 }); - Assert.assertTrue(ea1.equals(ea2)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - try { - ea1 = new EthernetAddress(new byte[] { (byte) 0x0, (byte) 0x0, - (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x1 }); - - ea2 = ea1.clone(); - Assert.assertTrue(ea1.equals(ea2)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - - // Check for well knowns - try { - ea1 = EthernetAddress.BROADCASTMAC; - ea2 = new EthernetAddress(new byte[] { (byte) 0xff, (byte) 0xff, - (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff }); - Assert.assertTrue(ea1.equals(ea2)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - } - - @Test - public void testUnEquality() { - EthernetAddress ea1; - EthernetAddress ea2; - try { - ea1 = new EthernetAddress(new byte[] { (byte) 0x0, (byte) 0x0, - (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x2 }); - - ea2 = new EthernetAddress(new byte[] { (byte) 0x0, (byte) 0x0, - (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x1 }); - Assert.assertTrue(!ea1.equals(ea2)); - } catch (ConstructionException e) { - // Exception is NOT expected if raised test will fail - Assert.assertTrue(false); - } - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/FlowOnNodeTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/FlowOnNodeTest.java deleted file mode 100644 index b27b275860..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/FlowOnNodeTest.java +++ /dev/null @@ -1,58 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.reader; - -import java.util.ArrayList; -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -public class FlowOnNodeTest { - - @Test - public void testFlowOnNodeMethods () { - Match match = new Match(); - NodeConnector inNC = NodeConnectorCreator.createNodeConnector((short)10, NodeCreator.createOFNode((long)10)); - NodeConnector outNC = NodeConnectorCreator.createNodeConnector((short)20, NodeCreator.createOFNode((long)20)); - - match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue()); - match.setField(MatchType.IN_PORT, inNC); - - Output output = new Output(outNC); - ArrayList action = new ArrayList(); - action.add(output); - - Flow flow = new Flow (match, action); - - FlowOnNode flowOnNode = new FlowOnNode (flow); - - Assert.assertTrue(flowOnNode.getFlow().equals(flow)); - - flowOnNode.setPacketCount((long)100); - flowOnNode.setByteCount((long)800); - flowOnNode.setTableId((byte)0x55); - flowOnNode.setDurationNanoseconds(40); - flowOnNode.setDurationSeconds(45); - - Assert.assertTrue(flowOnNode.getPacketCount() == 100); - Assert.assertTrue(flowOnNode.getByteCount() == 800); - Assert.assertTrue(flowOnNode.getDurationNanoseconds() == 40); - Assert.assertTrue(flowOnNode.getDurationSeconds() == 45); - Assert.assertTrue(flowOnNode.getTableId() == (byte)0x55); - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeConnectorStatisticsTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeConnectorStatisticsTest.java deleted file mode 100644 index cd160e8431..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeConnectorStatisticsTest.java +++ /dev/null @@ -1,50 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.reader; - -import org.junit.Test; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.junit.Assert; - -public class NodeConnectorStatisticsTest { - - @Test - public void testNodeConnectorStatisticsMethods() { - NodeConnector nc = NodeConnectorCreator.createNodeConnector((short)20, NodeCreator.createOFNode((long)20)); - NodeConnectorStatistics ncStats = new NodeConnectorStatistics(); - ncStats.setNodeConnector(nc); - ncStats.setReceiveByteCount(800); - ncStats.setReceiveCRCErrorCount(10); - ncStats.setReceiveDropCount(5); - ncStats.setReceiveErrorCount(20); - ncStats.setReceiveFrameErrorCount(25); - ncStats.setReceiveOverRunErrorCount(30); - ncStats.setReceivePacketCount(100); - ncStats.setTransmitByteCount(400); - ncStats.setTransmitDropCount(15); - ncStats.setTransmitErrorCount(18); - ncStats.setTransmitPacketCount(50); - ncStats.setCollisionCount(2); - - Assert.assertTrue(ncStats.getCollisionCount() == 2); - Assert.assertTrue(ncStats.getTransmitPacketCount() == 50); - Assert.assertTrue(ncStats.getTransmitErrorCount() == 18); - Assert.assertTrue(ncStats.getTransmitDropCount() == 15); - Assert.assertTrue(ncStats.getReceivePacketCount() == 100); - Assert.assertTrue(ncStats.getReceiveOverRunErrorCount() == 30); - Assert.assertTrue(ncStats.getReceiveFrameErrorCount() == 25); - Assert.assertTrue(ncStats.getReceiveDropCount() == 5); - Assert.assertTrue(ncStats.getReceiveCRCErrorCount() == 10); - Assert.assertTrue(ncStats.getReceiveByteCount() == 800); - Assert.assertTrue(ncStats.getNodeConnector().equals(nc)); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeDescriptionTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeDescriptionTest.java deleted file mode 100644 index c41c154f62..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeDescriptionTest.java +++ /dev/null @@ -1,39 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.reader; - -import org.junit.Assert; -import org.junit.Test; - -public class NodeDescriptionTest { - - @Test - public void testNodeDescriptionMethods() { - NodeDescription ncDesc = new NodeDescription(); - ncDesc.setHardware("Hardware1"); - ncDesc.setManufacturer("Manufacturer1"); - ncDesc.setDescription("SDNProtocol1"); - ncDesc.setSerialNumber("serialNumber1"); - ncDesc.setSoftware("Software1"); - - Assert.assertTrue(ncDesc.getHardware().equals("Hardware1")); - Assert.assertTrue(ncDesc.getManufacturer().equals("Manufacturer1")); - Assert.assertTrue(ncDesc.getDescription().equals("SDNProtocol1")); - Assert.assertTrue(ncDesc.getSerialNumber().equals("serialNumber1")); - Assert.assertTrue(ncDesc.getSoftware().equals("Software1")); - - Assert.assertFalse(ncDesc.getHardware().equals("Hardware2")); - Assert.assertFalse(ncDesc.getManufacturer().equals("Manufacturer2")); - Assert.assertFalse(ncDesc.getDescription().equals("SDNProtocol2")); - Assert.assertFalse(ncDesc.getSerialNumber().equals("serialNumber2")); - Assert.assertFalse(ncDesc.getSoftware().equals("Software2")); - - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeTableStatisticsTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeTableStatisticsTest.java deleted file mode 100644 index a29d4268da..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/reader/NodeTableStatisticsTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2013 Big Switch Networks, Inc. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.reader; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.utils.NodeTableCreator; - -public class NodeTableStatisticsTest { - - @Test - public void testNodeTableStatisticsMethods() { - NodeTable nt = NodeTableCreator.createNodeTable(Byte.valueOf("2") , NodeCreator.createOFNode((long)20)); - NodeTableStatistics ntStats = new NodeTableStatistics(); - - ntStats.setNodeTable(nt); - ntStats.setActiveCount(100); - ntStats.setLookupCount(200); - ntStats.setMatchedCount(500); - ntStats.setMaximumEntries(1000); - ntStats.setName("Test"); - - Assert.assertTrue(ntStats.getNodeTable().equals(nt)); - Assert.assertTrue(ntStats.getActiveCount() == 100); - Assert.assertTrue(ntStats.getLookupCount() == 200); - Assert.assertTrue(ntStats.getMatchedCount() == 500); - Assert.assertTrue(ntStats.getMaximumEntries() == 1000); - Assert.assertTrue(ntStats.getName().equals("Test")); - } -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/EtherTypesTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/EtherTypesTest.java deleted file mode 100644 index 5beb8713f9..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/EtherTypesTest.java +++ /dev/null @@ -1,71 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.util.ArrayList; -import org.junit.Assert; -import org.junit.Test; - -public class EtherTypesTest { - - @Test - public void testEthertypesCreation() { - - EtherTypes arp = EtherTypes.ARP; - - Assert.assertTrue(arp.toString().equals("ARP")); - Assert.assertTrue(arp.intValue() == 2054); - Assert.assertTrue(arp.shortValue() == (short)2054); - } - - @Test - public void testGetEtherTypesString() { - - Assert.assertTrue(EtherTypes.getEtherTypeName(34984).equals("QINQ")); - Assert.assertTrue(EtherTypes.getEtherTypeName((short)2048).equals("IPv4")); - Assert.assertTrue(EtherTypes.getEtherTypeName(0x010B).equals("PVSTP")); - - Assert.assertFalse(EtherTypes.getEtherTypeName(0x800).equals("ARP")); - } - - @Test - public void testGetEtherTypesNumber() { - Assert.assertTrue(EtherTypes.getEtherTypeNumberInt("VLAN Tagged") == 33024); - Assert.assertTrue(EtherTypes.getEtherTypeNumberShort("ARP") == 2054); - - Assert.assertFalse(EtherTypes.getEtherTypeNumberInt("CDP") == 1000); - } - - @Test - public void testGetEtherTypesList() { - ArrayList etherTypeNames = (ArrayList) EtherTypes.getEtherTypesNameList(); - Assert.assertTrue(etherTypeNames.get(0).equals("PVSTP")); - Assert.assertTrue(etherTypeNames.get(1).equals("CDP")); - Assert.assertTrue(etherTypeNames.get(2).equals("VTP")); - Assert.assertTrue(etherTypeNames.get(3).equals("IPv4")); - Assert.assertTrue(etherTypeNames.get(4).equals("ARP")); - Assert.assertTrue(etherTypeNames.get(5).equals("Reverse ARP")); - Assert.assertTrue(etherTypeNames.get(6).equals("VLAN Tagged")); - Assert.assertTrue(etherTypeNames.get(7).equals("IPv6")); - Assert.assertTrue(etherTypeNames.get(8).equals("MPLS Unicast")); - Assert.assertTrue(etherTypeNames.get(9).equals("MPLS Multicast")); - Assert.assertTrue(etherTypeNames.get(10).equals("QINQ")); - Assert.assertTrue(etherTypeNames.get(11).equals("LLDP")); - Assert.assertTrue(etherTypeNames.get(12).equals("Old QINQ")); - Assert.assertTrue(etherTypeNames.get(13).equals("Cisco QINQ")); - } - - @Test - public void testGetEtherTypesloadFromString() { - Assert.assertTrue(EtherTypes.loadFromString("37376").equals(EtherTypes.CISCOQINQ)); - Assert.assertTrue(EtherTypes.loadFromString("100") == null); - } - -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/HexEncodeTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/HexEncodeTest.java deleted file mode 100644 index 3cfa747be5..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/HexEncodeTest.java +++ /dev/null @@ -1,67 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import org.junit.Assert; -import org.junit.Test; - -public class HexEncodeTest { - - @Test - public void testbytesToHexString() { - byte[] bytes1 = {(byte)0x01, (byte)0x02, (byte)0x03}; - String str1 = HexEncode.bytesToHexString(bytes1); - Assert.assertTrue(str1.equals("010203")); - - byte[] bytes2 = {(byte)0x11, (byte)0x22, (byte)0x33}; - String str2 = HexEncode.bytesToHexString(bytes2); - Assert.assertFalse(str2.equals("010203")); - - } - - @Test - public void testLongToHexString() { - long value1 = 12345678L; - String str1 = HexEncode.longToHexString(value1); - Assert.assertTrue(str1.equals("00:00:00:00:00:bc:61:4e")); - - long value2 = 98765432L; - String str2 = HexEncode.longToHexString(value2); - Assert.assertFalse(str2.equals("00:44:33:22:11:bc:61:4e")); - - } - - @Test - public void testBytesFromHexString() { - String byteStr1 = "00:11:22:33:44:55"; - byte byteArray1[] = new byte[(byteStr1.length() + 1)/3]; - byteArray1 = HexEncode.bytesFromHexString(byteStr1); - - Assert.assertTrue(byteArray1[0] == (byte)0x0); - Assert.assertTrue(byteArray1[1] == (byte)0x11); - Assert.assertTrue(byteArray1[2] == (byte)0x22); - Assert.assertTrue(byteArray1[3] == (byte)0x33); - Assert.assertTrue(byteArray1[4] == (byte)0x44); - Assert.assertTrue(byteArray1[5] == (byte)0x55); - - String byteStr2 = "00:11:22:33:44:55"; - byte byteArray2[] = new byte[(byteStr2.length() + 1)/3]; - byteArray2 = HexEncode.bytesFromHexString(byteStr2); - - Assert.assertFalse(byteArray2[0] == (byte)0x55); - Assert.assertFalse(byteArray2[1] == (byte)0x44); - Assert.assertFalse(byteArray2[2] == (byte)0x33); - Assert.assertFalse(byteArray2[3] == (byte)0x22); - Assert.assertFalse(byteArray2[4] == (byte)0x11); - Assert.assertFalse(byteArray2[5] == (byte)0x0); - - } - -} diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/IPProtocolsTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/IPProtocolsTest.java deleted file mode 100644 index 0851c60349..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/IPProtocolsTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.utils; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -/** - * @author ykhodork - * - */ -public class IPProtocolsTest { - - static short shortVal = 1; - static int intVal = 1; - static byte byteVal = 1; - - /** - * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolName(int)}. - */ - @Test - public void testGetProtocolNameInt() { - assertEquals("ICMP", IPProtocols.getProtocolName(1)); - assertEquals("0x4d2", IPProtocols.getProtocolName(1234)); - } - - /** - * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolName(short)}. - */ - @Test - public void testGetProtocolNameShort() { - assertEquals("ICMP", IPProtocols.getProtocolName(shortVal)); - } - - /** - * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolName(byte)}. - */ - @Test - public void testGetProtocolNameByte() { - assertEquals("ICMP", IPProtocols.getProtocolName(byteVal)); - } - - /** - * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolNumberShort(java.lang.String)}. - */ - @Test - public void testGetProtocolNumberShort() { - assertEquals(shortVal, IPProtocols.getProtocolNumberShort("ICMP")); - } - - /** - * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolNumberInt(java.lang.String)}. - */ - @Test - public void testGetProtocolNumberInt() { - assertEquals(intVal, IPProtocols.getProtocolNumberInt("ICMP")); - } - - /** - * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#getProtocolNumberByte(java.lang.String)}. - */ - @Test - public void testGetProtocolNumberByte() { - assertEquals(byteVal, IPProtocols.getProtocolNumberByte("ICMP")); - } - - /** - * Test method for {@link org.opendaylight.controller.sal.utils.IPProtocols#fromString(java.lang.String)}. - */ - @Test - public void testFromString() { - assertTrue(null == IPProtocols.fromString("Not a protocol")); - assertTrue(null == IPProtocols.fromString("0xFFF")); - assertTrue(null == IPProtocols.fromString("-2")); - - assertTrue(IPProtocols.ANY == IPProtocols.fromString("any")); - assertTrue(IPProtocols.ANY == IPProtocols.fromString("ANY")); - assertTrue(IPProtocols.ANY == IPProtocols.fromString("*")); - assertTrue(IPProtocols.ANY == IPProtocols.fromString(null)); - - assertTrue(IPProtocols.TCP == IPProtocols.fromString("TCP")); - assertTrue(IPProtocols.TCP == IPProtocols.fromString("tcp")); - assertTrue(IPProtocols.UDP == IPProtocols.fromString("0x11")); - assertTrue(IPProtocols.UDP == IPProtocols.fromString("0X11")); - - } - -} - - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/NetUtilsTest.java b/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/NetUtilsTest.java deleted file mode 100644 index e5e0a0941b..0000000000 --- a/opendaylight/adsal/sal/api/src/test/java/org/opendaylight/controller/sal/utils/NetUtilsTest.java +++ /dev/null @@ -1,502 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.utils; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; - -import org.junit.Assert; -import org.junit.Test; - -public class NetUtilsTest { - - @Test - public void testByteArrayMethods() { - int ip = 8888; - Assert.assertTrue(NetUtils - .byteArray4ToInt(NetUtils.intToByteArray4(ip)) == ip); - - ip = 0xffffffff; - Assert.assertTrue(NetUtils - .byteArray4ToInt(NetUtils.intToByteArray4(ip)) == ip); - - ip = 0; - Assert.assertTrue(NetUtils - .byteArray4ToInt(NetUtils.intToByteArray4(ip)) == ip); - - ip = 0x1fffffff; - Assert.assertTrue(NetUtils - .byteArray4ToInt(NetUtils.intToByteArray4(ip)) == ip); - - ip = 0xfffffff; - Assert.assertTrue(NetUtils - .byteArray4ToInt(NetUtils.intToByteArray4(ip)) == ip); - - ip = 0xf000ffff; - Assert.assertTrue(NetUtils - .byteArray4ToInt(NetUtils.intToByteArray4(ip)) == ip); - - byte ba[] = { (byte) 0xf, (byte) 0xf, (byte) 0xf, (byte) 0xff }; - Assert.assertTrue(Arrays.equals(ba, NetUtils.intToByteArray4(NetUtils - .byteArray4ToInt(ba)))); - - byte ba1[] = { (byte) 255, (byte) 255, (byte) 255, (byte) 255 }; - Assert.assertTrue(Arrays.equals(ba1, NetUtils.intToByteArray4(NetUtils - .byteArray4ToInt(ba1)))); - - byte ba2[] = { (byte) 255, (byte) 0, (byte) 0, (byte) 0 }; - Assert.assertTrue(Arrays.equals(ba2, NetUtils.intToByteArray4(NetUtils - .byteArray4ToInt(ba2)))); - - byte ba3[] = { (byte) 0, (byte) 0, (byte) 0, (byte) 0 }; - Assert.assertTrue(Arrays.equals(ba3, NetUtils.intToByteArray4(NetUtils - .byteArray4ToInt(ba3)))); - - byte ba4[] = { (byte) 255, (byte) 128, (byte) 0, (byte) 0 }; - Assert.assertTrue(Arrays.equals(ba4, NetUtils.intToByteArray4(NetUtils - .byteArray4ToInt(ba4)))); - } - - @Test - public void testByteArrayMethodsForLong() { - // Test of longToByteArray6 method. - byte ba[] = { - (byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, - (byte) 0x55, (byte) 0x66 - }; - long mac = 0x112233445566L; - Assert.assertTrue(Arrays.equals(ba, NetUtils.longToByteArray6(mac))); - - byte ba1[] = { - (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, - (byte) 0xff, (byte) 0xff - }; - long mac1 = 0xffffffffffffL; - Assert.assertTrue(Arrays.equals(ba1, NetUtils.longToByteArray6(mac1))); - - byte ba2[] = { - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00 - }; - long mac2 = 0x000000000000L; - Assert.assertTrue(Arrays.equals(ba2, NetUtils.longToByteArray6(mac2))); - - byte ba3[] = { - (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x00, - (byte) 0x00, (byte) 0x00 - }; - long mac3 = 0xffffff000000L; - Assert.assertTrue(Arrays.equals(ba3, NetUtils.longToByteArray6(mac3))); - - byte ba4[] = { - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, - (byte) 0xff, (byte) 0xff - }; - long mac4 = 0x000000ffffffL; - Assert.assertTrue(Arrays.equals(ba4, NetUtils.longToByteArray6(mac4))); - - // Convert a long number to a byte array, - // and revert it to the long number again. - Assert.assertTrue(NetUtils - .byteArray6ToLong(NetUtils.longToByteArray6(mac)) == mac); - - Assert.assertTrue(NetUtils - .byteArray6ToLong(NetUtils.longToByteArray6(mac1)) == mac1); - - Assert.assertTrue(NetUtils - .byteArray6ToLong(NetUtils.longToByteArray6(mac2)) == mac2); - - Assert.assertTrue(NetUtils - .byteArray6ToLong(NetUtils.longToByteArray6(mac3)) == mac3); - - Assert.assertTrue(NetUtils - .byteArray6ToLong(NetUtils.longToByteArray6(mac4)) == mac4); - - // Convert a byte array to a long nubmer, - // and revert it to the byte array again. - Assert.assertTrue(Arrays.equals(ba, - NetUtils.longToByteArray6(NetUtils.byteArray6ToLong(ba)))); - - Assert.assertTrue(Arrays.equals(ba1, - NetUtils.longToByteArray6(NetUtils.byteArray6ToLong(ba1)))); - - Assert.assertTrue(Arrays.equals(ba2, - NetUtils.longToByteArray6(NetUtils.byteArray6ToLong(ba2)))); - - Assert.assertTrue(Arrays.equals(ba3, - NetUtils.longToByteArray6(NetUtils.byteArray6ToLong(ba3)))); - - Assert.assertTrue(Arrays.equals(ba4, - NetUtils.longToByteArray6(NetUtils.byteArray6ToLong(ba4)))); - - // Test of paramter validation of byteArray6ToLong method. - byte array5[] = { - (byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44 - }; - Assert.assertEquals(0, NetUtils.byteArray6ToLong(array5)); - - byte array7[] = { - (byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, - (byte) 0x55, (byte) 0x66, (byte) 0x77 - }; - Assert.assertEquals(0, NetUtils.byteArray6ToLong(array7)); - - byte arrayNull[] = null; - Assert.assertEquals(0, NetUtils.byteArray6ToLong(arrayNull)); - } - - @Test - public void testInetMethods() throws UnknownHostException { - int ip = 0xfffffff0; - InetAddress inet = InetAddress.getByName("255.255.255.240"); - Assert.assertTrue(inet.equals(NetUtils.getInetAddress(ip))); - - ip = 0; - inet = InetAddress.getByName("0.0.0.0"); - Assert.assertTrue(inet.equals(NetUtils.getInetAddress(ip))); - - ip = 0x9ffff09; - inet = InetAddress.getByName("9.255.255.9"); - Assert.assertTrue(inet.equals(NetUtils.getInetAddress(ip))); - } - - @Test - public void testMasksV4() throws UnknownHostException { - - InetAddress mask = InetAddress.getByName("128.0.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(1, false))); - - mask = InetAddress.getByName("192.0.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(2, false))); - - mask = InetAddress.getByName("224.0.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(3, false))); - - mask = InetAddress.getByName("240.0.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(4, false))); - - mask = InetAddress.getByName("248.0.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(5, false))); - - mask = InetAddress.getByName("252.0.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(6, false))); - - mask = InetAddress.getByName("254.0.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(7, false))); - - mask = InetAddress.getByName("255.0.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(8, false))); - - mask = InetAddress.getByName("255.128.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(9, false))); - - mask = InetAddress.getByName("255.192.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(10, false))); - - mask = InetAddress.getByName("255.224.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(11, false))); - - mask = InetAddress.getByName("255.240.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(12, false))); - - mask = InetAddress.getByName("255.248.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(13, false))); - - mask = InetAddress.getByName("255.252.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(14, false))); - - mask = InetAddress.getByName("255.254.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(15, false))); - - mask = InetAddress.getByName("255.255.0.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(16, false))); - - mask = InetAddress.getByName("255.255.128.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(17, false))); - - mask = InetAddress.getByName("255.255.192.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(18, false))); - - mask = InetAddress.getByName("255.255.224.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(19, false))); - - mask = InetAddress.getByName("255.255.240.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(20, false))); - - mask = InetAddress.getByName("255.255.248.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(21, false))); - - mask = InetAddress.getByName("255.255.252.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(22, false))); - - mask = InetAddress.getByName("255.255.254.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(23, false))); - - mask = InetAddress.getByName("255.255.255.0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(24, false))); - - mask = InetAddress.getByName("255.255.255.128"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(25, false))); - - mask = InetAddress.getByName("255.255.255.192"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(26, false))); - - mask = InetAddress.getByName("255.255.255.224"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(27, false))); - - mask = InetAddress.getByName("255.255.255.240"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(28, false))); - - mask = InetAddress.getByName("255.255.255.248"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(29, false))); - - mask = InetAddress.getByName("255.255.255.252"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(30, false))); - - mask = InetAddress.getByName("255.255.255.254"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(31, false))); - - mask = InetAddress.getByName("255.255.255.255"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(32, false))); - } - - @Test - public void testMasksV6() throws UnknownHostException { - - InetAddress mask = InetAddress.getByName("ff00::0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(8, true))); - - mask = InetAddress.getByName("8000::0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(1, true))); - - mask = InetAddress.getByName("f800::0"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(5, true))); - - mask = InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"); - Assert.assertTrue(mask.equals(NetUtils.getInetNetworkMask(127, true))); - } - - @Test - public void testGetSubnetLen() { - - byte address[] = { (byte) 128, (byte) 0, (byte) 0, 0 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address) == 1); - - byte address1[] = { (byte) 255, 0, 0, 0 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address1) == 8); - - byte address2[] = { (byte) 255, (byte) 255, (byte) 248, 0 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address2) == 21); - - byte address4[] = { (byte) 255, (byte) 255, (byte) 255, (byte) 254 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address4) == 31); - - byte address5[] = { (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, - (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, - (byte) 255 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address5) == 128); - - byte address6[] = { (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, - (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, - (byte) 254 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address6) == 127); - - byte address7[] = { (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, - (byte) 255, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address7) == 64); - - byte address8[] = { (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, - (byte) 254, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address8) == 63); - - byte address9[] = { (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 128, - (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address9) == 49); - - byte address10[] = { (byte) 128, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, - (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address10) == 1); - - byte address11[] = { (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, - (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0 }; - Assert.assertTrue(NetUtils.getSubnetMaskLength(address11) == 0); - } - - @Test - public void testGetSubnetPrefix() throws UnknownHostException { - InetAddress ip = InetAddress.getByName("192.128.64.252"); - int maskLen = 25; - Assert.assertTrue(NetUtils.getSubnetPrefix(ip, maskLen).equals( - InetAddress.getByName("192.128.64.128"))); - } - - @Test - public void testIsIPv6Valid() throws UnknownHostException { - Assert.assertTrue(NetUtils - .isIPv6AddressValid("fe80:0000:0000:0000:0204:61ff:fe9d:f156")); //normal ipv6 - Assert.assertTrue(NetUtils - .isIPv6AddressValid("fe80:0:0:0:204:61ff:fe9d:f156")); //no leading zeroes - Assert.assertTrue(NetUtils - .isIPv6AddressValid("fe80::204:61ff:fe9d:f156")); //zeroes to :: - Assert - .assertTrue(NetUtils - .isIPv6AddressValid("fe80:0000:0000:0000:0204:61ff:254.157.241.86")); // ipv4 ending - Assert.assertTrue(NetUtils - .isIPv6AddressValid("fe80:0:0:0:0204:61ff:254.157.241.86")); // no leading zeroes, ipv4 end - Assert.assertTrue(NetUtils - .isIPv6AddressValid("fe80::204:61ff:254.157.241.86")); // zeroes ::, no leading zeroes - - Assert.assertTrue(NetUtils.isIPv6AddressValid("2001::")); //link-local prefix - Assert.assertTrue(NetUtils.isIPv6AddressValid("::1")); //localhost - Assert.assertTrue(NetUtils.isIPv6AddressValid("fe80::")); //global-unicast - Assert.assertFalse(NetUtils.isIPv6AddressValid("abcd")); //not valid - Assert.assertFalse(NetUtils.isIPv6AddressValid("1")); //not valid - Assert.assertFalse(NetUtils - .isIPv6AddressValid("fe80:0:0:0:204:61ff:fe9d")); //not valid, too short - Assert.assertFalse(NetUtils - .isIPv6AddressValid("fe80:::0:0:0:204:61ff:fe9d")); //not valid - Assert.assertFalse(NetUtils.isIPv6AddressValid("192.168.1.1")); //not valid,ipv4 - Assert - .assertFalse(NetUtils - .isIPv6AddressValid("2001:0000:1234:0000:10001:C1C0:ABCD:0876")); //not valid, extra number - Assert - .assertFalse(NetUtils - .isIPv6AddressValid("20010:0000:1234:0000:10001:C1C0:ABCD:0876")); //not valid, extra number - - Assert - .assertTrue(NetUtils - .isIPv6AddressValid("2001:0DB8:0000:CD30:0000:0000:0000:0000/60")); //full with mask - Assert.assertTrue(NetUtils.isIPv6AddressValid("2001:0DB8:0:CD30::/64")); //shortened with mask - Assert.assertTrue(NetUtils.isIPv6AddressValid("2001:0DB8:0:CD30::/0")); //0 subnet with mask - Assert.assertTrue(NetUtils.isIPv6AddressValid("::1/128")); //localhost 128 mask - - Assert.assertFalse(NetUtils.isIPv6AddressValid("124.15.6.89/60")); //invalid, ip with mask - Assert - .assertFalse(NetUtils - .isIPv6AddressValid("2001:0DB8:0000:CD30:0000:0000:0000:0000/130")); //invalid, mask >128 - Assert - .assertFalse(NetUtils - .isIPv6AddressValid("2001:0DB8:0:CD30::/-5")); //invalid, mask < 0 - Assert.assertFalse(NetUtils - .isIPv6AddressValid("fe80:::0:0:0:204:61ff:fe9d/64")); //not valid ip, valid netmask - Assert.assertFalse(NetUtils - .isIPv6AddressValid("fe80:::0:0:0:204:61ff:fe9d/-1")); //not valid both - - } - - @Test - public void testInetAddressConflict() throws UnknownHostException { - - // test a ipv4 testAddress in the same subnet as the filter - // the method should return false as there is no conflict - Assert.assertFalse(NetUtils.inetAddressConflict( - InetAddress.getByName("9.9.1.1"), - InetAddress.getByName("9.9.1.0"), null, - InetAddress.getByName("255.255.255.0"))); - - // test a ipv4 testAddress not in the same subnet as the filter - // the method should return true as there is a conflict - Assert.assertTrue(NetUtils.inetAddressConflict( - InetAddress.getByName("9.9.2.1"), - InetAddress.getByName("9.9.1.0"), null, - InetAddress.getByName("255.255.255.0"))); - - // test a ipv4 testAddress more generic than the filter - // the method should return true as there is a conflict - Assert.assertTrue(NetUtils.inetAddressConflict( - InetAddress.getByName("9.9.1.1"), - InetAddress.getByName("9.9.1.0"), - InetAddress.getByName("255.255.0.0"), - InetAddress.getByName("255.255.255.0"))); - - // test a ipv4 testAddress less generic than the filter and in the same - // subnet as the filter - // the method should return false as there is no conflict - Assert.assertFalse(NetUtils.inetAddressConflict( - InetAddress.getByName("9.9.1.0"), - InetAddress.getByName("9.9.0.0"), - InetAddress.getByName("255.255.255.0"), - InetAddress.getByName("255.255.0.0"))); - - // test a ipv4 testAddress less generic than the filter and not in the - // same subnet as the filter - // the method should return true as there is a conflict - Assert.assertTrue(NetUtils.inetAddressConflict( - InetAddress.getByName("9.8.1.0"), - InetAddress.getByName("9.9.0.0"), - InetAddress.getByName("255.255.255.0"), - InetAddress.getByName("255.255.0.0"))); - - } - - @Test - public void testIPAddressValidity() { - Assert.assertFalse(NetUtils.isIPAddressValid(null)); - Assert.assertFalse(NetUtils.isIPAddressValid("abc")); - Assert.assertFalse(NetUtils.isIPAddressValid("1.1.1")); - Assert.assertFalse(NetUtils.isIPAddressValid("1.1.1.1/49")); - - Assert.assertTrue(NetUtils.isIPAddressValid("1.1.1.1")); - Assert.assertTrue(NetUtils.isIPAddressValid("1.1.1.1/32")); - Assert.assertTrue(NetUtils - .isIPAddressValid("2001:420:281:1004:407a:57f4:4d15:c355")); - } - - @Test - public void testGetUnsignedByte() { - Assert.assertEquals(0, NetUtils.getUnsignedByte((byte) 0x00)); - Assert.assertEquals(1, NetUtils.getUnsignedByte((byte) 0x01)); - Assert.assertEquals(127, NetUtils.getUnsignedByte((byte) 0x7f)); - - Assert.assertEquals(128, NetUtils.getUnsignedByte((byte) 0x80)); - Assert.assertEquals(255, NetUtils.getUnsignedByte((byte) 0xff)); - } - - @Test - public void testGetUnsignedShort() { - Assert.assertEquals(0, NetUtils.getUnsignedShort((short) 0x0000)); - Assert.assertEquals(1, NetUtils.getUnsignedShort((short) 0x0001)); - Assert.assertEquals(32767, NetUtils.getUnsignedShort((short) 0x7fff)); - - Assert.assertEquals(32768, NetUtils.getUnsignedShort((short) 0x8000)); - Assert.assertEquals(65535, NetUtils.getUnsignedShort((short) 0xffff)); - } - - @Test - public void testMulticastMACAddr() { - byte[] empty = new byte[0]; - Assert.assertFalse(NetUtils.isUnicastMACAddr(empty)); - Assert.assertFalse(NetUtils.isMulticastMACAddr(empty)); - - byte[] bcast = { - (byte)0xff, (byte)0xff, (byte)0xff, - (byte)0xff, (byte)0xff, (byte)0xff, - }; - Assert.assertFalse(NetUtils.isUnicastMACAddr(bcast)); - Assert.assertFalse(NetUtils.isMulticastMACAddr(bcast)); - - byte[] firstOctet = { - (byte)0x00, (byte)0x20, (byte)0x80, (byte)0xfe, - }; - for (int len = 1; len <= 10; len++) { - byte[] ba = new byte[len]; - boolean valid = (len == 6); - for (byte first: firstOctet) { - ba[0] = first; - Assert.assertFalse(NetUtils.isMulticastMACAddr(ba)); - Assert.assertEquals(valid, NetUtils.isUnicastMACAddr(ba)); - - ba[0] |= (byte)0x01; - Assert.assertEquals(valid, NetUtils.isMulticastMACAddr(ba)); - Assert.assertFalse(NetUtils.isUnicastMACAddr(ba)); - } - } - } -} diff --git a/opendaylight/adsal/sal/connection/api/pom.xml b/opendaylight/adsal/sal/connection/api/pom.xml deleted file mode 100644 index f9f52584c8..0000000000 --- a/opendaylight/adsal/sal/connection/api/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../commons/opendaylight - - - sal.connection - 0.3.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - sal - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.slf4j, - org.osgi.framework, - org.apache.felix.dm, - org.apache.commons.lang3.tuple, - javax.xml.bind.annotation, - javax.xml.bind.annotation.adapters, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils - org.opendaylight.controller.sal.connection - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionConstants.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionConstants.java deleted file mode 100644 index aaa883ba64..0000000000 --- a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionConstants.java +++ /dev/null @@ -1,33 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connection; - -/** - * ConnectionConstants - * Expand this enum as and when needed to support other connection parameters that - * might be needed for certain protocol plugins. - */ -public enum ConnectionConstants { - ADDRESS("address"), - PORT("port"), - PROTOCOL("protocol"), - USERNAME("username"), - PASSWORD("password"); - - private ConnectionConstants(String name) { - this.name = name; - } - - private String name; - - public String toString() { - return name; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionLocality.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionLocality.java deleted file mode 100644 index 39dd80d179..0000000000 --- a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/ConnectionLocality.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.connection; - -public enum ConnectionLocality { - /** - * This controller is the (or one of the) master for a given node - */ - LOCAL("This controller is the (or one of the) master for a given node"), - - /** - * This controller is not the master for a given node - */ - NOT_LOCAL("This controller is not the master for a given node"), - - /** - * The given node is not connected to any of the controllers in the cluster - */ - NOT_CONNECTED("The given node is not connected to any of the controllers in the cluster"); - - private ConnectionLocality(String description) { - this.description = description; - } - - private String description; - - public String toString() { - return description; - } -} diff --git a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionListener.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionListener.java deleted file mode 100644 index 7ab3bb2754..0000000000 --- a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionListener.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connection; -/** - * This interface defines the methods the SAL service which relay the Connection - * Notification events to the functional modules - */ -public interface IConnectionListener extends IPluginOutConnectionService { -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionService.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionService.java deleted file mode 100644 index ff63cf7578..0000000000 --- a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IConnectionService.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connection; - -import java.util.Map; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.Status; - -/** - * Interface that defines the methods available to the functional modules that operate - * above SAL for disconnecting or connecting to a particular node. - */ -public interface IConnectionService { - /** - * Connect to a node with a specified node type. - * - * @param type Type of the node representing NodeIDType. - * @param connectionIdentifier Convenient identifier for the applications to make use of - * @param params Connection Params in Map format. This is entirely handled by the south-bound - * plugins and is an opaque value for SAL. Typical values keyed inside this params are - * Management IP-Address, Username, Password, Security Keys, etc... - * - * @return Node {@link org.opendaylight.controller.sal.core.Node} - */ - public Node connect (String type, String connectionIdentifier, Map params); - - /** - * Discover the node type and Connect to the first plugin that is able to connect with the specified parameters. - * - * @param type Type of the node representing NodeIDType. - * @param connectionIdentifier Convenient identifier for the applications to make use of - * @param params Connection Params in Map format. This is entirely handled by the south-bound - * plugins and is an opaque value for SAL. Typical values keyed inside this params are - * Management IP-Address, Username, Password, Security Keys, etc... - * - * @return Node {@link org.opendaylight.controller.sal.core.Node} - */ - public Node connect (String connectionIdentifier, Map params); - - /** - * Disconnect a Node that is connected to this Controller. - * - * @param node - * the node {@link org.opendaylight.controller.sal.core.Node} - * @return Status {@link org.opendaylight.controller.sal.utils.Status} - */ - public Status disconnect(Node node); - - /** - * View Change notification - * - * @param node - * the node {@link org.opendaylight.controller.sal.core.Node} - */ - public void notifyNodeDisconnectFromMaster(Node node); - - /** - * View Change notification - */ - public void notifyClusterViewChanged(); -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginInConnectionService.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginInConnectionService.java deleted file mode 100644 index f4e16fac54..0000000000 --- a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginInConnectionService.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connection; - -import java.util.Map; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.Status; - -/** - * The interface describes methods to be implemented by protocol plugins - */ -public interface IPluginInConnectionService { - /** - * Disconnect a Node that is connected to this Controller. - * - * @param node - * the given node {@link org.opendaylight.controller.sal.core.Node} - */ - public Status disconnect(Node node); - - /** - * Connect to a node - * - * @param connectionIdentifier Convenient identifier for the applications to make use of - * @param params Connection Params in Map format. This is entirely handled by the south-bound - * plugins and is an opaque value for SAL. Typical values keyed inside this params are - * Management IP-Address, Username, Password, Security Keys, etc... - * - * @return Node - */ - public Node connect (String connectionIdentifier, Map params); - - /** - * View Change notification - */ - public void notifyClusterViewChanged(); - - /** - * Node Disconnected from the node's master controller. - * - * @param node - * the given node {@link org.opendaylight.controller.sal.core.Node} - */ - public void notifyNodeDisconnectFromMaster(Node node); - -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginOutConnectionService.java b/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginOutConnectionService.java deleted file mode 100644 index 16e215444e..0000000000 --- a/opendaylight/adsal/sal/connection/api/src/main/java/org/opendaylight/controller/sal/connection/IPluginOutConnectionService.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connection; - -import org.opendaylight.controller.sal.core.Node; - -/** - * The interface describes methods to be implemented by SAL connection service - */ -public interface IPluginOutConnectionService { - /** - * Method to test if a node is local to a controller. - * - * @param node - * the given node {@link org.opendaylight.controller.sal.core.Node} - * @return true if node is local to this controller. false otherwise. - */ - public boolean isLocal(Node node); - - public ConnectionLocality getLocalityStatus(Node node); -} \ No newline at end of file diff --git a/opendaylight/adsal/sal/connection/implementation/pom.xml b/opendaylight/adsal/sal/connection/implementation/pom.xml deleted file mode 100644 index b09a51733b..0000000000 --- a/opendaylight/adsal/sal/connection/implementation/pom.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../commons/opendaylight - - - sal.connection.implementation - 0.3.0-SNAPSHOT - bundle - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.slf4j, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.inventory, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.reader, - org.opendaylight.controller.sal.topology, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.connection, - org.apache.felix.dm, - org.eclipse.osgi.framework.console, - org.osgi.framework - - org.opendaylight.controller.sal.connection.implementation.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/Activator.java b/opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/Activator.java deleted file mode 100644 index c4e38a1d63..0000000000 --- a/opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/Activator.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connection.implementation.internal; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.sal.connection.IConnectionListener; -import org.opendaylight.controller.sal.connection.IConnectionService; -import org.opendaylight.controller.sal.connection.IPluginInConnectionService; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - /** - * Function that is used to communicate to dependency manager the list of - * known Global implementations - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - public Object[] getGlobalImplementations() { - Object[] res = { ConnectionService.class}; - return res; - } - - /** - * Function that is called when configuration of the dependencies is required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - */ - public void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(ConnectionService.class)) { - c.setInterface( - new String[] { IConnectionService.class.getName(), - IPluginOutConnectionService.class.getName() }, - null); - - c.add(createServiceDependency() - .setService(IPluginInConnectionService.class) - .setCallbacks("setPluginService", "unsetPluginService") - .setRequired(false)); - c.add(createServiceDependency() - .setService(IConnectionListener.class) - .setCallbacks("setListener", "unsetListener") - .setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/ConnectionService.java b/opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/ConnectionService.java deleted file mode 100644 index c73607ae83..0000000000 --- a/opendaylight/adsal/sal/connection/implementation/src/main/java/org/opendaylight/controller/sal/connection/implementation/internal/ConnectionService.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.connection.implementation.internal; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import org.opendaylight.controller.sal.connection.ConnectionConstants; -import org.opendaylight.controller.sal.connection.ConnectionLocality; -import org.opendaylight.controller.sal.connection.IConnectionListener; -import org.opendaylight.controller.sal.connection.IConnectionService; -import org.opendaylight.controller.sal.connection.IPluginInConnectionService; -import org.opendaylight.controller.sal.connection.IPluginOutConnectionService; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ConnectionService implements IPluginOutConnectionService, IConnectionService { - protected static final Logger logger = LoggerFactory - .getLogger(ConnectionService.class); - private IConnectionListener connectionListener; - private ConcurrentMap pluginService = - new ConcurrentHashMap(); - - void setPluginService (Map props, IPluginInConnectionService s) { - String type = null; - Object value = props.get(GlobalConstants.PROTOCOLPLUGINTYPE.toString()); - if (value instanceof String) { - type = (String) value; - } - if (type == null) { - logger.error("Received a PluginInConnectionService without any " - + "protocolPluginType provided"); - } else { - this.pluginService.put(type, s); - } - } - - void unsetPluginService(Map props, IPluginInConnectionService s) { - String type = null; - - Object value = props.get(GlobalConstants.PROTOCOLPLUGINTYPE.toString()); - if (value instanceof String) { - type = (String) value; - } - if (type == null) { - logger.error("Received a PluginInConnectionService without any " - + "protocolPluginType provided"); - } else if (this.pluginService.get(type).equals(s)) { - this.pluginService.remove(type); - } - } - - void setListener(IConnectionListener s) { - this.connectionListener = s; - } - - void unsetListener(IConnectionListener s) { - if (this.connectionListener == s) { - this.connectionListener = null; - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - connectionListener = null; - if (this.pluginService != null) { - this.pluginService.clear(); - } - } - - /** - * Method to test if a node is local to a controller. - * - * @return true if node is local to this controller. false otherwise. - */ - public boolean isLocal(Node node) { - if (this.connectionListener == null) return false; - return connectionListener.isLocal(node); - } - - @Override - public ConnectionLocality getLocalityStatus(Node node) { - if (this.connectionListener == null) { - return ConnectionLocality.NOT_CONNECTED; - } - return connectionListener.getLocalityStatus(node); - } - - @Override - public Node connect (String type, String connectionIdentifier, Map params) { - IPluginInConnectionService s = pluginService.get(type); - if (s != null) { - return s.connect(connectionIdentifier, params); - } - return null; - } - - @Override - public Node connect (String connectionIdentifier, Map params) { - synchronized (this.pluginService) { - for (String pluginType : this.pluginService.keySet()) { - IPluginInConnectionService s = pluginService.get(pluginType); - Node node = s.connect(connectionIdentifier, params); - if (node != null) { - return node; - } - } - } - return null; - } - - @Override - public Status disconnect(Node node) { - IPluginInConnectionService s = pluginService.get(node.getType()); - if (s != null) { - return s.disconnect(node); - } - return new Status(StatusCode.NOTFOUND); - } - - /** - * View Change notification - */ - @Override - public void notifyClusterViewChanged() { - for (String pluginType : this.pluginService.keySet()) { - IPluginInConnectionService s = pluginService.get(pluginType); - s.notifyClusterViewChanged(); - } - } - - /** - * Node Disconnected from the node's master controller. - */ - @Override - public void notifyNodeDisconnectFromMaster(Node node) { - IPluginInConnectionService s = pluginService.get(node.getType()); - if (s != null) { - s.notifyNodeDisconnectFromMaster(node); - } - } -} diff --git a/opendaylight/adsal/sal/implementation/pom.xml b/opendaylight/adsal/sal/implementation/pom.xml deleted file mode 100644 index 61c6acfc60..0000000000 --- a/opendaylight/adsal/sal/implementation/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - sal.implementation - 0.6.0-SNAPSHOT - bundle - - - equinoxSDK381 - org.eclipse.osgi - - - org.opendaylight.controller - sal - - - junit - junit - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.slf4j, - org.apache.commons.lang3.builder, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.inventory, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.reader, - org.opendaylight.controller.sal.topology, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.utils, - org.apache.felix.dm, - org.eclipse.osgi.framework.console, - org.osgi.framework - - org.opendaylight.controller.sal.implementation.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Activator.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Activator.java deleted file mode 100644 index 98cb3b83ca..0000000000 --- a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Activator.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.implementation.internal; - -import java.util.Dictionary; -import java.util.Hashtable; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener; -import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService; -import org.opendaylight.controller.sal.flowprogrammer.IPluginInFlowProgrammerService; -import org.opendaylight.controller.sal.flowprogrammer.IPluginOutFlowProgrammerService; -import org.opendaylight.controller.sal.inventory.IInventoryService; -import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; -import org.opendaylight.controller.sal.inventory.IPluginInInventoryService; -import org.opendaylight.controller.sal.inventory.IPluginOutInventoryService; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.sal.packet.IPluginInDataPacketService; -import org.opendaylight.controller.sal.packet.IPluginOutDataPacketService; -import org.opendaylight.controller.sal.reader.IPluginInReadService; -import org.opendaylight.controller.sal.reader.IPluginOutReadService; -import org.opendaylight.controller.sal.reader.IReadService; -import org.opendaylight.controller.sal.reader.IReadServiceListener; -import org.opendaylight.controller.sal.topology.IListenTopoUpdates; -import org.opendaylight.controller.sal.topology.IPluginInTopologyService; -import org.opendaylight.controller.sal.topology.IPluginOutTopologyService; -import org.opendaylight.controller.sal.topology.ITopologyService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the list of - * known Global implementations - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - public Object[] getGlobalImplementations() { - Object[] res = { Inventory.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies is required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - */ - public void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(Inventory.class)) { - Dictionary props = new Hashtable(); - props.put("scope", "Global"); - // export the service - c.setInterface( - new String[] { IPluginOutInventoryService.class.getName(), - IInventoryService.class.getName() }, props); - - // Now lets add a service dependency to make sure the - // provider of service exists - c.add(createServiceDependency() - .setService(IListenInventoryUpdates.class, "(scope=Global)") - .setCallbacks("setUpdateService", "unsetUpdateService") - .setRequired(false)); - c.add(createServiceDependency() - .setService(IPluginInInventoryService.class, "(scope=Global)") - .setCallbacks("setPluginService", "unsetPluginService") - .setRequired(false)); - } - } - - /** - * Function that is used to communicate to dependency manager the list of - * known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { Topology.class, Inventory.class, - FlowProgrammerService.class, ReadService.class, - DataPacketService.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies is - * required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - * @param containerName - * The containerName being configured, this allow also optional - * per-container different behavior if needed, usually should not - * be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(Topology.class)) { - // export the service for Apps and Plugins - c.setInterface( - new String[] { IPluginOutTopologyService.class.getName(), - ITopologyService.class.getName() }, null); - - // There can be multiple Topology listeners or there could - // be none, hence the dependency is optional - c.add(createContainerServiceDependency(containerName) - .setService(IListenTopoUpdates.class) - .setCallbacks("setUpdateService", "unsetUpdateService") - .setRequired(false)); - - // There can be multiple southbound plugins or there could - // be none, the dependency is optional - c.add(createContainerServiceDependency(containerName) - .setService(IPluginInTopologyService.class) - .setCallbacks("setPluginService", "unsetPluginService") - .setRequired(false)); - } - - if (imp.equals(Inventory.class)) { - // export the service - c.setInterface( - new String[] { IPluginOutInventoryService.class.getName(), - IInventoryService.class.getName() }, null); - - // Now lets add a service dependency to make sure the - // provider of service exists - c.add(createContainerServiceDependency(containerName) - .setService(IListenInventoryUpdates.class) - .setCallbacks("setUpdateService", "unsetUpdateService") - .setRequired(false)); - c.add(createContainerServiceDependency(containerName) - .setService(IPluginInInventoryService.class) - .setCallbacks("setPluginService", "unsetPluginService") - .setRequired(false)); - } - - if (imp.equals(FlowProgrammerService.class)) { - c.setInterface( - new String[] { IFlowProgrammerService.class.getName(), - IPluginOutFlowProgrammerService.class.getName() }, - null); - - c.add(createServiceDependency() - .setService(IPluginInFlowProgrammerService.class) - .setCallbacks("setService", "unsetService") - .setRequired(false)); - c.add(createContainerServiceDependency(containerName) - .setService(IFlowProgrammerListener.class) - .setCallbacks("setListener", "unsetListener") - .setRequired(false)); - } - - if (imp.equals(ReadService.class)) { - // export services - c.setInterface(new String[] { - IReadService.class.getName(),IPluginOutReadService.class.getName()}, null); - - // It is also the consumer of IPluginInReadService - c.add(createContainerServiceDependency(containerName) - .setService(IPluginInReadService.class) - .setCallbacks("setService", "unsetService") - .setRequired(false)); - - //consumes plugins' reader updates - c.add(createContainerServiceDependency(containerName) - .setService(IReadServiceListener.class) - .setCallbacks("setReaderListener", "unsetReaderListener") - .setRequired(false)); - - } - - /************************/ - /* DATA PACKET SERVICES */ - /************************/ - if (imp.equals(DataPacketService.class)) { - c.setInterface( - new String[] { IPluginOutDataPacketService.class.getName(), - IDataPacketService.class.getName() }, null); - - // Optionally use PluginInDataService if any southbound - // protocol plugin exists - c.add(createContainerServiceDependency(containerName) - .setService(IPluginInDataPacketService.class) - .setCallbacks("setPluginInDataService", - "unsetPluginInDataService").setRequired(false)); - - // Optionally listed to IListenDataPacket services - c.add(createContainerServiceDependency(containerName) - .setService(IListenDataPacket.class) - .setCallbacks("setListenDataPacket", - "unsetListenDataPacket").setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java deleted file mode 100644 index 6f23cc735a..0000000000 --- a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/DataPacketService.java +++ /dev/null @@ -1,473 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -/** - * @file DataPacketService.java - * - * @brief Implementation of Data Packet services in SAL - * - * Implementation of Data Packet services in SAL - */ - -package org.opendaylight.controller.sal.implementation.internal; - -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.atomic.AtomicInteger; - -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.packet.Ethernet; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.sal.packet.IPluginInDataPacketService; -import org.opendaylight.controller.sal.packet.IPluginOutDataPacketService; -import org.opendaylight.controller.sal.packet.LinkEncap; -import org.opendaylight.controller.sal.packet.Packet; -import org.opendaylight.controller.sal.packet.PacketResult; -import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DataPacketService implements IPluginOutDataPacketService, - IDataPacketService { - private int TXMAXQUEUESIZE = 1000; - protected static final Logger logger = LoggerFactory - .getLogger(DataPacketService.class); - /** - * Database that associates one NodeIDType to the - * IPluginDataPacketService, in fact we expect that there will be - * one instance of IPluginDataPacketService for each southbound - * plugin. - * Using the ConcurrentHashMap because the threads that will be - * adding a new service, removing a service, going through all of - * them maybe different. - */ - private ConcurrentHashMap> - pluginInDataService = - new ConcurrentHashMap>(); - private Map statistics = new HashMap(); - - /** - * Queue for packets that need to be transmitted to Data Path - */ - private LinkedBlockingQueue txQueue = new LinkedBlockingQueue( - TXMAXQUEUESIZE); - /** - * Transmission thread - */ - private Thread txThread = new Thread(new TxLoop(), - "DataPacketService TX thread"); - - /** - * Representation of a Data Packet Listener including of its - * properties - */ - private class DataPacketListener { - // Key fields - private String listenerName; - // Attribute fields - private IListenDataPacket listener; - private String dependency; - private Match match; - - DataPacketListener(String name, IListenDataPacket s, String dependency, - Match match) { - this.listenerName = name; - this.listener = s; - this.dependency = dependency; - this.match = match; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - DataPacketListener other = (DataPacketListener) obj; - if (!getOuterType().equals(other.getOuterType())) - return false; - if (listenerName == null) { - if (other.listenerName != null) - return false; - } else if (!listenerName.equals(other.listenerName)) - return false; - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + getOuterType().hashCode(); - result = prime * result - + ((listenerName == null) ? 0 : listenerName.hashCode()); - return result; - } - - private DataPacketService getOuterType() { - return DataPacketService.this; - } - } - - /** - * This very expensive version of List is being used because it - * work well in concurrent situation, as we expect new service - * addition, service removal and walk of the service will happen - * from different places - */ - private List> listenDataPacket = new CopyOnWriteArrayList>(); - // Quick index to make sure there are no duplicate elements - private Set indexDataPacket = Collections - .synchronizedSet(new HashSet()); - - /** - * Loop for processing Received packets - */ - private void dispatchPacket(RawPacket pkt) { - - // for now we treat all listeners as serial listeners - for (List serialListeners : listenDataPacket) { - for (DataPacketListener l : serialListeners) { - - // TODO: possibly deal with read-only and read-write packet - // copies - IListenDataPacket s = (l == null ? null : l.listener); - if (s != null) { - try { - // TODO Make sure to filter based on the match too, - // later on - PacketResult res = s.receiveDataPacket(pkt); - increaseStat("RXPacketSuccess"); - if (res.equals(PacketResult.CONSUME)) { - increaseStat("RXPacketSerialExit"); - break; - } - } catch (Exception e) { - increaseStat("RXPacketFailedForException"); - } - } - } - } - } - - /** - * Loop for processing packets to be transmitted - * - */ - private class TxLoop implements Runnable { - public void run() { - RawPacket pkt; - try { - for (pkt = txQueue.take(); pkt != null; pkt = txQueue.take()) { - // Retrieve outgoing node connector so to send out - // the packet to corresponding node - NodeConnector p = pkt.getOutgoingNodeConnector(); - if (p != null) { - String t = p.getNode() - .getType(); - // Now locate the TX dispatcher - ProtocolService service = - pluginInDataService.get(t); - if (service != null) { - try { - service.getService().transmitDataPacket(pkt); - increaseStat("TXPacketSuccess"); - } catch (Exception e) { - increaseStat("TXPacketFailedForException"); - } - } else { - increaseStat("TXpluginNotFound"); - } - } - } - } catch (InterruptedException e) { - // Not a big deal - } - } - } - - void setPluginInDataService(Map props, IPluginInDataPacketService s) { - ProtocolService.set(this.pluginInDataService, props, s, logger); - } - - void unsetPluginInDataService(Map props, IPluginInDataPacketService s) { - ProtocolService.unset(this.pluginInDataService, props, s, logger); - } - - void setListenDataPacket(Map props, IListenDataPacket s) { - if (this.listenDataPacket == null || this.indexDataPacket == null) { - logger.error("data structure to store data is NULL"); - return; - } - logger.trace("Received setListenDataPacket request"); - for (Map.Entry e : props.entrySet()) { - logger.trace("Prop key:({}) value:({})",e.getKey(), e.getValue()); - } - - String listenerName = null; - String listenerDependency = null; - Match filter = null; - Object value; - // Read the listenerName - value = props.get("salListenerName"); - if (value instanceof String) { - listenerName = (String) value; - } - - if (listenerName == null) { - logger.error("Trying to set a listener without a Name"); - return; - } - - //Read the dependency - value = props.get("salListenerDependency"); - if (value instanceof String) { - listenerDependency = (String) value; - } - - //Read match filter if any - value = props.get("salListenerFilter"); - if (value instanceof Match) { - filter = (Match) value; - } - - DataPacketListener l = new DataPacketListener(listenerName, s, - listenerDependency, filter); - - DataPacketListener lDependency = new DataPacketListener( - listenerDependency, null, null, null); - - // Now let see if there is any dependency - if (listenerDependency == null) { - logger.debug("listener without any dependency"); - if (this.indexDataPacket.contains(l)) { - logger.error("trying to add an existing element"); - } else { - logger.debug("adding listener: {}", listenerName); - CopyOnWriteArrayList serialListeners = new CopyOnWriteArrayList(); - serialListeners.add(l); - this.listenDataPacket.add(serialListeners); - this.indexDataPacket.add(l); - } - } else { - logger.debug("listener with dependency"); - // Now search for the dependency and put things in order - if (this.indexDataPacket.contains(l)) { - logger.error("trying to add an existing element"); - } else { - logger.debug("adding listener: {}", listenerName); - // Lets find the set with the dependency in it, if we - // find it lets just add our dependency at the end of - // the list. - for (List serialListeners : this.listenDataPacket) { - boolean done = false; - if (serialListeners.contains(lDependency)) { - serialListeners.add(l); - done = true; - } - // If we did fine the element, lets break early - if (done) { - break; - } - } - - this.indexDataPacket.add(l); - } - } - } - - void unsetListenDataPacket(Map props, IListenDataPacket s) { - if (this.listenDataPacket == null || this.indexDataPacket == null) { - logger.error("data structure to store data is NULL"); - return; - } - logger.trace("Received UNsetListenDataPacket request"); - for (Map.Entry e : props.entrySet()) { - logger.trace("Prop key:({}) value:({})",e.getKey(), e.getValue()); - } - - String listenerName = null; - Object value; - // Read the listenerName - value = props.get("salListenerName"); - if (value instanceof String) { - listenerName = (String) value; - } - - if (listenerName == null) { - logger.error("Trying to set a listener without a Name"); - return; - } - - DataPacketListener l = new DataPacketListener(listenerName, s, null, - null); - if (!this.indexDataPacket.contains(l)) { - logger.error("trying to remove a non-existing element"); - } else { - logger.debug("removing listener: {}", listenerName); - for (List serialListeners : this.listenDataPacket) { - int i = 0; - boolean done = false; - for (i = 0; i < serialListeners.size(); i++) { - if (serialListeners.get(i).equals(l)) { - serialListeners.remove(i); - done = true; - break; - } - } - // Now remove a serialListener that maybe empty - if (serialListeners.isEmpty()) { - this.listenDataPacket.remove(serialListeners); - } - // If we did fine the element, lets break early - if (done) { - break; - } - } - - this.indexDataPacket.remove(l); - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - this.txThread.start(); - } - - /** - * Function called by the dependency manager when at least one - * dependency become unsatisfied or when the component is shutting - * down because for example bundle is being stopped. - * - */ - void destroy() { - // Make sure to cleanup the data structure we use to track - // services - this.listenDataPacket.clear(); - this.indexDataPacket.clear(); - this.pluginInDataService.clear(); - this.statistics.clear(); - this.txQueue.clear(); - this.txThread.interrupt(); - // Wait for them to be done - try { - this.txThread.join(); - } catch (InterruptedException ex) { - // Not a big deal - } - } - - private void increaseStat(String name) { - if (this.statistics == null) { - return; - } - - AtomicInteger currValue = null; - synchronized (this.statistics) { - currValue = this.statistics.get(name); - - if (currValue == null) { - this.statistics.put(name, new AtomicInteger(0)); - return; - } - } - currValue.incrementAndGet(); - } - - @Override - public PacketResult receiveDataPacket(RawPacket inPkt) { - if (inPkt.getIncomingNodeConnector() == null) { - increaseStat("nullIncomingNodeConnector"); - return PacketResult.IGNORED; - } - - // send the packet off to be processed by listeners - this.dispatchPacket(inPkt); - - // Walk the chain of listener going first throw all the - // parallel ones and for each parallel in serial - return PacketResult.IGNORED; - } - - @Override - public void transmitDataPacket(RawPacket outPkt) { - if (outPkt.getOutgoingNodeConnector() == null) { - increaseStat("nullOutgoingNodeConnector"); - return; - } - - if (!this.txQueue.offer(outPkt)) { - increaseStat("fullTXQueue"); - return; - } - } - - @Override - public Packet decodeDataPacket(RawPacket pkt) { - // Sanity checks - if (pkt == null) { - return null; - } - byte[] data = pkt.getPacketData(); - if (data.length <= 0) { - return null; - } - if (pkt.getEncap().equals(LinkEncap.ETHERNET)) { - Ethernet res = new Ethernet(); - try { - res.deserialize(data, 0, data.length * NetUtils.NumBitsInAByte); - } catch (Exception e) { - logger.warn("Failed to decode packet: {}", e.getMessage()); - } - return res; - } - return null; - } - - @Override - public RawPacket encodeDataPacket(Packet pkt) { - // Sanity checks - if (pkt == null) { - return null; - } - byte[] data; - try { - data = pkt.serialize(); - } catch (Exception e) { - logger.error("",e); - return null; - } - if (data.length <= 0) { - return null; - } - try { - RawPacket res = new RawPacket(data); - return res; - } catch (ConstructionException cex) { - } - // If something goes wrong then we have to return null - return null; - } -} diff --git a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/FlowProgrammerService.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/FlowProgrammerService.java deleted file mode 100644 index 60a7882bda..0000000000 --- a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/FlowProgrammerService.java +++ /dev/null @@ -1,490 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.implementation.internal; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.Controller; -import org.opendaylight.controller.sal.action.Flood; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.action.PopVlan; -import org.opendaylight.controller.sal.action.SetNwDst; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.Node.NodeIDType; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener; -import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService; -import org.opendaylight.controller.sal.flowprogrammer.IPluginInFlowProgrammerService; -import org.opendaylight.controller.sal.flowprogrammer.IPluginOutFlowProgrammerService; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The SAL Flow Programmer Service. It dispatches the flow programming requests - * to the proper SDN protocol plugin and it notifies about asynchronous messages - * received from the network node related to flow programming. - */ -public class FlowProgrammerService implements IFlowProgrammerService, - IPluginOutFlowProgrammerService, CommandProvider { - - protected static final Logger logger = LoggerFactory - .getLogger(FlowProgrammerService.class); - private ConcurrentHashMap> pluginFlowProgrammer; - private Set listener; - private AtomicLong seq; - - public FlowProgrammerService() { - pluginFlowProgrammer = new ConcurrentHashMap>(); - listener = new HashSet(); - seq = new AtomicLong(); - /* - * This Request ID generator starts with 1. Each aysnc message is - * associated with an unique Request ID (!= 0). - */ - seq.lazySet(1); - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - logger.debug("INIT called!"); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - // Clear previous registration to avoid they are left hanging - this.pluginFlowProgrammer.clear(); - logger.debug("DESTROY called!"); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - logger.debug("START called!"); - // OSGI console - registerWithOSGIConsole(); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - logger.debug("STOP called!"); - } - - // Set the reference to the plugin flow programmer - public void setService(Map props, IPluginInFlowProgrammerService s) { - ProtocolService.set(this.pluginFlowProgrammer, props, s, logger); - } - - public void unsetService(Map props, IPluginInFlowProgrammerService s) { - ProtocolService.unset(this.pluginFlowProgrammer, props, s, logger); - } - - public void setListener(IFlowProgrammerListener s) { - this.listener.add(s); - } - - public void unsetListener(IFlowProgrammerListener s) { - this.listener.remove(s); - } - - @Override - public Status addFlow(Node node, Flow flow) { - if (pluginFlowProgrammer != null) { - ProtocolService service = - this.pluginFlowProgrammer.get(node.getType()); - if (service != null) { - return service.getService().addFlow(node, flow); - } - } - return new Status(StatusCode.NOSERVICE, "Plugin unuvailable"); - } - - @Override - public Status removeFlow(Node node, Flow flow) { - if (pluginFlowProgrammer != null) { - ProtocolService service = - this.pluginFlowProgrammer.get(node.getType()); - if (service != null) { - return service.getService().removeFlow(node, flow); - } - } - return new Status(StatusCode.NOSERVICE, "Plugin unuvailable"); - } - - @Override - public Status removeAllFlows(Node node) { - if (pluginFlowProgrammer != null) { - ProtocolService service = - this.pluginFlowProgrammer.get(node.getType()); - if (service != null) { - return service.getService().removeAllFlows(node); - } - } - return new Status(StatusCode.NOSERVICE, "Plugin unuvailable"); - } - - @Override - public Status modifyFlow(Node node, Flow oldFlow, Flow newFlow) { - if (pluginFlowProgrammer != null) { - ProtocolService service = - this.pluginFlowProgrammer.get(node.getType()); - if (service != null) { - return service.getService().modifyFlow(node, oldFlow, newFlow); - } - } - return new Status(StatusCode.NOSERVICE, "Plugin unuvailable"); - } - - @Override - public Status addFlowAsync(Node node, Flow flow) { - if (pluginFlowProgrammer != null) { - ProtocolService service = - this.pluginFlowProgrammer.get(node.getType()); - if (service != null) { - return service.getService().addFlowAsync(node, flow, getNextRid()); - } - } - return new Status(StatusCode.NOSERVICE, "Plugin unuvailable"); - } - - @Override - public Status removeFlowAsync(Node node, Flow flow) { - if (pluginFlowProgrammer != null) { - ProtocolService service = - this.pluginFlowProgrammer.get(node.getType()); - if (service != null) { - return service.getService().removeFlowAsync(node, flow, getNextRid()); - } - } - return new Status(StatusCode.NOSERVICE, "Plugin unuvailable"); - } - - @Override - public Status modifyFlowAsync(Node node, Flow oldFlow, Flow newFlow) { - if (pluginFlowProgrammer != null) { - ProtocolService service = - this.pluginFlowProgrammer.get(node.getType()); - if (service != null) { - return service.getService().modifyFlowAsync(node, oldFlow, newFlow, getNextRid()); - } - } - return new Status(StatusCode.NOSERVICE, "Plugin unuvailable"); - } - - @Override - public void flowRemoved(Node node, Flow flow) { - for (IFlowProgrammerListener l : listener) { - l.flowRemoved(node, flow); - } - } - - @Override - public void flowErrorReported(Node node, long rid, Object err) { - logger.error("Got error {} for message rid {} from node {}", - new Object[] { err, rid, node }); - - for (IFlowProgrammerListener l : listener) { - l.flowErrorReported(node, rid, err); - } - } - - // ---------------- OSGI TEST CODE ------------------------------// - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, - null); - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---SAL Flow Programmer testing commands---\n"); - help.append("\t addflow - Add a sample flow to the openflow switch \n"); - help.append("\t removeflow - Remove the sample flow from the openflow switch \n"); - return help.toString(); - } - - public void _addflow(CommandInterpreter ci) throws UnknownHostException { - Node node = null; - String nodeId = ci.nextArgument(); - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - try { - node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId)); - } catch (NumberFormatException e) { - logger.error("",e); - } catch (ConstructionException e) { - logger.error("",e); - } - ci.println(this.addFlow(node, getSampleFlow(node))); - } - - public void _modifyflow(CommandInterpreter ci) throws UnknownHostException { - Node node = null; - String nodeId = ci.nextArgument(); - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - try { - node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId)); - } catch (NumberFormatException e) { - logger.error("",e); - } catch (ConstructionException e) { - logger.error("",e); - } - Flow flowA = getSampleFlow(node); - Flow flowB = getSampleFlow(node); - Match matchB = flowB.getMatch(); - matchB.setField(MatchType.NW_DST, - InetAddress.getByName("190.190.190.190")); - flowB.setMatch(matchB); - ci.println(this.modifyFlow(node, flowA, flowB)); - } - - public void _removeflow(CommandInterpreter ci) throws UnknownHostException { - Node node = null; - String nodeId = ci.nextArgument(); - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - try { - node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId)); - } catch (NumberFormatException e) { - logger.error("",e); - } catch (ConstructionException e) { - logger.error("",e); - } - ci.println(this.removeFlow(node, getSampleFlow(node))); - } - - public void _addflowv6(CommandInterpreter ci) throws UnknownHostException { - Node node = null; - String nodeId = ci.nextArgument(); - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - try { - node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId)); - } catch (NumberFormatException e) { - logger.error("",e); - } catch (ConstructionException e) { - logger.error("",e); - } - ci.println(this.addFlow(node, getSampleFlowV6(node))); - } - - public void _removeflowv6(CommandInterpreter ci) - throws UnknownHostException { - Node node = null; - String nodeId = ci.nextArgument(); - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - try { - node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId)); - } catch (NumberFormatException e) { - logger.error("",e); - } catch (ConstructionException e) { - logger.error("",e); - } - ci.println(this.removeFlow(node, getSampleFlowV6(node))); - } - - private Flow getSampleFlow(Node node) throws UnknownHostException { - NodeConnector port = NodeConnectorCreator.createOFNodeConnector( - (short) 24, node); - NodeConnector oport = NodeConnectorCreator.createOFNodeConnector( - (short) 30, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, - (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, - (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress.getByName("172.28.30.50"); - InetAddress dstIP = InetAddress.getByName("171.71.9.52"); - InetAddress newIP = InetAddress.getByName("200.200.100.1"); - InetAddress ipMask = InetAddress.getByName("255.255.255.0"); - InetAddress ipMask2 = InetAddress.getByName("255.240.0.0"); - short ethertype = EtherTypes.IPv4.shortValue(); - short vlan = (short) 27; - byte vlanPr = 3; - Byte tos = 4; - byte proto = IPProtocols.TCP.byteValue(); - short src = (short) 55000; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(MatchType.IN_PORT, port); - match.setField(MatchType.DL_SRC, srcMac); - match.setField(MatchType.DL_DST, dstMac); - match.setField(MatchType.DL_TYPE, ethertype); - match.setField(MatchType.DL_VLAN, vlan); - match.setField(MatchType.DL_VLAN_PR, vlanPr); - match.setField(MatchType.NW_SRC, srcIP, ipMask); - match.setField(MatchType.NW_DST, dstIP, ipMask2); - match.setField(MatchType.NW_TOS, tos); - match.setField(MatchType.NW_PROTO, proto); - match.setField(MatchType.TP_SRC, src); - match.setField(MatchType.TP_DST, dst); - - List actions = new ArrayList(); - actions.add(new SetNwDst(newIP)); - actions.add(new Output(oport)); - actions.add(new PopVlan()); - actions.add(new Flood()); - actions.add(new Controller()); - - Flow flow = new Flow(match, actions); - flow.setPriority((short) 100); - flow.setHardTimeout((short) 360); - flow.setId(1234L); - - return flow; - } - - private Flow getSampleFlowV6(Node node) throws UnknownHostException { - NodeConnector port = NodeConnectorCreator.createOFNodeConnector( - (short) 24, node); - NodeConnector oport = NodeConnectorCreator.createOFNodeConnector( - (short) 30, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, - (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, - (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress - .getByName("2001:420:281:1004:407a:57f4:4d15:c355"); - InetAddress dstIP = InetAddress - .getByName("2001:420:281:1004:e123:e688:d655:a1b0"); - InetAddress ipMask = null; // InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0"); - // V6Match implementation assumes no mask is - // specified - InetAddress ipMask2 = null; // InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"); - short ethertype = EtherTypes.IPv6.shortValue(); - short vlan = (short) 27; - byte vlanPr = (byte) 3; - Byte tos = 4; - byte proto = IPProtocols.UDP.byteValue(); - short src = (short) 5500; - // short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(MatchType.IN_PORT, port); - match.setField(MatchType.DL_SRC, srcMac); - match.setField(MatchType.DL_DST, dstMac); - match.setField(MatchType.DL_TYPE, ethertype); - match.setField(MatchType.DL_VLAN, vlan); - match.setField(MatchType.DL_VLAN_PR, vlanPr); // V6Match does not handle - // this properly... - match.setField(MatchType.NW_SRC, srcIP, ipMask); - match.setField(MatchType.NW_DST, dstIP, ipMask2); - match.setField(MatchType.NW_TOS, tos); - match.setField(MatchType.NW_PROTO, proto); - match.setField(MatchType.TP_SRC, src); // V6Match does not handle this - // properly... - // match.setField(MatchType.TP_DST, dst); V6Match does not handle this - // properly... - - List actions = new ArrayList(); - actions.add(new Output(oport)); - actions.add(new PopVlan()); - actions.add(new Flood()); - - Flow flow = new Flow(match, actions); - flow.setPriority((short) 300); - flow.setHardTimeout((short) 240); - flow.setId(65536L); - - return flow; - } - - /** - * This Request ID generator starts with 1. Each aysnc message is - * associated with an unique Request ID (!= 0). - * - * @return Request ID - */ - private long getNextRid() { - return seq.getAndIncrement(); - } - - @Override - public Status syncSendBarrierMessage(Node node) { - if (this.pluginFlowProgrammer != null) { - ProtocolService service = - this.pluginFlowProgrammer.get(node.getType()); - if (service != null) { - return service.getService().syncSendBarrierMessage(node); - } - } - return new Status(StatusCode.NOSERVICE, "Plugin unuvailable"); - } - - @Override - public Status asyncSendBarrierMessage(Node node) { - if (this.pluginFlowProgrammer != null) { - ProtocolService service = - this.pluginFlowProgrammer.get(node.getType()); - if (service != null) { - return service.getService().asyncSendBarrierMessage(node); - } - } - return new Status(StatusCode.NOSERVICE, "Plugin unuvailable"); - } -} diff --git a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Inventory.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Inventory.java deleted file mode 100644 index fbb9fbc518..0000000000 --- a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Inventory.java +++ /dev/null @@ -1,175 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.implementation.internal; - -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.inventory.IInventoryService; -import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; -import org.opendaylight.controller.sal.inventory.IPluginInInventoryService; -import org.opendaylight.controller.sal.inventory.IPluginOutInventoryService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class describes SAL service to bridge inventory protocol plugin and upper - * applications. One instance per container of the network. - */ -public class Inventory implements IPluginOutInventoryService, IInventoryService { - protected static final Logger logger = LoggerFactory - .getLogger(Inventory.class); - private List updateService = new CopyOnWriteArrayList(); - private List pluginService = new CopyOnWriteArrayList(); - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - logger.trace("INIT called!"); - } - - /** - * Function called by the dependency manager when at least one - * dependency become unsatisfied or when the component is shutting - * down because for example bundle is being stopped. - * - */ - void destroy() { - logger.trace("DESTROY called!"); - } - - /** - * Function called by dependency manager after "init ()" is called - * and after the services provided by the class are registered in - * the service registry - * - */ - void start() { - logger.trace("START called!"); - - if (pluginService == null) { - logger.debug("plugin service not avaiable"); - return; - } - } - - /** - * Function called by the dependency manager before the services - * exported by the component are unregistered, this will be - * followed by a "destroy ()" calls - * - */ - void stop() { - logger.trace("STOP called!"); - } - - public void setPluginService(IPluginInInventoryService service) { - logger.trace("Got plugin service set request {}", service); - this.pluginService.add(service); - } - - public void unsetPluginService(IPluginInInventoryService service) { - logger.trace("Got plugin service UNset request"); - this.pluginService.remove(service); - } - - public void setUpdateService(IListenInventoryUpdates service) { - logger.trace("Got update service set request {}", service); - this.updateService.add(service); - } - - public void unsetUpdateService(IListenInventoryUpdates service) { - logger.trace("Got a service UNset request"); - this.updateService.remove(service); - } - - @Override - public void updateNode(Node node, UpdateType type, Set props) { - if (type == null) { - logger.trace("Input type is null"); - return; - } - - logger.trace("{} {}", node, type); - - for (IListenInventoryUpdates s : this.updateService) { - s.updateNode(node, type, props); - } - } - - @Override - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props) { - if (type == null) { - logger.trace("Input type is null"); - return; - } - - logger.trace("{} {}", nodeConnector, type); - - for (IListenInventoryUpdates s : this.updateService) { - s.updateNodeConnector(nodeConnector, type, props); - } - } - - @Override - public ConcurrentMap> getNodeProps() { - ConcurrentMap> nodeProps = - new ConcurrentHashMap>(), rv; - - for (IPluginInInventoryService s : this.pluginService) { - rv = s.getNodeProps(); - if (rv != null) { - nodeProps.putAll(rv); - } - } - - return nodeProps; - } - - @Override - public Set getConfiguredNotConnectedNodes() { - Set configuredNotConnected = new HashSet(), rv; - for (IPluginInInventoryService s : this.pluginService) { - rv = s.getConfiguredNotConnectedNodes(); - if (rv != null) { - configuredNotConnected.addAll(rv); - } - } - return configuredNotConnected; - } - - @Override - public ConcurrentMap> getNodeConnectorProps() { - ConcurrentMap> ncProps = - new ConcurrentHashMap>(), rv; - - for (IPluginInInventoryService s : this.pluginService) { - rv = s.getNodeConnectorProps(true); - if (rv != null) { - ncProps.putAll(rv); - } - } - - return ncProps; - } -} diff --git a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ProtocolService.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ProtocolService.java deleted file mode 100644 index c0b61278a6..0000000000 --- a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ProtocolService.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2014 NEC Corporation and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.implementation.internal; - -import java.util.Map; -import java.util.concurrent.ConcurrentMap; - -import org.slf4j.Logger; - -import org.opendaylight.controller.sal.utils.GlobalConstants; - -/** - * An instance of this class keeps a protocol plugin service handler. - * - * @param Type of protocol plugin service. - */ -public final class ProtocolService { - /** - * Default priority value. - */ - private static final int DEFAULT_PRIORITY = 0; - - /** - * A protocol plugin service handler. - */ - private final T service; - - /** - * A priority value assigned to this protocol plugin. - */ - private final int priority; - - /** - * Set protocol plugin service. - * - * @param map A map that keeps protocol plugin services. - * @param props Service properties. - * @param s Protocol plugin service. - * @param logger A logger instance. - * @param Type of protocol plugin service. - */ - public static void set(ConcurrentMap> map, - Map props, S s, Logger logger) { - if (map == null) { - logger.error("Protocol plugin service store is null."); - return; - } - if (s == null) { - logger.error("Protocol plugin service is null."); - return; - } - if (props == null) { - logger.error("Service property is null."); - return; - } - - if (logger.isTraceEnabled()) { - logger.trace("Received set service request: {}", s); - for (Map.Entry entry: props.entrySet()) { - logger.trace("Prop key:({}) value:({})", entry.getKey(), - entry.getValue()); - } - } - - Object value = props.get(GlobalConstants.PROTOCOLPLUGINTYPE.toString()); - if (!(value instanceof String)) { - logger.error("Unexpected protocol type: {}", value); - return; - } - - String type = (String)value; - ProtocolService service = new ProtocolService(props, s); - ProtocolService old = map.putIfAbsent(type, service); - while (old != null) { - // Compare priority value. - if (old.getPriority() >= service.getPriority()) { - logger.trace("Protocol plugin service for {} is already set: " + - "current={}, requested={}", type, old, service); - return; - } - - if (map.replace(type, old, service)) { - break; - } - old = map.putIfAbsent(type, service); - } - - logger.debug("Stored protocol plugin service for {}: {}", - type, service); - } - - /** - * Unset protocol plugin service. - * - * @param map A map that keeps protocol plugin services. - * @param props Service properties. - * @param s Protocol plugin service. - * @param logger A logger instance. - * @param Type of protocol plugin service. - */ - public static void unset(ConcurrentMap> map, - Map props, S s, Logger logger) { - if (map == null) { - logger.error("Protocol plugin service store is null."); - return; - } - if (s == null) { - logger.error("Protocol plugin service is null."); - return; - } - if (props == null) { - logger.error("Service property is null."); - return; - } - - if (logger.isTraceEnabled()) { - logger.trace("Received unset service request: {}", s); - for (Map.Entry entry: props.entrySet()) { - logger.trace("Prop key:({}) value:({})", - entry.getKey(), entry.getValue()); - } - } - - Object value = props.get(GlobalConstants.PROTOCOLPLUGINTYPE.toString()); - if (!(value instanceof String)) { - logger.error("Unexpected protocol type {}: service={}", value, s); - return; - } - - String type = (String)value; - ProtocolService plugin = new ProtocolService(props, s); - if (map.remove(type, plugin)) { - logger.debug("Removed protocol plugin service for {}: {}", - type, plugin); - } else { - logger.trace("Ignore unset service request for {}: {}", - type, plugin); - } - } - - /** - * Constructor. - * - * @param props Protocol plugin service properties. - * @param s A protocol plugin service handler. - */ - public ProtocolService(Map props, T s) { - service = s; - - String key = GlobalConstants.PROTOCOLPLUGINPRIORITY.toString(); - Object value = props.get(key); - if (value instanceof Integer) { - priority = ((Integer)value).intValue(); - } else { - priority = DEFAULT_PRIORITY; - } - } - - /** - * Return a protocol plugin service handler. - * - * @return A protocol plugin service handler. - */ - public T getService() { - return service; - } - - /** - * Return a priority value assigned to this protocol plugin. - * - * @return A priority value. - */ - public int getPriority() { - return priority; - } - - /** - * Determine whether the given object is identical to this object. - * - * @param o An object to be compared. - * @return {@code true} if identical. Otherwise {@code false}. - */ - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (o == null || o.getClass() != getClass()) { - return false; - } - - ProtocolService plugin = (ProtocolService)o; - return (service.equals(plugin.service) && priority == plugin.priority); - } - - /** - * Return the hash code of this object. - * - * @return The hash code. - */ - @Override - public int hashCode() { - return service.hashCode() + (priority * 31); - } - - /** - * Return a string representation of this instance. - * - * @return A string representation of this instance. - */ - @Override - public String toString() { - StringBuilder builder = new StringBuilder("[service="); - return builder.append(service).append(", priority=").append(priority). - append(']').toString(); - } -} diff --git a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ReadService.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ReadService.java deleted file mode 100644 index 356c0e57c8..0000000000 --- a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/ReadService.java +++ /dev/null @@ -1,576 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.implementation.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArraySet; - -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.Controller; -import org.opendaylight.controller.sal.action.Flood; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.action.PopVlan; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.Node.NodeIDType; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.IPluginInReadService; -import org.opendaylight.controller.sal.reader.IPluginOutReadService; -import org.opendaylight.controller.sal.reader.IReadService; -import org.opendaylight.controller.sal.reader.IReadServiceListener; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.utils.NodeTableCreator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The SAL Read Service. Dispatches read requests to the proper SDN protocol - * plugin, and notifies any listeners on updates from any plugin readers - */ -public class ReadService implements IReadService, CommandProvider, IPluginOutReadService { - - protected static final Logger logger = LoggerFactory.getLogger(ReadService.class); - private ConcurrentHashMap> pluginReader = - new ConcurrentHashMap>(); - private Set readerListeners = - new CopyOnWriteArraySet(); - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - } - - /** - * Function called by the dependency manager when at least one - * dependency become unsatisfied or when the component is shutting - * down because for example bundle is being stopped. - * - */ - void destroy() { - // In case of plugin disactivating make sure we clear the - // dependencies - this.pluginReader.clear(); - this.readerListeners.clear(); - } - - /** - * Function called by dependency manager after "init ()" is called - * and after the services provided by the class are registered in - * the service registry - * - */ - void start() { - registerWithOSGIConsole(); - } - - /** - * Function called by the dependency manager before the services - * exported by the component are unregistered, this will be - * followed by a "destroy ()" calls - * - */ - void stop() { - } - - // Set the reference to the plugin flow Reader service - public void setService(Map props, IPluginInReadService s) { - ProtocolService.set(this.pluginReader, props, s, logger); - } - - public void unsetService(Map props, IPluginInReadService s) { - ProtocolService.unset(this.pluginReader, props, s, logger); - } - - public void setReaderListener(IReadServiceListener service) { - logger.trace("Got a listener set request {}", service); - this.readerListeners.add(service); - } - - public void unsetReaderListener(IReadServiceListener service) { - logger.trace("Got a listener Unset request"); - this.readerListeners.remove(service); - } - - @Override - public FlowOnNode readFlow(Node node, Flow flow) { - if (pluginReader != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readFlow(node, flow, true); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return null; - } - - @Override - public FlowOnNode nonCachedReadFlow(Node node, Flow flow) { - if (pluginReader != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readFlow(node, flow, false); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return null; - } - - @Override - public List readAllFlows(Node node) { - if (pluginReader != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readAllFlow(node, true); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return Collections.emptyList(); - } - - @Override - public List nonCachedReadAllFlows(Node node) { - if (pluginReader != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readAllFlow(node, false); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return Collections.emptyList(); - } - - @Override - public NodeDescription readDescription(Node node) { - if (pluginReader != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readDescription(node, true); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return null; - } - - @Override - public NodeDescription nonCachedReadDescription(Node node) { - if (pluginReader != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readDescription(node, false); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return null; - } - - @Override - public NodeConnectorStatistics readNodeConnector(NodeConnector connector) { - Node node = connector.getNode(); - if (pluginReader != null && node != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readNodeConnector(connector, true); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return null; - } - - @Override - public NodeConnectorStatistics nonCachedReadNodeConnector( - NodeConnector connector) { - Node node = connector.getNode(); - if (pluginReader != null && node != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readNodeConnector(connector, false); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return null; - } - - @Override - public List readNodeConnectors(Node node) { - if (pluginReader != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readAllNodeConnector(node, true); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return Collections.emptyList(); - } - - @Override - public List readNodeTable(Node node) { - if (pluginReader != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readAllNodeTable(node, true); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return Collections.emptyList(); - } - - - @Override - public NodeTableStatistics nonCachedReadNodeTable(NodeTable table) { - Node node = table.getNode(); - if (pluginReader != null && node != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readNodeTable(table, false); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return null; - } - - @Override - public NodeTableStatistics readNodeTable(NodeTable table) { - Node node = table.getNode(); - if (pluginReader != null && node != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readNodeTable(table, true); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return null; - } - - @Override - public List nonCachedReadNodeConnectors(Node node) { - if (pluginReader != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().readAllNodeConnector(node, false); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return Collections.emptyList(); - } - - @Override - public long getTransmitRate(NodeConnector connector) { - Node node = connector.getNode(); - if (pluginReader != null && node != null) { - ProtocolService service = - this.pluginReader.get(node.getType()); - if (service != null) { - return service.getService().getTransmitRate(connector); - } - } - logger.warn("Plugin {} unavailable", node.getType()); - return 0; - } - - @Override - public void nodeFlowStatisticsUpdated(Node node, List flowStatsList) { - for (IReadServiceListener l : readerListeners){ - l.nodeFlowStatisticsUpdated(node, flowStatsList); - } - } - - @Override - public void nodeConnectorStatisticsUpdated(Node node, List ncStatsList) { - for (IReadServiceListener l : readerListeners){ - l.nodeConnectorStatisticsUpdated(node, ncStatsList); - } - } - - @Override - public void nodeTableStatisticsUpdated(Node node, List tableStatsList) { - for (IReadServiceListener l : readerListeners){ - l.nodeTableStatisticsUpdated(node, tableStatsList); - } - } - - @Override - public void descriptionStatisticsUpdated(Node node, NodeDescription nodeDescription) { - for (IReadServiceListener l : readerListeners){ - l.descriptionStatisticsUpdated(node, nodeDescription); - } - } - - // ---------------- OSGI TEST CODE ------------------------------// - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, - null); - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---SAL Reader testing commands---\n"); - help.append("\t readflows - Read all the (cached) flows from the openflow switch \n"); - help.append("\t readflow - Read the (cached) sample flow from the openflow switch \n"); - help.append("\t readdescr - Read the (cached) description from openflow switch \n"); - help.append("\t\t cached = (true|false). If false or not specified, the plugin cached info\n"); - help.append("\t\t is returned. If true, the info is directly retrieved from the switch\n"); - help.append("\t readport - Read port statistics for the specified port\n"); - help.append("\t readports - Read port statistics for all ports of specified switch\n"); - help.append("\t readtable - Read specified table statistics\n"); - - return help.toString(); - } - - public void _readflows(CommandInterpreter ci) { - String nodeId = ci.nextArgument(); - String cacheReq = ci.nextArgument(); - boolean cached; - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - cached = (cacheReq == null) ? true : cacheReq.equals("true"); - Node node = null; - try { - node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId)); - } catch (NumberFormatException e) { - logger.error("",e); - } catch (ConstructionException e) { - logger.error("",e); - } - List list = (cached) ? this.readAllFlows(node) : this - .nonCachedReadAllFlows(node); - if (list != null) { - ci.println(list.toString()); - } else { - ci.println("null"); - } - } - - // Requests the hw view for the specific sample flow - public void _readflow(CommandInterpreter ci) throws UnknownHostException { - String nodeId = ci.nextArgument(); - String cacheReq = ci.nextArgument(); - boolean cached; - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - cached = (cacheReq == null) ? true : cacheReq.equals("true"); - Node node = null; - try { - node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId)); - } catch (NumberFormatException e) { - logger.error("",e); - } catch (ConstructionException e) { - logger.error("",e); - } - Flow flow = getSampleFlow(node); - FlowOnNode flowOnNode = (cached) ? this.readFlow(node, flow) : this - .nonCachedReadFlow(node, flow); - if (flowOnNode != null) { - ci.println(flowOnNode.toString()); - } else { - ci.println("null"); - } - } - - public void _readports(CommandInterpreter ci) { - String nodeId = ci.nextArgument(); - String cacheReq = ci.nextArgument(); - boolean cached; - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - cached = (cacheReq == null) ? true : cacheReq.equals("true"); - Node node = null; - try { - node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId)); - } catch (NumberFormatException e) { - logger.error("",e); - } catch (ConstructionException e) { - logger.error("",e); - } - List list = (cached) ? this - .readNodeConnectors(node) : this - .nonCachedReadNodeConnectors(node); - if (list != null) { - ci.println(list.toString()); - } else { - ci.println("null"); - } - } - - public void _readport(CommandInterpreter ci) { - String nodeId = ci.nextArgument(); - String portId = ci.nextArgument(); - String cacheReq = ci.nextArgument(); - boolean cached; - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - if (portId == null) { - ci.print("Port id not specified"); - return; - } - cached = (cacheReq == null) ? true : cacheReq.equals("true"); - NodeConnector nodeConnector = null; - Node node = NodeCreator.createOFNode(Long.parseLong(nodeId)); - nodeConnector = NodeConnectorCreator.createNodeConnector(Short - .valueOf(portId), node); - NodeConnectorStatistics stats = (cached) ? this - .readNodeConnector(nodeConnector) : this - .nonCachedReadNodeConnector(nodeConnector); - if (stats != null) { - ci.println(stats.toString()); - } else { - ci.println("null"); - } - } - - public void _readtable(CommandInterpreter ci) { - String nodeId = ci.nextArgument(); - String tableId = ci.nextArgument(); - String cacheReq = ci.nextArgument(); - boolean cached; - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - if (tableId == null) { - ci.print("Table id not specified"); - return; - } - cached = (cacheReq == null) ? true : cacheReq.equals("true"); - NodeTable nodeTable = null; - Node node = NodeCreator.createOFNode(Long.parseLong(nodeId)); - nodeTable = NodeTableCreator.createNodeTable(Byte - .valueOf(tableId), node); - NodeTableStatistics stats = (cached) ? this - .readNodeTable(nodeTable) : this - .nonCachedReadNodeTable(nodeTable); - if (stats != null) { - ci.println(stats.toString()); - } else { - ci.println("null"); - } - } - - public void _readdescr(CommandInterpreter ci) { - String nodeId = ci.nextArgument(); - String cacheReq = ci.nextArgument(); - boolean cached; - if (nodeId == null) { - ci.print("Node id not specified"); - return; - } - cached = (cacheReq == null) ? true : cacheReq.equals("true"); - - Node node = null; - try { - node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId)); - } catch (NumberFormatException e) { - logger.error("",e); - } catch (ConstructionException e) { - logger.error("",e); - } - NodeDescription desc = (cached) ? this.readDescription(node) : this - .nonCachedReadDescription(node); - if (desc != null) { - ci.println(desc.toString()); - } else { - ci.println("null"); - } - } - - private Flow getSampleFlow(Node node) throws UnknownHostException { - NodeConnector port = NodeConnectorCreator.createOFNodeConnector( - (short) 24, node); - NodeConnector oport = NodeConnectorCreator.createOFNodeConnector( - (short) 30, node); - byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, - (byte) 0x9a, (byte) 0xbc }; - byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d, - (byte) 0x5e, (byte) 0x6f }; - InetAddress srcIP = InetAddress.getByName("172.28.30.50"); - InetAddress dstIP = InetAddress.getByName("171.71.9.52"); - InetAddress ipMask = InetAddress.getByName("255.255.255.0"); - InetAddress ipMask2 = InetAddress.getByName("255.0.0.0"); - short ethertype = EtherTypes.IPv4.shortValue(); - short vlan = (short) 27; - byte vlanPr = 3; - Byte tos = 4; - byte proto = IPProtocols.TCP.byteValue(); - short src = (short) 55000; - short dst = 80; - - /* - * Create a SAL Flow aFlow - */ - Match match = new Match(); - match.setField(MatchType.IN_PORT, port); - match.setField(MatchType.DL_SRC, srcMac); - match.setField(MatchType.DL_DST, dstMac); - match.setField(MatchType.DL_TYPE, ethertype); - match.setField(MatchType.DL_VLAN, vlan); - match.setField(MatchType.DL_VLAN_PR, vlanPr); - match.setField(MatchType.NW_SRC, srcIP, ipMask); - match.setField(MatchType.NW_DST, dstIP, ipMask2); - match.setField(MatchType.NW_TOS, tos); - match.setField(MatchType.NW_PROTO, proto); - match.setField(MatchType.TP_SRC, src); - match.setField(MatchType.TP_DST, dst); - - List actions = new ArrayList(); - actions.add(new Output(oport)); - actions.add(new PopVlan()); - actions.add(new Flood()); - actions.add(new Controller()); - return new Flow(match, actions); - } -} diff --git a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Topology.java b/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Topology.java deleted file mode 100644 index d488096648..0000000000 --- a/opendaylight/adsal/sal/implementation/src/main/java/org/opendaylight/controller/sal/implementation/internal/Topology.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.implementation.internal; - -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.topology.IListenTopoUpdates; -import org.opendaylight.controller.sal.topology.IPluginInTopologyService; -import org.opendaylight.controller.sal.topology.IPluginOutTopologyService; -import org.opendaylight.controller.sal.topology.ITopologyService; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Topology implements IPluginOutTopologyService, ITopologyService { - protected static final Logger logger = LoggerFactory - .getLogger(Topology.class); - private Set updateService = Collections - .synchronizedSet(new HashSet()); - private Set pluginService = Collections - .synchronizedSet(new HashSet()); - - void setPluginService(IPluginInTopologyService s) { - if (this.pluginService != null) { - this.pluginService.add(s); - } - } - - void unsetPluginService(IPluginInTopologyService s) { - if (this.pluginService != null) { - this.pluginService.remove(s); - } - } - - void setUpdateService(IListenTopoUpdates s) { - if (this.updateService != null) { - this.updateService.add(s); - } - } - - void unsetUpdateService(IListenTopoUpdates s) { - if (this.updateService != null) { - this.updateService.remove(s); - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - // Make sure to clear all the data structure we use to track - // services - if (this.updateService != null) { - this.updateService.clear(); - } - if (this.pluginService != null) { - this.pluginService.clear(); - } - } - - @Override - public void sollicitRefresh() { - synchronized (this.pluginService) { - for (IPluginInTopologyService s : this.pluginService) { - s.sollicitRefresh(); - } - } - } - - @Override - public void edgeUpdate(List topoedgeupdateList) { - synchronized (this.updateService) { - for (IListenTopoUpdates s : this.updateService) { - s.edgeUpdate(topoedgeupdateList); - } - } - } - - @Override - public void edgeOverUtilized(Edge edge) { - synchronized (this.updateService) { - for (IListenTopoUpdates s : this.updateService) { - s.edgeOverUtilized(edge); - } - } - } - - @Override - public void edgeUtilBackToNormal(Edge edge) { - synchronized (this.updateService) { - for (IListenTopoUpdates s : this.updateService) { - s.edgeUtilBackToNormal(edge); - } - } - } -} diff --git a/opendaylight/adsal/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/DataPacketServiceTest.java b/opendaylight/adsal/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/DataPacketServiceTest.java deleted file mode 100644 index 3a07288a9f..0000000000 --- a/opendaylight/adsal/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/DataPacketServiceTest.java +++ /dev/null @@ -1,180 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.implementation; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.implementation.internal.DataPacketService; -import org.opendaylight.controller.sal.packet.ARP; -import org.opendaylight.controller.sal.packet.Ethernet; -import org.opendaylight.controller.sal.packet.Packet; -import org.opendaylight.controller.sal.packet.RawPacket; - -public class DataPacketServiceTest { - - @Test - public void DataPacketServiceDecodeTest() throws ConstructionException, InstantiationException, IllegalAccessException { - - DataPacketService dService = new DataPacketService(); - RawPacket rawPkt = null; - - Assert.assertTrue(dService.decodeDataPacket(rawPkt) == null); - - byte[] data = { 10, 12, 14, 20, 55, 69, //DMAC - -90, -20, -100, -82, -78, -97, //SMAC - 8, 6, //ethype - 0, 1, // hw type - 8, 0, // proto (ip) - 6, // hw addr len - 4, // proto addr len - 0, 1, // op codes - -90, -20, -100, -82, -78, -97, //src hw addr - 9, 9, 9, 1, // src proto - 0, 0, 0, 0, 0, 0, // target hw addr - 9, 9, 9, -2 }; // target proto - - rawPkt = new RawPacket(data); - - Packet decodedPkt = dService.decodeDataPacket(rawPkt); - Class payloadClass = ARP.class; - Assert.assertTrue(payloadClass == decodedPkt.getPayload().getClass()); - - ARP arpPacket = (ARP) decodedPkt.getPayload(); - - Assert.assertTrue(arpPacket.getHardwareType() == (byte)0x1); - Assert.assertTrue(arpPacket.getProtocolType() == 2048); - Assert.assertTrue(arpPacket.getHardwareAddressLength() == (byte)0x6); - Assert.assertTrue(arpPacket.getProtocolAddressLength() == (byte)0x4); - Assert.assertTrue(arpPacket.getOpCode() == 1); - - byte[] senderHwAddress = arpPacket.getSenderHardwareAddress(); - byte[] senderProtocolAddress = arpPacket.getSenderProtocolAddress(); - - byte[] targetHwAddress = arpPacket.getTargetHardwareAddress(); - byte[] targetProtocolAddress = arpPacket.getTargetProtocolAddress(); - - - Assert.assertTrue(senderHwAddress[0] == (byte)0xA6); - Assert.assertTrue(senderHwAddress[1] == (byte)0xEC); - Assert.assertTrue(senderHwAddress[2] == (byte)0x9C); - Assert.assertTrue(senderHwAddress[3] == (byte)0xAE); - Assert.assertTrue(senderHwAddress[4] == (byte)0xB2); - Assert.assertTrue(senderHwAddress[5] == (byte)0x9F); - - Assert.assertTrue(senderProtocolAddress[0] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[1] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[2] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[3] == (byte)0x1); - - Assert.assertTrue(targetHwAddress[0] == (byte)0x0); - Assert.assertTrue(targetHwAddress[1] == (byte)0x0); - Assert.assertTrue(targetHwAddress[2] == (byte)0x0); - Assert.assertTrue(targetHwAddress[3] == (byte)0x0); - Assert.assertTrue(targetHwAddress[4] == (byte)0x0); - Assert.assertTrue(targetHwAddress[5] == (byte)0x0); - - Assert.assertTrue(senderProtocolAddress[0] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[1] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[2] == (byte)0x9); - Assert.assertTrue(senderProtocolAddress[3] == (byte)0x1); - - Assert.assertTrue(targetProtocolAddress[0] == (byte)0x9); - Assert.assertTrue(targetProtocolAddress[1] == (byte)0x9); - Assert.assertTrue(targetProtocolAddress[2] == (byte)0x9); - Assert.assertTrue(targetProtocolAddress[3] == (byte)0xFE); - } - - @Test - public void DataPacketServiceEncodeTest() throws ConstructionException, InstantiationException, IllegalAccessException { - - DataPacketService dService = new DataPacketService(); - Ethernet eth = new Ethernet(); - ARP arp = new ARP(); - - byte[] data = null; - RawPacket rawPkt; - - - byte[] dMAC = { 10, 12, 14, 20, 55, 69 }; - byte[] sMAC = { 82, 97, 109, 117, 127, -50 }; - short etherType = 2054; - - eth.setDestinationMACAddress(dMAC); - eth.setSourceMACAddress(sMAC); - eth.setEtherType(etherType); - - arp.setHardwareType((short)1); - arp.setProtocolType((short)2048); - arp.setHardwareAddressLength((byte)0x6); - arp.setProtocolAddressLength((byte)0x4); - arp.setOpCode((byte)0x1); - - byte[] senderHardwareAddress = {(byte)0xA6, (byte)0xEC, (byte)0x9C, (byte)0xAE, - (byte)0xB2, (byte)0x9F}; - byte[] senderProtocolAddress = {(byte)0x09, (byte)0x09, (byte)0x09, (byte)0x01}; - byte[] targetProtocolAddress = {(byte)0x09, (byte)0x09, (byte)0x09, (byte)0xFE}; - byte[] targetHardwareAddress = {(byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0, (byte)0x0}; - arp.setSenderHardwareAddress(senderHardwareAddress); - arp.setSenderProtocolAddress(senderProtocolAddress); - arp.setTargetHardwareAddress(targetHardwareAddress); - arp.setTargetProtocolAddress(targetProtocolAddress); - - arp.setParent(eth); - eth.setPayload(arp); - - rawPkt = dService.encodeDataPacket(eth); - data = rawPkt.getPacketData(); - - Assert.assertTrue(data[0] == (byte)0x0A);//Destination MAC - Assert.assertTrue(data[1] == (byte)0x0C); - Assert.assertTrue(data[2] == (byte)0x0E); - Assert.assertTrue(data[3] == (byte)0x14); - Assert.assertTrue(data[4] == (byte)0x37); - Assert.assertTrue(data[5] == (byte)0x45); - Assert.assertTrue(data[6] == (byte)0x52);//Source MAC - Assert.assertTrue(data[7] == (byte)0x61); - Assert.assertTrue(data[8] == (byte)0x6D); - Assert.assertTrue(data[9] == (byte)0x75); - Assert.assertTrue(data[10] == (byte)0x7F); - Assert.assertTrue(data[11] == (byte)0xCE); - Assert.assertTrue(data[12] == (byte)0x08);//EtherType - Assert.assertTrue(data[13] == (byte)0x06); - Assert.assertTrue(data[14] == (byte)0x00);//Hardware Type - Assert.assertTrue(data[15] == (byte)0x01); - Assert.assertTrue(data[16] == (byte)0x08);//Protocol Type - Assert.assertTrue(data[17] == (byte)0x0); - Assert.assertTrue(data[18] == (byte)0x6);//Hardware Address Length - Assert.assertTrue(data[19] == (byte)0x4);//Protocol Address Length - Assert.assertTrue(data[20] == (byte)0x0);//Opcode - Assert.assertTrue(data[21] == (byte)0x1);//Opcode - Assert.assertTrue(data[22] == (byte)0xA6);//Sender Hardware Address - Assert.assertTrue(data[23] == (byte)0xEC); - Assert.assertTrue(data[24] == (byte)0x9C); - Assert.assertTrue(data[25] == (byte)0xAE); - Assert.assertTrue(data[26] == (byte)0xB2); - Assert.assertTrue(data[27] == (byte)0x9F); - Assert.assertTrue(data[28] == (byte)0x09);//Sender Protocol Address - Assert.assertTrue(data[29] == (byte)0x09); - Assert.assertTrue(data[30] == (byte)0x09); - Assert.assertTrue(data[31] == (byte)0x01);//Target Hardware Address - Assert.assertTrue(data[32] == (byte)0x00); - Assert.assertTrue(data[33] == (byte)0x00); - Assert.assertTrue(data[34] == (byte)0x00); - Assert.assertTrue(data[35] == (byte)0x00); - Assert.assertTrue(data[36] == (byte)0x00); - Assert.assertTrue(data[37] == (byte)0x00); - Assert.assertTrue(data[38] == (byte)0x09);//Target Protocol Address - Assert.assertTrue(data[39] == (byte)0x09); - Assert.assertTrue(data[40] == (byte)0x09); - Assert.assertTrue(data[41] == (byte)0xFE); - } - -} diff --git a/opendaylight/adsal/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/ProtocolServiceTest.java b/opendaylight/adsal/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/ProtocolServiceTest.java deleted file mode 100644 index 079350bcc9..0000000000 --- a/opendaylight/adsal/sal/implementation/src/test/java/org/opendaylight/controller/sal/implementation/ProtocolServiceTest.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright (c) 2014 NEC Corporation and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.sal.implementation; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.opendaylight.controller.sal.implementation.internal.ProtocolService; -import org.opendaylight.controller.sal.utils.GlobalConstants; - -/** - * Unit test for {@link ProtocolService}. - */ -public class ProtocolServiceTest { - private static final Logger LOG = - LoggerFactory.getLogger(ProtocolServiceTest.class); - - @Test - public void testInstance() { - HashSet> set = new HashSet<>(); - TestService sv1 = new TestService(); - HashMap prop1 = new HashMap<>(); - - ProtocolService ps1 = - new ProtocolService(prop1, sv1); - assertEquals(sv1, ps1.getService()); - // Default priority is 0. - assertEquals(0, ps1.getPriority()); - assertTrue(set.add(ps1)); - assertFalse(set.add(ps1)); - - // Specify the same service and priority. - String priKey = GlobalConstants.PROTOCOLPLUGINPRIORITY.toString(); - prop1.put(priKey, Integer.valueOf(0)); - ProtocolService ps2 = - new ProtocolService(prop1, sv1); - assertEquals(sv1, ps2.getService()); - assertEquals(0, ps2.getPriority()); - assertEquals(ps1, ps2); - assertFalse(set.add(ps1)); - - // Specify different priority. - prop1.put(priKey, Integer.valueOf(Integer.MAX_VALUE)); - ps2 = new ProtocolService(prop1, sv1); - assertEquals(sv1, ps2.getService()); - assertEquals(Integer.MAX_VALUE, ps2.getPriority()); - assertFalse(ps1.equals(ps2)); - assertTrue(set.add(ps2)); - assertFalse(set.add(ps2)); - - // Specify another service. - TestService sv2 = new TestService(); - prop1.put(priKey, Integer.valueOf(0)); - ps2 = new ProtocolService(prop1, sv2); - assertEquals(sv2, ps2.getService()); - assertEquals(0, ps2.getPriority()); - assertFalse(ps1.equals(ps2)); - assertTrue(set.add(ps2)); - assertFalse(set.add(ps2)); - } - - @Test - public void testSetUnsetError() { - ConcurrentMap> services = - new ConcurrentHashMap<>(); - TestService sv = new TestService(); - Map props = new HashMap<>(); - - // null service. - ProtocolService.set(services, props, null, LOG); - assertTrue(services.isEmpty()); - - ProtocolService.unset(services, props, null, LOG); - assertTrue(services.isEmpty()); - - // null service property. - ProtocolService.set(services, null, sv, LOG); - assertTrue(services.isEmpty()); - - ProtocolService.unset(services, null, sv, LOG); - assertTrue(services.isEmpty()); - - // Type is not specified. - ProtocolService.set(services, props, sv, LOG); - assertTrue(services.isEmpty()); - - ProtocolService.unset(services, props, sv, LOG); - assertTrue(services.isEmpty()); - - // null service map. - final String typeKey = GlobalConstants.PROTOCOLPLUGINTYPE.toString(); - assertEquals(null, props.put(typeKey, "OF")); - ProtocolService.set(null, props, sv, LOG); - assertTrue(services.isEmpty()); - - ProtocolService.unset(null, props, sv, LOG); - assertTrue(services.isEmpty()); - } - - @Test - public void testSetUnset() { - ConcurrentMap> serviceMap = - new ConcurrentHashMap<>(); - ConcurrentMap> expected = - new ConcurrentHashMap<>(); - - final String typeKey = GlobalConstants.PROTOCOLPLUGINTYPE.toString(); - final String priKey = GlobalConstants.PROTOCOLPLUGINPRIORITY.toString(); - final String[] protocols = {"OF", "PE", "PK"}; - final int basePri = 0; - final int loop = 5; - - // Should override the service if higher priority is specified. - for (String proto: protocols) { - for (int pri = basePri - loop + 1; pri <= basePri; pri++) { - TestService sv = new TestService(); - Map props = new HashMap<>(); - assertEquals(null, props.put(typeKey, proto)); - assertEquals(null, props.put(priKey, Integer.valueOf(pri))); - ProtocolService.set(serviceMap, props, sv, LOG); - - ProtocolService service = serviceMap.get(proto); - assertNotNull(service); - assertEquals(sv, service.getService()); - assertEquals(pri, service.getPriority()); - - ProtocolService service1 = - new ProtocolService(props, sv); - expected.put(proto, service1); - assertEquals(expected, serviceMap); - - // Unset service request should be ignored if different - // parameters are specified. - TestService another = new TestService(); - ProtocolService.unset(serviceMap, props, another, LOG); - assertEquals(expected, serviceMap); - - props.put(priKey, Integer.valueOf(Integer.MAX_VALUE)); - ProtocolService.unset(serviceMap, props, sv, LOG); - assertEquals(expected, serviceMap); - } - } - - // Should reject the set service request if lower priority is specified. - for (String proto: protocols) { - for (int pri = basePri - loop; pri < basePri; pri++) { - TestService sv = new TestService(); - Map props = new HashMap<>(); - assertEquals(null, props.put(typeKey, proto)); - assertEquals(null, props.put(priKey, Integer.valueOf(pri))); - ProtocolService.set(serviceMap, props, sv, LOG); - assertEquals(expected, serviceMap); - } - } - - // Unset protocol services. - for (String proto: protocols) { - ProtocolService service = expected.remove(proto); - assertNotNull(service); - - ITestService sv = service.getService(); - Map props = new HashMap<>(); - assertEquals(null, props.put(typeKey, proto)); - assertEquals(null, props.put(priKey, Integer.valueOf(basePri))); - ProtocolService.unset(serviceMap, props, sv, LOG); - assertEquals(expected, serviceMap); - - // Should be ignored if the specified service does not exist. - ProtocolService.unset(serviceMap, props, sv, LOG); - assertEquals(expected, serviceMap); - } - - assertTrue(serviceMap.isEmpty()); - } -} - -interface ITestService { -} - -class TestService implements ITestService { -} diff --git a/opendaylight/adsal/sal/networkconfiguration/api/pom.xml b/opendaylight/adsal/sal/networkconfiguration/api/pom.xml deleted file mode 100644 index 36706f02f6..0000000000 --- a/opendaylight/adsal/sal/networkconfiguration/api/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../commons/opendaylight - - - sal.networkconfiguration - 0.2.0-SNAPSHOT - bundle - - - org.opendaylight.controller - sal - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.slf4j, - org.osgi.framework, - org.apache.felix.dm, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils - org.opendaylight.controller.sal.networkconfig.bridgedomain - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/BridgeDomainConfigServiceException.java b/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/BridgeDomainConfigServiceException.java deleted file mode 100644 index 19f467ea55..0000000000 --- a/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/BridgeDomainConfigServiceException.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.networkconfig.bridgedomain; - -/** - * Exception thrown by IPluginInBridgeDomainConfigService implementations. - */ -public class BridgeDomainConfigServiceException extends Exception { - private static final long serialVersionUID = 1L; - - public BridgeDomainConfigServiceException(String message) { - super(message); - } - - public BridgeDomainConfigServiceException(String message, Throwable cause) { - super(message, cause); - } -} - diff --git a/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/ConfigConstants.java b/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/ConfigConstants.java deleted file mode 100644 index def1b336f9..0000000000 --- a/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/ConfigConstants.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.networkconfig.bridgedomain; - -/** - * Enum constant that is used as a key for the configuration parameters for BridgeDomains and Ports. - * The main intention of having a constant type is to avoid fragmentation and find common grounds for - * applications to rely on. - * - * This is set to expand based on various capabilities south-bound protocol might expose. - * Not all of them be supported by all the plugins. But this gives a consolidated view of - * all the supported feature configs and avoid config fragmentation. - */ -public enum ConfigConstants { - TYPE("type"), - VLAN("Vlan"), - VLAN_MODE("vlan_mode"), - TUNNEL_TYPE("Tunnel Type"), - SOURCE_IP("Source IP"), - DEST_IP("Destination IP"), - MACADDRESS("MAC Address"), - INTERFACE_IDENTIFIER("Interface Identifier"), - MGMT("Management"), - CUSTOM("Custom Configurations"); - - private ConfigConstants(String name) { - this.name = name; - } - - private String name; - - public String toString() { - return name; - } -} diff --git a/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IBridgeDomainConfigService.java b/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IBridgeDomainConfigService.java deleted file mode 100644 index 590dff1ee5..0000000000 --- a/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IBridgeDomainConfigService.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.networkconfig.bridgedomain; - -/** - * This interface is just a wrapper of IPluginInBridgeDomainConfigService - */ -public interface IBridgeDomainConfigService extends IPluginInBridgeDomainConfigService { -} diff --git a/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IPluginInBridgeDomainConfigService.java b/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IPluginInBridgeDomainConfigService.java deleted file mode 100644 index c84136115c..0000000000 --- a/opendaylight/adsal/sal/networkconfiguration/api/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/IPluginInBridgeDomainConfigService.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.networkconfig.bridgedomain; - -import java.util.List; -import java.util.Map; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.Status; - -/** - * This interface defines bridge domain configuration service methods to be - * implemented by protocol plugins - */ -public interface IPluginInBridgeDomainConfigService { - /** - * Create a Bridge Domain - * - * @param node Node serving this configuration service - * @param bridgeIdentifier String representation of a Bridge Domain - * @param params Map representation of config name (ConfigConstants) and Parameter value (represented as Object). - * @return Status.StatusCode.SUCCESS if bridge domain is created successfully. Failure Status otherwise. - * @note This method will return false if one or more of the supplied params is not supported by the - * protocol plugin that serves the Node. - */ - public Status createBridgeDomain(Node node, String bridgeIdentifier, Map params) throws BridgeDomainConfigServiceException; - - /** - * Delete a Bridge Domain - * - * @param node Node serving this configuration service - * @param bridgeIdentifier String representation of a Bridge Domain - * @return Status.StatusCode.SUCCESS if bridge domain is deleted successfully. Failure Status otherwise. - */ - public Status deleteBridgeDomain(Node node, String bridgeIdentifier); - - /** - * Returns the configured Bridge Domains - * - * @param node Node serving this configuration service - * @return List of Bridge Domain Identifiers - */ - public List getBridgeDomains(Node node); - - /** - * add Bridge Domain Configuration - * - * @param node Node serving this configuration service - * @param bridgeIdentifier String representation of a Bridge Domain - * @param params Map representation of config Name (ConfigConstants) and config value(represented as Object). - * @return Status.StatusCode.SUCCESS if bridge domain configuration is added successfully. Failure Status otherwise. - * @note This method will return false if one or more of the supplied params is not supported by the - * protocol plugin that serves the Node. - */ - public Status addBridgeDomainConfig(Node node, String bridgeIdentifier, Map params); - - /** - * Delete Bridge Domain Configuration - * - * @param node Node serving this configuration service - * @param bridgeIdentifier String representation of a Bridge Domain - * @param params Map representation of config name (ConfigConstants) and Parameter value (represented as Object). - * @return Status.StatusCode.SUCCESS if bridge domain configuration is deleted successfully. Failure Status otherwise. - * @note This method will return false if one or more of the supplied params is not supported by the - * protocol plugin that serves the Node. - */ - public Status removeBridgeDomainConfig(Node node, String bridgeIdentifier, Map params); - - /** - * Returns Bridge Domain Configurations - * - * @param node Node serving this configuration service - * @param bridgeIdentifier String representation of a Bridge Domain - * @return Map representation of config Name (ConfigConstants) and config value(represented as Object). - */ - - public Map getBridgeDomainConfigs(Node node, String bridgeIdentifier); - - /** - * Returns a Node dedicated to a Bridge Domain (if available) that is created using createBridgeDomain. - * @param configNode Node serving this configuration service. - * @param bridgeIdentifier Name of the bridge domain that would map to a dedicated Node - * @return Node dedicated to a bridge domain that is created using createBridgeDomain. - * returns null if there is no such dedicated node is available or represented. - */ - public Node getBridgeDomainNode(Node configNode, String bridgeIdentifier); - - /** - * Add a port to a bridge domain - * - * @param node Node serving this configuration service - * @param bridgeIdentifier String representation of a Bridge Domain - * @param portIdentifier String representation of a Port. - * @param params Map representation of config name (ConfigConstants) and Parameter value (represented as Object). - * @return Status.StatusCode.SUCCESS if a port is added successfully. Failure Status otherwise. - * @note This method will return false if one or more of the supplied params is not supported by the - * protocol plugin that serves the Node. - */ - public Status addPort(Node node, String bridgeIdentifier, String portIdentifier, - Map params); - - /** - * Delete a Port from a bridge domain - * - * @param node Node serving this configuration service - * @param bridgeIdentifier String representation of a Bridge Domain - * @param portIdentifier String representation of a Port. - * @return Status.StatusCode.SUCCESS if a port is added successfully. Failure Status otherwise. - */ - public Status deletePort(Node node, String bridgeIdentifier, String portIdentifier); - - /** - * add Port Configuration - * - * @param node Node serving this configuration service - * @param bridgeIdentifier String representation of a Bridge Domain - * @param portIdentifier String representation of a Port. - * @param params Map representation of config name (ConfigConstants) and Parameter value (represented as Object). - * @return Status.StatusCode.SUCCESS if a port configuration is added successfully. Failure Status otherwise. - * @note This method will return false if one or more of the supplied params is not supported by the - * protocol plugin that serves the Node. - */ - public Status addPortConfig(Node node, String bridgeIdentifier, String portIdentifier, - Map params); - - /** - * Delete Port Configuration - * - * @param node Node serving this configuration service - * @param portIdentifier String representation of a Port. - * @param config Map representation of ConfigName and Configuration Value in Strings. - * @return Status.StatusCode.SUCCESS if a port configuration is removed successfully. Failure Status otherwise. - * @note This method will return false if one or more of the supplied params is not supported by the - * protocol plugin that serves the Node. - */ - public Status removePortConfig(Node node, String bridgeIdentifier, String portIdentifier, Map params); - - /** - * Returns Port Configurations - * - * @param node Node serving this configuration service - * @param bridgeIdentifier String representation of a Bridge Domain - * @param portIdentifier String representation of a Port. - * @return Map representation of Configuration Name (ConfigConstants) and Configuration value (represented as Object). - */ - public Map getPortConfigs(Node node, String bridgeIdentifier, String portIdentifier); - - - /** - * Returns a NodeConnector mapped to a Port (if available) that is created using addPort. - * @param configNode Node serving this configuration service. - * @param bridgeIdentifier Name of the bridge domain that would map to a dedicated Node - * @param portIdentifier String representation of a Port. - * @return NodeConnector that is mapped to a port created using addPort. - * returns null if there is no such nodeConnector is available or mapped. - */ - public NodeConnector getNodeConnector(Node configNode, String bridgeIdentifier, String portIdentifier); -} diff --git a/opendaylight/adsal/sal/networkconfiguration/implementation/pom.xml b/opendaylight/adsal/sal/networkconfiguration/implementation/pom.xml deleted file mode 100644 index da2bc97e0c..0000000000 --- a/opendaylight/adsal/sal/networkconfiguration/implementation/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../../commons/opendaylight - - - sal.networkconfiguration.implementation - 0.2.0-SNAPSHOT - bundle - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.networkconfiguration - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.slf4j, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.networkconfig.bridgedomain, - org.apache.felix.dm, - org.osgi.framework - - org.opendaylight.controller.sal.networkconfig.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/internal/BridgeDomainConfigService.java b/opendaylight/adsal/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/internal/BridgeDomainConfigService.java deleted file mode 100644 index 14c5e0d9e7..0000000000 --- a/opendaylight/adsal/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/bridgedomain/internal/BridgeDomainConfigService.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.networkconfig.bridgedomain.internal; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.networkconfig.bridgedomain.BridgeDomainConfigServiceException; -import org.opendaylight.controller.sal.networkconfig.bridgedomain.ConfigConstants; -import org.opendaylight.controller.sal.networkconfig.bridgedomain.IBridgeDomainConfigService; -import org.opendaylight.controller.sal.networkconfig.bridgedomain.IPluginInBridgeDomainConfigService; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class BridgeDomainConfigService implements IBridgeDomainConfigService { - protected static final Logger logger = LoggerFactory - .getLogger(BridgeDomainConfigService.class); - private final ConcurrentMap pluginService = - new ConcurrentHashMap(); - - void setPluginInService (Map props, IPluginInBridgeDomainConfigService s) { - String type = null; - Object value = props.get(GlobalConstants.PROTOCOLPLUGINTYPE.toString()); - if (value instanceof String) { - type = (String) value; - } - if (type == null) { - logger.error("Received a PluginInConnectionService without any " - + "protocolPluginType provided"); - } else { - this.pluginService.put(type, s); - } - } - - void unsetPluginInService(Map props, IPluginInBridgeDomainConfigService s) { - String type = null; - - Object value = props.get(GlobalConstants.PROTOCOLPLUGINTYPE.toString()); - if (value instanceof String) { - type = (String) value; - } - if (type == null) { - logger.error("Received a PluginInConnectionService without any " - + "protocolPluginType provided"); - } else if (this.pluginService.get(type).equals(s)) { - this.pluginService.remove(type); - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - if (this.pluginService != null) { - this.pluginService.clear(); - } - } - - @Override - public Status createBridgeDomain(Node node, String bridgeIdentifier, Map params) - throws BridgeDomainConfigServiceException { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.createBridgeDomain(node, bridgeIdentifier, params); - } - } - return new Status(StatusCode.NOSERVICE, "Requested Plugin Service Not available"); - } - - @Override - public Status deleteBridgeDomain(Node node, String bridgeIdentifier) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.deleteBridgeDomain(node, bridgeIdentifier); - } - } - return new Status(StatusCode.NOSERVICE, "Requested Plugin Service Not available"); - } - - @Override - public List getBridgeDomains(Node node) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.getBridgeDomains(node); - } - } - return null; - } - - @Override - public Status addBridgeDomainConfig(Node node, String bridgeIdentifier, Map params) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.addBridgeDomainConfig(node, bridgeIdentifier, params); - } - } - return new Status(StatusCode.NOSERVICE, "Requested Plugin Service Not available"); - } - - @Override - public Status removeBridgeDomainConfig(Node node, String bridgeIdentifier, Map params) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.removeBridgeDomainConfig(node, bridgeIdentifier, params); - } - } - return new Status(StatusCode.NOSERVICE, "Requested Plugin Service Not available"); - } - - @Override - public Map getBridgeDomainConfigs(Node node, String bridgeIdentifier) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.getBridgeDomainConfigs(node, bridgeIdentifier); - } - } - return null; - } - - @Override - public Node getBridgeDomainNode(Node configNode, String bridgeIdentifier) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(configNode.getType()); - if (plugin != null) { - return plugin.getBridgeDomainNode(configNode, bridgeIdentifier); - } - } - return null; - } - - @Override - public Status addPort(Node node, String bridgeIdentifier, String portIdentifier, Map params) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.addPort(node, bridgeIdentifier, portIdentifier, params); - } - } - return new Status(StatusCode.NOSERVICE, "Requested Plugin Service Not available"); - } - - @Override - public Status deletePort(Node node, String bridgeIdentifier, String portIdentifier) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.deletePort(node, bridgeIdentifier, portIdentifier); - } - } - return new Status(StatusCode.NOSERVICE, "Requested Plugin Service Not available"); - } - - @Override - public Status addPortConfig(Node node, String bridgeIdentifier, String portIdentifier, - Map params) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.addPortConfig(node, bridgeIdentifier, portIdentifier, params); - } - } - return new Status(StatusCode.NOSERVICE, "Requested Plugin Service Not available"); - } - - @Override - public Status removePortConfig(Node node, String bridgeIdentifier, String portIdentifier, - Map params) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.removePortConfig(node, bridgeIdentifier, portIdentifier, params); - } - } - return new Status(StatusCode.NOSERVICE, "Requested Plugin Service Not available"); - } - - @Override - public Map getPortConfigs(Node node, String bridgeIdentifier, String portIdentifier) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(node.getType()); - if (plugin != null) { - return plugin.getPortConfigs(node, bridgeIdentifier, portIdentifier); - } - } - return null; - } - - @Override - public NodeConnector getNodeConnector(Node configNode, String bridgeIdentifier, String portIdentifier) { - if (pluginService != null) { - IPluginInBridgeDomainConfigService plugin = this.pluginService.get(configNode.getType()); - if (plugin != null) { - return plugin.getNodeConnector(configNode, bridgeIdentifier, portIdentifier); - } - } - return null; - } -} diff --git a/opendaylight/adsal/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/internal/Activator.java b/opendaylight/adsal/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/internal/Activator.java deleted file mode 100644 index 1fc7349d44..0000000000 --- a/opendaylight/adsal/sal/networkconfiguration/implementation/src/main/java/org/opendaylight/controller/sal/networkconfig/internal/Activator.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.sal.networkconfig.internal; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.networkconfig.bridgedomain.IBridgeDomainConfigService; -import org.opendaylight.controller.sal.networkconfig.bridgedomain.IPluginInBridgeDomainConfigService; -import org.opendaylight.controller.sal.networkconfig.bridgedomain.internal.BridgeDomainConfigService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the list of - * known Global implementations - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - public Object[] getGlobalImplementations() { - Object[] res = { BridgeDomainConfigService.class}; - return res; - } - - /** - * Function that is called when configuration of the dependencies is required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - */ - public void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(BridgeDomainConfigService.class)) { - c.setInterface( - new String[] { IBridgeDomainConfigService.class.getName()}, - null); - - c.add(createServiceDependency() - .setService(IPluginInBridgeDomainConfigService.class) - .setCallbacks("setPluginInService", "unsetPluginInService") - .setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/samples/clustersession/pom.xml b/opendaylight/adsal/samples/clustersession/pom.xml deleted file mode 100644 index 977a324569..0000000000 --- a/opendaylight/adsal/samples/clustersession/pom.xml +++ /dev/null @@ -1,109 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - org.opendaylight.controller - clustersession - 1.2.0-SNAPSHOT - bundle - - - equinoxSDK381 - javax.servlet - - - orbit - org.apache.catalina - - - orbit - org.apache.catalina.ha - - - orbit - org.apache.coyote - - - orbit - org.apache.juli.extras - - - orbit - org.apache.tomcat.api - - - orbit - org.apache.tomcat.util - - - org.opendaylight.controller - clustering.services - 0.7.0-SNAPSHOT - - - org.slf4j - jcl-over-slf4j - - - org.osgi - org.osgi.core - provided - - - junit - junit - test - - - org.mockito - mockito-all - 1.9.5 - test - - - org.powermock - powermock-api-mockito - 1.5.4 - test - - - org.powermock - powermock-module-junit4 - 1.5.4 - test - - - - - - - org.apache.felix - maven-bundle-plugin - 2.4.0 - true - - - org.eclipse.gemini.web.tomcat - org.opendaylight.controller.clustersession - org.apache.catalina, - org.apache.catalina.session, - org.apache.catalina.util, - org.apache.catalina.ha.session, - javax.servlet, - javax.servlet.http, - org.slf4j, - org.osgi.framework, - org.eclipse.osgi.framework.console, - org.opendaylight.controller.clustering.services - - ${project.basedir}/META-INF - - - - - diff --git a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSession.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSession.java deleted file mode 100644 index dc93700c0d..0000000000 --- a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSession.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.opendaylight.controller.clustersession; - -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.security.Principal; -import java.util.ArrayList; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.catalina.Manager; -import org.apache.catalina.SessionListener; -import org.apache.catalina.session.StandardSession; -import org.opendaylight.controller.clustersession.service.ClusterSessionService; - -public class ClusterSession extends StandardSession implements Serializable { - - private static final long serialVersionUID = 1L; - - private transient ClusterSessionService sessionService; - - public ClusterSession(Manager manager, ClusterSessionService sessionService) { - super(manager); - this.sessionService = sessionService; - } - - public void setSessionService(ClusterSessionService sessionService){ - this.sessionService = sessionService; - } - - @Override - public void setAuthType(String authType) { - super.setAuthType(authType); - sessionService.updateSession(this); - } - - @Override - public void setCreationTime(long time) { - super.setCreationTime(time); - sessionService.updateSession(this); - } - - @Override - public void setMaxInactiveInterval(int interval) { - super.setMaxInactiveInterval(interval); - sessionService.updateSession(this); - } - - @Override - public void setNew(boolean isNew) { - super.setNew(isNew); - sessionService.updateSession(this); - } - - @Override - public void setPrincipal(Principal principal) { - super.setPrincipal(principal); - sessionService.updateSession(this); - } - - @Override - public void setValid(boolean isValid) { - super.setValid(isValid); - sessionService.updateSession(this); - } - - @Override - public void access() { - super.access(); - sessionService.updateSession(this); - } - - @Override - public void endAccess() { - super.endAccess(); - sessionService.updateSession(this); - } - - @Override - public void removeAttribute(String name, boolean notify) { - super.removeAttribute(name, notify); - sessionService.updateSession(this); - } - - @Override - public void setAttribute(String name, Object value, boolean notify) { - super.setAttribute(name, value, notify); - sessionService.updateSession(this); - } - - @Override - public void recycle() { - super.recycle(); - sessionService.updateSession(this); - } - - @Override - public void removeNote(String name) { - super.removeNote(name); - sessionService.updateSession(this); - } - - @Override - public void addSessionListener(SessionListener listener) { - super.addSessionListener(listener); - sessionService.updateSession(this); - } - - @Override - public void removeSessionListener(SessionListener listener) { - super.removeSessionListener(listener); - sessionService.updateSession(this); - } - - @Override - public void setNote(String name, Object value) { - super.setNote(name, value); - sessionService.updateSession(this); - } - - /* - * Certain fields inside Standard session are not serialized, We need to process them here - */ - public void afterDeserialization(){ - if (listeners == null){ - listeners = new ArrayList(); - } - if (notes == null){ - notes = new ConcurrentHashMap(); - } - if(support == null){ - support = new PropertyChangeSupport(this); - } - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("ClusterSession["); - sb.append(id); - sb.append(", isNew : "); - sb.append(isNew); - sb.append(", isValid : "); - sb.append(isValid); - sb.append("]"); - return sb.toString(); - } - - /* - * These methods are added for deserialization purpose - */ - - public void setAuthTypeInternal(String authType){ - this.authType = authType; - } - - public void setPrincipalInternal(Principal principal){ - this.principal = principal; - } - - public void setNoteInternal(String name, Object value) { - notes.put(name, value); - } -} diff --git a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionData.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionData.java deleted file mode 100644 index b5796d2a6f..0000000000 --- a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionData.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.opendaylight.controller.clustersession; - -import java.io.Serializable; -import java.util.Arrays; - -public class ClusterSessionData implements Serializable{ - - private static final long serialVersionUID = 1L; - - private ClusterSession session; - - private byte[] principalData; - - private byte[] savedRequestData; - - private byte[] savedPrincipalData; - - private String authType; - - private String userName; - - private String password; - - public ClusterSession getSession() { - return session; - } - - public void setSession(final ClusterSession session) { - this.session = session; - } - - public byte[] getPrincipalData() { - return principalData; - } - - public void setPrincipalData(final byte[] principalData) { - this.principalData = Arrays.copyOf(principalData, principalData.length); - } - - public String getAuthType() { - return authType; - } - - public void setAuthType(String authType) { - this.authType = authType; - } - - public byte[] getSavedRequestData() { - return savedRequestData; - } - - public void setSavedRequestData(byte[] savedRequestData) { - this.savedRequestData = Arrays.copyOf(savedRequestData, savedRequestData.length); - } - - public byte[] getSavedPrincipalData() { - return savedPrincipalData; - } - - public void setSavedPrincipalData(byte[] savedPrincipalData) { - this.savedPrincipalData = Arrays.copyOf(savedPrincipalData, savedPrincipalData.length); - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} diff --git a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionManager.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionManager.java deleted file mode 100644 index e285bb4f15..0000000000 --- a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionManager.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - */ -package org.opendaylight.controller.clustersession; - -import java.io.IOException; -import java.util.HashMap; - -import org.apache.catalina.LifecycleException; -import org.apache.catalina.LifecycleState; -import org.apache.catalina.Session; -import org.apache.catalina.session.ManagerBase; -import org.apache.catalina.util.SessionIdGenerator; -import org.opendaylight.controller.clustersession.impl.ClusterSessionServiceImpl; -import org.opendaylight.controller.clustersession.service.ClusterSessionService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -/** - * ClusterSession Manager is a custom session manager, that is used to persist session data - * across cluster of a storage such as infinispan or memcache - * @author harman singh - * - */ -public class ClusterSessionManager extends ManagerBase{ - /** - * Has this component been _started yet? - */ - protected boolean started = false; - - protected ClusterSessionService sessionService; - - private static final Logger LOGGER = LoggerFactory.getLogger(ClusterSessionManager.class); - /** - * The descriptive information about this implementation. - */ - protected static final String INFO = "ClusterSessionManager/1.0"; - - /** - * The descriptive name of this Manager implementation (for logging). - */ - protected static final String NAME = "ClusterSessionManager"; - - public ClusterSessionManager(){ - sessionService = new ClusterSessionServiceImpl(this); - } - - /** - * Return descriptive information about this Manager implementation and - * the corresponding version number, in the format - * <description>/<version>. - */ - @Override - public String getInfo(){ - return INFO; - } - - /** - * Return the descriptive short name of this Manager implementation. - */ - @Override - public String getName(){ - return NAME; - } - - /** - * {@inheritDoc} - */ - @Override - public void load() throws ClassNotFoundException, IOException { - // We are not persisting any session in database, infinispan does not persist data. - // loading of persisted session is not required. - } - - /** - * {@inheritDoc} - */ - @Override - public void unload() throws IOException { - // We are not persisting any session in database, infinispan does not persist data. - // unloading of session to persistence layer is not required. - } - - /** - * Start this component and implement the requirements - * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}. - * - * @exception LifecycleException if this component detects a fatal error - * that prevents this component from being used - */ - @Override - protected synchronized void startInternal() throws LifecycleException { - sessionIdGenerator = new SessionIdGenerator(); - sessionIdGenerator.setJvmRoute(getJvmRoute()); - sessionIdGenerator.setSecureRandomAlgorithm(getSecureRandomAlgorithm()); - sessionIdGenerator.setSecureRandomClass(getSecureRandomClass()); - sessionIdGenerator.setSecureRandomProvider(getSecureRandomProvider()); - sessionIdGenerator.setSessionIdLength(getSessionIdLength()); - sessionService.startInternal(sessionIdGenerator); - setState(LifecycleState.STARTING); - } - - /** - * Stop this component and implement the requirements - * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. - * - * @exception LifecycleException if this component detects a fatal error - * that prevents this component from being used - */ - @Override - protected synchronized void stopInternal() throws LifecycleException { - setState(LifecycleState.STOPPING); - - // Expire all active sessions - Session sessions[] = findSessions(); - for (int i = 0; i < sessions.length; i++) { - Session session = sessions[i]; - try { - if (session.isValid()) { - session.expire(); - } - } catch (Exception e) { - LOGGER.warn(e.toString()); - } finally { - // Measure against memory leaking if references to the session - // object are kept in a shared field somewhere - session.recycle(); - } - } - // Require a new random number generator if we are restarted - super.stopInternal(); - sessionService.stopInternal(); - } - - /** - * {@inheritDoc} - */ - @Override - public void expireSession(final String sessionId){ - LOGGER.debug("SESSION EXPIRE : ", sessionId); - sessionService.expireSession(sessionId); - } - - /** - * {@inheritDoc} - */ - @Override - public void remove(final Session session){ - LOGGER.debug("SESSION REMOVE : ", session.getId()); - sessionService.removeSession(session.getId()); - } - - /** - * {@inheritDoc} - */ - @Override - public void remove(Session session, boolean update) { - sessionService.removeSession(session.getId()); - } - - /** - * {@inheritDoc} - */ - @Override - public Session findSession(final String id) throws IOException{ - return sessionService.findSession(id); - } - - /** - * {@inheritDoc} - */ - @Override - public Session createSession(final String sessionId){ - LOGGER.debug("SESSION CREATE : ", sessionId); - if(sessionId != null){ - Session session = sessionService.findSession(sessionId); - if(session != null){ - return session; - } - } - return sessionService.createSession(sessionId); - } - - /** - * {@inheritDoc} - */ - @Override - public Session createEmptySession(){ - return sessionService.createEmptySession(); - } - /** - * {@inheritDoc} - */ - @Override - public void add(Session session){ - LOGGER.debug("SESSION ADD : ", session.getId()); - sessionService.addSession((ClusterSession)session); - } - /** - * {@inheritDoc} - */ - @Override - public HashMap getSession(String sessionId){ - return sessionService.getSession(sessionId); - } - /** - * {@inheritDoc} - */ - @Override - public Session[] findSessions() { - return sessionService.findSessions(); - } - - public ClusterSessionService getSessionService() { - return sessionService; - } - - public void setSessionService(ClusterSessionService sessionService) { - this.sessionService = sessionService; - } - -} diff --git a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionUtil.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionUtil.java deleted file mode 100644 index 01fad1aabd..0000000000 --- a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/ClusterSessionUtil.java +++ /dev/null @@ -1,269 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - */ -package org.opendaylight.controller.clustersession; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.catalina.authenticator.Constants; -import org.apache.catalina.authenticator.SavedRequest; -import org.apache.catalina.ha.session.SerializablePrincipal; -import org.apache.catalina.realm.GenericPrincipal; -import org.opendaylight.controller.clustersession.service.ClusterSessionService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * ClusterSessionUtil will be used to convert ClusterSession object into ClusterSessionData object, - * which is serializable and can be passed for storage. This class also perform deserialization to - * create ClusterSession object - * @author harman singh - * - */ - -public class ClusterSessionUtil { - - private static final Logger LOGGER = LoggerFactory.getLogger(ClusterSessionUtil.class); - - private ClusterSessionUtil() { - - } - - /** - * Serialize the ClusterSession object to provide ClusterSessionData object, - * that will be used for storage like in inifinispan or memcache etc. - * @param session an instance of ClusterSession - * @return an instance of ClusterSessionData - */ - public static ClusterSessionData getSerializableSession(ClusterSession session) { - if(session == null){ - return null; - } - ClusterSessionData sessionData = new ClusterSessionData(); - sessionData.setSession(session); - sessionData.setAuthType(session.getAuthType()); - sessionData.setPrincipalData(serializePrincipal(session.getPrincipal())); - sessionData.setSavedRequestData(serializeSavedRequest(session.getNote(Constants.FORM_REQUEST_NOTE))); - Principal notePrincipal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE); - byte[] principalBytes = serializePrincipal(notePrincipal); - sessionData.setSavedPrincipalData(principalBytes); - if(session.getPrincipal() == null && notePrincipal != null){ - sessionData.setPrincipalData(principalBytes); - } - sessionData.setUserName((String) session.getNote(Constants.FORM_USERNAME)); - sessionData.setPassword((String) session.getNote(Constants.FORM_PASSWORD)); - return sessionData; - } - - /** - * Deserialize the ClusterSessionData object that usually comes from storage - * to provide ClusterSession object, - * that will be used by Session Manager - * @param sessionData an instance of ClusterSessionData - * @param sessionService an instance of ClusterSessionService - * @param manager an instance of ClusterSessionManager - * @return an instance of ClusterSession - */ - - public static ClusterSession getDeserializedSession(ClusterSessionData sessionData, ClusterSessionService sessionService, - ClusterSessionManager manager) { - if(sessionData == null){ - return null; - } - ClusterSession session = sessionData.getSession(); - session.afterDeserialization(); - session.setManager(manager); - session.setSessionService(sessionService); - if(sessionData.getAuthType() != null) { - session.setAuthTypeInternal(sessionData.getAuthType()); - } - if(sessionData.getPrincipalData() != null && sessionData.getPrincipalData().length > 0){ - session.setPrincipalInternal(deserializePrincipal(sessionData.getPrincipalData())); - } - if(sessionData.getSavedPrincipalData() != null && sessionData.getSavedPrincipalData().length > 0){ - session.setNoteInternal(Constants.FORM_PRINCIPAL_NOTE, deserializePrincipal(sessionData.getSavedPrincipalData())); - } - if(sessionData.getSavedRequestData() != null && sessionData.getSavedRequestData().length > 0){ - session.setNoteInternal(Constants.FORM_REQUEST_NOTE, deserializeSavedRequest(sessionData.getSavedRequestData())); - } - if(sessionData.getUserName() != null){ - session.setNoteInternal(Constants.FORM_USERNAME, sessionData.getUserName()); - } - if(sessionData.getPassword() != null){ - session.setNoteInternal(Constants.FORM_PASSWORD, sessionData.getPassword()); - } - return session; - } - - private static byte[] serializePrincipal(final Principal principal){ - if(principal == null) { - return new byte[0]; - } - ByteArrayOutputStream bos = null; - ObjectOutputStream oos = null; - try { - bos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(bos); - SerializablePrincipal.writePrincipal((GenericPrincipal) principal, oos ); - oos.flush(); - return bos.toByteArray(); - } catch (IOException e) { - throw new IllegalArgumentException( "Non-serializable object", e); - } finally { - closeSilently(bos); - closeSilently(oos); - } - } - - private static byte[] serializeSavedRequest(final Object obj) { - if(obj == null) { - return new byte[0]; - } - final SavedRequest savedRequest = (SavedRequest) obj; - ByteArrayOutputStream bos = null; - ObjectOutputStream oos = null; - try { - bos = new ByteArrayOutputStream(); - oos = new ObjectOutputStream(bos); - oos.writeObject(savedRequest.getContentType()); - oos.writeObject(getHeaders(savedRequest)); - oos.writeObject(newArrayList(savedRequest.getLocales())); - oos.writeObject(savedRequest.getMethod()); - oos.writeObject(savedRequest.getQueryString()); - oos.writeObject(savedRequest.getRequestURI()); - oos.writeObject(savedRequest.getDecodedRequestURI()); - oos.flush(); - return bos.toByteArray(); - } catch (IOException e) { - throw new IllegalArgumentException( "Non-serializable object", e); - } finally { - closeSilently(bos); - closeSilently(oos); - } - } - - private static Principal deserializePrincipal(final byte[] data) { - ByteArrayInputStream bis = null; - ObjectInputStream ois = null; - try { - bis = new ByteArrayInputStream(data); - ois = new ObjectInputStream(bis); - return SerializablePrincipal.readPrincipal(ois); - } catch (IOException e) { - throw new IllegalArgumentException( "Could not deserialize principal", e); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException( "Could not deserialize principal", e); - } finally { - closeSilently(bis); - closeSilently(ois); - } - } - - @SuppressWarnings("unchecked") - private static SavedRequest deserializeSavedRequest(final byte[] data) { - ByteArrayInputStream bis = null; - ObjectInputStream ois = null; - try { - bis = new ByteArrayInputStream(data); - ois = new ObjectInputStream(bis); - final SavedRequest savedRequest = new SavedRequest(); - savedRequest.setContentType((String) ois.readObject()); - setHeaders(savedRequest, (Map>) ois.readObject()); - setLocales(savedRequest, (List) ois.readObject()); - savedRequest.setMethod((String) ois.readObject()); - savedRequest.setQueryString((String) ois.readObject()); - savedRequest.setRequestURI((String) ois.readObject()); - savedRequest.setDecodedRequestURI((String) ois.readObject()); - return savedRequest; - } catch (final IOException e) { - throw new IllegalArgumentException( "Could not deserialize SavedRequest", e ); - } catch (final ClassNotFoundException e) { - throw new IllegalArgumentException( "Could not deserialize SavedRequest", e ); - } finally { - closeSilently(bis); - closeSilently(ois); - } - } - - private static void setLocales(final SavedRequest savedRequest, final List locales) { - if(locales != null && !locales.isEmpty()) { - for (final Locale locale : locales) { - savedRequest.addLocale(locale); - } - } - } - - private static List newArrayList(final Iterator iter) { - if(!iter.hasNext()) { - return Collections.emptyList(); - } - final List result = new ArrayList(); - while (iter.hasNext()) { - result.add(iter.next()); - } - return result; - } - - private static Map> getHeaders(final SavedRequest obj) { - final Map> result = new HashMap>(); - final Iterator namesIter = obj.getHeaderNames(); - while (namesIter.hasNext()) { - final String name = namesIter.next(); - final List values = new ArrayList(); - result.put(name, values); - final Iterator valuesIter = obj.getHeaderValues(name); - while (valuesIter.hasNext()) { - final String value = valuesIter.next(); - values.add(value); - } - } - return result; - } - - private static void setHeaders(final SavedRequest obj, final Map> headers) { - if(headers != null) { - for (final Entry> entry : headers.entrySet()) { - final List values = entry.getValue(); - for (final String value : values) { - obj.addHeader(entry.getKey(), value); - } - } - } - } - - private static void closeSilently(final OutputStream os) { - if (os != null) { - try { - os.close(); - } catch (final IOException f) { - LOGGER.debug("Exception occurred while closing output stream", f.toString()); - } - } - } - - private static void closeSilently(final InputStream is) { - if (is != null) { - try { - is.close(); - } catch (final IOException f) { - LOGGER.debug("Exception occurred while closing input stream", f.toString()); - } - } - } -} diff --git a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/impl/ClusterSessionServiceImpl.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/impl/ClusterSessionServiceImpl.java deleted file mode 100644 index e1c7dfd65d..0000000000 --- a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/impl/ClusterSessionServiceImpl.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - */ -package org.opendaylight.controller.clustersession.impl; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumSet; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.concurrent.ConcurrentMap; - -import org.apache.catalina.Session; -import org.apache.catalina.util.SessionIdGenerator; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.clustersession.ClusterSession; -import org.opendaylight.controller.clustersession.ClusterSessionData; -import org.opendaylight.controller.clustersession.ClusterSessionManager; -import org.opendaylight.controller.clustersession.ClusterSessionUtil; -import org.opendaylight.controller.clustersession.service.ClusterSessionService; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.osgi.util.tracker.ServiceTracker; -import org.osgi.util.tracker.ServiceTrackerCustomizer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Implementation to persist and retrieve session data from infinispan cache - * @author harman singh - * - */ -public class ClusterSessionServiceImpl implements ClusterSessionService, - ServiceTrackerCustomizer{ - - private IClusterGlobalServices clusterGlobalServices = null; - private static final Logger LOGGER = LoggerFactory.getLogger(ClusterSessionServiceImpl.class); - private ConcurrentMap sessions = null; - private static final String SESSION_CACHE = "customSessionManager.sessionData"; - private ClusterSessionManager manager = null; - private SessionIdGenerator sessionIdGenerator = null; - private BundleContext context = null; - private ServiceTracker clusterTracker; - public ClusterSessionServiceImpl(ClusterSessionManager manager) { - this.manager = manager; - } - /** - * This method initialize the cluster service of opendaylight and - * create a cache map in infinispan - */ - - @Override - public void startInternal(SessionIdGenerator sessionIdGenerator){ - this.sessionIdGenerator = sessionIdGenerator; - context = FrameworkUtil.getBundle(ClusterSessionManager.class).getBundleContext(); - getClusterService(); - createCache(); - } - - /** - * Removes the cluster service tracker while shut down - */ - @Override - public void stopInternal(){ - if(clusterTracker != null){ - clusterTracker.close(); - } - } - /** - * {@inheritDoc} - */ - @Override - public Session findSession(final String id){ - if(id == null) { - return null; - } - if(sessions == null) { - LOGGER.debug("Session cache not present, try to create."); - createCache(); - return null; - } - ClusterSessionData sessionData = sessions.get(id); - if(sessionData != null) { - LOGGER.debug("SESSION FOUND : ", id); - } else { - LOGGER.debug("SESSION NOTFOUND : ", id); - } - return ClusterSessionUtil.getDeserializedSession(sessionData, this, this.manager); - } - - /** - * {@inheritDoc} - */ - @Override - public Session[] findSessions() { - if(sessions == null) { - LOGGER.debug("Session cache not present, try to create."); - createCache(); - return new Session[0]; - } - Collection sessionDataList = sessions.values(); - ArrayList sessionList = new ArrayList(); - for(ClusterSessionData sessionData : sessionDataList){ - sessionList.add(ClusterSessionUtil.getDeserializedSession(sessionData, this, this.manager)); - } - return sessionList.toArray(new Session[0]); - } - - /** - * {@inheritDoc} - */ - @Override - public void removeSession(final String id){ - if(sessions == null) { - LOGGER.debug("Session cache not present, try to create."); - createCache(); - return; - } - sessions.remove(id); - } - - /** - * {@inheritDoc} - */ - @Override - public void expireSession(final String id){ - if(sessions == null) { - LOGGER.debug("Session cache not present, try to create."); - createCache(); - return; - } - ClusterSessionData sessionData = sessions.get(id); - if(sessionData != null) { - sessionData.getSession().expire(); - removeSession(id); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Session createSession(final String sessionId){ - if(sessions == null) { - LOGGER.debug("Session cache not present, try to create."); - createCache(); - return null; - } - Session session = createEmptySession(); - session.setNew(true); - session.setValid(true); - session.setCreationTime(System.currentTimeMillis()); - String id = sessionId; - if (id == null) { - id = generateSessionId(); - } - session.setId(id); - return session; - } - - /** - * {@inheritDoc} - */ - @Override - public void addSession(final ClusterSession session){ - if(sessions == null) { - LOGGER.debug("Session cache not present, try to create."); - createCache(); - return; - } - ClusterSessionData sessionData = ClusterSessionUtil.getSerializableSession(session); - sessions.put(session.getId(), sessionData); - } - - /** - * {@inheritDoc} - */ - @Override - public Session createEmptySession(){ - return getNewSession(); - } - - /** - * Returns information about the session with the given session id. - * - *

The session information is organized as a HashMap, mapping - * session attribute names to the String representation of their values. - * - * @param sessionId Session id - * - * @return HashMap mapping session attribute names to the String - * representation of their values, or null if no session with the - * specified id exists, or if the session does not have any attributes - */ - public HashMap getSession(String sessionId) { - if(sessions == null) { - LOGGER.debug("Session cache not present, try to create."); - createCache(); - return null; - } - ClusterSessionData sessionData = sessions.get(sessionId); - if (sessionData == null) { - return null; - } - ClusterSession s = ClusterSessionUtil.getDeserializedSession(sessionData, this, this.manager); - Enumeration ee = s.getAttributeNames(); - if (ee == null || !ee.hasMoreElements()) { - return null; - } - HashMap map = new HashMap(); - while (ee.hasMoreElements()) { - String attrName = ee.nextElement(); - map.put(attrName, s.getAttribute(attrName).toString()); - } - return map; - } - - /** - * {@inheritDoc} - */ - @Override - public void updateSession(ClusterSession session) { - if(sessions == null) { - LOGGER.debug("Session cache not present, try to create."); - createCache(); - return; - } - if(session.getId() != null && sessions.get(session.getId()) != null){ - ClusterSessionData sessionData = ClusterSessionUtil.getSerializableSession(session); - sessions.put(session.getId(), sessionData); - } - } - - @Override - public IClusterGlobalServices addingService(ServiceReference reference) { - if (clusterGlobalServices == null) { - this.clusterGlobalServices = context.getService(reference); - createCache(); - return clusterGlobalServices; - } - return null; - } - - @Override - public void modifiedService(ServiceReference reference, IClusterGlobalServices service) { - // This method is added from ServiceTracker interface, We don't have to modify service. - } - - @Override - public void removedService(ServiceReference reference, IClusterGlobalServices service) { - if (clusterGlobalServices == service) { - clusterGlobalServices = null; - } - } - - /* - * Return an instance of Standard Session object with current session manager - */ - private ClusterSession getNewSession() { - return new ClusterSession(this.manager, this); - } - - /* - * Generate and return a new session identifier. - */ - private String generateSessionId() { - String result = null; - do { - result = sessionIdGenerator.generateSessionId(); - } while (sessions.containsKey(result)); - return result; - } - - private void createCache() { - allocateCache(); - retrieveCache(); - } - - /* - * This is a fragment bundle, so We can't use Activator to set Service. - * This is the alternative to get registered clustered service - */ - private void getClusterService(){ - if (context != null) { - clusterTracker = new ServiceTracker<>(context, IClusterGlobalServices.class, this); - clusterTracker.open(); - } - } - - /* - * Allocate space in infinispan to persist session data - */ - private void allocateCache() { - if (clusterGlobalServices == null) { - LOGGER.trace("un-initialized clusterGlobalService, can't create cache"); - return; - } - try { - clusterGlobalServices.createCache(SESSION_CACHE, - EnumSet.of(IClusterServices.cacheMode.SYNC , IClusterServices.cacheMode.TRANSACTIONAL)); - - } catch (CacheConfigException cce) { - LOGGER.error("Cache configuration invalid - check cache mode", cce.toString()); - } catch (CacheExistException ce) { - LOGGER.debug("Skipping cache creation as already present", ce.toString()); - } - } - - /* - * Fetch cached session data map object from infinispan - */ - @SuppressWarnings("unchecked") - private void retrieveCache(){ - if (clusterGlobalServices == null) { - LOGGER.trace("un-initialized clusterGlobalService, can't retrieve cache"); - return; - } - sessions = (ConcurrentMap)clusterGlobalServices.getCache(SESSION_CACHE); - if(sessions == null){ - LOGGER.warn("Failed to get session cache"); - } - } -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/service/ClusterSessionService.java b/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/service/ClusterSessionService.java deleted file mode 100644 index 9991b33f80..0000000000 --- a/opendaylight/adsal/samples/clustersession/src/main/java/org/opendaylight/controller/clustersession/service/ClusterSessionService.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.opendaylight.controller.clustersession.service; - -import java.util.HashMap; - -import org.apache.catalina.Session; -import org.apache.catalina.util.SessionIdGenerator; -import org.opendaylight.controller.clustersession.ClusterSession; - -/** - * A service to handle session persistence and retrieval in any data store - * - * @author harman singh - * - */ -public interface ClusterSessionService { - - /** - * This method performs all startup operations - */ - void startInternal(SessionIdGenerator sessionIdGenerator); - - /** - * Method to perform all clean up operations - */ - void stopInternal(); - - /** - * Find Session object based on provided session id from persistance - * @param id - * @return an instance of Session - */ - Session findSession(final String id); - - /** - * Get an array of session objects available in storage - */ - Session[] findSessions(); - - /** - * Remove a session object from persistence - * @param id of session object need to be removed - */ - void removeSession(final String id); - - /** - * Expire and remove a session object from persistence - * @param id of session object need to be expired - */ - void expireSession(final String id); - - /** - * Create a session object based on session id, if session is not present - * use random session id - * @param sessionId - * @return an instance of Session - */ - Session createSession(final String sessionId); - - /** - * Add a session object in persistence - * @param session an instance of ClusterSession - */ - void addSession(final ClusterSession session); - - /** - * Create an empty Session object - * @return session object - */ - Session createEmptySession(); - - /** - * Fetch attributes of Session object fetched by supplied session id - * @param sessionId - * @return - */ - HashMap getSession(String sessionId); - - /** - * update the session object in persistence - * @param session - */ - void updateSession(final ClusterSession session); - -} diff --git a/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionManagerTest.java b/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionManagerTest.java deleted file mode 100644 index 9aae2bb3b7..0000000000 --- a/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionManagerTest.java +++ /dev/null @@ -1,157 +0,0 @@ -package org.opendaylight.controller.clustersession; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.HashMap; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.apache.catalina.Context; -import org.apache.catalina.LifecycleException; -import org.apache.catalina.Session; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustersession.impl.ClusterSessionServiceImpl; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({FrameworkUtil.class}) -public class ClusterSessionManagerTest { - static ClusterSessionManager manager = null; - static ClusterSessionServiceImpl sessionService = null; - private static final String SESSION_CACHE = "customSessionManager.sessionData"; - static ConcurrentMap sessions = new ConcurrentHashMap(); - private String sessionId = "1234567"; - final String AUTH_TYPE = "FORM"; - final String ATTRIBUTE_NAME = "AuthType"; - final int SESSION_ID_LENGTH = 7; - @SuppressWarnings("unchecked") - @BeforeClass - public static void init(){ - Bundle bundle = mock(Bundle.class); - BundleContext context = mock(BundleContext.class); - IClusterGlobalServices clusterGlobalService = mock(IClusterGlobalServices.class); - ServiceReference serviceReference = mock(ServiceReference.class); - PowerMockito.mockStatic(FrameworkUtil.class); - when(FrameworkUtil.getBundle(ClusterSessionManager.class)).thenReturn(bundle); - when(bundle.getBundleContext()).thenReturn(context); - when(context.getService(serviceReference)).thenReturn(clusterGlobalService); - when((ConcurrentMap)clusterGlobalService.getCache(SESSION_CACHE)).thenReturn(sessions); - Context containerContext = mock(Context.class); - manager = new ClusterSessionManager(); - manager.setContainer(containerContext); - try { - manager.startInternal(); - } catch (LifecycleException e) { - } - sessionService = (ClusterSessionServiceImpl) manager.getSessionService(); - sessionService.addingService(serviceReference); - } - - @Test - public void checkSessionManagerCreated(){ - assertEquals("session manager info does not match", "ClusterSessionManager/1.0", manager.getInfo()); - assertEquals("session manager name does not match", "ClusterSessionManager", manager.getName()); - } - - @Test - public void testCreateEmptySession(){ - Session session = manager.createEmptySession(); - assertEquals("session manager does not match", manager, session.getManager()); - } - - @Test - public void testCreateRandomSessionId(){ - Session session = manager.createSession(null); - assertEquals("Session should be valid", true, session.isValid()); - manager.remove(session); - } - - @Test - public void testCreateSession(){ - Session session = manager.createSession(sessionId); - assertEquals("Session should be valid", true, session.isValid()); - assertEquals("Session id does not match", sessionId, session.getId()); - manager.remove(session); - } - - @Test - public void testReCreateSession(){ - Session session = manager.createSession(sessionId); - assertEquals("Session should be valid", true, session.isValid()); - assertEquals("Session id does not match", sessionId, session.getId()); - manager.createSession(sessionId); - manager.remove(session); - } - - @Test - public void testSessionCRUD() throws IOException{ - Session foundSession = manager.findSession(sessionId); - assertNull("Session should not exist here", foundSession); - Session session = manager.createSession(sessionId); - manager.add(session); - foundSession = manager.findSession(sessionId); - assertEquals("Session was not found, id does not match", sessionId, foundSession.getId()); - manager.remove(session); - foundSession = manager.findSession(sessionId); - assertEquals("Session was not removed", null, foundSession); - } - - @Test - public void testExpireSession() throws IOException{ - Session session = manager.createSession(sessionId); - session.setAuthType(AUTH_TYPE); - manager.add(session); - Session foundSession = manager.findSession(sessionId); - assertEquals("Session was not found", sessionId, foundSession.getId()); - manager.expireSession(sessionId); - foundSession = manager.findSession(sessionId); - assertEquals("Session was not expired", null, foundSession); - } - - @Test - public void testFindSessions(){ - Session session = manager.createSession(sessionId); - session.setAuthType(AUTH_TYPE); - manager.add(session); - Session[] sessions = manager.findSessions(); - assertEquals("Session array size does not match", 1, sessions.length); - assertEquals("Session array size does not match", sessionId, sessions[0].getId()); - manager.remove(session); - } - - @Test - public void testGetSession(){ - ClusterSession session = (ClusterSession) manager.createSession(sessionId); - session.setAttribute(ATTRIBUTE_NAME, AUTH_TYPE); - manager.add(session); - HashMap sessionAttributes = manager.getSession(sessionId); - assertNotNull("Session attribute should not be null", sessionAttributes); - assertEquals("Session attribute size does not match", 1, sessionAttributes.size()); - assertEquals("Session attribute size does not match", AUTH_TYPE, sessionAttributes.get(ATTRIBUTE_NAME)); - manager.remove(session); - } - - @AfterClass - public static void cleanup(){ - try { - manager.stopInternal(); - } catch (LifecycleException e) { - } - } - -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionServiceImplTest.java b/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionServiceImplTest.java deleted file mode 100644 index 1835db5976..0000000000 --- a/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionServiceImplTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.opendaylight.controller.clustersession; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.apache.catalina.Context; -import org.apache.catalina.Session; -import org.apache.catalina.util.SessionIdGenerator; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustersession.impl.ClusterSessionServiceImpl; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -@RunWith(PowerMockRunner.class) -@PrepareForTest({FrameworkUtil.class}) -public class ClusterSessionServiceImplTest { - static ClusterSessionManager manager = null; - static ClusterSessionServiceImpl sessionService = null; - private static final String SESSION_CACHE = "customSessionManager.sessionData"; - static ConcurrentMap sessions = new ConcurrentHashMap(); - private String sessionId = "1234567"; - final String AUTH_TYPE = "FORM"; - final String ATTRIBUTE_NAME = "AuthType"; - - @SuppressWarnings("unchecked") - @BeforeClass - public static void init(){ - Bundle bundle = mock(Bundle.class); - BundleContext context = mock(BundleContext.class); - IClusterGlobalServices clusterGlobalService = mock(IClusterGlobalServices.class); - ServiceReference serviceReference = mock(ServiceReference.class); - PowerMockito.mockStatic(FrameworkUtil.class); - when(FrameworkUtil.getBundle(ClusterSessionManager.class)).thenReturn(bundle); - when(bundle.getBundleContext()).thenReturn(context); - when(context.getService(serviceReference)).thenReturn(clusterGlobalService); - when((ConcurrentMap)clusterGlobalService.getCache(SESSION_CACHE)).thenReturn(sessions); - Context containerContext = mock(Context.class); - manager = new ClusterSessionManager(); - sessionService = (ClusterSessionServiceImpl) manager.getSessionService(); - manager.setContainer(containerContext); - sessionService.startInternal(new SessionIdGenerator()); - sessionService.addingService(serviceReference); - } - - @Test - public void testCreateEmptySession(){ - Session session = sessionService.createEmptySession(); - assertEquals("session manager does not match", manager, session.getManager()); - } - - @Test - public void testCreateSessionwithRandomId(){ - Session session = sessionService.createSession(null); - assertEquals("Session should be valid", true, session.isValid()); - sessionService.removeSession(session.getId()); - } - - @Test - public void testCreateSession(){ - Session session = sessionService.createSession(sessionId); - assertEquals("Session should be valid", true, session.isValid()); - assertEquals("Session id does not match", sessionId, session.getId()); - sessionService.removeSession(sessionId); - } - - @Test - public void testNullfindSession() { - Session session = sessionService.findSession(null); - assertNull("Session should be null", session); - } - - @Test - public void testSessionCRUD(){ - Session foundSession = sessionService.findSession(sessionId); - assertNull("Session should not exist here", foundSession); - Session session = sessionService.createSession(sessionId); - foundSession = sessionService.findSession(sessionId); - assertEquals("Session was not added", sessionId, foundSession.getId()); - session.setAuthType(AUTH_TYPE); - sessionService.updateSession((ClusterSession)session); - foundSession = sessionService.findSession(sessionId); - assertEquals("Session was not found, id does not match", sessionId, foundSession.getId()); - assertEquals("Session was not found, auth type does match", AUTH_TYPE, foundSession.getAuthType()); - sessionService.removeSession(sessionId); - foundSession = sessionService.findSession(sessionId); - assertEquals("Session was not removed", null, foundSession); - } - - @Test - public void testExpireSession(){ - Session session = sessionService.createSession(sessionId); - session.setAuthType(AUTH_TYPE); - sessionService.addSession((ClusterSession)session); - Session foundSession = sessionService.findSession(sessionId); - assertEquals("Session was not found", sessionId, foundSession.getId()); - sessionService.expireSession(sessionId); - foundSession = sessionService.findSession(sessionId); - assertEquals("Session was not expired", null, foundSession); - } - - @Test - public void testFindSessions(){ - Session session = sessionService.createSession(sessionId); - session.setAuthType(AUTH_TYPE); - sessionService.addSession((ClusterSession)session); - Session[] sessions = sessionService.findSessions(); - assertEquals("Session array size does not match", 1, sessions.length); - assertEquals("Session array size does not match", sessionId, sessions[0].getId()); - sessionService.removeSession(sessionId); - } - - @Test - public void testGetSession(){ - ClusterSession session = (ClusterSession) sessionService.createSession(sessionId); - session.setAttribute(ATTRIBUTE_NAME, AUTH_TYPE); - HashMap sessionAttributes = sessionService.getSession(sessionId); - assertNotNull("Session attribute should not be null", sessionAttributes); - assertEquals("Session attribute size does not match", 1, sessionAttributes.size()); - assertEquals("Session attribute size does not match", AUTH_TYPE, sessionAttributes.get(ATTRIBUTE_NAME)); - sessionService.removeSession(sessionId); - } - - @Test - public void testNullSessionCache(){ - ClusterSessionManager clustermanager = new ClusterSessionManager(); - ClusterSessionServiceImpl service = new ClusterSessionServiceImpl(clustermanager); - Session session = service.findSession(sessionId); - assertNull("Session should be null, as cache is null", session); - Session[] sessions = service.findSessions(); - assertEquals("Session array should be empty", 0, sessions.length); - service.removeSession(sessionId); - service.expireSession(sessionId); - session = service.createSession(sessionId); - assertNull("Session should be null, as cache is null", session); - service.addSession(null); - Map attributes = service.getSession(sessionId); - assertNull("Attributes should be null, as cache is null", attributes); - service.updateSession(null); - } - - @AfterClass - public static void cleanup(){ - sessionService.stopInternal(); - } -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionUtilTest.java b/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionUtilTest.java deleted file mode 100644 index 563b2be63c..0000000000 --- a/opendaylight/adsal/samples/clustersession/src/test/java/org/opendaylight/controller/clustersession/ClusterSessionUtilTest.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.opendaylight.controller.clustersession; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInput; -import java.io.ObjectInputStream; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.apache.catalina.authenticator.Constants; -import org.apache.catalina.authenticator.SavedRequest; -import org.apache.catalina.realm.GenericPrincipal; -import org.junit.Test; -import org.opendaylight.controller.clustersession.impl.ClusterSessionServiceImpl; -import org.opendaylight.controller.clustersession.service.ClusterSessionService; - - -public class ClusterSessionUtilTest { - - final String AUTH_TYPE = "FORM"; - final String ADMIN = "admin"; - final String REQUEST_URI = "/test"; - final String BLANK = ""; - final String HEADER_NAME = "ContentType"; - final String HEADER_VALUE = "JSON"; - final long creationTime = 54545454L; - final int interval = 0; - ClusterSessionManager manager = new ClusterSessionManager(); - ClusterSessionService sessionService = new ClusterSessionServiceImpl(manager); - - @Test - public void testNullSerializableClusterSession() { - ClusterSessionData sessionData = ClusterSessionUtil.getSerializableSession(null); - assertEquals("Session data should be null for null session", null, sessionData); - } - - @Test - public void testSerializableClusterSession() { - ClusterSession customSession = createClusterSesion(); - ClusterSessionData sessionData = ClusterSessionUtil.getSerializableSession(customSession); - assertEquals("Session authentication type not valid", AUTH_TYPE, sessionData.getAuthType()); - assertEquals("Session username does not match", ADMIN, sessionData.getUserName()); - assertEquals("Session password does not match", ADMIN, sessionData.getPassword()); - assertEquals("Session prinicpal does not match", ADMIN, sessionData.getSession().getPrincipal().getName()); - } - - @Test - public void testNullDeserialzableclusterSession() { - ClusterSession session = ClusterSessionUtil.getDeserializedSession(null, sessionService, manager); - assertEquals("Session should be null for null session data", null, session); - } - - @Test - public void testDeserializableClusterSesion() { - ClusterSession customSession = createClusterSesion(); - ClusterSessionData sessionData = ClusterSessionUtil.getSerializableSession(customSession); - customSession = sessionData.getSession(); - customSession.setAuthType(AUTH_TYPE); - customSession.setNote(Constants.FORM_PRINCIPAL_NOTE, BLANK); - customSession.setNote(Constants.FORM_REQUEST_NOTE, BLANK); - ClusterSession session = ClusterSessionUtil.getDeserializedSession(sessionData, sessionService, manager); - assertEquals("Session authentication type not valid", AUTH_TYPE, session.getAuthType()); - assertEquals("prinicpal name is not valid", ADMIN, session.getPrincipal().getName()); - SavedRequest savedRequest = (SavedRequest)session.getNote(Constants.FORM_REQUEST_NOTE); - assertEquals("saved request uri does not match", REQUEST_URI, savedRequest.getRequestURI()); - assertEquals("saved request header does not match", HEADER_VALUE, savedRequest.getHeaderValues(HEADER_NAME).next()); - assertEquals("saved request header does not match", Locale.ENGLISH, savedRequest.getLocales().next()); - String username = (String)session.getNote(Constants.FORM_USERNAME); - assertEquals("username does not match", ADMIN, username); - String password = (String)session.getNote(Constants.FORM_PASSWORD); - assertEquals("password does not match", ADMIN, password); - assertEquals("session manager does not match", manager, session.getManager()); - assertEquals("session creation time does not match", creationTime, session.getCreationTime()); - assertEquals("session man inactive interval does not match", interval, session.getMaxInactiveInterval()); - assertEquals("is session new does not match", true, session.isNew()); - assertEquals("is session valid does not match", true, session.isValid()); - } - - @Test - public void testSerializationtoFile(){ - ClusterSession customSession = createClusterSesion(); - ClusterSessionData sessionData = ClusterSessionUtil.getSerializableSession(customSession); - try( - OutputStream file = new FileOutputStream("sessionData.ser"); - OutputStream buffer = new BufferedOutputStream(file); - ObjectOutput output = new ObjectOutputStream(buffer); - ){ - output.writeObject(sessionData); - } - catch(IOException ex){ - fail("IO exception while serializing object to a file."); - } - try( - InputStream file = new FileInputStream("sessionData.ser"); - InputStream buffer = new BufferedInputStream(file); - ObjectInput input = new ObjectInputStream (buffer); - ){ - //deserialize the session - ClusterSessionData recovedSession = (ClusterSessionData)input.readObject(); - //display its data - ClusterSession session = ClusterSessionUtil.getDeserializedSession(recovedSession, sessionService, manager); - assertEquals("Session authentication type not valid", AUTH_TYPE, session.getAuthType()); - assertEquals("prinicpal name is not valid", ADMIN, session.getPrincipal().getName()); - SavedRequest savedRequest = (SavedRequest)session.getNote(Constants.FORM_REQUEST_NOTE); - assertEquals("saved request uri is not valid", REQUEST_URI, savedRequest.getRequestURI()); - assertEquals("saved request header does not match", HEADER_VALUE, savedRequest.getHeaderValues(HEADER_NAME).next()); - assertEquals("saved request header does not match", Locale.ENGLISH, savedRequest.getLocales().next()); - String username = (String)session.getNote(Constants.FORM_USERNAME); - assertEquals("username does not match", ADMIN, username); - String password = (String)session.getNote(Constants.FORM_PASSWORD); - assertEquals("password does not match", ADMIN, password); - } - catch(ClassNotFoundException ex){ - fail("Exception in object deserialization from file"); - } - catch(IOException ex){ - fail("Exception in object deserialization from file"); - } - File serializedFile = new File("sessionData.ser"); - serializedFile.delete(); - } - - private ClusterSession createClusterSesion(){ - ClusterSession clusterSession = new ClusterSession(manager, sessionService); - clusterSession.setAuthType(AUTH_TYPE); - clusterSession.setCreationTime(creationTime); - clusterSession.setMaxInactiveInterval(interval); - clusterSession.setNew(true); - clusterSession.setValid(true); - List roles = new ArrayList(); - roles.add(ADMIN); - GenericPrincipal principal = new GenericPrincipal(ADMIN, ADMIN, roles); - clusterSession.setPrincipal(principal); - clusterSession.setNote(Constants.FORM_PRINCIPAL_NOTE, principal); - SavedRequest savedRequest = new SavedRequest(); - savedRequest.setRequestURI(REQUEST_URI); - savedRequest.addHeader(HEADER_NAME, HEADER_VALUE); - savedRequest.addLocale(Locale.ENGLISH); - clusterSession.setNote(Constants.FORM_REQUEST_NOTE, savedRequest); - clusterSession.setNote(Constants.FORM_USERNAME, ADMIN); - clusterSession.setNote(Constants.FORM_PASSWORD, ADMIN); - return clusterSession; - } -} diff --git a/opendaylight/adsal/samples/loadbalancer/pom.xml b/opendaylight/adsal/samples/loadbalancer/pom.xml deleted file mode 100644 index d8d72a2da8..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/pom.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - samples.loadbalancer - 0.7.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - topologymanager - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.samples.loadbalancer, - org.opendaylight.controller.samples.loadbalancer.entities, - org.opendaylight.controller.samples.loadbalancer.internal, - org.opendaylight.controller.samples.loadbalancer.policies - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.routing, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.packet.address, - org.opendaylight.controller.hosttracker, - org.opendaylight.controller.hosttracker.hostAware, - org.opendaylight.controller.samples.loadbalancer, - org.opendaylight.controller.samples.loadbalancer.entities, - org.opendaylight.controller.samples.loadbalancer.internal, - org.opendaylight.controller.samples.loadbalancer.policies, - org.opendaylight.controller.topologymanager, - org.opendaylight.controller.forwardingrulesmanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.clustering.services, - javax.xml.bind.annotation, - javax.xml.bind, - org.apache.felix.dm, - org.apache.commons.lang3.builder, - org.osgi.service.component, - org.slf4j, - org.eclipse.osgi.framework.console, - org.osgi.framework - org.opendaylight.controller.samples.loadbalancer.internal.Activator - - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/ConfigManager.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/ConfigManager.java deleted file mode 100644 index e7b261c8a2..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/ConfigManager.java +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; - -import org.opendaylight.controller.samples.loadbalancer.entities.Pool; -import org.opendaylight.controller.samples.loadbalancer.entities.PoolMember; -import org.opendaylight.controller.samples.loadbalancer.entities.VIP; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class represents a configuration manager for the Load Balancer service. - * This class is responsible for managing(store/update/delete) the load balancer - * configuration that it receives through REST APIs or from any other applications - * present in the controller. - * - */ -public class ConfigManager implements IConfigManager{ - - /* - * Logger instance - */ - private static final Logger cmLogger = LoggerFactory.getLogger(ConfigManager.class); - - /* - * All the available VIPs - */ - private HashMap vips = new HashMap(); - - /* - * All the available Pools - */ - private HashMap pools = new HashMap(); - - public ConfigManager(){ - } - - @Override - public boolean vipExists(String name) { - return this.vips.containsKey(name); - } - - @Override - public boolean vipExists(VIP vip){ - if(vip.getName()==null){ - if(!vips.containsValue(vip)){ - return false; - } - }else{ - if(!vips.containsKey(vip.getName())){ - if(!vips.containsValue(vip)){ - return false; - } - } - } - return true; - } - - @Override - public boolean vipExists(String name,String ip,String protocol,short protocolPort,String poolName){ - - VIP vip = new VIP(name,ip,protocol,protocolPort,poolName); - - //Check VIP with the same name - - if(!vips.containsKey(name)){ - //Check VIP with the same ip, protocol and protocolPort - if(!vips.containsValue(vip)){ - - //if you reach here, means this VIP don't exist - return false; - } - } - - //Yeah, i have it. - return true; - } - - @Override - public Set getAllVIPs(){ - return new HashSet(this.vips.values()); - } - - public VIP getVIPWithPoolName(VIP vip){ - cmLogger.trace("Search a VIP with name:{}",vip); - for(VIP vipTemp: this.vips.values()){ - if(vipTemp.equals(vip)){ - - cmLogger.trace("Found VIP with pool detail : {}",vipTemp); - return vipTemp; - } - } - - cmLogger.trace("VIP with pool detail not found "); - return null; - } - - @Override - public VIP createVIP(String name,String ip,String protocol,short protocolPort,String poolName){ - - cmLogger.trace("Create VIP with the following details :[ name : "+name - +" ip : "+ip - +" protocol : "+protocol - +" protocol_port : "+protocolPort - +" pool name : "+poolName); - - VIP vip = new VIP(name,ip,protocol,protocolPort,poolName); - - if(poolName !=null && !poolName.isEmpty()){ - if(pools.containsKey(poolName)){ - pools.get(poolName).addVIP(vip); - } - } - - vip.setStatus(LBConst.STATUS_ACTIVE); - this.vips.put(name, vip); - - cmLogger.trace("New VIP created : "+vip.toString()); - return vip; - } - - @Override - public String getVIPAttachedPool(String name) { - return this.vips.get(name).getPoolName(); - } - - @Override - public VIP updateVIP(String name, String poolName){ - - cmLogger.trace("Updating VIP : "+name+" pool name to "+poolName); - - if(vips.containsKey(name)){ - VIP vip = vips.get(name); - if(vip.getPoolName() == null){ - vip.setPoolName(poolName); - cmLogger.error("VIP is now attached to the pool : {}",vip.toString()); - return vip; - } - cmLogger.error("VIP is already attached to one pool : {}",vip.toString()); - } - cmLogger.error("VIP with name: "+name+" does not exist"); - return null; - } - - @Override - public VIP deleteVIP(String name){ - - cmLogger.trace("Deleting VIP : "+name); - - VIP vip = vips.get(name); - - String poolName = vip.getPoolName(); - - if(poolName != null){ - if(pools.containsKey(poolName)){ - Pool pool = pools.get(poolName); - pool.removeVIP(vip.getName()); - } - } - - cmLogger.trace("VIP removed : "+vip.toString()); - - vips.remove(vip.getName()); - - return vip; - } - - @Override - public boolean memberExists(String name, String poolName) { - if (this.pools.containsKey(poolName)) { - if (this.pools.get(poolName).getMember(name) != null) { - return true; - } - } - return false; - } - - @Override - public boolean memberExists(String name, String memberIP,String poolName) { - if (!this.pools.containsKey(poolName)) { - return false; - } - - return this.pools.get(poolName).poolMemberExists(new PoolMember(name, memberIP, poolName)); - } - - @Override - public PoolMember addPoolMember(String name, String memberIP, String poolName){ - - PoolMember pm = new PoolMember(name,memberIP,poolName); - - cmLogger.trace("Adding pool member : "+pm.toString()); - - pools.get(poolName).addMember(pm); - - return pm; - } - - @Override - public PoolMember removePoolMember(String name, String poolName){ - - cmLogger.trace("Removing pool member : {} from pool {}",name, poolName); - - Pool pool = pools.get(poolName); - - PoolMember pm = pool.getMember(name); - - pool.removeMember(name); - - cmLogger.trace("Pool member {} removed from {} ",name,poolName); - - return pm; - } - - @Override - public Set getAllPools(){ - return new HashSet(this.pools.values()); - } - - @Override - public boolean poolExists(String name) { - return this.pools.containsKey(name); - } - - @Override - public boolean poolExists(String name, String lbMethod){ - - return pools.containsValue(new Pool(name,lbMethod)); - } - - @Override - public Pool createPool(String name, String lbMethod){ - - Pool newPool = new Pool(name,lbMethod); - - cmLogger.trace("New pool created : " + newPool.toString()); - - pools.put(name, newPool); - - return newPool; - } - - @Override - public Pool deletePool(String poolName){ - - Pool pool = pools.get(poolName); - - for(VIP vip:pool.getAllVip()){ - - vip.setPoolName(null); - - } - - cmLogger.trace("Pool removed : "+pool.toString()); - - pools.remove(poolName); - - return pool; - } - - @Override - public Pool getPool( String poolName){ - if(pools.containsKey(poolName)){ - return pools.get(poolName); - } - return null; - } - - @Override - public Set getAllPoolMembers(String poolName) { - - if(pools.containsKey(poolName)){ - return new HashSet(pools.get(poolName).getAllMembers()); - } - return null; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "ConfigManager [vips=" + vips + ", pools=" + pools + "]"; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/IConfigManager.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/IConfigManager.java deleted file mode 100644 index 5e55b2a3dd..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/IConfigManager.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer; - -import java.util.Set; - -import org.opendaylight.controller.samples.loadbalancer.entities.Pool; -import org.opendaylight.controller.samples.loadbalancer.entities.PoolMember; -import org.opendaylight.controller.samples.loadbalancer.entities.VIP; - -/** - * Interface implemented by the configuration manager. - * - */ -public interface IConfigManager { - - /** - * Return all existing VIPs - * @return Set of VIP's - * if there is no VIP, it will return empty set. - */ - public Set getAllVIPs(); - - /** - * Check if VIP with the 'name' exists - * @param name Name of the VIP - * @return true if exists - * false else - */ - public boolean vipExists(String name); - - /** - * Check if VIP exists with the details 'VIP' - * @param vip Search for this VIP - * @return true if exists - * false else - */ - public boolean vipExists(VIP vip); - - /** - * Check if VIP with the provided details exists - * @param name Name of the VIP - * @param ip IP of the VIP - * @param protocol IP Protocol of the VIP (TCP/UDP) - * @param protocolPort Transport port of the VIP (e.g 5550) - * @param poolName Name of the pool attached with the VIP - * @return true if exists - * false else - */ - public boolean vipExists(String name,String ip,String protocol,short protocolPort,String poolName); - - /** - * Add VIP to the configuration - * @param name Name of the VIP - * @param ip IP of the VIP - * @param protocol IP Protocol of the VIP (TCP/UDP) - * @param protocolPort Transport port of the VIP - * @param poolName Name of the pool that VIP will use for load balancing its traffic - * @return Newly created VIP - */ - public VIP createVIP(String name,String ip,String protocol,short protocolPort,String poolName); - - /** - * Return pool attached to VIP - * @param name Name of the VIP - * @return Name of the pool attached to VIP - * else null - */ - public String getVIPAttachedPool(String name); - /** - * Update pool name of the VIP. - * @param name Name of the VIP - * @param poolName Attach this pool to VIP - * @return Updated VIP If successful - * null If this VIP is already attached to any existing pool. - */ - public VIP updateVIP(String name, String poolName); - - /** - * Delete the VIP - * @param name Delete VIP with this name - * @return Details of the deleted VIP - */ - public VIP deleteVIP(String name); - - /** - * Check if pool member with the 'name' present in the pool with name 'poolName' - * @param name Name of the pool member - * @param poolName Name of the pool, you want to search for pool member - * @return true If exist - * false else - */ - public boolean memberExists(String name, String poolName); - - /** - * Check if pool member with name 'name' and IP 'memberIP' exist in the pool 'poolName' - * @param name Name of the pool member - * @param memberIP IP of the pool member - * @param poolName Name of the pool member you want to search - * @return true If Exist - * false else - */ - public boolean memberExists(String name, String memberIP,String poolName); - - /** - * Return all pool members of the pool 'poolName' - * @param poolName Name of the pool - * @return Set of all the pool members if pool with the name present in the configuration - * null else - * - */ - public Set getAllPoolMembers(String poolName); - - /** - * Add new pool member to the configuration - * @param name Name of the pool - * @param memberIP IP of the pool - * @param poolName Attach pool member to this pool - * @return Newly created pool member - */ - public PoolMember addPoolMember(String name, String memberIP, String poolName); - - /** - * Remove pool member from the pool - * @param name Name of the pool member - * @param poolName Name of the pool - * @return Details of the removed pool member - */ - public PoolMember removePoolMember(String name, String poolName); - - /** - * Return all the existing pools - * @return Set of Pools - */ - public Set getAllPools(); - - /** - * Return pool with input name - * @param poolName Name of the pool - * @return Details of the pool if pool exist - * null else - */ - public Pool getPool(String poolName); - - /** - * Check if pool exists with the input name - * @param name Name of the pool - * @return true If exists - * false else - */ - public boolean poolExists(String name); - - /** - * Check if pool exists with the input name and loadbalancing method. - * @param name Name of the pool - * @param lbMethod Load balancing method name - * @return true If exists - * false else - */ - public boolean poolExists(String name, String lbMethod); - - /** - * Create new pool with the provided details - * @param name Name of the pool - * @param lbMethod Load balancing method this pool will use - * @return Details of the newly created pool - */ - public Pool createPool(String name, String lbMethod); - - /** - * Delete pool with the provided name - * @param poolName Name of the pool - * @return Details of the deleted pool - */ - public Pool deletePool(String poolName); - -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBConst.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBConst.java deleted file mode 100644 index bd6fb473c1..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBConst.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer; - -/** - * Class defines all the constants used by load balancer service - * - */ -public class LBConst { - - public static final int FORWARD_DIRECTION_LB_FLOW = 0; - - public static final int REVERSE_DIRECTION_LB_FLOW = 1; - - public static final String ROUND_ROBIN_LB_METHOD = "roundrobin"; - - public static final String RANDOM_LB_METHOD = "random"; - - public static final String STATUS_ACTIVE="active"; - - public static final String STATUS_INACTIVE="inactive"; - - public static final String STATUS_PENDING="pending"; - - public static final String STATUS_ERROR="error"; - -} diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBUtil.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBUtil.java deleted file mode 100644 index 729a49ba5c..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/LBUtil.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer; - -import org.opendaylight.controller.sal.packet.IPv4; -import org.opendaylight.controller.sal.packet.Packet; -import org.opendaylight.controller.sal.packet.TCP; -import org.opendaylight.controller.sal.packet.UDP; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.samples.loadbalancer.entities.Client; -import org.opendaylight.controller.samples.loadbalancer.entities.VIP; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class defines utilty methods that will be used by different components - * of the load balancer service - * - */ -public class LBUtil { - - private static final Logger lbuLogger = LoggerFactory.getLogger(LBUtil.class); - - public LBUtil(){} - - /** - * Extract the details of the source machine that sent this packet 'inPkt' - * @param inPkt Packet that is received by the controller - * @return Details of the source machine in Client object. - */ - public Client getClientFromPacket(IPv4 inPkt){ - lbuLogger.trace("Find client information from packet : {}",inPkt.toString()); - - String ip = NetUtils.getInetAddress(inPkt.getSourceAddress()).getHostAddress(); - - String protocol = IPProtocols.getProtocolName(inPkt.getProtocol()); - - lbuLogger.trace("client ip {} and protocl {}",ip,protocol); - - Packet tpFrame= inPkt.getPayload(); - - lbuLogger.trace("Get protocol layer {}",tpFrame.toString()); - - short port = 0; - - if(protocol.equals(IPProtocols.TCP.toString())){ - TCP tcpFrame = (TCP)tpFrame; - port = tcpFrame.getSourcePort(); - }else{ - UDP udpFrame = (UDP)tpFrame; - port = udpFrame.getSourcePort(); - } - - lbuLogger.trace("Found port {}",port); - - Client source = new Client(ip, protocol,port); - - lbuLogger.trace("Client information : {}",source.toString()); - - return source; - } - - /** - * Extract the details of the destination machine where this packet 'inPkt' need - * to be delivered - * @param inPkt Packet that is received by controller for forwarding - * @return Details of the destination machine packet in VIP - */ - public VIP getVIPFromPacket(IPv4 inPkt){ - - lbuLogger.trace("Find VIP information from packet : {}",inPkt.toString()); - - String ip = NetUtils.getInetAddress(inPkt.getDestinationAddress()).getHostAddress(); - - String protocol = IPProtocols.getProtocolName(inPkt.getProtocol()); - - Packet tpFrame= inPkt.getPayload(); - - short port = 0; - - if(protocol.equals(IPProtocols.TCP.toString())){ - TCP tcpFrame = (TCP)tpFrame; - port = tcpFrame.getDestinationPort(); - }else{ - - UDP udpFrame = (UDP)tpFrame; - port = udpFrame.getDestinationPort(); - } - - VIP dest = new VIP(null,ip, protocol,port,null); - - lbuLogger.trace("VIP information : {}",dest.toString()); - - return dest; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Client.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Client.java deleted file mode 100644 index a16582d532..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Client.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.entities; - -/** - * This class represents the source host that sends any traffic to any existing virtual IP (VIP). - * This source host is referred to as a 'Client'. Clients will be differentiated from each other - * based on the following three properties: - * 1. IP address of the client. - * 2. Protocol of the traffic it is using for sending traffic - * 3. Source port from which it is sending traffic. - * e.g TCP traffic from two different ports from the same host to a given VIP will be considered - * as two different clients by this service. Similarly, traffic using two different protocols - * (TCP, UDP) from the same host will be considered as two different clients. - * - */ -public class Client { - - /* - * IP address of the client (source address) - */ - private String ip; - - /* - * Network protocol of the traffic sent by client - */ - private String protocol; - - /* - * Port used to send network traffic (source port) - */ - private short port; - - public Client(String ip, String protocol, short port){ - this.ip = ip; - this.protocol = protocol; - this.port = port; - } - - /** - * @return the client IP - */ - public String getIp() { - return ip; - } - - /** - * @param ip the IP to set - */ - public void setIp(String ip) { - this.ip = ip; - } - - /** - * @return the client network protocol - */ - public String getProtocol() { - return protocol; - } - - /** - * @param protocol the protocol to set - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - /** - * @return the client port - */ - public short getPort() { - return port; - } - - /** - * @param port the port to set - */ - public void setPort(short port) { - this.port = port; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((ip == null) ? 0 : ip.hashCode()); - result = prime * result + port; - result = prime * result+ ((protocol == null) ? 0 : protocol.hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof Client)) { - return false; - } - Client other = (Client) obj; - if (ip == null) { - if (other.ip != null) { - return false; - } - }else if (!ip.equals(other.ip)) { - return false; - } - if (port != other.port) { - return false; - } - if (protocol == null) { - if (other.protocol != null) { - return false; - } - }else if (!protocol.equals(other.protocol)) { - return false; - } - return true; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "Client [ip=" + ip + ", protocol=" + protocol + ", port=" + port+ "]"; - } -} diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Pool.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Pool.java deleted file mode 100644 index 86e6a360dd..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/Pool.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.entities; - -import java.util.ArrayList; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * This class represents the pool of hosts among which incoming traffic - * will be load balanced. Each pool will load balance the traffic among its pool members - * based on the loadbalancing policy set for the pool. - * Currently, the pool supports two load balancing policies: - * 1. Round Robin Policy{@link org.opendaylight.controller.samples.loadbalancer.policies.RoundRobinLBPolicy} - * 2. Random Policy {@link org.opendaylight.controller.samples.loadbalancer.policies.RandomLBPolicy} - * - * NOTE: After creation of the pool, user can't update (change) its load balancing policy. - * NOTE: Each Pool should have a unique name. - */ - -@XmlRootElement(name="pool") -@XmlAccessorType(XmlAccessType.NONE) -public class Pool { - - /* - * Unique name of the pool - */ - @XmlElement - private String name; - - /* - * Associated load balancing policy - */ - @XmlElement(name="lbmethod") - private String lbMethod; - - /* - * Status of the pool (active/inactive) - */ - @XmlElement - private String status; - - /* - * List of all the VIPs using this pool for load balancing their traffic - more than - * one VIP can be mapped to each pool. - */ - @XmlElement - private ArrayList vips = new ArrayList(); - - /* - * List of all the pool members used for load balancing the traffic - */ - @XmlElement - private ArrayList members = new ArrayList(); - - /* - * Private constructor used for JAXB mapping - */ - @SuppressWarnings("unused") - private Pool() {} - - /** - * Getter/ Setter methods - */ - - public Pool(String name, - String lbMethod) { - this.name = name; - this.lbMethod = lbMethod; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the lbMethod - */ - public String getLbMethod() { - return lbMethod; - } - - /** - * @param lbMethod the lbMethod to set - */ - public void setLbMethod(String lbMethod) { - this.lbMethod = lbMethod; - } - - /** - * @return the status - */ - public String getStatus() { - return status; - } - - /** - * @param status the status to set - */ - public void setStatus(String status) { - this.status = status; - } - - /** - * @return the vip - */ - public ArrayList getAllVip() { - return vips; - } - - /** - * @param vip the vip to set - */ - public void setVips(ArrayList vips) { - this.vips = vips; - } - - /** - * @return the members - */ - public ArrayList getAllMembers() { - return members; - } - - /** - * @param members the members to set - */ - public void setMembers(ArrayList members) { - this.members = members; - } - - /** - * Add new VIP to the VIP list - * @param vip new VIP to add - */ - public void addVIP(VIP vip){ - this.vips.add(vip); - } - - /** - * Remove VIP with given name from the VIP list of the pool - * @param name Name of the VIP - * @return true If VIP was using this pool and removed - * false IF VIP is not using this pool - */ - public boolean removeVIP(String name){ - for(VIP vip: this.vips){ - if(vip.getName().equals(name)){ - this.vips.remove(vip); - return true; - } - } - return false; - } - - /** - * Check if the given pool member is part of this pool - * @param pm Search for this pool member - * @return true If pool member is attached to this pool - * false else - */ - public boolean poolMemberExists(PoolMember pm){ - return this.members.contains(pm); - } - - /** - * Returns the pool member with the given name - * @param name Search for this pool member - * @return PoolMember If pool member is attached to this pool - * null else - */ - public PoolMember getMember(String name){ - - for(PoolMember pm: this.members){ - if(pm.getName().equals(name)){ - return pm; - } - } - return null; - } - - /** - * Add new pool member to the pool - * @param pm Add this new pool - */ - public void addMember(PoolMember pm){ - this.members.add(pm); - } - - /** - * Remove pool member from the pool list - * @param name Remove this pool member - * @return true If pool member was attached to this pool and successfully removed - * false If pool member is not attached to this pool - */ - public boolean removeMember(String name){ - for(PoolMember pm: this.members){ - if(pm.getName().equals(name)){ - this.members.remove(pm); - return true; - } - } - return false; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result+ ((lbMethod == null) ? 0 : lbMethod.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof Pool)) { - return false; - } - Pool other = (Pool) obj; - if (lbMethod == null) { - if (other.lbMethod != null) { - return false; - } - }else if (!lbMethod.equals(other.lbMethod)) { - return false; - } - if (name == null) { - if (other.name != null) { - return false; - } - }else if (!name.equals(other.name)) { - return false; - } - return true; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "Pool [name=" + name + ", lbMethod=" + lbMethod + ", status=" - + status + ", vips=" + vips + ", members=" + members + "]"; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/PoolMember.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/PoolMember.java deleted file mode 100644 index 31949b43d4..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/PoolMember.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.entities; - - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * This class represents the host where load balancing service will - * redirect VIP traffic for load balancing. All these hosts have to - * register with a pool to be a part of traffic load balancing. - * This entity is referred to as a 'PoolMember'. - * Load balancer service differentiates each pool member based on its - * two properties { ip address, attached pool }. - * A host (IP) can be attached to two different pools through creation of two - * different pool member objects. - * - * NOTE: Each pool member should have a unique name. - * - */ -@XmlRootElement(name="poolmember") -@XmlAccessorType(XmlAccessType.NONE) -public class PoolMember { - - /* - * Unique name of the pool member - */ - @XmlElement - private String name; - - /* - * IP address of the pool member - */ - @XmlElement - private String ip; - - /* - * Name of the pool this member is attached to. - */ - @XmlElement(name="poolname") - private String poolName; - - /* - * Status (active/inactive) - */ - @XmlElement - private String status; - - /** - * Private constructor used for JAXB mapping - */ - @SuppressWarnings("unused") - private PoolMember() {} - - public PoolMember(String name, String memberIP, String poolName){ - this.name = name; - this.ip = memberIP; - this.poolName = poolName; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the ip - */ - public String getIp() { - return ip; - } - - /** - * @param ip the ip to set - */ - public void setIp(String ip) { - this.ip = ip; - } - - /** - * @return the poolName - */ - public String getPoolName() { - return poolName; - } - - /** - * @param poolName the poolName to set - */ - public void setPoolName(String poolName) { - this.poolName = poolName; - } - - /** - * @return the status - */ - public String getStatus() { - return status; - } - - /** - * @param status the status to set - */ - public void setStatus(String status) { - this.status = status; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((ip == null) ? 0 : ip.hashCode()); - result = prime * result - + ((poolName == null) ? 0 : poolName.hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(obj instanceof PoolMember)) { - return false; - } - PoolMember other = (PoolMember) obj; - if (ip == null) { - if (other.ip != null) { - return false; - } - }else if (!ip.equals(other.ip)) { - return false; - } - if (poolName == null) { - if (other.poolName != null) { - return false; - } - }else if (!poolName.equals(other.poolName)) { - return false; - } - return true; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "PoolMember [name=" + name + ", ip=" + ip + ", poolName=" - + poolName + ", status=" + status + "]"; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/VIP.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/VIP.java deleted file mode 100644 index 22a7109f59..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/entities/VIP.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.entities; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * This class represents the Virtual IP (VIP) address exposed by the load balancer application. - * Load balancer service differentiates one VIP from the other, using the following three properties: - * 1. IP address of the VIP exposed by the application - * 2. Protocol of the network traffic (TCP/UDP) - * 3. Port to which incoming traffic is destined - * - * User is allowed to create mutliple VIPs with the same IP, but all such VIPs (with the same IP) - * should differ at least in the protocol or port or both. - * - * NOTE: Each VIP should have a unique name. - */ -@XmlRootElement(name="vip") -@XmlAccessorType(XmlAccessType.NONE) - -public class VIP { - - /* - * Unique name of the VIP - */ - @XmlElement - private String name; - - /* - * Virtual IP address of the VIP - */ - @XmlElement - private String ip; - - /* - * Network traffic protocol - */ - @XmlElement - private String protocol; - - /* - * Port where network traffic is destined (destination port) - */ - @XmlElement - private short port; - - /* - * Name of the pool attached to the VIP for load balancing its traffic - */ - @XmlElement(name="poolname") - private String poolName; - - /* - * Status (Active/inactive) - */ - @XmlElement - private String status; - - /** - * Private constructor used for JAXB mapping - */ - @SuppressWarnings("unused") - private VIP() {} - - public VIP(String name, - String ip, - String protocol, - short port, - String poolName){ - this.name = name; - this.ip=ip; - this.protocol=protocol; - this.port = port; - this.poolName = poolName; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getIp() { - return ip; - } - - public void setIp(String ip) { - this.ip = ip; - } - - public String getProtocol() { - return protocol; - } - - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - public short getPort() { - return port; - } - - public void setPort(short port) { - this.port = port; - } - - public String getPoolName() { - return poolName; - } - - public void setPoolName(String poolName) { - this.poolName = poolName; - } - - /** - * @return the status - */ - public String getStatus() { - return status; - } - - /** - * @param status the status to set - */ - public void setStatus(String status) { - this.status = status; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((ip == null) ? 0 : ip.hashCode()); - result = prime * result + port; - result = prime * result - + ((protocol == null) ? 0 : protocol.hashCode()); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - - } - if (obj == null) { - return false; - } - if (!(obj instanceof VIP)) { - return false; - } - - VIP other = (VIP) obj; - if (ip == null) { - if (other.ip != null) { - return false; - } - }else if (!ip.equals(other.ip)) { - return false; - } - if (port != other.port) { - return false; - } - if (protocol == null) { - if (other.protocol != null) { - return false; - } - }else if (!protocol.equalsIgnoreCase(other.protocol)) { - return false; - } - return true; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "VIP [name=" + name + ", ip=" + ip + ", protocol=" + protocol - + ", port=" + port + ", poolName=" + poolName + ", status=" - + status + "]"; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/Activator.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/Activator.java deleted file mode 100644 index 8979fecf45..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/Activator.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.internal; - -import java.util.Dictionary; -import java.util.Hashtable; - -import org.apache.felix.dm.Component; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.sal.routing.IRouting; -import org.opendaylight.controller.samples.loadbalancer.IConfigManager; - -/** - * Main application activator class for registering the dependencies and - * initialising the load balancer application. - * - */ - -public class Activator extends ComponentActivatorAbstractBase { - - /* - * Logger instance - */ - protected static final Logger logger = LoggerFactory.getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - public Object[] getImplementations() { - Object[] res = { LoadBalancerService.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(LoadBalancerService.class)) { - // export the service - Dictionary props = new Hashtable(); - props.put("salListenerName", "loadbalancer"); - - c.setInterface(new String[] { IListenDataPacket.class.getName(), - IConfigManager.class.getName()}, props); - - c.add(createContainerServiceDependency(containerName).setService( - IDataPacketService.class).setCallbacks( - "setDataPacketService", "unsetDataPacketService") - .setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - IRouting.class).setCallbacks("setRouting", "unsetRouting") - .setRequired(false)); - - c.add(createContainerServiceDependency(containerName).setService( - IfIptoHost.class).setCallbacks("setHostTracker", - "unsetHostTracker").setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - IForwardingRulesManager.class).setCallbacks( - "setForwardingRulesManager", "unsetForwardingRulesManager") - .setRequired(true)); - } - } - - /** - * Method which tells how many Global implementations are - * supported by the bundle. This way we can tune the number of - * components created. This components will be created ONLY at the - * time of bundle startup and will be destroyed only at time of - * bundle destruction, this is the major difference with the - * implementation retrieved via getImplementations where all of - * them are assumed to be in a container ! - * - * - * @return The list of implementations the bundle will support, - * in Global version - */ - protected Object[] getGlobalImplementations() { - return null; - } - - /** - * Configure the dependency for a given instance Global - * - * @param c Component assigned for this instance, this will be - * what will be used for configuration - * @param imp implementation to be configured - * @param containerName container on which the configuration happens - */ - protected void configureGlobalInstance(Component c, Object imp) { - } -} diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerService.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerService.java deleted file mode 100644 index b4836e9f17..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerService.java +++ /dev/null @@ -1,555 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Dictionary; -import java.util.List; -import java.util.Set; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.forwardingrulesmanager.FlowEntry; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; -import org.opendaylight.controller.hosttracker.HostIdFactory; -import org.opendaylight.controller.hosttracker.IHostId; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.action.SetDlDst; -import org.opendaylight.controller.sal.action.SetDlSrc; -import org.opendaylight.controller.sal.action.SetNwDst; -import org.opendaylight.controller.sal.action.SetNwSrc; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Path; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.packet.Ethernet; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.sal.packet.IPv4; -import org.opendaylight.controller.sal.packet.Packet; -import org.opendaylight.controller.sal.packet.PacketResult; -import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.routing.IRouting; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.IPProtocols; -import org.opendaylight.controller.samples.loadbalancer.ConfigManager; -import org.opendaylight.controller.samples.loadbalancer.IConfigManager; -import org.opendaylight.controller.samples.loadbalancer.LBConst; -import org.opendaylight.controller.samples.loadbalancer.LBUtil; -import org.opendaylight.controller.samples.loadbalancer.entities.Client; -import org.opendaylight.controller.samples.loadbalancer.entities.Pool; -import org.opendaylight.controller.samples.loadbalancer.entities.PoolMember; -import org.opendaylight.controller.samples.loadbalancer.entities.VIP; -import org.opendaylight.controller.samples.loadbalancer.policies.RandomLBPolicy; -import org.opendaylight.controller.samples.loadbalancer.policies.RoundRobinLBPolicy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class is the main class that represents the load balancer service. This - * is a sample load balancer application that balances traffic to backend - * servers based on the source address and source port on each incoming packet. - * The service reactively installs OpenFlow rules to direct all packets with a - * specific source address and source port to one of the appropriate backend - * servers. The servers may be chosen using a round robin policy or a random - * policy. This service can be configured via a REST APIs which are similar to - * the OpenStack Quantum LBaaS (Load-balancer-as-a-Service) v1.0 API proposal - * (http://wiki.openstack.org/Quantum/LBaaS) - * - * To use this service, a virtual IP (or VIP) should be exposed to the clients - * of this service and used as the destination address. A VIP is a entity that - * comprises of a virtual IP, port and protocol (TCP or UDP). Assumptions: 1. - * One or more VIPs may be mapped to the same server pool. All VIPs that share - * the same pool must also share the same load balancing policy (random or round - * robin). - * - * 2. Only one server pool can be be assigned to a VIP. - * - * 3. All flow rules are installed with an idle timeout of 5 seconds. - * - * 4. Packets to a VIP must leave the OpenFlow cluster from the same switch from - * where it entered it. - * - * 5. When you delete a VIP or a server pool or a server from a pool, the - * service does not delete the flow rules it has already installed. The flow - * rules should automatically time out after the idle timeout of 5 seconds. - * - */ -public class LoadBalancerService implements IListenDataPacket, IConfigManager { - - /* - * Logger instance - */ - private static Logger lbsLogger = LoggerFactory.getLogger(LoadBalancerService.class); - - /* - * Single instance of the configuration manager. Application passes this - * reference to all the new policies implemented for load balancing. - */ - private static ConfigManager configManager = new ConfigManager(); - - /* - * Round robing policy instance. Need to implement factory patterns to get - * policy instance. - */ - private static RoundRobinLBPolicy rrLBMethod = new RoundRobinLBPolicy(configManager); - - /* - * Random policy instance. - */ - private static RandomLBPolicy ranLBMethod = new RandomLBPolicy(configManager); - - /* - * Reference to the data packet service - */ - private IDataPacketService dataPacketService = null; - - /* - * Reference to the host tracker service - */ - private IfIptoHost hostTracker; - - /* - * Reference to the forwarding manager - */ - private IForwardingRulesManager ruleManager; - - /* - * Reference to the routing service - */ - private IRouting routing; - - /* - * Load balancer application installs all flows with priority 2. - */ - private static short LB_IPSWITCH_PRIORITY = 2; - - /* - * Name of the container where this application will register. - */ - private String containerName = null; - - /* - * Set/unset methods for the service instance that load balancer service - * requires - */ - public String getContainerName() { - if (containerName == null) { - return GlobalConstants.DEFAULT.toString(); - } - return containerName; - } - - void setDataPacketService(IDataPacketService s) { - this.dataPacketService = s; - } - - void unsetDataPacketService(IDataPacketService s) { - if (this.dataPacketService == s) { - this.dataPacketService = null; - } - } - - public void setRouting(IRouting routing) { - this.routing = routing; - } - - public void unsetRouting(IRouting routing) { - if (this.routing == routing) { - this.routing = null; - } - } - - public void setHostTracker(IfIptoHost hostTracker) { - lbsLogger.debug("Setting HostTracker"); - this.hostTracker = hostTracker; - } - - public void unsetHostTracker(IfIptoHost hostTracker) { - if (this.hostTracker == hostTracker) { - this.hostTracker = null; - } - } - - public void setForwardingRulesManager(IForwardingRulesManager forwardingRulesManager) { - lbsLogger.debug("Setting ForwardingRulesManager"); - this.ruleManager = forwardingRulesManager; - } - - public void unsetForwardingRulesManager(IForwardingRulesManager forwardingRulesManager) { - if (this.ruleManager == forwardingRulesManager) { - this.ruleManager = null; - } - } - - /** - * This method receives first packet of flows for which there is no matching - * flow rule installed on the switch. IP addresses used for VIPs are not - * supposed to be used by any real/virtual host in the network. Hence, any - * forwarding/routing service will not install any flows rules matching - * these VIPs. This ensures that all the flows destined for VIPs will not - * find a match in the switch and will be forwarded to the load balancing - * service. Service will decide where to route this traffic based on the - * load balancing policy of the VIP's attached pool and will install - * appropriate flow rules in a reactive manner. - */ - @Override - public PacketResult receiveDataPacket(RawPacket inPkt) { - - if (inPkt == null) { - return PacketResult.IGNORED; - } - - Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt); - - if (formattedPak instanceof Ethernet) { - byte[] vipMacAddr = ((Ethernet) formattedPak).getDestinationMACAddress(); - Object ipPkt = formattedPak.getPayload(); - - if (ipPkt instanceof IPv4) { - - lbsLogger.debug("Packet recieved from switch : {}", inPkt.getIncomingNodeConnector().getNode() - .toString()); - IPv4 ipv4Pkt = (IPv4) ipPkt; - if (IPProtocols.getProtocolName(ipv4Pkt.getProtocol()).equals(IPProtocols.TCP.toString()) - || IPProtocols.getProtocolName(ipv4Pkt.getProtocol()).equals(IPProtocols.UDP.toString())) { - - lbsLogger.debug("Packet protocol : {}", IPProtocols.getProtocolName(ipv4Pkt.getProtocol())); - Client client = new LBUtil().getClientFromPacket(ipv4Pkt); - VIP vip = new LBUtil().getVIPFromPacket(ipv4Pkt); - - if (configManager.vipExists(vip)) { - VIP vipWithPoolName = configManager.getVIPWithPoolName(vip); - String poolMemberIp = null; - if (vipWithPoolName.getPoolName() == null) { - lbsLogger.error("No pool attached. Please attach pool with the VIP -- {}", vip); - return PacketResult.IGNORED; - } - if (configManager.getPool(vipWithPoolName.getPoolName()).getLbMethod() - .equalsIgnoreCase(LBConst.ROUND_ROBIN_LB_METHOD)) { - - poolMemberIp = rrLBMethod.getPoolMemberForClient(client, vipWithPoolName); - } - - if (configManager.getPool(vipWithPoolName.getPoolName()).getLbMethod() - .equalsIgnoreCase(LBConst.RANDOM_LB_METHOD)) { - poolMemberIp = ranLBMethod.getPoolMemberForClient(client, vipWithPoolName); - } - - try { - - Node clientNode = inPkt.getIncomingNodeConnector().getNode(); - // HostTracker hosts db key scheme implementation - IHostId id = HostIdFactory.create(InetAddress.getByName(poolMemberIp), null); - HostNodeConnector hnConnector = this.hostTracker.hostFind(id); - - Node destNode = hnConnector.getnodeconnectorNode(); - - lbsLogger.debug("Client is connected to switch : {}", clientNode.toString()); - lbsLogger - .debug("Destination pool machine is connected to switch : {}", destNode.toString()); - - // Get path between both the nodes - NodeConnector forwardPort = null; - - if (clientNode.getNodeIDString().equals(destNode.getNodeIDString())) { - - forwardPort = hnConnector.getnodeConnector(); - - lbsLogger - .trace("Both source (client) and destination pool machine is connected to same switch nodes. Respective ports are - {},{}", - forwardPort, inPkt.getIncomingNodeConnector()); - - } else { - - Path route = this.routing.getRoute(clientNode, destNode); - - lbsLogger.trace("Path between source (client) and destination switch nodes : {}", - route.toString()); - - forwardPort = route.getEdges().get(0).getTailNodeConnector(); - - } - - if (installLoadBalancerFlow(client, vip, clientNode, poolMemberIp, - hnConnector.getDataLayerAddressBytes(), forwardPort, - LBConst.FORWARD_DIRECTION_LB_FLOW)) { - lbsLogger.trace("Traffic from client : {} will be routed " + "to pool machine : {}", - client, poolMemberIp); - } else { - lbsLogger.error("Not able to route traffic from client : {}", client); - } - - if (installLoadBalancerFlow(client, vip, clientNode, poolMemberIp, vipMacAddr, - inPkt.getIncomingNodeConnector(), LBConst.REVERSE_DIRECTION_LB_FLOW)) { - lbsLogger.trace("Flow rule installed to change the source ip/mac from " - + "pool machine ip {} to VIP {} for traffic coming pool machine", poolMemberIp, - vip); - } else { - lbsLogger.error("Not able to route traffic from client : {}", client); - } - } catch (UnknownHostException e) { - lbsLogger.error("Pool member not found in the network : {}", e.getMessage()); - lbsLogger.error("", e); - } - } - } - } - } - return PacketResult.IGNORED; - } - - /* - * This method installs the flow rule for routing the traffic between two - * hosts. - * - * @param source Traffic is sent by this source - * - * @param dest Traffic is destined to this destination (VIP) - * - * @param sourceSwitch Switch from where controller received the packet - * - * @param destMachineIp IP address of the pool member where traffic needs to - * be routed - * - * @param destMachineMac MAC address of the pool member where traffic needs - * to be routed - * - * @param outport Use this port to send out traffic - * - * @param flowDirection FORWARD_DIRECTION_LB_FLOW or - * REVERSE_DIRECTION_LB_FLOW - * - * @return true If flow installation was successful false else - * - * @throws UnknownHostException - */ - private boolean installLoadBalancerFlow(Client source, VIP dest, Node sourceSwitch, String destMachineIp, - byte[] destMachineMac, NodeConnector outport, int flowDirection) throws UnknownHostException { - - Match match = new Match(); - List actions = new ArrayList(); - - if (flowDirection == LBConst.FORWARD_DIRECTION_LB_FLOW) { - match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue()); - match.setField(MatchType.NW_SRC, InetAddress.getByName(source.getIp())); - match.setField(MatchType.NW_DST, InetAddress.getByName(dest.getIp())); - match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(dest.getProtocol())); - match.setField(MatchType.TP_SRC, source.getPort()); - match.setField(MatchType.TP_DST, dest.getPort()); - - actions.add(new SetNwDst(InetAddress.getByName(destMachineIp))); - actions.add(new SetDlDst(destMachineMac)); - } - - if (flowDirection == LBConst.REVERSE_DIRECTION_LB_FLOW) { - match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue()); - match.setField(MatchType.NW_SRC, InetAddress.getByName(destMachineIp)); - match.setField(MatchType.NW_DST, InetAddress.getByName(source.getIp())); - match.setField(MatchType.NW_PROTO, IPProtocols.getProtocolNumberByte(source.getProtocol())); - match.setField(MatchType.TP_SRC, dest.getPort()); - match.setField(MatchType.TP_DST, source.getPort()); - - actions.add(new SetNwSrc(InetAddress.getByName(dest.getIp()))); - actions.add(new SetDlSrc(destMachineMac)); - } - - actions.add(new Output(outport)); - - // Make sure the priority for IP switch entries is - // set to a level just above default drop entries - - Flow flow = new Flow(match, actions); - flow.setIdleTimeout((short) 5); - flow.setHardTimeout((short) 0); - flow.setPriority(LB_IPSWITCH_PRIORITY); - - String policyName = source.getIp() + ":" + source.getProtocol() + ":" + source.getPort(); - String flowName = null; - - if (flowDirection == LBConst.FORWARD_DIRECTION_LB_FLOW) { - flowName = "[" + policyName + ":" + source.getIp() + ":" + dest.getIp() + "]"; - } - - if (flowDirection == LBConst.REVERSE_DIRECTION_LB_FLOW) { - - flowName = "[" + policyName + ":" + dest.getIp() + ":" + source.getIp() + "]"; - } - - FlowEntry fEntry = new FlowEntry(policyName, flowName, flow, sourceSwitch); - - lbsLogger.trace("Install flow entry {} on node {}", fEntry.toString(), sourceSwitch.toString()); - - if (!this.ruleManager.checkFlowEntryConflict(fEntry)) { - if (this.ruleManager.installFlowEntry(fEntry).isSuccess()) { - return true; - } else { - lbsLogger.error("Error in installing flow entry to node : {}", sourceSwitch); - } - } else { - lbsLogger.error("Conflicting flow entry exists : {}", fEntry.toString()); - } - return false; - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init(Component c) { - Dictionary props = c.getServiceProperties(); - if (props != null) { - this.containerName = (String) props.get("containerName"); - - lbsLogger.trace("Running container name:" + this.containerName); - } else { - - // In the Global instance case the containerName is empty - this.containerName = ""; - } - lbsLogger.trace(configManager.toString()); - - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - } - - /* - * All the methods below are just proxy methods to direct the REST API - * requests to configuration manager. We need this redirection as currently, - * opendaylight supports only one implementation of the service. - */ - @Override - public Set getAllVIPs() { - return configManager.getAllVIPs(); - } - - @Override - public boolean vipExists(String name, String ip, String protocol, short protocolPort, String poolName) { - return configManager.vipExists(name, ip, protocol, protocolPort, poolName); - } - - @Override - public boolean vipExists(VIP vip) { - return configManager.vipExists(vip); - } - - @Override - public VIP createVIP(String name, String ip, String protocol, short protocolPort, String poolName) { - return configManager.createVIP(name, ip, protocol, protocolPort, poolName); - } - - @Override - public VIP updateVIP(String name, String poolName) { - return configManager.updateVIP(name, poolName); - } - - @Override - public VIP deleteVIP(String name) { - return configManager.deleteVIP(name); - } - - @Override - public boolean memberExists(String name, String memberIP, String poolName) { - return configManager.memberExists(name, memberIP, poolName); - } - - @Override - public Set getAllPoolMembers(String poolName) { - - return configManager.getAllPoolMembers(poolName); - } - - @Override - public PoolMember addPoolMember(String name, String memberIP, String poolName) { - return configManager.addPoolMember(name, memberIP, poolName); - } - - @Override - public PoolMember removePoolMember(String name, String poolName) { - - return configManager.removePoolMember(name, poolName); - } - - @Override - public Set getAllPools() { - - return configManager.getAllPools(); - } - - @Override - public Pool getPool(String poolName) { - return configManager.getPool(poolName); - } - - @Override - public boolean poolExists(String name, String lbMethod) { - return configManager.poolExists(name, lbMethod); - } - - @Override - public Pool createPool(String name, String lbMethod) { - return configManager.createPool(name, lbMethod); - } - - @Override - public Pool deletePool(String poolName) { - return configManager.deletePool(poolName); - } - - @Override - public boolean vipExists(String name) { - return configManager.vipExists(name); - } - - @Override - public boolean memberExists(String name, String poolName) { - return configManager.memberExists(name, poolName); - } - - @Override - public boolean poolExists(String name) { - return configManager.poolExists(name); - } - - @Override - public String getVIPAttachedPool(String name) { - return configManager.getVIPAttachedPool(name); - } -} diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/ILoadBalancingPolicy.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/ILoadBalancingPolicy.java deleted file mode 100644 index f9562d6c52..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/ILoadBalancingPolicy.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.policies; - -import org.opendaylight.controller.samples.loadbalancer.entities.Client; -import org.opendaylight.controller.samples.loadbalancer.entities.VIP; - -/** - * All new load balancer policies must implement this interface. - */ -public interface ILoadBalancingPolicy { - - /** - * Returns IP address of the next pool member from the pool - * to which the load balancer service can direct incoming packets. - * @param source source on the packet - * @param dest virtual IP (VIP) that is used as destination on the packet - * @return IP address of the next pool member which will serve - * all incoming traffic destined for the given VIP and with the given source - * information - */ - public String getPoolMemberForClient(Client source, VIP dest); - -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RandomLBPolicy.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RandomLBPolicy.java deleted file mode 100644 index c169d79799..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RandomLBPolicy.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.policies; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Random; - -import org.opendaylight.controller.samples.loadbalancer.ConfigManager; -import org.opendaylight.controller.samples.loadbalancer.entities.Client; -import org.opendaylight.controller.samples.loadbalancer.entities.Pool; -import org.opendaylight.controller.samples.loadbalancer.entities.PoolMember; -import org.opendaylight.controller.samples.loadbalancer.entities.VIP; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class implements the random load balancing policy. - * - */ -public class RandomLBPolicy implements ILoadBalancingPolicy { - - /* - * Instance logger - */ - private static final Logger rLogger = LoggerFactory.getLogger(RandomLBPolicy.class); - - /* - * Reference to the configuration manager. This reference is passed from load balancer - * class. - */ - private ConfigManager cmgr; - - /* - * Mapping between the client and the pool member that serves all traffic for that client. - */ - private HashMap clientMemberMap; - - /* - * Random generator - */ - Random randomGenerator = null; - - @SuppressWarnings("unused") - private RandomLBPolicy(){} - - public RandomLBPolicy(ConfigManager cmgr){ - this.cmgr = cmgr; - this.clientMemberMap = new HashMap(); - randomGenerator = new Random(); - } - @Override - public String getPoolMemberForClient(Client source, VIP dest){ - - rLogger.trace("Received traffic from client : {} for VIP : {} ",source, dest); - - syncWithLoadBalancerData(); - - PoolMember pm= null; - - if(this.clientMemberMap.containsKey(source)){ - pm= this.clientMemberMap.get(source); - rLogger.trace("Client {} had sent traffic before,new traffic will be routed to the same pool member {}",source,pm); - }else{ - Pool pool = null; - pool = this.cmgr.getPool(dest.getPoolName()); - int memberNum = this.randomGenerator.nextInt(pool.getAllMembers().size()-1); - pm = pool.getAllMembers().get(memberNum); - this.clientMemberMap.put(source, pm ); - rLogger.trace("Network traffic from client {} will be directed to pool member {}",pm); - } - return pm.getIp(); - } - - /* - * This method does the clean up. Whenever a new client packet arrives with a given VIP, - * this method checks the current configuration to see if any pool members have been deleted and - * cleans up the metadata stored by this loadbalancing algorithm. - */ - private void syncWithLoadBalancerData(){ - rLogger.debug("[Client - PoolMember] table before cleanup : {}",this.clientMemberMap.toString()); - - ArrayList removeClient = new ArrayList(); - - if(this.clientMemberMap.size() != 0){ - for(Client client : this.clientMemberMap.keySet()){ - - if(!this.cmgr.memberExists(this.clientMemberMap.get(client).getName(), - this.clientMemberMap.get(client).getPoolName())){ - removeClient.add(client); - } - } - } - - for(Client client : removeClient){ - this.clientMemberMap.remove(client); - - rLogger.debug("Removed client : {} ",client); - } - rLogger.debug("[Client - PoolMember] table after cleanup : {}",this.clientMemberMap.toString()); - } - -} diff --git a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RoundRobinLBPolicy.java b/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RoundRobinLBPolicy.java deleted file mode 100644 index 492c7a9aa7..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/policies/RoundRobinLBPolicy.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.policies; - -import java.util.ArrayList; -import java.util.HashMap; - -import org.opendaylight.controller.samples.loadbalancer.ConfigManager; -import org.opendaylight.controller.samples.loadbalancer.entities.Client; -import org.opendaylight.controller.samples.loadbalancer.entities.Pool; -import org.opendaylight.controller.samples.loadbalancer.entities.PoolMember; -import org.opendaylight.controller.samples.loadbalancer.entities.VIP; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class implements the round robin load balancing policy. - * - */ -public class RoundRobinLBPolicy implements ILoadBalancingPolicy{ - - /* - * Logger instance - */ - private static final Logger rrLogger = LoggerFactory.getLogger(RoundRobinLBPolicy.class); - - /* - * Reference to the configuration manager. This reference is passed from load balancer - * class. - */ - private ConfigManager cmgr; - - /* - * Mapping between the client and the pool member that serves all traffic for that client. - */ - private HashMap clientMemberMap; - - /* - * Maintains the next pool member counter for the VIPs. - * More than one VIP can be attached to one pool, so each VIP - * will have its own counter for the next pool member from - * the same pool. - */ - private HashMap nextItemFromPool; - - @SuppressWarnings("unused") - private RoundRobinLBPolicy(){} - - public RoundRobinLBPolicy(ConfigManager cmgr){ - this.cmgr = cmgr; - this.clientMemberMap = new HashMap(); - this.nextItemFromPool = new HashMap(); - } - - @Override - public String getPoolMemberForClient(Client source, VIP dest){ - - rrLogger.trace("Received traffic from client : {} for VIP : {} ",source, dest); - - syncWithLoadBalancerData(); - - PoolMember pm= null; - - if(this.clientMemberMap.containsKey(source)){ - - pm= this.clientMemberMap.get(source); - rrLogger.trace("Client {} had sent traffic before,new traffic will be routed to the same pool member {}",source,pm); - }else{ - - Pool pool = null; - if(nextItemFromPool.containsKey(dest)){ - - int memberNum = nextItemFromPool.get(dest).intValue(); - rrLogger.debug("Packet is from new client for VIP {}",dest); - pool = this.cmgr.getPool(dest.getPoolName()); - pm = pool.getAllMembers().get(memberNum); - this.clientMemberMap.put(source, pm ); - rrLogger.trace("New client's packet will be directed to pool member {}",pm); - memberNum++; - - if(memberNum > pool.getAllMembers().size()-1){ - memberNum = 0; - } - rrLogger.debug("Next pool member for new client of VIP is set to {}",pool.getAllMembers().get(memberNum)); - - this.nextItemFromPool.put(dest, memberNum); - }else{ - rrLogger.debug("Network traffic for VIP : {} has appeared first time from client {}",dest,source); - pool = this.cmgr.getPool(dest.getPoolName()); - pm = pool.getAllMembers().get(0); - this.clientMemberMap.put(source, pm); - - rrLogger.trace("Network traffic from client {} will be directed to pool member {}",pm); - this.nextItemFromPool.put(dest, 1); - rrLogger.debug("Next pool member for new client of VIP is set to {}",pool.getAllMembers().get(1)); - } - } - return pm.getIp(); - } - - /* - * This method does the clean up. Whenever a new client packet arrives with a given VIP, - * this method checks the current configuration to see if any pool members have been deleted and - * cleans up the metadata stored by this loadbalancing algorithm. - */ - private void syncWithLoadBalancerData(){ - rrLogger.debug("[Client - PoolMember] table before cleanup : {}",this.clientMemberMap.toString()); - ArrayList removeClient = new ArrayList(); - - if(this.clientMemberMap.size() != 0){ - for(Client client : this.clientMemberMap.keySet()){ - if(!this.cmgr.memberExists(this.clientMemberMap.get(client).getName(), - this.clientMemberMap.get(client).getPoolName())){ - - removeClient.add(client); - } - } - } - - for(Client client : removeClient){ - this.clientMemberMap.remove(client); - - rrLogger.debug("Removed client : {} ",client); - } - rrLogger.debug("[Client - PoolMember] table after cleanup : {}",this.clientMemberMap.toString()); - - rrLogger.debug("[VIP- NextMember] table before cleanup : {}",this.nextItemFromPool.toString()); - - ArrayList resetVIPPoolMemberCount= new ArrayList(); - - if(this.nextItemFromPool.size() != 0){ - - for(VIP vip:this.nextItemFromPool.keySet()){ - if(this.nextItemFromPool.get(vip).intValue() > this.cmgr.getPool(vip.getPoolName()).getAllMembers().size()-1){ - - resetVIPPoolMemberCount.add(vip); - } - } - } - - for(VIP vip:resetVIPPoolMemberCount){ - rrLogger.debug("VIP next pool member counter reset to 0"); - this.nextItemFromPool.put(vip, 0); - } - - rrLogger.debug("[VIP- NextMember] table after cleanup : {}",this.nextItemFromPool.toString()); - } -} diff --git a/opendaylight/adsal/samples/loadbalancer/src/test/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerTest.java b/opendaylight/adsal/samples/loadbalancer/src/test/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerTest.java deleted file mode 100644 index cfffb7e73a..0000000000 --- a/opendaylight/adsal/samples/loadbalancer/src/test/java/org/opendaylight/controller/samples/loadbalancer/internal/LoadBalancerTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.internal; - - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.samples.loadbalancer.ConfigManager; -import org.opendaylight.controller.samples.loadbalancer.entities.Client; -import org.opendaylight.controller.samples.loadbalancer.entities.Pool; -import org.opendaylight.controller.samples.loadbalancer.entities.PoolMember; -import org.opendaylight.controller.samples.loadbalancer.entities.VIP; -import org.opendaylight.controller.samples.loadbalancer.policies.RoundRobinLBPolicy; - -/** - * - * Class to unit test the load balancing policies. - * - */ -public class LoadBalancerTest { - @Test - public void testRoundRobinPolicy() { - ConfigManager cm = null; - cm = new ConfigManager(); - - Pool pool = cm.createPool("TestPool","roundrobin"); - VIP vip = cm.createVIP("TestVIP","10.0.0.9","TCP",(short)5550,"TestPool"); - PoolMember host1 = new PoolMember("host1","10.0.0.1","TestPool"); - PoolMember host2 = new PoolMember("host2","10.0.0.2","TestPool"); - PoolMember host3 = new PoolMember("host3","10.0.0.3","TestPool"); - PoolMember host4 = new PoolMember("host4","10.0.0.4","TestPool"); - PoolMember host5 = new PoolMember("host5","10.0.0.5","TestPool"); - PoolMember host6 = new PoolMember("host6","10.0.0.6","TestPool"); - PoolMember host7 = new PoolMember("host7","10.0.0.7","TestPool"); - - pool.addMember(host1); - pool.addMember(host2); - pool.addMember(host3); - pool.addMember(host4); - pool.addMember(host5); - pool.addMember(host6); - pool.addMember(host7); - pool.addVIP(vip); - - Assert.assertTrue(cm.getAllPoolMembers("TestPool").size() == pool.getAllMembers().size()); - - RoundRobinLBPolicy rrp = new RoundRobinLBPolicy(cm); - - Client c1 = new Client("10.0.0.1","TCP",(short)5000); - Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host1.getIp())); - - c1 = new Client("10.0.0.1","TCP",(short)5001); - Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host2.getIp())); - - c1 = new Client("10.0.0.1","TCP",(short)5002); - Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host3.getIp())); - - c1 = new Client("10.0.0.1","TCP",(short)5003); - Assert.assertTrue(rrp.getPoolMemberForClient(c1, vip).equals(host4.getIp())); - } -} diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/enunciate.xml b/opendaylight/adsal/samples/northbound/loadbalancer/enunciate.xml deleted file mode 100644 index 13ec7ca5ec..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/enunciate.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/pom.xml b/opendaylight/adsal/samples/northbound/loadbalancer/pom.xml deleted file mode 100644 index 5c4322f856..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - adsal-enunciate-parent - 1.6.0-SNAPSHOT - ../../../adsal-enunciate-parent - - - samples.loadbalancer.northbound - 0.6.0-SNAPSHOT - bundle - - - org.codehaus.enunciate - enunciate-core-annotations - - - org.opendaylight.controller - commons.northbound - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - samples.loadbalancer - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.samples.loadbalancer, - org.opendaylight.controller.samples.loadbalancer.entities, - org.opendaylight.controller.samples.loadbalancer.internal, - org.opendaylight.controller.samples.loadbalancer.policies, - org.opendaylight.controller.hosttracker, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.switchmanager, - org.apache.commons.logging, - com.sun.jersey.spi.container.servlet, - org.opendaylight.controller.northbound.commons, - org.opendaylight.controller.northbound.commons.exception, - javax.ws.rs, - javax.ws.rs.core, - javax.xml.bind.annotation, - javax.xml.bind, - org.slf4j, - org.apache.catalina.filters, - com.fasterxml.jackson.jaxrs.base, - com.fasterxml.jackson.jaxrs.json, - !org.codehaus.enunciate.jaxrs - /one/nb/v2/lb - ,${classes;ANNOTATION;javax.ws.rs.Path} - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/LoadBalancerNorthbound.java b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/LoadBalancerNorthbound.java deleted file mode 100644 index 2734c09183..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/LoadBalancerNorthbound.java +++ /dev/null @@ -1,470 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.northbound; - -import java.util.List; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.codehaus.enunciate.jaxrs.ResponseCode; -import org.codehaus.enunciate.jaxrs.StatusCodes; -import org.codehaus.enunciate.jaxrs.TypeHint; -import org.opendaylight.controller.containermanager.IContainerManager; -import org.opendaylight.controller.samples.loadbalancer.entities.Pool; -import org.opendaylight.controller.samples.loadbalancer.entities.PoolMember; -import org.opendaylight.controller.samples.loadbalancer.entities.VIP; -import org.opendaylight.controller.northbound.commons.RestMessages; -import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException; -import org.opendaylight.controller.northbound.commons.exception.MethodNotAllowedException; -import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException; -import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; -import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; -import org.opendaylight.controller.northbound.commons.exception.UnsupportedMediaTypeException; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.samples.loadbalancer.IConfigManager; - -/** - * This class exposes North bound REST APIs for the Load Balancer Service. - * Following APIs are exposed by the Load Balancer Service: - * - * Data retrieval REST APIs:: - * 1. Get details of all existing pools - * Type : GET - * URI : /one/nb/v2/lb/{container-name}/ - * NOTE: Current implementation of the opendaylight usage 'default' as a container-name - * e.g : http://localhost:8080/one/nb/v2/lb/default will give you list of all the pools - * - * 2. Get details of all the existing VIPs - * Type : GET - * URI: /one/nb/v2/lb/{container-name}/vips - * - * Pool related REST APIs:: - * 1. Create Pool : - * Type : POST - * URI : /one/nb/v2/lb/{container-name}/create/pool - * Request body : - * { - * "name":"", - * "lbmethod":"" - * } - * Currently, two load balancing policies are allowed {"roundrobin" and "random" } - * - * 2. Delete Pool : - * Type : DELETE - * URI : /one/nb/v2/lb/{container-name}/delete/pool/{pool-name} - * - * VIP related REST APIs:: - * 1. Create VIP: - * Type : POST - * URI : /one/nb/v2/lb/{container-name}/create/vip - * Request body : - * { - * "name":"", - * "ip":"ip in (xxx.xxx.xxx.xxx) format", - * "protocol":"TCP/UDP", - * "port":"any valid port number", - * "poolname":"" (optional) - * } - * The pool name is optional and can be set up at a later stage (using the REST API given below). - * - * 2. Update VIP: Update pool name of the VIP - * Type : PUT - * URI : /one/nb/v2/lb/{container-name}/update/vip - * Request body : - * { - * "name":"", - * "poolname":"" - * } - * Currently, we only allow update of the VIP pool name (if a VIP does not have an attached pool) - * and not of the VIP name itself. - * The specified pool name must already exist. If the specified VIP is already attached to a pool, the update - * will fail. - * - * 3. Delete VIP : - * Type : DELETE - * URI : /one/nb/v2/lb/{container-name}/delete/vip/{vip-name} - * - * Pool member related REST APIs:: - * 1. Create pool member: - * Type : POST - * URI : /one/nb/v2/lb/default/create/poolmember - * Request body : - * { - * "name":"", - * "ip":"ip in (xxx.xxx.xxx.xxx) format", - * "poolname":"existing pool name" - * } - * - * 2. Delete pool member: - * Type : DELETE - * URI : /one/nb/v2/lb/{container-name}/delete/poolmember/{pool-member-name}/{pool-name} - * - * NOTE: Property "name" of each individual entity must be unique. - * All the above REST APIs throw appropriate response codes in case of error/success. - * Please consult the respective methods to get details of various response codes. - */ - -@Path("/") -public class LoadBalancerNorthbound { - - /* - * Method returns the Load balancer service instance running within - * 'default' container. - */ - private IConfigManager getConfigManagerService(String containerName) { - IContainerManager containerManager = (IContainerManager) ServiceHelper - .getGlobalInstance(IContainerManager.class, this); - if (containerManager == null) { - throw new ServiceUnavailableException("Container " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - boolean found = false; - List containerNames = containerManager.getContainerNames(); - for (String cName : containerNames) { - if (cName.trim().equalsIgnoreCase(containerName.trim())) { - found = true; - } - } - - if (found == false) { - throw new ResourceNotFoundException(containerName + " " - + RestMessages.NOCONTAINER.toString()); - } - - IConfigManager configManager = (IConfigManager) ServiceHelper.getInstance( - IConfigManager.class, containerName, this); - - if (configManager == null) { - throw new ServiceUnavailableException("Load Balancer" - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - return configManager; - } - - @Path("/{containerName}") - @GET - @Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(Pools.class) - @StatusCodes( { - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "Load balancer service is unavailable") }) - public Pools getAllPools( - @PathParam("containerName") String containerName) { - - IConfigManager configManager = getConfigManagerService(containerName); - if (configManager == null) { - throw new ServiceUnavailableException("Load Balancer " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - return new Pools(configManager.getAllPools()); - } - - @Path("/{containerName}/vips") - @GET - @Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @TypeHint(VIPs.class) - @StatusCodes( { - @ResponseCode(code = 200, condition = "Operation successful"), - @ResponseCode(code = 404, condition = "The containerName is not found"), - @ResponseCode(code = 503, condition = "Load balancer service is unavailable") }) - public VIPs getAllVIPs( - @PathParam("containerName") String containerName) { - - IConfigManager configManager = getConfigManagerService(containerName); - if (configManager == null) { - throw new ServiceUnavailableException("Load Balancer " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - return new VIPs(configManager.getAllVIPs()); - } - - @Path("/{containerName}/create/vip") - @POST - @Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes( { - @ResponseCode(code = 201, condition = "VIP created successfully"), - @ResponseCode(code = 404, condition = "The Container Name not found"), - @ResponseCode(code = 503, condition = "Load balancer service is unavailable"), - @ResponseCode(code = 409, condition = "VIP already exist"), - @ResponseCode(code = 415, condition = "Invalid input data")}) - public Response addVIP(@PathParam("containerName") String containerName, - @TypeHint(VIP.class) VIP inVIP){ - - VIP vipInput = inVIP; - String name = vipInput.getName(); - String ip = vipInput.getIp(); - String protocol = vipInput.getProtocol(); - short protocolPort = vipInput.getPort(); - String poolName = vipInput.getPoolName(); - if(name.isEmpty() || - ip.isEmpty()|| - protocol.isEmpty()|| - protocolPort < 0 ){ - throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString()); - } - - IConfigManager configManager = getConfigManagerService(containerName); - - if (configManager == null) { - throw new ServiceUnavailableException("Load Balancer " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if(!configManager.vipExists(name, ip, protocol, protocolPort, poolName)){ - - VIP vip = configManager.createVIP(name, ip, protocol, protocolPort, poolName); - if ( vip != null){ - return Response.status(Response.Status.CREATED).build(); - } - }else{ - throw new ResourceConflictException(NBConst.RES_VIP_ALREADY_EXIST); - } - throw new InternalServerErrorException(NBConst.RES_VIP_CREATION_FAILED); - } - - @Path("/{containerName}/update/vip") - @PUT - @Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes( { - @ResponseCode(code = 201, condition = "VIP updated successfully"), - @ResponseCode(code = 404, condition = "The containerName not found"), - @ResponseCode(code = 503, condition = "VIP not found"), - @ResponseCode(code = 404, condition = "Pool not found"), - @ResponseCode(code = 405, condition = "Pool already attached to the VIP"), - @ResponseCode(code = 415, condition = "Invalid input name")}) - public Response updateVIP(@PathParam("containerName") String containerName, - @TypeHint(VIP.class) VIP inVIP) { - - VIP vipInput = inVIP; - String name = vipInput.getName(); - String poolName = vipInput.getPoolName(); - if(name.isEmpty() || - poolName.isEmpty()){ - throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString()); - } - - IConfigManager configManager = getConfigManagerService(containerName); - if (configManager == null) { - throw new ServiceUnavailableException("Load Balancer " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if(!configManager.poolExists(poolName)) - throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND); - - if(configManager.getVIPAttachedPool(name)!=null) - throw new MethodNotAllowedException(NBConst.RES_VIP_POOL_EXIST); - - if(configManager.updateVIP(name, poolName)!= null) - return Response.status(Response.Status.ACCEPTED).build(); - - throw new InternalServerErrorException(NBConst.RES_VIP_UPDATE_FAILED); - } - - @Path("/{containerName}/delete/vip/{vipName}") - @DELETE - @Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes( { - @ResponseCode(code = 200, condition = "VIP deleted successfully"), - @ResponseCode(code = 404, condition = "The containerName not found"), - @ResponseCode(code = 503, condition = "Load balancer service is unavailable"), - @ResponseCode(code = 404, condition = "VIP not found"), - @ResponseCode(code = 500, condition = "Failed to delete VIP")}) - public Response deleteVIP( - @PathParam(value = "containerName") String containerName, - @PathParam(value = "vipName") String vipName) { - - if(vipName.isEmpty()) - throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString()); - - IConfigManager configManager = getConfigManagerService(containerName); - if (configManager == null) { - throw new ServiceUnavailableException("Load Balancer" - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if(!configManager.vipExists(vipName)) - throw new ResourceNotFoundException(NBConst.RES_VIP_NOT_FOUND); - - for(VIP vip : configManager.getAllVIPs()){ - if(vip.getName().equals(vipName)){ - configManager.deleteVIP(vipName); - return Response.ok().build(); - } - } - throw new InternalServerErrorException(NBConst.RES_VIP_DELETION_FAILED); - } - - @Path("/{containerName}/create/pool") - @POST - @Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes( { - @ResponseCode(code = 201, condition = "Pool created successfully"), - @ResponseCode(code = 404, condition = "The containerName not found"), - @ResponseCode(code = 503, condition = "Load balancer service is unavailable"), - @ResponseCode(code = 409, condition = "Pool already exist"), - @ResponseCode(code = 415, condition = "Invalid input data")}) - public Response addPool(@PathParam("containerName") String containerName, - @TypeHint(Pool.class) Pool inPool) { - - Pool poolInput = inPool; - String name = poolInput.getName(); - String lbMethod =poolInput.getLbMethod(); - if(name.isEmpty() || - lbMethod.isEmpty()){ - throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString()); - } - - IConfigManager configManager = getConfigManagerService(containerName); - if (configManager == null) { - throw new ServiceUnavailableException("Load Balancer " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if(!configManager.poolExists(name)){ - - Pool pool = configManager.createPool(name, lbMethod); - if ( pool != null){ - return Response.status(Response.Status.CREATED).build(); - } - }else{ - throw new ResourceConflictException(NBConst.RES_POOL_ALREADY_EXIST); - } - throw new InternalServerErrorException(NBConst.RES_POOL_CREATION_FAILED); - } - - @Path("/{containerName}/delete/pool/{poolName}") - @DELETE - @Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes( { - @ResponseCode(code = 200, condition = "Pool deleted successfully"), - @ResponseCode(code = 404, condition = "The containerName not found"), - @ResponseCode(code = 503, condition = "Load balancer service is unavailable"), - @ResponseCode(code = 404, condition = "Pool not found"), - @ResponseCode(code = 500, condition = "Failed to delete Pool")}) - public Response deletePool( - @PathParam(value = "containerName") String containerName, - @PathParam(value = "poolName") String poolName) { - - if(poolName.isEmpty()) - throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString()); - - IConfigManager configManager = getConfigManagerService(containerName); - if (configManager == null) { - throw new ServiceUnavailableException("Load Balancer" - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if(!configManager.poolExists(poolName)) - throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND); - - for(Pool pool:configManager.getAllPools()){ - if(pool.getName().equals(poolName)){ - configManager.deletePool(poolName); - return Response.ok().build(); - } - } - throw new InternalServerErrorException(NBConst.RES_POOL_DELETION_FAILED); - } - - @Path("/{containerName}/create/poolmember") - @POST - @Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes( { - @ResponseCode(code = 201, condition = "Pool member created successfully"), - @ResponseCode(code = 404, condition = "The containerName not found"), - @ResponseCode(code = 503, condition = "Load balancer service is unavailable"), - @ResponseCode(code = 404, condition = "Pool not found"), - @ResponseCode(code = 409, condition = "Pool member already exist"), - @ResponseCode(code = 415, condition = "Invalid input data")}) - public Response addPoolMember(@PathParam("containerName") String containerName, - @TypeHint(PoolMember.class) PoolMember inPoolMember){ - - PoolMember pmInput = inPoolMember; - String name = pmInput.getName(); - String memberIP = pmInput.getIp(); - String poolName = pmInput.getPoolName(); - - if(name.isEmpty() || - memberIP.isEmpty()|| - poolName.isEmpty()){ - throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString()); - } - - IConfigManager configManager = getConfigManagerService(containerName); - if (configManager == null) { - throw new ServiceUnavailableException("Load Balancer " - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if(!configManager.poolExists(poolName)) - throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND); - - if(!configManager.memberExists(name, memberIP, poolName)){ - - PoolMember poolMember = configManager.addPoolMember(name, memberIP, poolName); - if ( poolMember != null){ - return Response.status(Response.Status.CREATED).build(); - } - }else{ - throw new ResourceConflictException(NBConst.RES_POOLMEMBER_ALREADY_EXIST); - } - throw new InternalServerErrorException(NBConst.RES_POOLMEMBER_CREATION_FAILED); - } - - @Path("/{containerName}/delete/poolmember/{poolMemberName}/{poolName}") - @DELETE - @Consumes( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) - @StatusCodes( { - @ResponseCode(code = 200, condition = "Pool member deleted successfully"), - @ResponseCode(code = 404, condition = "The containerName not found"), - @ResponseCode(code = 503, condition = "Load balancer service is unavailable"), - @ResponseCode(code = 404, condition = "Pool member not found"), - @ResponseCode(code = 404, condition = "Pool not found")}) - public Response deletePoolMember( - @PathParam(value = "containerName") String containerName, - @PathParam(value = "poolMemberName") String poolMemberName, - @PathParam(value = "poolName") String poolName) { - - if(poolMemberName.isEmpty()|| - poolName.isEmpty()) - throw new UnsupportedMediaTypeException(RestMessages.INVALIDDATA.toString()); - - IConfigManager configManager = getConfigManagerService(containerName); - - if (configManager == null) { - throw new ServiceUnavailableException("Load Balancer" - + RestMessages.SERVICEUNAVAILABLE.toString()); - } - - if(!configManager.poolExists(poolName)) - throw new ResourceNotFoundException(NBConst.RES_POOL_NOT_FOUND); - - if(configManager.memberExists(poolMemberName, poolName)){ - - configManager.removePoolMember(poolMemberName, poolName); - - return Response.ok().build(); - } - throw new ResourceNotFoundException(NBConst.RES_POOLMEMBER_NOT_FOUND); - } -} diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/NBConst.java b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/NBConst.java deleted file mode 100644 index a5d2091470..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/NBConst.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.northbound; - -/** - * This class defines all the constants used by the load balancer north bound service - * - */ -public class NBConst { - - public static final String RES_VIP_ALREADY_EXIST= " VIP already exists"; - - public static final String RES_VIP_NOT_FOUND= " VIP not found"; - - public static final String RES_VIP_CREATION_FAILED = " Creation of VIP failed"; - - public static final String RES_VIP_DELETION_FAILED = " Deletion of VIP failed"; - - public static final String RES_VIP_UPDATE_FAILED = " Update of VIP failed"; - - public static final String RES_POOL_ALREADY_EXIST= " Pool already exists"; - - public static final String RES_POOL_NOT_FOUND= " Pool not found"; - - public static final String RES_POOL_CREATION_FAILED = " Creation of pool failed"; - - public static final String RES_POOL_DELETION_FAILED = " Deletion of pool failed"; - - public static final String RES_POOLMEMBER_ALREADY_EXIST= " Pool member already exists"; - - public static final String RES_POOLMEMBER_NOT_FOUND= " Pool member not found"; - - public static final String RES_POOLMEMBER_CREATION_FAILED = " Creation of pool member failed"; - - public static final String RES_POOLMEMBER_DELETION_FAILED = " Deletion of pool member failed"; - - public static final String RES_VIP_POOL_EXIST = "Pool already attached to a VIP"; -} diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/Pools.java b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/Pools.java deleted file mode 100644 index 74be568018..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/Pools.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.northbound; - -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.samples.loadbalancer.entities.Pool; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -/** - * JAX-RS resource for handling details of all the available pools - * in response to respective REST API requests. - */ - -public class Pools { - - @XmlElement (name="pool") - Set loadBalancerPools; - - public Pools() { - } - - public Pools (Set loadBalancerPools) { - this.loadBalancerPools = loadBalancerPools; - } - - /** - * @return the loadBalancerPools - */ - public Set getLoadBalancerPools() { - return loadBalancerPools; - } - - /** - * @param loadBalancerPools the loadBalancerPools to set - */ - public void setLoadBalancerPools(Set loadBalancerPools) { - this.loadBalancerPools = loadBalancerPools; - } -} diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/VIPs.java b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/VIPs.java deleted file mode 100644 index 66a20338ab..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/java/org/opendaylight/controller/samples/loadbalancer/northbound/VIPs.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright IBM Corporation, 2013. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.samples.loadbalancer.northbound; - -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.samples.loadbalancer.entities.VIP; - -/** - * JAX-RS resource for handling details of all the available VIPs - * in response to respective REST API requests. - */ - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) - -public class VIPs { - - @XmlElement (name="vip") - Set loadBalancerVIPs; - - public VIPs() {} - - - public VIPs (Set loadBalancerVIPs) { - this.loadBalancerVIPs = loadBalancerVIPs; - } - - /** - * @return the loadBalancerVIPs - */ - public Set getLoadBalancerVIPs() { - return loadBalancerVIPs; - } - - /** - * @param loadBalancerVIPs the loadBalancerVIPs to set - */ - - public void setLoadBalancerVIPs(Set loadBalancerVIPs) { - this.loadBalancerVIPs = loadBalancerVIPs; - } -} \ No newline at end of file diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 20529e90b4..0000000000 --- a/opendaylight/adsal/samples/northbound/loadbalancer/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - JAXRSLoadBalancer - com.sun.jersey.spi.container.servlet.ServletContainer - - javax.ws.rs.Application - org.opendaylight.controller.northbound.commons.NorthboundApplication - - 1 - - - - JAXRSLoadBalancer - /* - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - NB api - /* - POST - GET - PUT - PATCH - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - BASIC - opendaylight - - diff --git a/opendaylight/adsal/samples/simpleforwarding/pom.xml b/opendaylight/adsal/samples/simpleforwarding/pom.xml deleted file mode 100644 index a90fd6947f..0000000000 --- a/opendaylight/adsal/samples/simpleforwarding/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - samples.simpleforwarding - 0.6.0-SNAPSHOT - bundle - - - junit - junit - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - topologymanager - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.forwardingrulesmanager, - org.opendaylight.controller.hosttracker, - org.opendaylight.controller.hosttracker.hostAware, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.inventory, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.routing, - org.opendaylight.controller.topologymanager, - org.apache.commons.lang3.builder, - org.junit;resolution:=optional, - org.slf4j, - org.apache.felix.dm - org.opendaylight.controller.samples.simpleforwarding - org.opendaylight.controller.samples.simpleforwarding.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/HostNodePair.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/HostNodePair.java deleted file mode 100644 index 2d0d468466..0000000000 --- a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/HostNodePair.java +++ /dev/null @@ -1,85 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.samples.simpleforwarding; - -import java.io.Serializable; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.Node; - -/** - * Class that represent a pair of {Host, Node}, the intent of it - * is to be used as a key in the database kept by IPSwitching module - * where for every Host, Switch we will have a Forwarding Rule that - * will route the traffic toward the /32 destination - * - */ -public class HostNodePair implements Serializable { - private static final long serialVersionUID = 1L; - private HostNodeConnector host; - private Node node; - - public HostNodePair(HostNodeConnector h, Node s) { - setNode(s); - setHost(h); - } - - public Node getNode() { - return node; - } - - public void setNode(Node nodeId) { - this.node = nodeId; - } - - public HostNodeConnector getHost() { - return host; - } - - public void setHost(HostNodeConnector host) { - this.host = host; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((node == null) ? 0 : node.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - HostNodePair other = (HostNodePair) obj; - if (host == null) { - if (other.host != null) - return false; - } else if (!host.equals(other.host)) - return false; - if (node == null) { - if (other.node != null) - return false; - } else if (!node.equals(other.node)) - return false; - return true; - } - - @Override - public String toString() { - return "HostNodePair [host=" + host + ", node=" + node + "]"; - } -} diff --git a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastHandler.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastHandler.java deleted file mode 100644 index 3ae5d82a1a..0000000000 --- a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastHandler.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2013 IBM and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.samples.simpleforwarding; - -import org.opendaylight.controller.sal.packet.RawPacket; - - -/** - * Provides support for flooding/broadcasting of packets. - */ -public interface IBroadcastHandler { - - /** - * The mode to select which ports to broadcast a given packet. See the - * individual modes for the expected behavior. - */ - static enum BroadcastMode { - /** - * Turn off broadcast handling and ignore all received data packets. - */ - DISABLED, - - /** - * sends broadcast packets out ports where there are known hosts as - * discovered by {@link ITopologyManager#getNodeConnectorWithHost}. - */ - BROADCAST_TO_HOSTS, - - /** - * sends broadcast packets out all non-internal links as discovered by - * {@link ITopologyManager#isInternal}. Also ignores ports which have - * {@link NodeConnector#getType} of "SW" indicating OFPP_LOCAL. - */ - BROADCAST_TO_NONINTERNAL, - - /** - * sends broadcast packets out the ports specified by an external - * implementation of {@link IBroadcastPortSelector}. - */ - EXTERNAL_QUERY - }; - - /** - * Set the {@link BroadcastMode} for this {@link IBroadcastHandler}. - * @param m - */ - void setMode(BroadcastMode m); - - /** - * Safely flood/broadcast a {@link RawPacket} received on a given - * {@link NodeConnector}. - * - * @param pkt - * The packet to flood/broadcast - * @return true if the broadcast is successful, false - * otherwise - */ - boolean broadcastPacket(RawPacket pkt); -} diff --git a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastPortSelector.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastPortSelector.java deleted file mode 100644 index 438c9214c6..0000000000 --- a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/IBroadcastPortSelector.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright (c) 2013 IBM and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.samples.simpleforwarding; - -import java.util.Set; - -import org.opendaylight.controller.sal.core.NodeConnector; - -public interface IBroadcastPortSelector { - Set getBroadcastPorts(); -} diff --git a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/Activator.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/Activator.java deleted file mode 100644 index 6ee04b4e19..0000000000 --- a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/Activator.java +++ /dev/null @@ -1,133 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.samples.simpleforwarding.internal; - -import java.util.Dictionary; -import java.util.Hashtable; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.IfNewHostNotify; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.sal.routing.IListenRoutingUpdates; -import org.opendaylight.controller.sal.routing.IRouting; -import org.opendaylight.controller.samples.simpleforwarding.IBroadcastHandler; -import org.opendaylight.controller.samples.simpleforwarding.IBroadcastPortSelector; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { SimpleForwardingImpl.class, - SimpleBroadcastHandlerImpl.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(SimpleForwardingImpl.class)) { - Dictionary props = new Hashtable(); - props.put("salListenerName", "simpleforwarding"); - - // export the service - c.setInterface(new String[] { IInventoryListener.class.getName(), - IfNewHostNotify.class.getName(), - IListenRoutingUpdates.class.getName(), - IListenDataPacket.class.getName() }, props); - - c.add(createContainerServiceDependency(containerName).setService( - IClusterContainerServices.class).setCallbacks( - "setClusterContainerService", - "unsetClusterContainerService").setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - ISwitchManager.class).setCallbacks("setSwitchManager", - "unsetSwitchManager").setRequired(false)); - - c.add(createContainerServiceDependency(containerName).setService( - IfIptoHost.class).setCallbacks("setHostTracker", - "unsetHostTracker").setRequired(false)); - - c.add(createContainerServiceDependency(containerName).setService( - IForwardingRulesManager.class).setCallbacks( - "setForwardingRulesManager", "unsetForwardingRulesManager") - .setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - ITopologyManager.class).setCallbacks("setTopologyManager", - "unsetTopologyManager").setRequired(false)); - - c.add(createContainerServiceDependency(containerName).setService( - IRouting.class).setCallbacks("setRouting", "unsetRouting") - .setRequired(false)); - c.add(createContainerServiceDependency(containerName).setService( - IDataPacketService.class).setCallbacks("setDataPacketService", - "unsetDataPacketService").setRequired(false)); - - } else if (imp.equals(SimpleBroadcastHandlerImpl.class)) { - Dictionary props = new Hashtable(); - props.put("salListenerName", "simplebroadcasthandler"); - - // export the service - c.setInterface(new String[] { IBroadcastHandler.class.getName(), - IListenDataPacket.class.getName() }, props); - - c.add(createContainerServiceDependency(containerName).setService( - IDataPacketService.class).setCallbacks("setDataPacketService", - "unsetDataPacketService").setRequired(false)); - - c.add(createContainerServiceDependency(containerName).setService( - ITopologyManager.class).setCallbacks("setTopologyManager", - "unsetTopologyManager").setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - IBroadcastPortSelector.class).setCallbacks("setBroadcastPortSelector", - "unsetBroadcastPortSelector").setRequired(false)); - - c.add(createContainerServiceDependency(containerName).setService( - ISwitchManager.class).setCallbacks("setSwitchManager", - "unsetSwitchManager").setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleBroadcastHandlerImpl.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleBroadcastHandlerImpl.java deleted file mode 100644 index 96e36f413c..0000000000 --- a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleBroadcastHandlerImpl.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2013 IBM and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.samples.simpleforwarding.internal; - -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.packet.Ethernet; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.sal.packet.Packet; -import org.opendaylight.controller.sal.packet.PacketResult; -import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.samples.simpleforwarding.IBroadcastHandler; -import org.opendaylight.controller.samples.simpleforwarding.IBroadcastPortSelector; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The simple broadcast handler simply sends broadcast packets out all ports - * that are not known to belong to an internal, i.e., switch-switch, link. Note - * that this is *not* safe in the general case when an OpenDaylight-controlled - * network has L2 peering with normal a normal L2 network. It is entirely - * possible for a packet to be flooded to a legacy/non-controlled switch and - * then be reflected back into the OpenDaylight-controlled region resulting in a - * loop. - */ -public class SimpleBroadcastHandlerImpl implements IBroadcastHandler, IListenDataPacket { - - private static Logger log = LoggerFactory.getLogger(SimpleBroadcastHandlerImpl.class); - protected IDataPacketService dataPacketService = null; - protected ITopologyManager topoManager = null; - protected ISwitchManager swMgr = null; - protected IBroadcastPortSelector bcastPorts = null; - - protected ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - - BroadcastMode mode = BroadcastMode.DISABLED; - - @Override - public PacketResult receiveDataPacket(RawPacket inPkt) { - /* - * note that this assumes that the protocol plugin will do appropriate - * filtering to ensure that this only receives packets for its - * container. - */ - - if (mode == BroadcastMode.DISABLED) { - return PacketResult.IGNORED; - } - - Packet decodedPkt = this.dataPacketService.decodeDataPacket(inPkt); - if (decodedPkt instanceof Ethernet) { - Ethernet eth = (Ethernet) decodedPkt; - - // TODO: should we offer an option to not handle ARP since the - // ARPHandler already does that - - // ignore LLDP - if (eth.getEtherType() != EtherTypes.LLDP.shortValue()) { - - if (eth.isBroadcast()) { - broadcastPacket(inPkt); - } else if (eth.isMulticast()) { - // TODO: for now just treat multicast as broadcast - broadcastPacket(inPkt); - } - } - } - - return PacketResult.KEEP_PROCESSING; - } - - @Override - public boolean broadcastPacket(RawPacket pkt) { - Set toPacketOut = new HashSet(); - - // make sure that topoManager/datPacketService aren't pulled out from - // under us - lock.readLock().lock(); - if (topoManager == null || dataPacketService == null - || swMgr == null) { - lock.readLock().unlock(); - return false; - } - - // find all non-internal NodeConnectors - switch (mode) { - case DISABLED: - // intentionally blank; don't send the packet anywhere - break; - - case BROADCAST_TO_HOSTS: - toPacketOut.addAll(topoManager.getNodeConnectorWithHost()); - break; - - case BROADCAST_TO_NONINTERNAL: - for (Node n : swMgr.getNodes()) { - // getUpNodeConnectors will filter out NodeConnectors of type "SW" - for (NodeConnector nc : swMgr.getUpNodeConnectors(n)) { - if (!topoManager.isInternal(nc)) { - toPacketOut.add(nc); - } - } - } - break; - - case EXTERNAL_QUERY: - if (bcastPorts != null) { - toPacketOut.addAll(bcastPorts.getBroadcastPorts()); - } else { - log.error("Mode set to " - + BroadcastMode.EXTERNAL_QUERY - + ", but no external source of broadcast ports was provided."); - lock.readLock().unlock(); - return false; - } - break; - - default: - log.error("Mode " + mode + " is not supported."); - break; - } - - // remove the NodeConnector it came in on - toPacketOut.remove(pkt.getIncomingNodeConnector()); - - // send it out all the node connectors - for (NodeConnector nc : toPacketOut) { - try { - RawPacket toSend = new RawPacket(pkt); - toSend.setOutgoingNodeConnector(nc); - dataPacketService.transmitDataPacket(toSend); - } catch (ConstructionException e) { - log.error("Could create packet: {}", e); - } - } - - lock.readLock().unlock(); - - return true; - } - - public void setDataPacketService(IDataPacketService s) { - // make sure dataPacketService doesn't change while we're in the middle - // of stuff - lock.writeLock().lock(); - this.dataPacketService = s; - lock.writeLock().unlock(); - } - - public void unsetDataPacketService(IDataPacketService s) { - // make sure dataPacketService doesn't change while we're in the middle - // of stuff - lock.writeLock().lock(); - if (this.dataPacketService == s) { - this.dataPacketService = null; - } - lock.writeLock().unlock(); - } - - public void setTopologyManager(ITopologyManager t) { - // make sure topoManager doesn't change while we're in the middle of - // stuff - lock.writeLock().lock(); - this.topoManager = t; - lock.writeLock().unlock(); - } - - public void unsetTopologyManager(ITopologyManager t) { - // make sure topoManager doesn't change while we're in the middle of - // stuff - lock.writeLock().lock(); - if (this.topoManager == t) { - this.topoManager = null; - } - lock.writeLock().unlock(); - } - - public void setSwitchManager(ISwitchManager i) { - lock.writeLock().lock(); - this.swMgr = i; - lock.writeLock().unlock(); - } - - public void unsetSwitchManager(ISwitchManager i) { - lock.writeLock().lock(); - if (this.swMgr == i) { - this.swMgr = null; - } - lock.writeLock().unlock(); - } - - public void setBroadcastPortSelector(IBroadcastPortSelector bps) { - lock.writeLock().lock(); - bcastPorts = bps; - lock.writeLock().unlock(); - } - - public void unsetBroadcastPortSelector(IBroadcastPortSelector bps) { - lock.writeLock().lock(); - if (bcastPorts == bps) { - this.bcastPorts = null; - } - lock.writeLock().unlock(); - } - - @Override - public void setMode(BroadcastMode m) { - lock.writeLock().lock(); - mode = m; - lock.writeLock().unlock(); - } - -} diff --git a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleForwardingImpl.java b/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleForwardingImpl.java deleted file mode 100644 index a48d331773..0000000000 --- a/opendaylight/adsal/samples/simpleforwarding/src/main/java/org/opendaylight/controller/samples/simpleforwarding/internal/SimpleForwardingImpl.java +++ /dev/null @@ -1,1145 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.samples.simpleforwarding.internal; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.Timer; -import java.util.TimerTask; - -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.forwardingrulesmanager.FlowEntry; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; -import org.opendaylight.controller.hosttracker.IfIptoHost; -import org.opendaylight.controller.hosttracker.IfNewHostNotify; -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.Output; -import org.opendaylight.controller.sal.action.PopVlan; -import org.opendaylight.controller.sal.action.SetDlDst; -import org.opendaylight.controller.sal.action.SetVlanId; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; -import org.opendaylight.controller.sal.core.Path; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.packet.Ethernet; -import org.opendaylight.controller.sal.packet.IDataPacketService; -import org.opendaylight.controller.sal.packet.IListenDataPacket; -import org.opendaylight.controller.sal.packet.IPv4; -import org.opendaylight.controller.sal.packet.Packet; -import org.opendaylight.controller.sal.packet.PacketResult; -import org.opendaylight.controller.sal.packet.RawPacket; -import org.opendaylight.controller.sal.routing.IListenRoutingUpdates; -import org.opendaylight.controller.sal.routing.IRouting; -import org.opendaylight.controller.sal.utils.EtherTypes; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.samples.simpleforwarding.HostNodePair; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class implements basic L3 forwarding within the managed devices. - * Forwarding is only done within configured subnets.
- *
- * The basic flow is that the module listens for new hosts from the - * {@link org.opendaylight.controller.hosttracker.IfIptoHost HostTracker} - * service and on discovering a new host it first calls - * preparePerHostRules() to create a set of new rules that must be - * installed in the network. This is done by repeatedly calling - * updatePerHostRuleInSW() for each switch in the network. Then it - * installs those rules using installPerHostRules(). - */ -public class SimpleForwardingImpl implements IfNewHostNotify, - IListenRoutingUpdates, IInventoryListener, IListenDataPacket { - private static Logger log = LoggerFactory.getLogger(SimpleForwardingImpl.class); - private static short DEFAULT_IPSWITCH_PRIORITY = 1; - static final String FORWARDING_RULES_CACHE_NAME = "forwarding.ipswitch.rules"; - private IfIptoHost hostTracker; - private IForwardingRulesManager frm; - private ITopologyManager topologyManager; - private IRouting routing; - - /** - * The set of all forwarding rules: (host) -> (switch -> flowmod). Note that - * the host includes an attachment point and that while the switch appears - * to be a switch's port, in actuality it is a special port which just - * represents the switch. - */ - private ConcurrentMap> rulesDB; - private Map> tobePrunedPos = new HashMap>(); - private IClusterContainerServices clusterContainerService = null; - private ISwitchManager switchManager; - private IDataPacketService dataPacketService; - - /** - * Ip packets that are punted may not have their destination known by hostTracker at the time it - * is presented to SimpleForwardingImpl. Instead of dropping the packet, we will keep it around - * for a 'little' while, to accommodate any transients. See bug 590 for more details. - */ - private class PendingPacketData { - private final static byte MAX_AGE = 2; - - public final IPv4 pkt; - public final NodeConnector incomingNodeConnector; - private byte age; - - public PendingPacketData(IPv4 pkt, NodeConnector incomingNodeConnector) { - this.pkt = pkt; - this.incomingNodeConnector = incomingNodeConnector; - this.age = 0; - } - boolean bumpAgeAndCheckIfTooOld() { return ++age > MAX_AGE; } - } - private static final int MAX_PENDING_PACKET_DESTINATIONS = 64; - private ConcurrentMap pendingPacketDestinations; - private Timer pendingPacketsAgerTimer; - - private class PendingPacketsAgerTimerHandler extends TimerTask { - @Override - public void run() { - if (pendingPacketDestinations == null) { - return; - } - try { - Iterator> iterator = - pendingPacketDestinations.entrySet().iterator(); - while (iterator.hasNext()) { - ConcurrentHashMap.Entry entry = iterator.next(); - InetAddress dIP = entry.getKey(); - PendingPacketData pendingPacketData = entry.getValue(); - - if (pendingPacketData.bumpAgeAndCheckIfTooOld()) { - iterator.remove(); // safe to remove while iterating... - log.debug("Pending packet for {} has been aged out", dIP); - } else { - /** Replace the entry for a key only if currently mapped to some value. - * This will protect the concurrent map against a race where this thread - * would be re-adding an entry that just got taken out. - */ - pendingPacketDestinations.replace(dIP, pendingPacketData); - } - } - } catch (IllegalStateException e) { - log.warn("IllegalStateException Received by PendingPacketsAgerTimerHandler from: {}", - e.getMessage()); - } - } - } - - /** - * Add punted packet to pendingPackets - */ - private void addToPendingPackets(InetAddress dIP, IPv4 pkt, NodeConnector incomingNodeConnector) { - if (pendingPacketDestinations.size() >= MAX_PENDING_PACKET_DESTINATIONS) { - log.info("Will not pend packet for {}: Too many destinations", dIP); - return; - } - - /** TODO: The current implementation allows for up to 1 pending packet per InetAddress. - * This limitation is done for sake of simplicity. A potential enhancement could be to use a - * ConcurrentMultiMap instead of ConcurrentMap. - */ - if (pendingPacketDestinations.containsKey(dIP)) { - log.trace("Will not pend packet for {}: Already have a packet pending", dIP); - return; - } - - PendingPacketData pendingPacketData = new PendingPacketData(pkt, incomingNodeConnector); - pendingPacketDestinations.put(dIP, pendingPacketData); - log.debug("Pending packet for {}", dIP); - } - - /** - * Send punted packet to given destination. This is invoked when there is a certain level of - * hope that the destination is known by hostTracker. - */ - private void sendPendingPacket(InetAddress dIP) { - PendingPacketData pendingPacketData = pendingPacketDestinations.get(dIP); - if (pendingPacketData != null) { - handlePuntedIPPacket(pendingPacketData.pkt, pendingPacketData.incomingNodeConnector, false); - log.trace("Packet for {} is no longer pending", dIP); - pendingPacketDestinations.remove(dIP); - } - } - - /** - * Return codes from the programming of the perHost rules in HW - */ - public enum RulesProgrammingReturnCode { - SUCCESS, FAILED_FEW_SWITCHES, FAILED_ALL_SWITCHES, FAILED_WRONG_PARAMS - } - public void setDataPacketService(IDataPacketService s) { - log.debug("Setting dataPacketService"); - this.dataPacketService = s; - } - - public void unsetDataPacketService(IDataPacketService s) { - if (this.dataPacketService == s) { - this.dataPacketService = null; - } - } - - public void setRouting(IRouting routing) { - log.debug("Setting routing"); - this.routing = routing; - } - - public void unsetRouting(IRouting routing) { - if (this.routing == routing) { - this.routing = null; - } - } - - public void setTopologyManager(ITopologyManager topologyManager) { - log.debug("Setting topologyManager"); - this.topologyManager = topologyManager; - } - - public void unsetTopologyManager(ITopologyManager topologyManager) { - if (this.topologyManager == topologyManager) { - this.topologyManager = null; - } - } - - public void setHostTracker(IfIptoHost hostTracker) { - log.debug("Setting HostTracker"); - this.hostTracker = hostTracker; - } - - public void setForwardingRulesManager( - IForwardingRulesManager forwardingRulesManager) { - log.debug("Setting ForwardingRulesManager"); - this.frm = forwardingRulesManager; - } - - public void unsetHostTracker(IfIptoHost hostTracker) { - if (this.hostTracker == hostTracker) { - this.hostTracker = null; - } - } - - public void unsetForwardingRulesManager( - IForwardingRulesManager forwardingRulesManager) { - if (this.frm == forwardingRulesManager) { - this.frm = null; - } - } - - /** - * Function called when the bundle gets activated - * - */ - public void startUp() { - allocateCaches(); - retrieveCaches(); - nonClusterObjectCreate(); - } - - public void nonClusterObjectCreate() { - pendingPacketDestinations = new ConcurrentHashMap(); - - /* Pending Packets Ager Timer to go off every 6 seconds to implement pending packet aging */ - pendingPacketsAgerTimer = new Timer(); - pendingPacketsAgerTimer.schedule(new PendingPacketsAgerTimerHandler(), 6000, 6000); - } - - /** - * Function called when the bundle gets stopped - * - */ - public void shutDown() { - log.debug("Destroy all the host Rules given we are shutting down"); - uninstallPerHostRules(); - destroyCaches(); - } - - private void allocateCaches() { - if (this.clusterContainerService == null) { - log.trace("un-initialized clusterContainerService, can't create cache"); - return; - } - - try { - clusterContainerService.createCache(FORWARDING_RULES_CACHE_NAME, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheExistException cee) { - log.error("\nCache already exists - destroy and recreate if needed"); - } catch (CacheConfigException cce) { - log.error("\nCache configuration invalid - check cache mode"); - } - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - if (this.clusterContainerService == null) { - log.trace("un-initialized clusterContainerService, can't retrieve cache"); - return; - } - - rulesDB = (ConcurrentMap>) clusterContainerService - .getCache(FORWARDING_RULES_CACHE_NAME); - if (rulesDB == null) { - log.error("\nFailed to get rulesDB handle"); - } - } - - private void destroyCaches() { - if (this.clusterContainerService == null) { - log.trace("un-initialized clusterContainerService, can't destroy cache"); - return; - } - - clusterContainerService.destroyCache(FORWARDING_RULES_CACHE_NAME); - } - - /** - * Populates rulesDB with rules specifying how to reach - * host from currNode assuming that: - *

    - *
  • host is attached to rootNode - *
  • link is the next part of the path to reach rootNode - * from currNode - *
  • rulesDB.get(key) represents the list of rules stored about - * host at currNode - *
- * - * @param host - * The host to be reached. - * @param currNode - * The current node being processed. - * @param rootNode - * The node to be reached. Really, the switch which host is - * attached to. - * @param link - * The link to follow from curNode to get to rootNode - * @param key - * The key to store computed rules at in the rulesDB. For now, - * this is a {@link HostNodePair} of host and currNode. - */ - private void updatePerHostRuleInSW(HostNodeConnector host, Node currNode, - Node rootNode, Edge link, HostNodePair key) { - - // only the link parameter is optional - if (host == null || key == null || currNode == null || rootNode == null) { - return; - } - - Set ports = new HashSet(); - // add a special port of type ALL and port 0 to represent the node - // without specifying a port on that node - ports.add(NodeConnectorCreator.createNodeConnector( - NodeConnectorIDType.ALL, NodeConnector.SPECIALNODECONNECTORID, - currNode)); - - HashMap pos = this.rulesDB.get(key); - if (pos == null) { - pos = new HashMap(); - } - - for (NodeConnector inPort : ports) { - // skip the port connected to the target host - if (currNode.equals(rootNode) - && (host.getnodeConnector().equals(inPort))) { - continue; - } - - // remove the current rule, if any - FlowEntry removed_po = pos.remove(inPort); - Match match = new Match(); - List actions = new ArrayList(); - - // IP destination based forwarding on /32 entries only! - match.setField(MatchType.DL_TYPE, EtherTypes.IPv4.shortValue()); - match.setField(MatchType.NW_DST, host.getNetworkAddress()); - - /* Action for the policy is to forward to a port except on the - * switch where the host sits, which is to rewrite also the MAC - * and to forward on the Host port */ - NodeConnector outPort = null; - - if (currNode.equals(rootNode)) { - /* If we're at the root node, then rewrite the DL addr and - * possibly pop the VLAN tag. This allows for MAC rewriting - * in the core of the network assuming we can uniquely ID - * packets based on IP address. */ - - outPort = host.getnodeConnector(); - if (inPort.equals(outPort)) { - // TODO: isn't this code skipped already by the above continue? - // skip the host port - continue; - } - actions.add(new SetDlDst(host.getDataLayerAddressBytes())); - - if (!inPort.getType().equals(NodeConnectorIDType.ALL)) { - // Container mode: at the destination switch, we need to strip out the tag (VLAN) - actions.add(new PopVlan()); - } - } else { - // currNode is NOT the rootNode, find the next hop and create a rule - if (link != null) { - outPort = link.getTailNodeConnector(); - if (inPort.equals(outPort)) { - // skip the outgoing port - continue; - } - - // If outPort is network link, add VLAN tag - if (topologyManager.isInternal(outPort)) { - log.debug("outPort {}/{} is internal uplink port", - currNode, outPort); - } else { - log.debug("outPort {}/{} is host facing port", - currNode, outPort); - } - - if ((!inPort.getType().equals(NodeConnectorIDType.ALL)) - && (topologyManager.isInternal(outPort))) { - Node nextNode = link.getHeadNodeConnector() - .getNode(); - // TODO: Replace this with SAL equivalent - //short tag = container.getTag((Long)nextNode.getNodeID()); - short tag = 0; - if (tag != 0) { - log.debug("adding SET_VLAN {} for traffic " + - "leaving {}/{} toward switch {}", - new Object[] { tag, currNode, outPort, - nextNode}); - actions.add(new SetVlanId(tag)); - } else { - log.debug("No tag assigned to switch {}", nextNode); - } - } - } - } - if (outPort != null) { - actions.add(new Output(outPort)); - } - if (!inPort.getType().equals(NodeConnectorIDType.ALL)) { - // include input port in the flow match field - match.setField(MatchType.IN_PORT, inPort); - - if (topologyManager.isInternal(inPort)) { - log.debug("inPort {}/{} is internal uplink port", currNode, - inPort); - } else { - log.debug("inPort {}/{} is host facing port", currNode, - inPort); - } - - // for incoming network link; if the VLAN tag is defined, include it for incoming flow matching - if (topologyManager.isInternal(inPort)) { - // TODO: Replace this with SAL equivalent - //short tag = container.getTag((Long)currNode.getNodeID()); - short tag = 0; - if (tag != 0) { - log.debug("adding MATCH VLAN {} for traffic entering" + - " {}/{}", - new Object[] {tag, currNode, inPort}); - match.setField(MatchType.DL_VLAN, tag); - } else { - log.debug("No tag assigned to switch {}", currNode); - } - } - } - // Make sure the priority for IP switch entries is - // set to a level just above default drop entries - Flow flow = new Flow(match, actions); - flow.setIdleTimeout((short) 0); - flow.setHardTimeout((short) 0); - flow.setPriority(DEFAULT_IPSWITCH_PRIORITY); - - String policyName = host.getNetworkAddress().getHostAddress() - + "/32"; - String flowName = "[" - + (!inPort.getType().equals(NodeConnectorIDType.ALL) ? - (inPort.getID()).toString() - + "," : "") - + host.getNetworkAddress().getHostAddress() + "/32 on N " - + currNode + "]"; - FlowEntry po = new FlowEntry(policyName, flowName, flow, currNode); - - /* Now save the rule in the DB rule, so on updates from topology we - * can selectively */ - pos.put(inPort, po); - this.rulesDB.put(key, pos); - if (!inPort.getType().equals(NodeConnectorIDType.ALL)) { - log.debug("Adding Match(inPort = {} , DIP = {})" + - " Action(outPort= {}) to node {}", - new Object[] { inPort, - host.getNetworkAddress().getHostAddress(), - outPort, currNode}); - if ((removed_po != null) - && (!po.getFlow().getMatch().equals( - removed_po.getFlow().getMatch()))) { - log.debug("Old Flow match: {}, New Flow match: {}", - removed_po.getFlow().getMatch(), po.getFlow() - .getMatch()); - addTobePrunedPolicy(currNode, removed_po, po); - } - - } else { - log.debug("Adding policyMatch(DIP = {}) Action(outPort= {}) " + - "to node {}", new Object[] { - host.getNetworkAddress().getHostAddress(), outPort, - currNode}); - } - } - } - - /** - * Calculate the per-Host rules to be installed in the rulesDB, - * and that will later on be installed in HW, this routine will - * implicitly calculate the shortest path tree among the switch - * to which the host is attached and all the other switches in the - * network and will automatically create all the rules that allow - * a /32 destination IP based forwarding, as in traditional IP - * networks. - * - * @param host Host for which we are going to prepare the rules in the rulesDB - * - * @return A set of switches touched by the calculation - */ - private Set preparePerHostRules(HostNodeConnector host) { - if (host == null) { - return null; - } - - //TODO: race condition! unset* functions can make these null. - if (this.routing == null) { - return null; - } - if (this.switchManager == null) { - return null; - } - if (this.rulesDB == null) { - return null; - } - - Node rootNode = host.getnodeconnectorNode(); - Set nodes = this.switchManager.getNodes(); - Set switchesToProgram = new HashSet(); - HostNodePair key; - HashMap pos; - FlowEntry po; - - // for all nodes in the system - for (Node node : nodes) { - if (node.equals(rootNode)) { - // We skip it because for the node with host attached - // we will process in every case even if there are no - // routes - continue; - } - List links; - Path res = this.routing.getRoute(node, rootNode); - if ((res == null) || ((links = res.getEdges()) == null)) { - // No route from node to rootNode can be found, back out any - // existing forwarding rules if they exist. - log.debug("NO Route/Path between SW[{}] --> SW[{}] cleaning " + - "potentially existing entries", node, rootNode); - key = new HostNodePair(host, node); - pos = this.rulesDB.get(key); - if (pos != null) { - for (Map.Entry e : pos.entrySet()) { - po = e.getValue(); - if (po != null) { - // uninstall any existing rules we put in the - // ForwardingRulesManager - this.frm.uninstallFlowEntry(po); - } - } - this.rulesDB.remove(key); - } - continue; - } - - log.debug("Route between SW[{}] --> SW[{}]", node, rootNode); - Node currNode = node; - key = new HostNodePair(host, currNode); - - // for each link in the route from here to there - for (Edge link : links) { - if (link == null) { - log.error("Could not retrieve the Link"); - // TODO: should we keep going? - continue; - } - - log.debug(link.toString()); - - // Index all the switches to be programmed - updatePerHostRuleInSW(host, currNode, rootNode, link, key); - if ((this.rulesDB.get(key)) != null) { - /* Calling updatePerHostRuleInSW() doesn't guarantee that - * rules will be added in currNode (e.g, there is only one - * link from currNode to rootNode This check makes sure that - * there are some rules in the rulesDB for the given key - * prior to adding switch to switchesToProgram - */ - switchesToProgram.add(currNode); - } - currNode = link.getHeadNodeConnector().getNode(); - key = new HostNodePair(host, currNode); - } - } - - // This rule will be added no matter if any topology is built - // or no, it serve as a way to handle the case of a node with - // multiple hosts attached to it but not yet connected to the - // rest of the world - switchesToProgram.add(rootNode); - updatePerHostRuleInSW(host, rootNode, rootNode, null, - new HostNodePair(host, rootNode)); - - // log.debug("Getting out at the end!"); - return switchesToProgram; - } - - /** - * Calculate the per-Host rules to be installed in the rulesDB - * from a specific switch when a host facing port comes up. - * These rules will later on be installed in HW. This routine - * will implicitly calculate the shortest path from the switch - * where the port has come up to the switch where host is , - * attached and will automatically create all the rules that allow - * a /32 destination IP based forwarding, as in traditional IP - * networks. - * - * @param host Host for which we are going to prepare the rules in the rulesDB - * @param swId Switch ID where the port has come up - * - * @return A set of switches touched by the calculation - */ - private Set preparePerHostPerSwitchRules(HostNodeConnector host, - Node node, NodeConnector swport) { - if ((host == null) || (node == null)) { - return null; - } - if (this.routing == null) { - return null; - } - if (this.switchManager == null) { - return null; - } - if (this.rulesDB == null) { - return null; - } - - Node rootNode = host.getnodeconnectorNode(); - Set switchesToProgram = new HashSet(); - HostNodePair key; - Map pos; - FlowEntry po; - List links; - - Path res = this.routing.getRoute(node, rootNode); - if ((res == null) || ((links = res.getEdges()) == null)) { - // the routing service doesn't know how to get there from here - log.debug("NO Route/Path between SW[{}] --> SW[{}] cleaning " + - "potentially existing entries", node, rootNode); - key = new HostNodePair(host, node); - pos = this.rulesDB.get(key); - if (pos != null) { - for (Map.Entry e : pos.entrySet()) { - po = e.getValue(); - if (po != null) { - //Uninstall the policy - this.frm.uninstallFlowEntry(po); - } - } - this.rulesDB.remove(key); - } - return null; - } - - log.debug("Route between SW[{}] --> SW[{}]", node, rootNode); - Integer curr; - Node currNode = node; - key = new HostNodePair(host, currNode); - Edge link; - for (curr = 0; curr < links.size(); curr++) { - link = links.get(curr); - if (link == null) { - log.error("Could not retrieve the Link"); - continue; - } - - log.debug("Link [{}/{}] --> [{}/{}]", new Object[] { - currNode, link.getHeadNodeConnector(), - link.getHeadNodeConnector().getNode(), - link.getTailNodeConnector()}); - - // Index all the switches to be programmed - switchesToProgram.add(currNode); - updatePerHostRuleInSW(host, currNode, rootNode, link, key); - break; // come out of the loop for port up case, interested only in programming one switch - } - - // This rule will be added no matter if any topology is built - // or no, it serve as a way to handle the case of a node with - // multiple hosts attached to it but not yet connected to the - // rest of the world - // switchesToProgram.add(rootNode); - //updatePerHostRuleInSW(host, rootNode, - // rootNode, null, - // new HostNodePair(host, rootNode),ports); - - // log.debug("Getting out at the end!"); - return switchesToProgram; - } - - /** - * Routine that fetch the per-Host rules from the rulesDB and - * install in HW, the one having the same match rules will be - * overwritten silently. - * - * @param host host for which we want to install in HW the per-Host rules - * @param switchesToProgram list of switches to be programmed in - * HW, usually are them all, but better to be explicit, that list - * may change with time based on new switch addition/removal - * - * @return a return code that convey the programming status of the HW - */ - private RulesProgrammingReturnCode installPerHostRules( - HostNodeConnector host, Set switchesToProgram) { - RulesProgrammingReturnCode retCode = RulesProgrammingReturnCode.SUCCESS; - if (host == null || switchesToProgram == null) { - return RulesProgrammingReturnCode.FAILED_WRONG_PARAMS; - } - Map pos; - FlowEntry po; - // Now program every single switch - log.debug("Inside installPerHostRules"); - for (Node swId : switchesToProgram) { - HostNodePair key = new HostNodePair(host, swId); - pos = this.rulesDB.get(key); - if (pos == null) { - continue; - } - for (Map.Entry e : pos.entrySet()) { - po = e.getValue(); - if (po != null) { - // Populate the Policy field now - Status poStatus = this.frm.modifyOrAddFlowEntry(po); - if (!poStatus.isSuccess()) { - log.error("Failed to install policy: " - + po.getGroupName() + " (" - + poStatus.getDescription() + ")"); - - retCode = RulesProgrammingReturnCode.FAILED_FEW_SWITCHES; - // Remove the entry from the DB, it was not installed! - this.rulesDB.remove(key); - } else { - log.debug("Successfully installed policy " - + po.toString() + " on switch " + swId); - } - } else { - log.error("Cannot find a policy for SW:({}) Host: ({})", - swId, host); - /* // Now dump every single rule */ - /* for (HostNodePair dumpkey : this.rulesDB.keySet()) { */ - /* po = this.rulesDB.get(dumpkey); */ - /* log.debug("Dumping entry H{" + dumpkey.getHost() + "} S{" + dumpkey.getSwitchId() + "} = {" + (po == null ? "null policy" : po)); */ - /* } */ - } - } - } - log.debug("Leaving installPerHostRules"); - return retCode; - } - - /** - * Cleanup all the host rules for a given host - * - * @param host Host for which the host rules need to be cleaned - * up, the host could be null in that case it match all the hosts - * - * @return a return code that convey the programming status of the HW - */ - private RulesProgrammingReturnCode uninstallPerHostRules(HostNodeConnector host) { - RulesProgrammingReturnCode retCode = RulesProgrammingReturnCode.SUCCESS; - Map pos; - FlowEntry po; - // Now program every single switch - for (HostNodePair key : this.rulesDB.keySet()) { - if (host == null || key.getHost().equals(host)) { - pos = this.rulesDB.get(key); - for (Map.Entry e : pos.entrySet()) { - po = e.getValue(); - if (po != null) { - // Uninstall the policy - this.frm.uninstallFlowEntry(po); - } - } - this.rulesDB.remove(key); - } - } - return retCode; - } - - /** - * Cleanup all the host rules for a given node, triggered when the - * switch disconnects, so there is no reason for Hw cleanup - * because it's disconnected anyhow - * TBD - Revisit above stmt in light of CSCus88743 - * @param targetNode Node for which we want to do cleanup - * - */ - private void uninstallPerNodeRules(Node targetNode) { - //RulesProgrammingReturnCode retCode = RulesProgrammingReturnCode.SUCCESS; - Map pos; - FlowEntry po; - - // Now program every single switch - for (HostNodePair key : this.rulesDB.keySet()) { - Node node = key.getNode(); - if (targetNode == null || node.equals(targetNode)) { - log.debug("Work on {} host {}", node, key.getHost()); - pos = this.rulesDB.get(key); - for (Map.Entry e : pos.entrySet()) { - po = e.getValue(); - if (po != null) { - // Uninstall the policy - this.frm.uninstallFlowEntry(po); - } - } - log.debug("Remove {}", key); - this.rulesDB.remove(key); - } - } - } - - /** - * Cleanup all the host rules currently present in the rulesDB - * - * @return a return code that convey the programming status of the HW - */ - private RulesProgrammingReturnCode uninstallPerHostRules() { - return uninstallPerHostRules(null); - } - - @Override - public void recalculateDone() { - if (this.hostTracker == null) { - //Not yet ready to process all the updates - //TODO: we should make sure that this call is executed eventually - return; - } - Set allHosts = this.hostTracker.getAllHosts(); - for (HostNodeConnector host : allHosts) { - Set switches = preparePerHostRules(host); - if (switches != null) { - // This will refresh existing rules, by overwriting - // the previous ones - installPerHostRules(host, switches); - pruneExcessRules(switches); - } - } - } - - void addTobePrunedPolicy(Node swId, FlowEntry po, FlowEntry new_po) { - List pl = tobePrunedPos.get(swId); - if (pl == null) { - pl = new LinkedList(); - tobePrunedPos.put(swId, pl); - } - pl.add(po); - log.debug("Adding Pruned Policy for SwId: {}", swId); - log.debug("Old Policy: {}", po); - log.debug("New Policy: {}", new_po); - } - - private void pruneExcessRules(Set switches) { - for (Node swId : switches) { - List pl = tobePrunedPos.get(swId); - if (pl != null) { - log.debug("Policies for Switch: {} in the list to be deleted: {}", swId, pl); - Iterator plIter = pl.iterator(); - //for (Policy po: pl) { - while (plIter.hasNext()) { - FlowEntry po = plIter.next(); - log.error("Removing Policy, Switch: {} Policy: {}", swId, po); - this.frm.uninstallFlowEntry(po); - plIter.remove(); - } - } - // tobePrunedPos.remove(swId); - } - } - - /** - * A Host facing port has come up in a container. Add rules on the switch where this - * port has come up for all the known hosts to the controller. - * @param swId switch id of the port where port came up - * @param swPort port which came up - */ - private void updateRulesforHIFup(Node node, NodeConnector swPort) { - if (this.hostTracker == null) { - //Not yet ready to process all the updates - return; - } - log.debug("Host Facing Port in a container came up, install the rules for all hosts from this port !"); - Set allHosts = this.hostTracker.getAllHosts(); - for (HostNodeConnector host : allHosts) { - if (node.equals(host.getnodeconnectorNode())) { - /* - * This host resides behind the same switch and port for which a port up - * message is received. Ideally this should not happen, but if it does, - * don't program any rules for this host - */ - continue; - } - Set switches = preparePerHostPerSwitchRules(host, node, - swPort); - if (switches != null) { - // This will refresh existing rules, by overwriting - // the previous ones - installPerHostRules(host, switches); - } - } - - } - - @Override - public void notifyHTClient(HostNodeConnector host) { - if (host == null) { - return; - } - Set switches = preparePerHostRules(host); - if (switches != null) { - installPerHostRules(host, switches); - - // Green light for sending pending packet to this host. Safe to call if there are none. - sendPendingPacket(host.getNetworkAddress()); - } - } - - @Override - public void notifyHTClientHostRemoved(HostNodeConnector host) { - if (host == null) { - return; - } - uninstallPerHostRules(host); - } - - @Override - public void notifyNode(Node node, UpdateType type, - Map propMap) { - if (node == null) { - return; - } - - switch (type) { - case REMOVED: - log.debug("Node {} gone, doing a cleanup", node); - uninstallPerNodeRules(node); - break; - default: - break; - } - } - - @Override - public void notifyNodeConnector(NodeConnector nodeConnector, - UpdateType type, Map propMap) { - if (nodeConnector == null) { - return; - } - - boolean up = false; - switch (type) { - case ADDED: - up = true; - break; - case REMOVED: - break; - case CHANGED: - State state = (State) propMap.get(State.StatePropName); - if ((state != null) && (state.getValue() == State.EDGE_UP)) { - up = true; - } - break; - default: - return; - } - - if (up) { - handleNodeConnectorStatusUp(nodeConnector); - } else { - handleNodeConnectorStatusDown(nodeConnector); - } - } - - private void handleNodeConnectorStatusUp(NodeConnector nodeConnector) { - if (topologyManager == null) { - log.debug("topologyManager is not set yet"); - return; - } - - if (topologyManager.isInternal(nodeConnector)) { - log.debug("{} is not a host facing link", nodeConnector); - return; - } - - log.debug("{} is up", nodeConnector); - updateRulesforHIFup(nodeConnector.getNode(), nodeConnector); - } - - private void handleNodeConnectorStatusDown(NodeConnector nodeConnector) { - log.debug("{} is down", nodeConnector); - } - - void setClusterContainerService(IClusterContainerServices s) { - log.debug("Cluster Service set"); - this.clusterContainerService = s; - } - - void unsetClusterContainerService(IClusterContainerServices s) { - if (this.clusterContainerService == s) { - log.debug("Cluster Service removed!"); - this.clusterContainerService = null; - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - startUp(); - } - - /** - * Function called by the dependency manager when at least one - * dependency become unsatisfied or when the component is shutting - * down because for example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called - * and after the services provided by the class are registered in - * the service registry - * - */ - void start() { - } - - /** - * Function called by the dependency manager before the services - * exported by the component are unregistered, this will be - * followed by a "destroy ()" calls - * - */ - void stop() { - pendingPacketsAgerTimer.cancel(); - pendingPacketDestinations.clear(); - } - - public void setSwitchManager(ISwitchManager switchManager) { - this.switchManager = switchManager; - } - - public void unsetSwitchManager(ISwitchManager switchManager) { - if (this.switchManager == switchManager) { - this.switchManager = null; - } - } - - @Override - public PacketResult receiveDataPacket(RawPacket inPkt) { - if (inPkt == null) { - return PacketResult.IGNORED; - } - log.trace("Received a frame of size: {}", inPkt.getPacketData().length); - Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt); - if (formattedPak instanceof Ethernet) { - Object nextPak = formattedPak.getPayload(); - if (nextPak instanceof IPv4) { - log.trace("Handle punted IP packet: {}", formattedPak); - handlePuntedIPPacket((IPv4) nextPak, inPkt.getIncomingNodeConnector(), true); - } - } - return PacketResult.IGNORED; - - } - - private void handlePuntedIPPacket(IPv4 pkt, NodeConnector incomingNodeConnector, boolean allowAddPending) { - InetAddress dIP = NetUtils.getInetAddress(pkt.getDestinationAddress()); - if (dIP == null || hostTracker == null) { - log.debug("Invalid param(s) in handlePuntedIPPacket.. DestIP: {}. hostTracker: {}", dIP, hostTracker); - return; - } - HostNodeConnector destHost = hostTracker.hostFind(dIP); - /* - * In cases when incoming and outgoing connectors are in the same node, there is no need - * to verify that there is a route. Because of that, we will only need routing.getRoute() - * if we know that src and dst nodes are different. - */ - if (destHost != null - && (incomingNodeConnector.getNode().equals(destHost.getnodeconnectorNode()) || - routing == null || - routing.getRoute(incomingNodeConnector.getNode(), destHost.getnodeconnectorNode()) != null)) { - - log.trace("Host {} is at {}", dIP, destHost.getnodeConnector()); - - // If SimpleForwarding is aware of this host, it will try to install - // a path. Forward packet until it's done. - if (dataPacketService != null) { - - /* - * if we know where the host is and there's a path from where this - * packet was punted to where the host is, then attempt best effort delivery to the host - */ - NodeConnector nc = destHost.getnodeConnector(); - log.trace("Forwarding punted IP received at {} to {}", incomingNodeConnector, nc); - // re-encode the Ethernet packet (the parent of the IPv4 packet) - RawPacket rp = this.dataPacketService.encodeDataPacket(pkt.getParent()); - rp.setOutgoingNodeConnector(nc); - this.dataPacketService.transmitDataPacket(rp); - } - } else if (allowAddPending) { - // If we made it here, let's hang on to the punted packet, with hopes that its destination - // will become available soon. - addToPendingPackets(dIP, pkt, incomingNodeConnector); - } else { - log.warn("Dropping punted IP packet received at {} to Host {}", incomingNodeConnector, dIP); - } - } -} diff --git a/opendaylight/adsal/samples/simpleforwarding/src/test/java/org/opendaylight/controller/samples/simpleforwarding/internal/HostSwitchTest.java b/opendaylight/adsal/samples/simpleforwarding/src/test/java/org/opendaylight/controller/samples/simpleforwarding/internal/HostSwitchTest.java deleted file mode 100644 index 6627029ef0..0000000000 --- a/opendaylight/adsal/samples/simpleforwarding/src/test/java/org/opendaylight/controller/samples/simpleforwarding/internal/HostSwitchTest.java +++ /dev/null @@ -1,380 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.samples.simpleforwarding.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashMap; -import org.junit.Test; -import org.junit.Assert; - -import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.samples.simpleforwarding.HostNodePair; - - -public class HostSwitchTest { - @Test - public void TestEquality() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - HostNodePair hsw1 = new HostNodePair(h1, NodeCreator.createOFNode(1L)); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(1L)); - Assert.assertTrue(hsw1.equals(hsw2)); - } - - @Test - public void TestDiversityHost() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.2"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - - HostNodePair hsw1 = new HostNodePair(h1, NodeCreator.createOFNode(1L)); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(1L)); - Assert.assertTrue(!hsw1.equals(hsw2)); - } - - @Test - public void TestDiversitySwitch() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - - HostNodePair hsw1 = new HostNodePair(h1, NodeCreator.createOFNode(1L)); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(2L)); - Assert.assertTrue(!hsw1.equals(hsw2)); - } - - @Test - public void TestDiversityAll() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.2"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - - HostNodePair hsw1 = new HostNodePair(h1, NodeCreator.createOFNode(1L)); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(2L)); - Assert.assertTrue(!hsw1.equals(hsw2)); - } - - @Test - public void TestEqualHashCode1() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - HostNodePair hsw1 = new HostNodePair(h1, NodeCreator.createOFNode(1L)); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(1L)); - Assert.assertTrue(hsw1.hashCode() == hsw2.hashCode()); - } - - @Test - public void TestEqualHashCode2() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.2"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.2"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - - HostNodePair hsw1 = new HostNodePair(h1, NodeCreator.createOFNode(1L)); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(1L)); - Assert.assertTrue(hsw1.hashCode() == hsw2.hashCode()); - } - - @Test - public void TestDiverseHashCodeHost() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.2"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - HostNodePair hsw1 = new HostNodePair(h1, NodeCreator.createOFNode(1L)); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(1L)); - Assert.assertTrue(hsw1.hashCode() != hsw2.hashCode()); - } - - @Test - public void TestDiverseHashCodeSwitch() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - - HostNodePair hsw1 = new HostNodePair(h1, NodeCreator.createOFNode(1L)); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(2L)); - Assert.assertTrue(hsw1.hashCode() != hsw2.hashCode()); - } - - @Test - public void TestDiverseHashCodeAll() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.3"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - - HostNodePair hsw1 = new HostNodePair(h1, NodeCreator.createOFNode(1L)); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(2L)); - Assert.assertTrue(hsw1.hashCode() != hsw2.hashCode()); - } - - @Test - public void TestUsageAsKey() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - - HostNodePair hsw1 = new HostNodePair(h1, NodeCreator.createOFNode(1L)); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(1L)); - HashMap hm = new HashMap(); - hm.put(hsw1, new Long(10)); - Assert.assertTrue(hm.get(hsw2) != null); - Assert.assertTrue(hm.get(hsw2).equals(new Long(10))); - } - - @Test - public void TestUsageAsKeyChangingField() { - HostNodeConnector h1 = null; - HostNodeConnector h2 = null; - InetAddress ip1 = null; - try { - ip1 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - InetAddress ip2 = null; - try { - ip2 = InetAddress.getByName("10.0.0.1"); - } catch (UnknownHostException e) { - return; - } - try { - h1 = new HostNodeConnector(ip1); - } catch (ConstructionException e) { - return; - } - try { - h2 = new HostNodeConnector(ip2); - } catch (ConstructionException e) { - return; - } - HostNodePair hsw1 = new HostNodePair(h1, null); - HostNodePair hsw2 = new HostNodePair(h2, NodeCreator.createOFNode(1L)); - hsw1.setNode(NodeCreator.createOFNode(1L)); - HashMap hm = new HashMap(); - hm.put(hsw1, new Long(10)); - Assert.assertTrue(hm.get(hsw2) != null); - Assert.assertTrue(hm.get(hsw2).equals(new Long(10))); - } -} \ No newline at end of file diff --git a/opendaylight/adsal/security/pom.xml b/opendaylight/adsal/security/pom.xml deleted file mode 100644 index 4467aafa17..0000000000 --- a/opendaylight/adsal/security/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../commons/opendaylight - - - security - 0.6.0-SNAPSHOT - bundle - - - orbit - org.apache.catalina - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - usermanager - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.apache.catalina - org.slf4j, - javax.servlet, - org.apache.catalina, - org.apache.catalina.connector, - org.apache.catalina.valves, - org.apache.catalina.realm, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.usermanager - org.opendaylight.controller.security - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/security/src/main/java/org/opendaylight/controller/security/ControllerCustomRealm.java b/opendaylight/adsal/security/src/main/java/org/opendaylight/controller/security/ControllerCustomRealm.java deleted file mode 100644 index 157909424b..0000000000 --- a/opendaylight/adsal/security/src/main/java/org/opendaylight/controller/security/ControllerCustomRealm.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.security; - -import java.security.Principal; -import java.util.ArrayList; -import java.util.List; - -import org.apache.catalina.realm.GenericPrincipal; -import org.apache.catalina.realm.RealmBase; -import org.opendaylight.controller.sal.authorization.AuthResultEnum; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.usermanager.IUserManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ControllerCustomRealm extends RealmBase { - - private static final String name = "ControllerCustomRealm"; - - private static final Logger logger = LoggerFactory - .getLogger(ControllerCustomRealm.class); - - @Override - protected String getName() { - return name; - } - - @Override - protected String getPassword(String username) { - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - if (userManager != null) { - return userManager.getPassword(username); - } else { - throw new RuntimeException("User Manager reference is null"); - } - } - - @Override - protected Principal getPrincipal(String username) { - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - if (userManager != null) { - List controllerRoles = new ArrayList(); - for (UserLevel level : userManager.getUserLevels(username)) { - controllerRoles.add(level.toString()); - } - return new GenericPrincipal(username, "", controllerRoles); - } else { - throw new RuntimeException("User Manager reference is null"); - } - } - - @Override - public Principal authenticate(String username, String credentials) { - - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - if (userManager != null) { - AuthResultEnum result = userManager.authenticate(username, - credentials); - if (result.equals(AuthResultEnum.AUTHOR_PASS) - || result.equals(AuthResultEnum.AUTH_ACCEPT_LOC) - || result.equals(AuthResultEnum.AUTH_ACCEPT)) { - return this.getPrincipal(username); - } else { - logger.debug("Authentication failed for user " + username); - return null; - } - } else { - throw new RuntimeException("User Manager reference is null"); - } - } - -} diff --git a/opendaylight/adsal/statisticsmanager/api/pom.xml b/opendaylight/adsal/statisticsmanager/api/pom.xml deleted file mode 100644 index a7c59df22f..0000000000 --- a/opendaylight/adsal/statisticsmanager/api/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - statisticsmanager - 0.7.0-SNAPSHOT - bundle - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - sal - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.forwardingrulesmanager, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.flowprogrammer, org.slf4j, - org.opendaylight.controller.sal.reader, - org.apache.felix.dm - org.opendaylight.controller.statisticsmanager - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/statisticsmanager/api/src/main/java/org/opendaylight/controller/statisticsmanager/IStatisticsManager.java b/opendaylight/adsal/statisticsmanager/api/src/main/java/org/opendaylight/controller/statisticsmanager/IStatisticsManager.java deleted file mode 100644 index c717ccf208..0000000000 --- a/opendaylight/adsal/statisticsmanager/api/src/main/java/org/opendaylight/controller/statisticsmanager/IStatisticsManager.java +++ /dev/null @@ -1,120 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statisticsmanager; - -import java.util.List; -import java.util.Map; - -import org.opendaylight.controller.forwardingrulesmanager.FlowEntry; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; - -/** - * Interface which defines the available methods for retrieving - * the network nodes statistics. - */ -public interface IStatisticsManager { - /** - * Return all the statistics for all the flows present on the specified node - * in the current container context. If the context is the default - * container, the returned statistics are for all the flows installed on the - * node, regardless of the container they belong to - * - * @param node - * The network node - * @return List of flows installed on the network node. Null if specified - * node is null. Empty list if node/stat is not present. - */ - List getFlows(Node node); - - /** - * Same as the getFlows method. - * The only difference is that this method does not return cached flows. - * It will always make a request to the node to get all the flows for that node. - * If the request times out or gets an error, we revert to getting the cached flows. - * @see IStatisticsManager#getFlows - * @param node - * @return List of flows installed on the network node. - */ - List getFlowsNoCache(Node node); - - /** - * Returns the statistics for the flows specified in the list - * - * @param flows - * @return A map of flows per node installed on that node, empty map if - * flows is null/empty. - */ - Map> getFlowStatisticsForFlowList(List flows); - - /** - * Returns the number of flows installed on the switch in the current - * container context If the context is the default container, the returned - * value is the number of all the flows installed on the switch regardless - * of the container they belong to - * - * @param node - * @return number of flows on specified node or (-1) if node was not found - */ - int getFlowsNumber(Node node); - - /** - * Returns the node description for the specified node retrieved by the - * protocol plugin component and cached by statistics manager. - * Null if node not found. - * - * @param node - * @return node description - */ - NodeDescription getNodeDescription(Node node); - - /** - * Returns the statistics for the specified node connector as it was - * retrieved by the protocol plugin component and cached by statistics - * manager. - * - * @param node - * @return Node connector statistics or null if requested stats was not - * found. - */ - NodeConnectorStatistics getNodeConnectorStatistics(NodeConnector nodeConnector); - - /** - * Returns the statistics for all the node connector present on the - * specified network node - * - * @param node - * @return List of node connector statistics. Null if node is null. Empty - * list if node/stats is not present. - */ - List getNodeConnectorStatistics(Node node); - - /** - * Returns the statistics for the specified table of the node - * - * @param nodeTable - * @return Table statistics. Null if node table is null or stats not found. - */ - NodeTableStatistics getNodeTableStatistics(NodeTable nodeTable); - - /** - * Returns the statistics for all the tables of the node - * - * @param nodeTable - * @return List of table stats. Null if node is null. Empty list if - * node/stats not found. - */ - List getNodeTableStatistics(Node node); -} diff --git a/opendaylight/adsal/statisticsmanager/implementation/pom.xml b/opendaylight/adsal/statisticsmanager/implementation/pom.xml deleted file mode 100644 index f4334f3878..0000000000 --- a/opendaylight/adsal/statisticsmanager/implementation/pom.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - statisticsmanager.implementation - 0.6.0-SNAPSHOT - bundle - - - reuseReports - target/jacoco-it.exec - target/jacoco.exec - - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller - statisticsmanager - - - org.opendaylight.controller - switchmanager - - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.reader, - org.opendaylight.controller.sal.utils, - org.slf4j, - org.opendaylight.controller.sal.inventory, - org.opendaylight.controller.sal.match, - org.opendaylight.controller.sal.connection, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.statisticsmanager, - org.opendaylight.controller.forwardingrulesmanager, - org.opendaylight.controller.connectionmanager, - org.apache.felix.dm - org.opendaylight.controller.statisticsmanager.internal.Activator - - - ${project.basedir}/META-INF - - - - org.jacoco - jacoco-maven-plugin - - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - report - - test - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/Activator.java b/opendaylight/adsal/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/Activator.java deleted file mode 100644 index 7eb32b05f7..0000000000 --- a/opendaylight/adsal/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/Activator.java +++ /dev/null @@ -1,92 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statisticsmanager.internal; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.core.IContainer; -import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; -import org.opendaylight.controller.sal.reader.IReadService; -import org.opendaylight.controller.sal.reader.IReadServiceListener; -import org.opendaylight.controller.statisticsmanager.IStatisticsManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory.getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the list of - * known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - public Object[] getImplementations() { - Object[] res = { StatisticsManager.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies is - * required. - * - * @param c - * dependency manager Component object, used for configuring the - * dependencies exported and imported - * @param imp - * Implementation class that is being configured, needed as long - * as the same routine can configure multiple implementations - * @param containerName - * The containerName being configured, this allow also optional - * per-container different behavior if needed, usually should not - * be the case though. - */ - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(StatisticsManager.class)) { - // export the service - Dictionary props = new Hashtable(); - Set propSet = new HashSet(); - // trigger cache - propSet.add(StatisticsManager.TRIGGERS_CACHE); - // flow statistics cache - propSet.add(StatisticsManager.FLOW_STATISTICS_CACHE); - props.put("cachenames", propSet); - - String interfaces[] = new String[] { - IStatisticsManager.class.getName(), - IReadServiceListener.class.getName(), - IListenInventoryUpdates.class.getName(), - ICacheUpdateAware.class.getName() }; - c.setInterface(interfaces, props); - - c.add(createContainerServiceDependency(containerName).setService(IReadService.class) - .setCallbacks("setReaderService", "unsetReaderService").setRequired(true)); - c.add(createContainerServiceDependency(containerName).setService(IClusterContainerServices.class) - .setCallbacks("setClusterContainerService", "unsetClusterContainerService").setRequired(true)); - c.add(createContainerServiceDependency(containerName).setService(IContainer.class) - .setCallbacks("setIContainer", "unsetIContainer").setRequired(true)); - c.add(createServiceDependency().setService(IConnectionManager.class) - .setCallbacks("setIConnectionManager", "unsetIConnectionManager").setRequired(false)); - - } - } -} diff --git a/opendaylight/adsal/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManager.java b/opendaylight/adsal/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManager.java deleted file mode 100644 index 2376b8752f..0000000000 --- a/opendaylight/adsal/statisticsmanager/implementation/src/main/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManager.java +++ /dev/null @@ -1,594 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statisticsmanager.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.forwardingrulesmanager.FlowEntry; -import org.opendaylight.controller.sal.connection.ConnectionLocality; -import org.opendaylight.controller.sal.core.IContainer; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeTable; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.IReadService; -import org.opendaylight.controller.sal.reader.IReadServiceListener; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.opendaylight.controller.sal.reader.NodeTableStatistics; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.statisticsmanager.IStatisticsManager; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class caches latest network nodes statistics as notified by reader - * services and provides API to retrieve them. - */ -public class StatisticsManager implements IStatisticsManager, IReadServiceListener, IListenInventoryUpdates, - ICacheUpdateAware { - private static final Logger log = LoggerFactory.getLogger(StatisticsManager.class); - private IContainer container; - private IClusterContainerServices clusterContainerService; - private IReadService reader; - private IConnectionManager connectionManager; - //statistics caches - private ConcurrentMap> flowStatistics; - private ConcurrentMap> nodeConnectorStatistics; - private ConcurrentMap> tableStatistics; - private ConcurrentMap descriptionStatistics; - - // data structure for latches - // this is not a cluster cache - private ConcurrentMap latches = new ConcurrentHashMap(); - // 30 seconds is the timeout. - // the value of this can be tweaked based on performance tests. - private static long latchTimeout = 30; - - // cache for flow stats refresh triggers - // an entry added to this map triggers the statistics manager - // to which the node is connected to get the latest flow stats from that node - // this is a cluster cache - private ConcurrentMap triggers; - - // use an atomic integer for the triggers key - private AtomicInteger triggerKey = new AtomicInteger(); - - // single thread executor for the triggers - private ExecutorService triggerExecutor; - - static final String TRIGGERS_CACHE = "statisticsmanager.triggers"; - static final String FLOW_STATISTICS_CACHE = "statisticsmanager.flowStatistics"; - - private void nonClusterObjectCreate() { - flowStatistics = new ConcurrentHashMap>(); - nodeConnectorStatistics = new ConcurrentHashMap>(); - tableStatistics = new ConcurrentHashMap>(); - descriptionStatistics = new ConcurrentHashMap(); - triggers = new ConcurrentHashMap(); - } - - private void allocateCaches() { - if (clusterContainerService == null) { - nonClusterObjectCreate(); - log.error("Clustering service unavailable. Allocated non-cluster statistics manager cache."); - return; - } - - try { - clusterContainerService.createCache(FLOW_STATISTICS_CACHE, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache("statisticsmanager.nodeConnectorStatistics", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache("statisticsmanager.tableStatistics", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache("statisticsmanager.descriptionStatistics", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache(TRIGGERS_CACHE, - EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL, IClusterServices.cacheMode.ASYNC)); - } catch (CacheConfigException cce) { - log.error("Statistics cache configuration invalid - check cache mode"); - } catch (CacheExistException ce) { - log.debug("Skipping statistics cache creation - already present"); - } - } - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - ConcurrentMap map; - - if (this.clusterContainerService == null) { - log.warn("Can't retrieve statistics manager cache, Clustering service unavailable."); - return; - } - - log.debug("Statistics Manager - retrieveCaches for Container {}", container); - - map = clusterContainerService.getCache(FLOW_STATISTICS_CACHE); - if (map != null) { - this.flowStatistics = (ConcurrentMap>) map; - } else { - log.error("Cache allocation failed for statisticsmanager.flowStatistics in container {}", container.getName()); - } - - map = clusterContainerService.getCache("statisticsmanager.nodeConnectorStatistics"); - if (map != null) { - this.nodeConnectorStatistics = (ConcurrentMap>) map; - } else { - log.error("Cache allocation failed for statisticsmanager.nodeConnectorStatistics in container {}", container.getName()); - } - - map = clusterContainerService.getCache("statisticsmanager.tableStatistics"); - if (map != null) { - this.tableStatistics = (ConcurrentMap>) map; - } else { - log.error("Cache allocation failed for statisticsmanager.tableStatistics in container {}", container.getName()); - } - - map = clusterContainerService.getCache("statisticsmanager.descriptionStatistics"); - if (map != null) { - this.descriptionStatistics = (ConcurrentMap) map; - } else { - log.error("Cache allocation failed for statisticsmanager.descriptionStatistics in container {}", container.getName()); - } - - map = clusterContainerService.getCache(TRIGGERS_CACHE); - if (map != null) { - this.triggers = (ConcurrentMap) map; - } else { - log.error("Cache allocation failed for " + TRIGGERS_CACHE +" in container {}", container.getName()); - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - log.debug("INIT called!"); - allocateCaches(); - retrieveCaches(); - - } - - /** - * Function called by the dependency manager when at least one - * dependency become unsatisfied or when the component is shutting - * down because for example bundle is being stopped. - * - */ - void destroy() { - log.debug("DESTROY called!"); - } - - /** - * Function called by dependency manager after "init ()" is called - * and after the services provided by the class are registered in - * the service registry - * - */ - void start() { - log.debug("START called!"); - this.triggerExecutor = Executors.newSingleThreadExecutor(); - } - - /** - * Function called after registering the service in OSGi service registry. - */ - void started(){ - // Retrieve current statistics so we don't have to wait for next refresh - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance( - ISwitchManager.class, container.getName(), this); - if ((reader != null) && (switchManager != null)) { - Set nodeSet = switchManager.getNodes(); - for (Node node : nodeSet) { - List flows = reader.readAllFlows(node); - if (flows != null) { - flowStatistics.put(node, flows); - } - NodeDescription descr = reader.readDescription(node); - if (descr != null) { - descriptionStatistics.put(node, descr); - } - List tableStats = reader.readNodeTable(node); - if (tableStats != null) { - tableStatistics.put(node, tableStats); - } - List ncStats = reader.readNodeConnectors(node); - if (ncStats != null) { - nodeConnectorStatistics.put(node, ncStats); - } - } - - } else { - log.trace("Failed to retrieve current statistics. Statistics will not be immediately available!"); - } - } - - /** - * Function called by the dependency manager before the services - * exported by the component are unregistered, this will be - * followed by a "destroy ()" calls - * - */ - void stop() { - log.debug("STOP called!"); - this.triggerExecutor.shutdownNow(); - } - - void setClusterContainerService(IClusterContainerServices s) { - log.debug("Cluster Service set for Statistics Mgr"); - this.clusterContainerService = s; - } - - void unsetClusterContainerService(IClusterContainerServices s) { - if (this.clusterContainerService == s) { - log.debug("Cluster Service removed for Statistics Mgr!"); - this.clusterContainerService = null; - } - } - void setIContainer(IContainer c){ - container = c; - } - public void unsetIContainer(IContainer s) { - if (this.container == s) { - this.container = null; - } - } - - public void setReaderService(IReadService service) { - log.debug("Got inventory service set request {}", service); - this.reader = service; - } - - public void unsetReaderService(IReadService service) { - log.debug("Got a service UNset request {}", service); - this.reader = null; - } - - @Override - public List getFlows(Node node) { - if (node == null) { - return Collections.emptyList(); - } - - List flowList = new ArrayList(); - List cachedList = flowStatistics.get(node); - if (cachedList != null){ - flowList.addAll(cachedList); - } - return flowList; - } - - /** - * {@inheritDoc} - */ - @Override - public List getFlowsNoCache(Node node) { - if (node == null) { - return Collections.emptyList(); - } - // check if the node is local to this controller - ConnectionLocality locality = ConnectionLocality.LOCAL; - if(this.connectionManager != null) { - locality = this.connectionManager.getLocalityStatus(node); - } - if (locality == ConnectionLocality.NOT_LOCAL) { - // send a trigger to all and wait for either a response or timeout - CountDownLatch newLatch = new CountDownLatch(1); - CountDownLatch oldLatch = this.latches.putIfAbsent(node, newLatch); - this.triggers.put(this.triggerKey.incrementAndGet(), node); - try { - boolean retStatus; - if(oldLatch != null) { - retStatus = oldLatch.await(StatisticsManager.latchTimeout, TimeUnit.SECONDS); - } else { - retStatus = newLatch.await(StatisticsManager.latchTimeout, TimeUnit.SECONDS); - } - // log the return code as it will give us, if - // the latch timed out. - log.debug("latch timed out {}", !retStatus); - } catch (InterruptedException e) { - // log the error and move on - log.warn("Waiting for statistics response interrupted", e); - // restore the interrupt status - // its a good practice to restore the interrupt status - // if you are not propagating the InterruptedException - Thread.currentThread().interrupt(); - } - // now that the wait is over - // remove the latch entry - this.latches.remove(node); - } else { - // the node is local. - // call the read service - if (this.reader != null) { - List flows = reader.nonCachedReadAllFlows(node); - if (flows != null) { - nodeFlowStatisticsUpdated(node, flows); - } - } - } - // at this point we are ready to return the cached value. - // this cached value will be up to date with a very high probability - // due to what we have done previously ie:- send a trigger for cache update - // or refreshed the cache if the node is local. - return getFlows(node); - } - - @Override - public Map> getFlowStatisticsForFlowList(List flowList) { - Map> statMapOutput = new HashMap>(); - - if (flowList == null || flowList.isEmpty()){ - return statMapOutput; - } - - Node node; - // Index FlowEntries' flows by node so we don't traverse entire flow list for each flowEntry - Map> index = new HashMap>(); - for (FlowEntry flowEntry : flowList) { - node = flowEntry.getNode(); - Set set = (index.containsKey(node) ? index.get(node) : new HashSet()); - set.add(flowEntry.getFlow()); - index.put(node, set); - } - - // Iterate over flows per indexed node and add to output - for (Entry> indexEntry : index.entrySet()) { - node = indexEntry.getKey(); - List flowsPerNode = flowStatistics.get(node); - - if (flowsPerNode != null && !flowsPerNode.isEmpty()){ - List filteredFlows = statMapOutput.containsKey(node) ? - statMapOutput.get(node) : new ArrayList(); - - for (FlowOnNode flowOnNode : flowsPerNode) { - if (indexEntry.getValue().contains(flowOnNode.getFlow())) { - filteredFlows.add(flowOnNode); - } - } - statMapOutput.put(node, filteredFlows); - } - } - return statMapOutput; - } - - @Override - public int getFlowsNumber(Node node) { - List l; - if (node == null || (l = flowStatistics.get(node)) == null){ - return -1; - } - return l.size(); - } - - @Override - public NodeDescription getNodeDescription(Node node) { - if (node == null){ - return null; - } - NodeDescription nd = descriptionStatistics.get(node); - return nd != null? nd.clone() : null; - } - - @Override - public NodeConnectorStatistics getNodeConnectorStatistics(NodeConnector nodeConnector) { - if (nodeConnector == null){ - return null; - } - - List statList = nodeConnectorStatistics.get(nodeConnector.getNode()); - if (statList != null){ - for (NodeConnectorStatistics stat : statList) { - if (stat.getNodeConnector().equals(nodeConnector)){ - return stat; - } - } - } - return null; - } - - @Override - public List getNodeConnectorStatistics(Node node) { - if (node == null){ - return Collections.emptyList(); - } - - List statList = new ArrayList(); - List cachedList = nodeConnectorStatistics.get(node); - if (cachedList != null) { - statList.addAll(cachedList); - } - return statList; - } - - @Override - public NodeTableStatistics getNodeTableStatistics(NodeTable nodeTable) { - if (nodeTable == null){ - return null; - } - List statList = tableStatistics.get(nodeTable.getNode()); - if (statList != null){ - for (NodeTableStatistics stat : statList) { - if (stat.getNodeTable().getID().equals(nodeTable.getID())){ - return stat; - } - } - } - return null; - } - - @Override - public List getNodeTableStatistics(Node node){ - if (node == null){ - return Collections.emptyList(); - } - List statList = new ArrayList(); - List cachedList = tableStatistics.get(node); - if (cachedList != null) { - statList.addAll(cachedList); - } - return statList; - } - - @Override - public void nodeFlowStatisticsUpdated(Node node, List flowStatsList) { - // No equality check because duration fields change constantly - this.flowStatistics.put(node, flowStatsList); - } - - @Override - public void nodeConnectorStatisticsUpdated(Node node, List ncStatsList) { - List currentStat = this.nodeConnectorStatistics.get(node); - if (! ncStatsList.equals(currentStat)){ - this.nodeConnectorStatistics.put(node, ncStatsList); - } - } - - @Override - public void nodeTableStatisticsUpdated(Node node, List tableStatsList) { - List currentStat = this.tableStatistics.get(node); - if (! tableStatsList.equals(currentStat)) { - this.tableStatistics.put(node, tableStatsList); - } - } - - @Override - public void descriptionStatisticsUpdated(Node node, NodeDescription nodeDescription) { - NodeDescription currentDesc = this.descriptionStatistics.get(node); - if (! nodeDescription.equals(currentDesc)){ - this.descriptionStatistics.put(node, nodeDescription); - } - } - - @Override - public void updateNode(Node node, UpdateType type, Set props) { - // If node is removed, clean up stats mappings - if (type == UpdateType.REMOVED) { - flowStatistics.remove(node); - nodeConnectorStatistics.remove(node); - tableStatistics.remove(node); - descriptionStatistics.remove(node); - } - } - - @Override - public void updateNodeConnector(NodeConnector nodeConnector, UpdateType type, Set props) { - // Not interested in this update - } - - public void unsetIConnectionManager(IConnectionManager s) { - if (s == this.connectionManager) { - this.connectionManager = null; - } - } - - public void setIConnectionManager(IConnectionManager s) { - this.connectionManager = s; - } - - @Override - public void entryCreated(Object key, String cacheName, boolean originLocal) { - /* - * Do nothing - */ - } - - @Override - public void entryUpdated(Object key, Object new_value, String cacheName, boolean originLocal) { - if (originLocal) { - /* - * Local updates are of no interest - */ - return; - } - if (cacheName.equals(TRIGGERS_CACHE)) { - log.trace("Got a trigger for key {} : value {}", key, new_value); - final Node n = (Node) new_value; - // check if the node is local to this controller - ConnectionLocality locality = ConnectionLocality.NOT_LOCAL; - if(this.connectionManager != null) { - locality = this.connectionManager.getLocalityStatus(n); - } - if (locality == ConnectionLocality.LOCAL) { - log.trace("trigger for node {} processes locally", n); - // delete the trigger and proceed with handling the trigger - this.triggers.remove(key); - // this is a potentially long running task - // off load it from the listener thread - Runnable r = new Runnable() { - @Override - public void run() { - // the node is local. - // call the read service - if (reader != null) { - List flows = reader.nonCachedReadAllFlows(n); - if (flows != null) { - flowStatistics.put(n, flows); - } - } - } - }; - // submit the runnable for execution - if(this.triggerExecutor != null) { - this.triggerExecutor.execute(r); - } - } - } else if (cacheName.equals(FLOW_STATISTICS_CACHE)) { - // flow statistics cache updated - // get the node - log.trace("Got a flow statistics cache update for key {}", key); - // this is a short running task - // no need of off loading from the listener thread - final Node n = (Node) key; - // check if an outstanding trigger exists for this node - CountDownLatch l = this.latches.get(n); - if(l != null) { - // someone was waiting for this update - // let him know - l.countDown(); - } - } - } - - @Override - public void entryDeleted(Object key, String cacheName, boolean originLocal) { - /* - * Do nothing - */ - } -} diff --git a/opendaylight/adsal/statisticsmanager/implementation/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerTest.java b/opendaylight/adsal/statisticsmanager/implementation/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerTest.java deleted file mode 100644 index a09876eeeb..0000000000 --- a/opendaylight/adsal/statisticsmanager/implementation/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.statisticsmanager.internal; - -import org.junit.Test; - -public class StatisticsManagerTest { - - @Test - public void test() { - StatisticsManager sm = new StatisticsManager(); - - sm.init(); - sm.start(); - sm.stop(); - sm.destroy(); - - } - -} diff --git a/opendaylight/adsal/statisticsmanager/integrationtest/pom.xml b/opendaylight/adsal/statisticsmanager/integrationtest/pom.xml deleted file mode 100644 index 00670cdf25..0000000000 --- a/opendaylight/adsal/statisticsmanager/integrationtest/pom.xml +++ /dev/null @@ -1,172 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.integrationtest - 0.7.0-SNAPSHOT - ../../commons/integrationtest - - - statisticsmanager.integrationtest - 0.6.0-SNAPSHOT - - ../../implementation/target/jacoco-it.exec - - ../../implementation/target/jacoco.exec - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - clustering.stub - - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - configuration.implementation - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - connectionmanager.implementation - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.it.implementation - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - protocol_plugins.stub - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.connection - - - org.opendaylight.controller - sal.connection.implementation - - - org.opendaylight.controller - sal.implementation - - - org.opendaylight.controller - statisticsmanager - - - org.opendaylight.controller - statisticsmanager.implementation - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - switchmanager.implementation - - - org.opendaylight.controller - topologymanager - - - org.slf4j - log4j-over-slf4j - - - - org.ops4j.pax.exam - pax-exam-container-native - test - - - org.ops4j.pax.exam - pax-exam-junit4 - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - test - - - org.ops4j.pax.url - pax-url-aether - test - - - - - - org.jacoco - jacoco-maven-plugin - - ../../implementation/target/jacoco-it.exec - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - true - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/statisticsmanager/integrationtest/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerIT.java b/opendaylight/adsal/statisticsmanager/integrationtest/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerIT.java deleted file mode 100644 index 18cce74c1d..0000000000 --- a/opendaylight/adsal/statisticsmanager/integrationtest/src/test/java/org/opendaylight/controller/statisticsmanager/internal/StatisticsManagerIT.java +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.statisticsmanager.internal; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; -import static org.ops4j.pax.exam.CoreOptions.options; -import static org.ops4j.pax.exam.CoreOptions.systemPackages; -import static org.ops4j.pax.exam.CoreOptions.systemProperty; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.inject.Inject; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.forwardingrulesmanager.FlowEntry; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.Drop; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.flowprogrammer.Flow; -import org.opendaylight.controller.sal.match.Match; -import org.opendaylight.controller.sal.match.MatchType; -import org.opendaylight.controller.sal.reader.FlowOnNode; -import org.opendaylight.controller.sal.reader.NodeConnectorStatistics; -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.opendaylight.controller.statisticsmanager.IStatisticsManager; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.util.PathUtils; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(PaxExam.class) -public class StatisticsManagerIT { - private Logger log = LoggerFactory - .getLogger(StatisticsManagerIT.class); - // get the OSGI bundle context - @Inject - private BundleContext bc; - - private IStatisticsManager manager = null; - - // Configure the OSGi container - @Configuration - public Option[] config() { - return options( - // - systemProperty("logback.configurationFile").value( - "file:" + PathUtils.getBaseDir() - + "/src/test/resources/logback.xml"), - // To start OSGi console for inspection remotely - systemProperty("osgi.console").value("2401"), - // Set the systemPackages (used by clustering) - systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"), - // List framework bundles - mavenBundle("equinoxSDK381", "org.eclipse.equinox.console").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.util").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.osgi.services").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell").versionAsInProject(), - // List logger bundles - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), - mavenBundle("org.slf4j", "log4j-over-slf4j") - .versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-core") - .versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-classic") - .versionAsInProject(), - // needed by statisticsmanager - mavenBundle("org.opendaylight.controller", "containermanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "containermanager.it.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "clustering.services") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "clustering.stub") - .versionAsInProject(), - // needed by forwardingrulesmanager - mavenBundle("org.opendaylight.controller", "configuration") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "configuration.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "hosttracker") - .versionAsInProject(), - - // List all the bundles on which the test case depends - mavenBundle("org.opendaylight.controller", "sal") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "protocol_plugins.stub") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "switchmanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "switchmanager.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "statisticsmanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "statisticsmanager.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "forwardingrulesmanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "connectionmanager.implementation"). - versionAsInProject(), - mavenBundle("org.opendaylight.controller", "connectionmanager"). - versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.connection"). - versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.connection.implementation"). - versionAsInProject(), - - // needed by hosttracker - mavenBundle("org.opendaylight.controller", "topologymanager") - .versionAsInProject(), - mavenBundle("org.jboss.spec.javax.transaction", - "jboss-transaction-api_1.1_spec").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3") - .versionAsInProject(), - mavenBundle("org.apache.felix", - "org.apache.felix.dependencymanager") - .versionAsInProject(), junitBundles()); - } - - private String stateToString(int state) { - switch (state) { - case Bundle.ACTIVE: - return "ACTIVE"; - case Bundle.INSTALLED: - return "INSTALLED"; - case Bundle.RESOLVED: - return "RESOLVED"; - case Bundle.UNINSTALLED: - return "UNINSTALLED"; - default: - return "Not CONVERTED"; - } - } - - @Before - public void areWeReady() { - assertNotNull(bc); - boolean debugit = false; - Bundle b[] = bc.getBundles(); - for (int i = 0; i < b.length; i++) { - int state = b[i].getState(); - if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) { - log.debug("Bundle:" + b[i].getSymbolicName() + " state:" - + stateToString(state)); - debugit = true; - } - } - if (debugit) { - log.debug("Do some debugging because some bundle is " - + "unresolved"); - } - - // Assert if true, if false we are good to go! - assertFalse(debugit); - - ServiceReference r = bc.getServiceReference(IStatisticsManager.class - .getName()); - if (r != null) { - this.manager = (IStatisticsManager) bc.getService(r); - } - // If StatisticsManager is null, cannot run tests. - assertNotNull(this.manager); - - } - - @Test - public void testGetFlows() { - try { - Node node = new Node("STUB", new Integer(0xCAFE)); - List flows = this.manager.getFlows(node); - FlowOnNode fn = flows.get(0); - Assert.assertTrue(fn.getByteCount() == 100); - Assert.assertTrue(fn.getDurationNanoseconds() == 400); - Assert.assertTrue(fn.getDurationSeconds() == 40); - Assert.assertTrue(fn.getTableId() == (byte) 0x1); - Assert.assertTrue(fn.getPacketCount() == 200); - - Match match = new Match(); - try { - match.setField(MatchType.NW_DST, - InetAddress.getByName("1.1.1.1")); - } catch (UnknownHostException e) { - fail("Couldn't create match"); - } - Assert.assertTrue(match.equals(fn.getFlow().getMatch())); - Assert.assertTrue(fn.getFlow().getActions().get(0) - .equals(new Drop())); - } catch (ConstructionException e) { - // Got an unexpected exception - Assert.assertTrue(false); - } - - } - - @Test - public void testGetFlowStatistics() { - Flow flow = new Flow(); - - Match match = new Match(); - try { - match.setField(MatchType.NW_DST, InetAddress.getByName("1.1.1.1")); - } catch (UnknownHostException e) { - } - flow.setMatch(match); - Action action = new Drop(); - - List actions = new ArrayList(); - actions.add(action); - flow.setActions(actions); - // as in stub - flow.setPriority((short) 3500); - flow.setIdleTimeout((short) 1000); - flow.setHardTimeout((short) 2000); - flow.setId(12345); - - try { - Node node = new Node("STUB", 0xCAFE); - FlowEntry fe = new FlowEntry("g1", "f1", flow, node); - List list = new ArrayList(); - list.add(fe); - FlowEntry fe2 = new FlowEntry("g1", "f2", flow, node); - list.add(fe2); - - Map> result = this.manager - .getFlowStatisticsForFlowList(null); - Assert.assertTrue(result.isEmpty()); - result = this.manager.getFlowStatisticsForFlowList(list); - List results = result.get(node); - FlowOnNode fn = results.get(0); - Assert.assertTrue(fn.getByteCount() == 100); - Assert.assertTrue(fn.getDurationNanoseconds() == 400); - Assert.assertTrue(fn.getDurationSeconds() == 40); - Assert.assertTrue(fn.getTableId() == (byte) 0x1); - Assert.assertTrue(fn.getPacketCount() == 200); - Assert.assertTrue(fn.getFlow().equals(flow)); - } catch (ConstructionException e) { - Assert.assertTrue(false); - } - - } - - @Test - public void testGetFlowsNumber() { - try { - Node node = new Node("STUB", 0xCAFE); - Assert.assertEquals(21, this.manager.getFlowsNumber(node)); - }catch(ConstructionException e){ - Assert.assertTrue(false); - } - } - - @Test - public void testGetNodeDescription() { - try { - Node node = new Node("STUB", 0xCAFE); - NodeDescription desc = this.manager.getNodeDescription(node); - Assert.assertTrue(desc.getDescription().equals( - "This is a sample node description")); - Assert.assertTrue(desc.getHardware().equals("stub hardware")); - Assert.assertTrue(desc.getSoftware().equals("stub software")); - Assert.assertTrue(desc.getSerialNumber().equals("123")); - Assert.assertTrue(desc.getManufacturer().equals("opendaylight")); - } catch (ConstructionException e) { - Assert.assertTrue(false); - } - - } - - @Test - public void testGetNodeConnectorStatistics() { - try { - Node node = new Node("STUB", 0xCAFE); - List stats = this.manager - .getNodeConnectorStatistics(node); - NodeConnectorStatistics ns = stats.get(0); - Assert.assertTrue(ns.getCollisionCount() == 4); - Assert.assertTrue(ns.getReceiveByteCount() == 1000); - Assert.assertTrue(ns.getReceiveCRCErrorCount() == 1); - Assert.assertTrue(ns.getReceiveDropCount() == 2); - Assert.assertTrue(ns.getReceiveErrorCount() == 3); - Assert.assertTrue(ns.getReceiveFrameErrorCount() == 5); - Assert.assertTrue(ns.getReceiveOverRunErrorCount() == 6); - Assert.assertTrue(ns.getReceivePacketCount() == 250); - Assert.assertTrue(ns.getTransmitByteCount() == 5000); - Assert.assertTrue(ns.getTransmitDropCount() == 50); - Assert.assertTrue(ns.getTransmitErrorCount() == 10); - Assert.assertTrue(ns.getTransmitPacketCount() == 500); - - NodeConnector nc = ns.getNodeConnector(); - NodeConnectorStatistics ns2 = this.manager - .getNodeConnectorStatistics(nc); - Assert.assertTrue(ns2.getCollisionCount() == 4); - Assert.assertTrue(ns2.getReceiveByteCount() == 1000); - Assert.assertTrue(ns2.getReceiveCRCErrorCount() == 1); - Assert.assertTrue(ns2.getReceiveDropCount() == 2); - Assert.assertTrue(ns2.getReceiveErrorCount() == 3); - Assert.assertTrue(ns2.getReceiveFrameErrorCount() == 5); - Assert.assertTrue(ns2.getReceiveOverRunErrorCount() == 6); - Assert.assertTrue(ns2.getReceivePacketCount() == 250); - Assert.assertTrue(ns2.getTransmitByteCount() == 5000); - Assert.assertTrue(ns2.getTransmitDropCount() == 50); - Assert.assertTrue(ns2.getTransmitErrorCount() == 10); - Assert.assertTrue(ns2.getTransmitPacketCount() == 500); - - } catch (ConstructionException e) { - Assert.assertTrue(false); - } - } - -} diff --git a/opendaylight/adsal/statisticsmanager/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/statisticsmanager/integrationtest/src/test/resources/logback.xml deleted file mode 100644 index 2d63ce5744..0000000000 --- a/opendaylight/adsal/statisticsmanager/integrationtest/src/test/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/opendaylight/adsal/switchmanager/api/pom.xml b/opendaylight/adsal/switchmanager/api/pom.xml deleted file mode 100644 index a0824ce86f..0000000000 --- a/opendaylight/adsal/switchmanager/api/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - switchmanager - 0.9.0-SNAPSHOT - bundle - - - - reuseReports - target/jacoco.exec - target/jacoco-it.exec - - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - sal - - - junit - junit - test - - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.switchmanager - org.opendaylight.controller.configuration, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.inventory, - org.slf4j, - javax.xml.bind.annotation - - ${project.basedir}/META-INF - - - - org.jacoco - jacoco-maven-plugin - - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - report - - test - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/IInventoryListener.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/IInventoryListener.java deleted file mode 100644 index 29d0a42f85..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/IInventoryListener.java +++ /dev/null @@ -1,46 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import java.util.Map; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; - -/** - * Primary purpose of this interface is to provide methods to listen to inventory changes - */ -public interface IInventoryListener { - /** - * This method is called when some properties of a node are added/deleted/changed. - * - * @param node {@link org.opendaylight.controller.sal.core.Node} being updated - * @param type {@link org.opendaylight.controller.sal.core.UpdateType} - * @param propMap map of {@link org.opendaylight.controller.sal.core.Property} such as - * {@link org.opendaylight.controller.sal.core.Description} and/or - * {@link org.opendaylight.controller.sal.core.Tier} etc. - */ - public void notifyNode(Node node, UpdateType type, - Map propMap); - - /** - * This method is called when some properties of a node connector are added/deleted/changed. - * - * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} being updated - * @param type {@link org.opendaylight.controller.sal.core.UpdateType} - * @param propMap map of {@link org.opendaylight.controller.sal.core.Property} such as - * {@link org.opendaylight.controller.sal.core.Description} and/or - * {@link org.opendaylight.controller.sal.core.State} etc. - */ - public void notifyNodeConnector(NodeConnector nodeConnector, - UpdateType type, Map propMap); -} diff --git a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISpanAware.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISpanAware.java deleted file mode 100644 index 1e4a79fcc0..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISpanAware.java +++ /dev/null @@ -1,30 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import java.util.List; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; - -/** - * The interface provides the methods for notifying when span ports - * are configured/unconfigured. - */ -public interface ISpanAware { - /** - * This method is called when list of ports in a node are added/deleted as span ports. - * - * @param node {@link org.opendaylight.controller.sal.core.Node} being updated - * @param portList list of span {@link org.opendaylight.controller.sal.core.NodeConnector} - * @param add true if add; false if delete. - */ - public void spanUpdate(Node node, List portList, boolean add); -} \ No newline at end of file diff --git a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManager.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManager.java deleted file mode 100644 index 072544c214..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManager.java +++ /dev/null @@ -1,435 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import java.net.InetAddress; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.utils.Status; - -/** - * Primary purpose of this interface is to provide methods for application to - * access various system resources and inventory data including nodes, node - * connectors and their properties, Layer3 configurations, Span configurations, - * node configurations, network device representations viewed by Controller Web - * applications. - */ -public interface ISwitchManager { - /** - * Add a subnet configuration - * - * @param configObject refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig} - * @return the Status object representing the result of the request - */ - public Status addSubnet(SubnetConfig configObject); - - /** - * Remove a subnet configuration - * - * @param configObject refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig} - * @return the Status object representing the result of the request - */ - public Status removeSubnet(SubnetConfig configObject); - - /** - * Modify a subnet configuration - * - * @param configObject refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SubnetConfig} - * @return the Status object representing the result of the request - */ - public Status modifySubnet(SubnetConfig configObject); - - /** - * Remove a subnet configuration given the name - * - * @param name subnet name - * @return "Success" or failure reason - */ - public Status removeSubnet(String name); - - /** - * Return a list of all known devices in the system - * - * @return returns a list of {@link org.opendaylight.controller.switchmanager.Switch} - */ - public List getNetworkDevices(); - - /** - * Return a Set of all configured devices that are not connected to the controller - * - * @return Set of {@link org.opendaylight.controller.switchmanager.Switch} - */ - public Set getConfiguredNotConnectedSwitches(); - - /** - * Return a list of subnet that were previously configured - * - * @return list of L3 interface {@link org.opendaylight.controller.switchmanager.SubnetConfig} configurations - */ - public List getSubnetsConfigList(); - - /** - * Return the subnet configuration - * - * @param subnet subnet - * @return a L3 interface {@link org.opendaylight.controller.switchmanager.SubnetConfig} configuration - */ - public SubnetConfig getSubnetConfig(String subnet); - - /** - * Return a subnet configuration given the network address - * - * @param networkAddress the ip address in long format - * @return the {@link org.opendaylight.controller.switchmanager.Subnet} - */ - public Subnet getSubnetByNetworkAddress(InetAddress networkAddress); - - /** - * Save the current switch configurations - * - * @return the status code - */ - public Status saveSwitchConfig(); - - /** - * Add a span port configuration - * - * @param SpanConfig refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SpanConfig} - * @return status code - */ - public Status addSpanConfig(SpanConfig configObject); - - /** - * Remove a span port configuration - * - * @param SpanConfig refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SpanConfig} - * @return status code - */ - public Status removeSpanConfig(SpanConfig cfgObject); - - /** - * Return a list of span configurations that were configured previously - * - * @return list of {@link org.opendaylight.controller.switchmanager.SpanConfig} resources - */ - public List getSpanConfigList(); - - /** - * Return the list of span ports of a given node - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @return the list of span {@link org.opendaylight.controller.sal.core.NodeConnector} of the node - */ - public List getSpanPorts(Node node); - - /** - * Update Switch specific configuration such as Switch Name and Tier - * - * @param cfgConfig refer to {@link Open Declaration org.opendaylight.controller.switchmanager.SwitchConfig} - * - * @deprecated replaced by updateNodeConfig(switchConfig) - */ - @Deprecated - public void updateSwitchConfig(SwitchConfig cfgObject); - - /** - * Update Node specific configuration such as Node Name and Tier - * - * @param cfgConfig - * refer to {@link Open Declaration - * org.opendaylight.controller.switchmanager.SwitchConfig} - * @return "Success" or failure reason - */ - public Status updateNodeConfig(SwitchConfig switchConfig); - - /** - * Removes node properties configured by the user - * - * @param nodeId - * Node Identifier as specified by - * {@link org.opendaylight.controller.sal.core.Node} - * @return "Success" or failure reason - */ - public Status removeNodeConfig(String nodeId); - - /** - * Return the previously configured Switch Configuration given the node id - * - * @param nodeId - * Node Identifier as specified by - * {@link org.opendaylight.controller.sal.core.Node} - * @return {@link org.opendaylight.controller.switchmanager.SwitchConfig} - * resources - */ - public SwitchConfig getSwitchConfig(String nodeId); - - /** - * Add node connectors to a subnet - * - * @param name The configured subnet name - * @param nodeConnectors list of string each representing a node connector as specified by {@link Open Declaration org.opendaylight.controller.sal.core.NodeConnector} - * @return The Status object indicating the result of this request - */ - public Status addPortsToSubnet(String name, List nodeConnectors); - - /** - * Remove node connectors from a subnet - * - * @param name the configured subnet name - * @param nodeConnectors list of string each representing a node connector as specified by {@link Open Declaration org.opendaylight.controller.sal.core.NodeConnector} - * @return The Status object indicating the result of this request - */ - public Status removePortsFromSubnet(String name, List nodeConnectors); - - /** - * Return the set of all the nodes - * - * @return set of {@link org.opendaylight.controller.sal.core.Node} - */ - public Set getNodes(); - - /** - * Return all the properties of a node - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @return map of {@link org.opendaylight.controller.sal.core.Property} such as - * {@link org.opendaylight.controller.sal.core.Description} and/or - * {@link org.opendaylight.controller.sal.core.Tier} etc. - */ - public Map getNodeProps(Node node); - - /** - * Return a specific property of a node given the property name - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @param propName the property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes - * @return {@link org.opendaylight.controller.sal.core.Property} - */ - public Property getNodeProp(Node node, String propName); - - /** - * Set a specific property of a node - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @param prop {@link org.opendaylight.controller.sal.core.Property} - */ - public void setNodeProp(Node node, Property prop); - - /** - * Remove a property of a node - * - * @param nc {@link org.opendaylight.controller.sal.core.Node} - * @param propName the property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes - * @return success or failed reason - */ - public Status removeNodeProp(Node node, String propName); - - /** - * Remove all the properties of a node - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @return success or failed reason - */ - public Status removeNodeAllProps(Node node); - - /** - * Return all the node connectors in up state for a given node - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @return set of {@link org.opendaylight.controller.sal.core.NodeConnector} - */ - public Set getUpNodeConnectors(Node node); - - /** - * Return all the node connectors including those special ones. Status of each node connector varies. - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @return all listed {@link org.opendaylight.controller.sal.core.NodeConnector} - */ - public Set getNodeConnectors(Node node); - - /** - * Return all the physical node connectors of a node. Status of each node connector varies. - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @return all physical {@link org.opendaylight.controller.sal.core.NodeConnector} - */ - public Set getPhysicalNodeConnectors(Node node); - - /** - * Return all the properties of a node connector - * - * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} - * @return map of {@link org.opendaylight.controller.sal.core.Property} such as - * {@link org.opendaylight.controller.sal.core.Description} and/or - * {@link org.opendaylight.controller.sal.core.State} etc. - */ - public Map getNodeConnectorProps( - NodeConnector nodeConnector); - - /** - * Return a specific property of a node connector given the property name - * - * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} - * @param propName property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes - * @return {@link org.opendaylight.controller.sal.core.Property} - */ - public Property getNodeConnectorProp(NodeConnector nodeConnector, - String propName); - - /** - * Add a node connector and its property - * - * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} - * @param prop {@link org.opendaylight.controller.sal.core.Property} - * @return success or failed reason - */ - public Status addNodeConnectorProp(NodeConnector nodeConnector, - Property prop); - - /** - * Remove a property of a node connector - * - * @param nc {@link org.opendaylight.controller.sal.core.NodeConnector} - * @param propName property name specified by {@link org.opendaylight.controller.sal.core.Property} and its extended classes - * @return success or failed reason - */ - public Status removeNodeConnectorProp(NodeConnector nc, String propName); - - /** - * Remove all the properties of a node connector - * - * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} - * @return success or failed reason - */ - public Status removeNodeConnectorAllProps(NodeConnector nodeConnector); - - /** - * Return the node connector given its name - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @param nodeConnectorName node connector identifier specified by {@link org.opendaylight.controller.sal.core.NodeConnector} - * @return {@link org.opendaylight.controller.sal.core.NodeConnector} - */ - public NodeConnector getNodeConnector(Node node, String nodeConnectorName); - - /** - * Return whether the specified node connector is a special node port - * Example of node's special node connector are software stack, hardware path, controller... - * - * @param p {@link org.opendaylight.controller.sal.core.NodeConnector} - * @return true or false - */ - public boolean isSpecial(NodeConnector p); - - /** - * Check if the node connector is up running - * - * @param nodeConnector {@link org.opendaylight.controller.sal.core.NodeConnector} - * @return true or false - */ - public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector); - - /** - * Test whether the given node connector exists. - * - * @param nc {@link org.opendaylight.controller.sal.core.NodeConnector} - * @return True if exists, false otherwise. - */ - public boolean doesNodeConnectorExist(NodeConnector nc); - - /** - * Return controller MAC address - * - * @return MAC address in byte array - */ - public byte[] getControllerMAC(); - - /** - * Return MAC address for a given node - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @return MAC address in byte array - */ - public byte[] getNodeMAC(Node node); - - /** - * Create a Name/Tier/Bandwidth Property object based on given property name - * and value. Other property types are not supported yet. - * - * @param propName - * Name of the Property specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * @param propValue - * Value of the Property specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * @return {@link org.opendaylight.controller.sal.core.Property} - */ - public Property createProperty(String propName, String propValue); - - /** - * Returns the description for the specified node. It is either the one - * configured by user or the description advertised by the node. - * - * @param node the network node identifier - * @return the description of the specified node. If no description is - * configured and the network node does not provide its description, - * an empty string is returned. - */ - @Deprecated - public String getNodeDescription(Node node); - - /** - * Return all the properties of the controller - * - * @return map of {@link org.opendaylight.controller.sal.core.Property} such - * as {@link org.opendaylight.controller.sal.core.Description} - * and/or {@link org.opendaylight.controller.sal.core.Tier} etc. - */ - public Map getControllerProperties(); - - /** - * Return a specific property of the controller given the property name - * - * @param propName - * the property name specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * @return {@link org.opendaylight.controller.sal.core.Property} - */ - public Property getControllerProperty(String propertyName); - - /** - * Set a specific property of the controller - * - * @param property - * {@link org.opendaylight.controller.sal.core.Property} - * @return - */ - public Status setControllerProperty(Property property); - - /** - * Remove a property of a node - * - * @param propertyName - * the property name specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * @return success or failed reason - */ - public Status removeControllerProperty(String propertyName); -} diff --git a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManagerAware.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManagerAware.java deleted file mode 100644 index 4fde7a929e..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/ISwitchManagerAware.java +++ /dev/null @@ -1,35 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import org.opendaylight.controller.sal.core.Node; - - -/** - * The interface provides methods to notify listeners about subnet and mode - * changes. - */ -public interface ISwitchManagerAware { - /** - * The method is called when subnet is added/deleted - * - * @param sub {@link org.opendaylight.controller.switchmanager.Subnet} - * @param add true if add; false if delete. - */ - public void subnetNotify(Subnet sub, boolean add); - - /** - * The method is called when proactive/reactive mode is changed in a node - * - * @param node {@link org.opendaylight.controller.sal.core.Node} - * @param proactive true if mode is set as proactive; false if mode is reactive. - */ - public void modeChangeNotify(Node node, boolean proactive); -} diff --git a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SpanConfig.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SpanConfig.java deleted file mode 100644 index eeccf1080b..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SpanConfig.java +++ /dev/null @@ -1,144 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import java.io.Serializable; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; - -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.GUIField; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class represents a Span Port configuration for a network node. - */ -public class SpanConfig extends ConfigurationObject implements Serializable { - protected static final Logger logger = LoggerFactory - .getLogger(SpanConfig.class); - private static final long serialVersionUID = 1L; - private static final String guiFields[] = { GUIField.NODE.toString(), - GUIField.SPANPORTS.toString() }; - - // Order matters: JSP file expects following fields in the following order - private String nodeId; - private String spanPort; - - public SpanConfig() { - } - - public String getNodeId() { - return nodeId; - } - - public String getSpanPort() { - return spanPort; - } - - public Node getNode() { - return Node.fromString(nodeId); - } - - private boolean hasValidNodeId() { - return (getNode() != null); - } - - private boolean hasValidSpanPort() { - return (spanPort != null && !spanPort.isEmpty()); - } - - public boolean isValidConfig() { - return (hasValidNodeId() && hasValidSpanPort()); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((nodeId == null) ? 0 : nodeId.hashCode()); - result = prime * result - + ((spanPort == null) ? 0 : spanPort.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SpanConfig other = (SpanConfig) obj; - if (nodeId == null) { - if (other.nodeId != null) { - return false; - } - } else if (!nodeId.equals(other.nodeId)) { - return false; - } - if (spanPort == null) { - if (other.spanPort != null) { - return false; - } - } else if (!spanPort.equals(other.spanPort)) { - return false; - } - return true; - } - - public static ArrayList getFieldsNames() { - ArrayList fieldList = new ArrayList(); - for (Field fld : SpanConfig.class.getDeclaredFields()) { - fieldList.add(fld.getName()); - } - //remove the two static fields - for (short i = 0; i < 2; i++) { - fieldList.remove(0); - } - return fieldList; - } - - public static List getGuiFieldsNames() { - List fieldList = new ArrayList(); - for (String str : guiFields) { - fieldList.add(str); - } - return fieldList; - } - - public ArrayList getPortArrayList() { - ArrayList portList = new ArrayList(); - String[] elemArray = spanPort.split(","); - for (String elem : elemArray) { - NodeConnector nodeConnector = NodeConnector.fromString(elem); - if (nodeConnector != null) { - portList.add(nodeConnector); - } - } - return portList; - } - - public boolean matchNode(String nodeId) { - return this.nodeId.equals(nodeId); - } - - @Override - public String toString() { - return ("SpanConfig [nodeId=" + nodeId + ", spanPort=" + spanPort + "]"); - } -} diff --git a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Subnet.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Subnet.java deleted file mode 100644 index 2794109c24..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Subnet.java +++ /dev/null @@ -1,262 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import java.io.Serializable; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashSet; -import java.util.Set; - -import org.opendaylight.controller.sal.core.NodeConnector; - -/** - * The class describes subnet information including L3 address, vlan and set of - * ports associated with the subnet. - */ -public class Subnet implements Cloneable, Serializable { - private static final long serialVersionUID = 1L; - // Key fields - private InetAddress networkAddress; - private transient InetAddress subnetPrefix; - private short subnetMaskLength; - // Property fields - private short vlan; - private final Set nodeConnectors; - - public Subnet(InetAddress ip, short maskLen, short vlan) { - this.networkAddress = ip; - this.subnetMaskLength = maskLen; - this.vlan = vlan; - this.nodeConnectors = new HashSet(); - } - - public Subnet(SubnetConfig conf) { - networkAddress = conf.getIPAddress(); - subnetMaskLength = conf.getIPMaskLen(); - nodeConnectors = conf.getNodeConnectors(); - } - - public Subnet(Subnet subnet) { - networkAddress = subnet.networkAddress; - subnetMaskLength = subnet.subnetMaskLength; - vlan = subnet.vlan; - nodeConnectors = new HashSet(subnet.nodeConnectors); - } - - /** - * Add NodeConnectors to a subnet - * - * @param sp Set of NodeConnectors to add to the subnet - */ - public void addNodeConnectors(Set sp) { - if (sp != null) { - this.nodeConnectors.addAll(sp); - } - } - - /** - * Delete NodeConnectors from subnet - * - * @param sp Set of NodeConnectors to add to the subnet - */ - public void deleteNodeConnectors(Set sp) { - if (sp == null) { - return; - } - for (NodeConnector p : sp) { - this.nodeConnectors.remove(p); - } - } - - /** - * Return the list of NodeConnectors configured for this subnet, - * could be also an empty set in case of all the known - * nodeconnectors. - * - * - * @return The list of NodeConnectors attached to the subnet - */ - public Set getNodeConnectors() { - return this.nodeConnectors; - } - - /** - * If the subnet has no node connectors attached to it then it - * means that is a whole L2 flat domain - * - * - * @return true if there are no node connectors configured for the - * subnet else false - */ - public boolean isFlatLayer2() { - return nodeConnectors.isEmpty(); - } - - /** - * getter method - * - * - * @return the Network Address part of the subnet - */ - public InetAddress getNetworkAddress() { - return networkAddress; - } - - /** - * @param networkAddress the networkAddress to set - */ - public Subnet setNetworkAddress(InetAddress networkAddress) { - this.networkAddress = networkAddress; - this.subnetPrefix = null; - return this; - } - - /** - * getter method - * - * - * @return the subnet mask length - */ - public short getSubnetMaskLength() { - return this.subnetMaskLength; - } - - public Subnet setSubnetMaskLength(short m) { - this.subnetMaskLength = m; - return this; - } - - /* - * returns the prefix of a given IP by applying this subnet's mask - */ - private InetAddress getPrefixForAddress(InetAddress ip) { - int bytes = this.subnetMaskLength / 8; - int bits = this.subnetMaskLength % 8; - byte modifiedByte; - byte[] sn = ip.getAddress(); - if (bits > 0) { - modifiedByte = (byte) (sn[bytes] >> (8 - bits)); - sn[bytes] = (byte) (modifiedByte << (8 - bits)); - bytes++; - } - for (; bytes < sn.length; bytes++) { - sn[bytes] = (byte) (0); - } - try { - return InetAddress.getByAddress(sn); - } catch (UnknownHostException e) { - return null; - } - } - - public boolean isSubnetOf(InetAddress ip) { - if (ip == null) { - return false; - } - if(subnetPrefix == null) { - subnetPrefix = getPrefixForAddress(this.networkAddress); - } - InetAddress otherPrefix = getPrefixForAddress(ip); - boolean isSubnetOf = true; - if (((subnetPrefix == null) || (otherPrefix == null)) || (!subnetPrefix.equals(otherPrefix)) ) { - isSubnetOf = false; - } - return isSubnetOf; - } - - public short getVlan() { - return this.vlan; - } - - public Subnet setVlan(short i) { - this.vlan = i; - return this; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((networkAddress == null) ? 0 : networkAddress.hashCode()); - result = prime * result - + ((nodeConnectors == null) ? 0 : nodeConnectors.hashCode()); - result = prime * result + subnetMaskLength; - result = prime * result + vlan; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Subnet other = (Subnet) obj; - if (networkAddress == null) { - if (other.networkAddress != null) { - return false; - } - } else if (!networkAddress.equals(other.networkAddress)) { - return false; - } - if (nodeConnectors == null) { - if (other.nodeConnectors != null) { - return false; - } - } else if (!nodeConnectors.equals(other.nodeConnectors)) { - return false; - } - if (subnetMaskLength != other.subnetMaskLength) { - return false; - } - if (vlan != other.vlan) { - return false; - } - return true; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return ("Subnet [networkAddress=" + networkAddress.getHostAddress() - + "/" + subnetMaskLength - + ((vlan == 0) ? "" : (", vlan=" + vlan)) + ", " - + ((isFlatLayer2()) ? "{[*, *]}" : nodeConnectors.toString()) + "]"); - } - - public boolean hasNodeConnector(NodeConnector p) { - if (p == null) { - return false; - } - return isFlatLayer2() || nodeConnectors.contains(p); - } - - public boolean isMutualExclusive(Subnet otherSubnet) { - return !(isSubnetOf(otherSubnet.getNetworkAddress()) || otherSubnet.isSubnetOf(getNetworkAddress())); - } - - /** - * Implement clonable interface - */ - @Override - public Subnet clone() { - return new Subnet(this); - } - -} diff --git a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SubnetConfig.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SubnetConfig.java deleted file mode 100644 index b3dead5fa4..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SubnetConfig.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import java.io.Serializable; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.packet.BitBufferHelper; -import org.opendaylight.controller.sal.utils.GUIField; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; - -/** - * The class represents a subnet configuration. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class SubnetConfig extends ConfigurationObject implements Cloneable, Serializable { - private static final long serialVersionUID = 1L; - private static final String prettyFields[] = { GUIField.NAME.toString(), GUIField.GATEWAYIP.toString(), - GUIField.NODEPORTS.toString() }; - - /** - * Name of the subnet - */ - @XmlElement - private String name; - /** - * A.B.C.D/MM Where A.B.C.D is the Default Gateway IP (L3) or ARP Querier IP - * (L2) - */ - @XmlElement - private String subnet; - /** - * Set of node connectors in the format: Port Type|Port Id@Node Type|Node Id - */ - @XmlElement - private List nodeConnectors; - - public SubnetConfig() { - } - - public SubnetConfig(String name, String subnet, List nodeConnectors) { - this.name = name; - this.subnet = subnet; - this.nodeConnectors = nodeConnectors; - } - - public SubnetConfig(SubnetConfig subnetConfig) { - name = subnetConfig.name; - subnet = subnetConfig.subnet; - nodeConnectors = (subnetConfig.nodeConnectors == null) ? null : new ArrayList( - subnetConfig.nodeConnectors); - } - - public String getName() { - return name; - } - - public List getNodePorts() { - return (nodeConnectors == null) ? new ArrayList(0) : new ArrayList(nodeConnectors); - } - - public String getSubnet() { - return subnet; - } - - public InetAddress getIPAddress() { - InetAddress ip = null; - try { - ip = InetAddress.getByName(subnet.split("/")[0]); - } catch (UnknownHostException e1) { - return null; - } - return ip; - } - - public Short getIPMaskLen() { - Short maskLen = 0; - String[] s = subnet.split("/"); - - try { - maskLen = (s.length == 2) ? Short.valueOf(s[1]) : 32; - } catch (NumberFormatException e) { - maskLen = 32; - } - return maskLen; - } - - private Status validateSubnetAddress() { - if (!NetUtils.isIPAddressValid(subnet)) { - return new Status(StatusCode.BADREQUEST, String.format("Invalid Subnet configuration: Invalid address: %s", - subnet)); - } - if ((this.getIPMaskLen() == 0) || (this.getIPMaskLen() == 32)) { - return new Status(StatusCode.BADREQUEST, String.format("Invalid Subnet configuration: Invalid mask: /%s", - this.getIPMaskLen())); - } - - //checks that address doesn't start with 0 or 255 - String address = subnet.split("/")[0]; - if (address.startsWith("0.") || address.startsWith("255.")) { - return new Status(StatusCode.BADREQUEST, String.format("Invalid Subnet configuration: Invalid address: %s", address)); - } - - byte[] bytePrefix = NetUtils.getSubnetPrefix(this.getIPAddress(), this.getIPMaskLen()).getAddress(); - long prefix = BitBufferHelper.getLong(bytePrefix); - if (prefix == 0) { - return new Status(StatusCode.BADREQUEST, "Invalid network source address: subnet zero"); - } - - //check that host is not set to all 0's or 1's - long hostAddress = BitBufferHelper.getLong(this.getIPAddress().getAddress()) - prefix; - if (hostAddress == 0 || hostAddress == Math.pow(2, 32-this.getIPMaskLen()) - 1) { - return new Status(StatusCode.BADREQUEST, String.format("Invalid subnet gateway address: /%s", subnet)); - } - - return new Status(StatusCode.SUCCESS); - } - - public static Status validatePorts(List nodeConnectors) { - if (nodeConnectors != null) { - for (String port : nodeConnectors) { - if (null == NodeConnector.fromString(port)) { - return new Status(StatusCode.BADREQUEST, - "Invalid Subnet configuration: Not parsable node connector: " + port); - } - } - } - return new Status(StatusCode.SUCCESS); - } - - private Status validateName() { - if (!isValidResourceName(name)) { - return new Status(StatusCode.BADREQUEST, "Invalid name"); - } - return new Status(StatusCode.SUCCESS); - } - - public Status validate() { - Status status = validateName(); - if (status.isSuccess()) { - status = validateSubnetAddress(); - if (status.isSuccess()) { - status = validatePorts(this.nodeConnectors); - } - } - return status; - } - - public static List getGuiFieldsNames() { - List fieldList = new ArrayList(); - for (String str : prettyFields) { - fieldList.add(str); - } - return fieldList; - } - - public Set getNodeConnectors() { - return NodeConnector.fromString(this.nodeConnectors); - } - - public boolean isGlobal() { - // If no ports are specified to be part of the domain, then it's a - // global domain IP - return (nodeConnectors == null || nodeConnectors.isEmpty()); - } - - public void addNodeConnectors(List nc) { - if (nc != null) { - if (nodeConnectors == null) { - nodeConnectors = new ArrayList(nc); - } else { - nodeConnectors.addAll(nc); - } - } - } - - public void removeNodeConnectors(List nc) { - if (nc != null && nodeConnectors != null) { - nodeConnectors.removeAll(nc); - } - } - - @Override - public String toString() { - return ("SubnetConfig [Name=" + name + ", Subnet=" + subnet + ", NodeConnectors=" + nodeConnectors + "]"); - } - - /** - * Implement clonable interface - */ - @Override - public SubnetConfig clone() { - return new SubnetConfig(this); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((nodeConnectors == null) ? 0 : nodeConnectors.hashCode()); - result = prime * result + ((subnet == null) ? 0 : subnet.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SubnetConfig other = (SubnetConfig) obj; - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - if (nodeConnectors == null) { - if (other.nodeConnectors != null) { - return false; - } - } else if (!nodeConnectors.equals(other.nodeConnectors)) { - return false; - } - if (subnet == null) { - if (other.subnet != null) { - return false; - } - } else if (!subnet.equals(other.subnet)) { - return false; - } - return true; - } -} diff --git a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Switch.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Switch.java deleted file mode 100644 index e0c120a05f..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/Switch.java +++ /dev/null @@ -1,171 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.HexEncode; - -/** - * The class describes switch related information including L2 address, ports, - * span ports and associated node representation - */ -public class Switch implements Serializable { - private static final long serialVersionUID = 1L; - private byte[] dataLayerAddress; - private Set nodeConnectors; - private final List spanPorts; - private Node node; - - /* - * As we are adding switches on per event basis in a map, we do not need a default constructor - * This way we can keep the validations internal, in the proper constructor - public Switch() { - this.swPorts = new HashSet(); - this.spanPorts = new ArrayList(2); - } - */ - - public Switch(Node node) { - this.node = node; - this.nodeConnectors = new HashSet(); - this.spanPorts = new ArrayList(2); - this.dataLayerAddress = null; - } - - /** - * @return the dataLayerAddress - */ - public byte[] getDataLayerAddress() { - return dataLayerAddress; - } - - /** - * @param dataLayerAddress the dataLayerAddress to set - */ - public void setDataLayerAddress(byte[] dataLayerAddress) { - this.dataLayerAddress = (dataLayerAddress == null) ? null - : dataLayerAddress.clone(); - } - - /** - * @return the nodeConnectors - */ - public Set getNodeConnectors() { - return new HashSet(nodeConnectors); - } - - /** - * @param nodeConnectors nodeConnector set - */ - public void setNodeConnectors(Set nodeConnectors) { - this.nodeConnectors = nodeConnectors; - } - - public void addNodeConnector(NodeConnector nodeConnector) { - if (!nodeConnectors.contains(nodeConnector)) { - nodeConnectors.add(nodeConnector); - } - } - - public void removeNodeConnector(NodeConnector nodeConnector) { - nodeConnectors.remove(nodeConnector); - } - - public List getSpanPorts() { - return new ArrayList(this.spanPorts); - } - - public Node getNode() { - return node; - } - - public void setNode(Node node) { - this.node = node; - } - - public void addSpanPorts(List portList) { - for (NodeConnector port : portList) { - spanPorts.add(port); - } - } - - public void removeSpanPorts(List portList) { - for (NodeConnector port : portList) { - spanPorts.remove(port); - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(dataLayerAddress); - result = prime * result + ((node == null) ? 0 : node.hashCode()); - result = prime * result - + ((nodeConnectors == null) ? 0 : nodeConnectors.hashCode()); - result = prime * result - + ((spanPorts == null) ? 0 : spanPorts.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Switch other = (Switch) obj; - if (!Arrays.equals(dataLayerAddress, other.dataLayerAddress)) { - return false; - } - if (node == null) { - if (other.node != null) { - return false; - } - } else if (!node.equals(other.node)) { - return false; - } - if (nodeConnectors == null) { - if (other.nodeConnectors != null) { - return false; - } - } else if (!nodeConnectors.equals(other.nodeConnectors)) { - return false; - } - if (spanPorts == null) { - if (other.spanPorts != null) { - return false; - } - } else if (!spanPorts.equals(other.spanPorts)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "Switch [dataLayerAddress=" + HexEncode.bytesToHexStringFormat(dataLayerAddress) - + ", nodeConnectors=" + nodeConnectors + ", spanPorts=" - + spanPorts + ", node=" + node + "]"; - } -} diff --git a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SwitchConfig.java b/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SwitchConfig.java deleted file mode 100644 index b8d022f30e..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/main/java/org/opendaylight/controller/switchmanager/SwitchConfig.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.sal.core.Description; -import org.opendaylight.controller.sal.core.ForwardingMode; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.Tier; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; - -/** - * The class describes a switch configuration as a collection of properties - */ -public class SwitchConfig extends ConfigurationObject implements Cloneable, Serializable { - private static final long serialVersionUID = 1L; - private final String nodeId; - private final Map nodeProperties; - - public SwitchConfig(String nodeId, Map nodeProperties) { - this.nodeId = nodeId; - this.nodeProperties = (nodeProperties == null) ? new HashMap() - : new HashMap(nodeProperties); - } - - @Deprecated - public SwitchConfig(String nodeId, String description, String tier, String mode) { - this.nodeId = nodeId; - this.nodeProperties = new HashMap(); - Property desc = new Description(description); - this.nodeProperties.put(desc.getName(), desc); - Property nodeTier = new Tier(Integer.valueOf(tier)); - this.nodeProperties.put(nodeTier.getName(), nodeTier); - Property forwardingMode = new ForwardingMode(Integer.valueOf(mode)); - this.nodeProperties.put(forwardingMode.getName(), forwardingMode); - } - - public String getNodeId() { - return this.nodeId; - } - - public Map getNodeProperties() { - return new HashMap(this.nodeProperties); - } - - public Property getProperty(String PropName) { - return nodeProperties.get(PropName); - } - - /** - * This method returns the configured description of the node - * - * @return Configured description - * - * @deprecated replaced by getProperty(Description.propertyName) - */ - @Deprecated - public String getNodeDescription() { - Description description = (Description) getProperty(Description.propertyName); - return (description == null) ? null : description.getValue(); - } - - /** - * This method returns the configured Tier of a node - * - * @return Configured tier - * - * @deprecated replaced by getProperty(Tier.TierPropName) - */ - @Deprecated - public String getTier() { - Tier tier = (Tier) getProperty(Tier.TierPropName); - return (tier == null) ? null : String.valueOf(tier.getValue()); - } - - /** - * This method returns the configured Forwarding Mode of a node - * - * @return Configured Forwarding Mode - * - * @deprecated replaced by getProperty(ForwardingMode.name) - */ - @Deprecated - public String getMode() { - ForwardingMode forwardingMode = (ForwardingMode) getProperty(ForwardingMode.name); - return (forwardingMode == null) ? null : String.valueOf(forwardingMode.getValue()); - } - - /** - * This method returns true, if the configured forwarding mode is proactive, - * else false - * - * @return true, if the configured forwarding mode is proactive, else false - * - * @deprecated replaced by isProactive() API of ForwardingMode property - */ - @Deprecated - public boolean isProactive() { - return Integer.parseInt(getMode()) == ForwardingMode.PROACTIVE_FORWARDING; - } - - public static long getSerialversionuid() { - return serialVersionUID; - } - - public Status validate() { - Status validCheck = validateNodeId(); - if (validCheck.isSuccess()) { - validCheck = validateNodeProperties(); - } - return validCheck; - } - - private Status validateNodeId() { - if (nodeId == null || nodeId.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid node id"); - } - return new Status(StatusCode.SUCCESS); - } - - private Status validateNodeProperties() { - if (nodeProperties == null) { - return new Status(StatusCode.BADREQUEST, "Node properties must be specified"); - } - if (nodeProperties.containsKey(Description.propertyName)) { - if (!isValidResourceName(((Description)nodeProperties.get(Description.propertyName)).getValue())) { - return new Status(StatusCode.BADREQUEST, "Invalid node description"); - } - } - return new Status(StatusCode.SUCCESS); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((nodeId == null) ? 0 : nodeId.hashCode()); - result = prime * result + ((nodeProperties == null) ? 0 : nodeProperties.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SwitchConfig other = (SwitchConfig) obj; - if (nodeId == null) { - if (other.nodeId != null) { - return false; - } - } else if (!nodeId.equals(other.nodeId)) { - return false; - } - if (nodeProperties == null) { - if (other.nodeProperties != null) { - return false; - } - } else if (!nodeProperties.equals(other.nodeProperties)) { - return false; - } - return true; - } - - @Override - public String toString() { - return ("SwitchConfig [Node=" + nodeId + ", Properties=" + nodeProperties + "]"); - } - - /** - * Implement clonable interface - */ - @Override - public SwitchConfig clone() { - Map nodeProperties = (this.nodeProperties == null) ? null : new HashMap( - this.nodeProperties); - return new SwitchConfig(this.nodeId, nodeProperties); - } - -} diff --git a/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetConfigTest.java b/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetConfigTest.java deleted file mode 100644 index df6ed7456e..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetConfigTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.switchmanager; - -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.Status; - -public class SubnetConfigTest { - - @Test - public void configuration() throws ConstructionException { - // Create the node connector string list - Node node1 = new Node(Node.NodeIDType.OPENFLOW, 1L); - Node node2 = new Node(Node.NodeIDType.OPENFLOW, 2L); - Node node3 = new Node(Node.NodeIDType.OPENFLOW, 3L); - NodeConnector nc1 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)1, node1); - NodeConnector nc2 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)2, node2); - NodeConnector nc3 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)3, node3); - List portList = new ArrayList(); - portList.add(nc1.toString()); - portList.add(nc2.toString()); - portList.add(nc3.toString()); - - // Full subnet creation - SubnetConfig config = new SubnetConfig("eng", "11.1.1.254/16", portList); - Status status = config.validate(); - Assert.assertTrue(status.isSuccess()); - - // No port set specified - config = new SubnetConfig("eng", "11.1.1.254/16", null); - status = config.validate(); - Assert.assertTrue(status.isSuccess()); - - // Empty port set - config = new SubnetConfig("eng", "11.1.1.254/16", new ArrayList(0)); - status = config.validate(); - Assert.assertTrue(status.isSuccess()); - - // Zero subnet - config = new SubnetConfig("eng", "1.2.3.254/1", null); - status = config.validate(); - Assert.assertFalse(status.isSuccess()); - - // Port set with invalid port notation - List badPortList = new ArrayList(); - badPortList.add("1/1"); - config = new SubnetConfig("eng", "1.2.3.254/1", badPortList); - status = config.validate(); - Assert.assertFalse(status.isSuccess()); - } -} diff --git a/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetTest.java b/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetTest.java deleted file mode 100644 index 8b6a149917..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SubnetTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import static org.junit.Assert.fail; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashSet; -import java.util.Set; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; - -public class SubnetTest { - - @Test - public void testSubnet() throws Exception { - InetAddress ipaddr = InetAddress.getByName("100.0.0.1"); - Subnet subnet = new Subnet(ipaddr, (short) 24, (short) 5); - assertTrue(subnet.equals(subnet)); - assertFalse(subnet.equals(null)); - assertFalse(subnet.equals(ipaddr)); - Subnet subnet2 = new Subnet(ipaddr, (short) 24, (short) 5); - Inet6Address ipv6 = (Inet6Address) Inet6Address - .getByName("1111::2222:3333:4444:5555:6666"); - Subnet subnet3 = new Subnet(ipv6, (short) 24, (short) 5); - assertTrue(subnet.equals(subnet2)); - assertFalse(subnet.isMutualExclusive(subnet2)); - assertTrue(subnet.isMutualExclusive(subnet3)); - InetAddress subnetAddr = InetAddress.getByName("200.0.0.100"); - - assertTrue(subnet.isFlatLayer2() == true); - - Set ncSet = new HashSet(); - Node node = NodeCreator.createOFNode(((long) 10)); - NodeConnector nc0 = NodeConnectorCreator.createOFNodeConnector( - (short) 20, node); - NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector( - (short) 30, node); - NodeConnector nc2 = NodeConnectorCreator.createOFNodeConnector( - (short) 40, node); - - ncSet.add(nc0); - ncSet.add(nc1); - ncSet.add(nc2); - - assertTrue(subnet.hasNodeConnector(nc0)); - assertFalse(subnet.hasNodeConnector(null)); - subnet.addNodeConnectors(ncSet); - assertTrue(subnet.hasNodeConnector(nc0)); - - Set resultncSet = subnet.getNodeConnectors(); - Assert.assertEquals(resultncSet, ncSet); - subnet.addNodeConnectors(null); - Assert.assertEquals(subnet.getNodeConnectors(), ncSet); - - subnet.deleteNodeConnectors(null); - Assert.assertEquals(subnet.getNodeConnectors(), ncSet); - - Set ncSet2 = new HashSet(); - ncSet2.add(nc0); - subnet.deleteNodeConnectors(ncSet2); - assertFalse(subnet.getNodeConnectors().contains(nc0)); - assertFalse(subnet.hasNodeConnector(nc0)); - assertTrue(subnet.getNodeConnectors().contains(nc1)); - assertTrue(subnet.getNodeConnectors().contains(nc2)); - - subnet.deleteNodeConnectors(ncSet2); - - subnet.setNetworkAddress(subnetAddr); - assertTrue(subnet.isMutualExclusive(subnet2)); - assertTrue(subnet.getNetworkAddress().equals(subnetAddr)); - - subnet.setSubnetMaskLength((short) 16); - assertTrue(subnet.getSubnetMaskLength() == 16); - - subnet.setVlan((short) 100); - assertTrue(subnet.getVlan() == 100); - - assertTrue(subnet.isFlatLayer2() == false); - } - - @Test - public void checkIsSubnetOfComparisonMatch() { - String host = "10.0.0.1"; - InetAddress ipAddrForSubnetComparison = null; - try { - ipAddrForSubnetComparison = InetAddress.getByName(host); - } catch (UnknownHostException e) { - fail("Failed to create InetAddress object for" + host); - } - SubnetConfig subnetConf = new SubnetConfig("subnet", "10.0.0.254/24",null); - Subnet subnet = new Subnet(subnetConf); - assertTrue(subnet.isSubnetOf(ipAddrForSubnetComparison)); - } - - @Test - public void checkIsSubnetOfComparisonNoMatch() { - String host = "100.0.0.1"; - InetAddress ipAddrForSubnetComparison = null; - try { - ipAddrForSubnetComparison = InetAddress.getByName(host); - } catch (UnknownHostException e) { - fail("Failed to create InetAddress object for" + host); - } - SubnetConfig subnetConf = new SubnetConfig("subnet", "10.0.0.254/24",null); - Subnet subnet = new Subnet(subnetConf); - assertFalse(subnet.isSubnetOf(ipAddrForSubnetComparison)); - } - - @Test - public void checkIsSubnetOfComparisonIpEmpty() { - SubnetConfig subnetConf = new SubnetConfig("subnet", "10.0.0.254/24",null); - Subnet subnet = new Subnet(subnetConf); - assertFalse(subnet.isSubnetOf(null)); - } - - - -} diff --git a/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SwitchTest.java b/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SwitchTest.java deleted file mode 100644 index 64b57eba3c..0000000000 --- a/opendaylight/adsal/switchmanager/api/src/test/java/org/opendaylight/controller/switchmanager/SwitchTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager; - -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.Description; -import org.opendaylight.controller.sal.core.ForwardingMode; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.Tier; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; - -public class SwitchTest { - - @Test - public void testSwitchCreation() { - - Node node = NodeCreator.createOFNode(((long) 10)); - Node node2 = NodeCreator.createOFNode(((long) 11)); - NodeConnector nc0 = NodeConnectorCreator.createOFNodeConnector( - (short) 20, node); - NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector( - (short) 30, node); - NodeConnector nc2 = NodeConnectorCreator.createOFNodeConnector( - (short) 40, node); - NodeConnector nc3 = NodeConnectorCreator.createOFNodeConnector( - (short) 50, node); - NodeConnector nc4 = NodeConnectorCreator.createOFNodeConnector( - (short) 60, node); - NodeConnector nc5 = NodeConnectorCreator.createOFNodeConnector( - (short) 70, node); - - Set ncSet = new HashSet(); - ArrayList portList = new ArrayList(); - - Switch sw = new Switch(node); - Switch sw2 = new Switch(node); - Assert.assertTrue(sw.equals(sw2)); - sw2.setNode(node2); - Assert.assertTrue(sw2.getNode().equals(node2)); - Assert.assertFalse(sw.equals(sw2)); - - ncSet.add(nc0); - ncSet.add(nc1); - ncSet.add(nc2); - sw.addNodeConnector(nc3); - try { - sw.addNodeConnector(nc3); - } catch (Exception e) { - fail("Attempted to add duplicate NodeConnector to set"); - } - - portList.add(nc4); - portList.add(nc5); - - sw.setNodeConnectors(ncSet); - sw.addSpanPorts(portList); - - sw.setDataLayerAddress(null); - Assert.assertNull(sw.getDataLayerAddress()); - byte[] dlAddress = { (byte) 0x01, (byte) 0x02, (byte) 0x03, - (byte) 0x04, (byte) 0x05, (byte) 0x06 }; - sw.setDataLayerAddress(dlAddress); - - Node resultNode = sw.getNode(); - Set resultncSet = sw.getNodeConnectors(); - byte[] resultdlAddress = sw.getDataLayerAddress(); - ArrayList resultSpanPort = (ArrayList) sw - .getSpanPorts(); - - Assert.assertEquals(node, resultNode); - for (int i = 0; i < dlAddress.length; i++) { - Assert.assertEquals(dlAddress[i], resultdlAddress[i]); - } - - Assert.assertTrue(ncSet.equals(resultncSet)); - - for (int i = 0; i < portList.size(); i++) { - Assert.assertEquals(portList.get(i), resultSpanPort.get(i)); - } - } - - @Test - public void testSwitchAddRemovePort() { - Node node = NodeCreator.createOFNode(((long) 10)); - - NodeConnector nc0 = NodeConnectorCreator.createOFNodeConnector( - (short) 20, node); - NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector( - (short) 30, node); - NodeConnector nc4 = NodeConnectorCreator.createOFNodeConnector( - (short) 60, node); - NodeConnector nc5 = NodeConnectorCreator.createOFNodeConnector( - (short) 70, node); - ArrayList portList = new ArrayList(); - - portList.add(nc4); - portList.add(nc5); - - Set ncSet = new HashSet(); - ncSet.add(nc0); - ncSet.add(nc1); - - Switch sw = new Switch(node); - sw.setNodeConnectors(ncSet); - sw.removeNodeConnector(nc0); - Assert.assertFalse(ncSet.contains(nc0)); - - sw.removeSpanPorts(portList); - Assert.assertTrue(sw.getSpanPorts().isEmpty()); - - } - - @Test - public void testSwitchConfig(){ - Map prop = new HashMap(); - Property desc = new Description("swicth1"); - prop.put(desc.getName(), desc); - Property tier = new Tier(1); - prop.put(tier.getName(), tier); - SwitchConfig sc1 = new SwitchConfig("123", prop); - SwitchConfig sc2 = new SwitchConfig("123", prop); - Property mode = new ForwardingMode(1); - prop.put(mode.getName(), mode); - SwitchConfig sc3 = new SwitchConfig("123", prop); - Assert.assertTrue(sc1.equals(sc2)); - Assert.assertEquals(tier, sc1.getProperty(Tier.TierPropName)); - Assert.assertFalse(sc1.equals(sc3)); - Assert.assertTrue(sc1.hashCode() == sc2.hashCode()); - Assert.assertTrue(sc1.getNodeProperties().equals(sc2.getNodeProperties())); - } - -} diff --git a/opendaylight/adsal/switchmanager/implementation/pom.xml b/opendaylight/adsal/switchmanager/implementation/pom.xml deleted file mode 100644 index 4aa92e6216..0000000000 --- a/opendaylight/adsal/switchmanager/implementation/pom.xml +++ /dev/null @@ -1,126 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - switchmanager.implementation - 0.6.0-SNAPSHOT - bundle - - - - reuseReports - target/jacoco.exec - target/jacoco-it.exec - - - - equinoxSDK381 - org.apache.felix.gogo.runtime - - - equinoxSDK381 - org.eclipse.osgi - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - statisticsmanager - - - org.opendaylight.controller - switchmanager - - - - - - - org.jacoco - jacoco-maven-plugin - ${jacoco.version} - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.configuration, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.reader, - org.opendaylight.controller.sal.inventory, - org.opendaylight.controller.statisticsmanager, - org.slf4j, - org.apache.felix.dm, - org.eclipse.osgi.framework.console, - org.osgi.framework, - org.apache.felix.service.command, - javax.xml.bind.annotation, - org.apache.commons.lang3.builder - org.opendaylight.controller.switchmanager.internal.Activator - - ${project.basedir}/META-INF - - - - org.jacoco - jacoco-maven-plugin - - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - report - - test - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/Activator.java b/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/Activator.java deleted file mode 100644 index deecf26e0d..0000000000 --- a/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/Activator.java +++ /dev/null @@ -1,134 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.internal; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.inventory.IInventoryService; -import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; -import org.opendaylight.controller.statisticsmanager.IStatisticsManager; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISpanAware; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.ISwitchManagerAware; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * SwitchManager Bundle Activator - * - * - */ -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { SwitchManager.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(SwitchManager.class)) { - // export the service - c.setInterface(new String[] { - IListenInventoryUpdates.class.getName(), - ISwitchManager.class.getName(), - IConfigurationContainerAware.class.getName() }, null); - - // Now lets add a service dependency to make sure the - // provider of service exists - c.add(createContainerServiceDependency(containerName).setService( - IInventoryService.class).setCallbacks( - "setInventoryService", "unsetInventoryService") - .setRequired(true)); - c.add(createContainerServiceDependency(containerName).setService( - IStatisticsManager.class).setCallbacks( - "setStatisticsManager", "unsetStatisticsManager") - .setRequired(false)); - c.add(createContainerServiceDependency(containerName).setService( - ISwitchManagerAware.class).setCallbacks( - "setSwitchManagerAware", "unsetSwitchManagerAware") - .setRequired(false)); - c.add(createContainerServiceDependency(containerName).setService( - IInventoryListener.class).setCallbacks( - "setInventoryListener", "unsetInventoryListener") - .setRequired(false)); - c.add(createContainerServiceDependency(containerName).setService( - ISpanAware.class).setCallbacks("setSpanAware", - "unsetSpanAware").setRequired(false)); - c.add(createContainerServiceDependency(containerName).setService( - IClusterContainerServices.class).setCallbacks( - "setClusterContainerService", - "unsetClusterContainerService").setRequired(true)); - c.add(createContainerServiceDependency(containerName).setService( - IConfigurationContainerService.class).setCallbacks( - "setConfigurationContainerService", - "unsetConfigurationContainerService").setRequired(true)); - c.add(createServiceDependency() - .setService(IControllerProperties.class) - .setCallbacks("setControllerProperties", "unsetControllerProperties") - .setRequired(true)); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected Object[] getGlobalImplementations() { - final Object[] res = { ControllerProperties.class, SwitchManagerCLI.class }; - return res; - } - - /** - * {@inheritDoc} - */ - @Override - public void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(ControllerProperties.class)) { - c.setInterface(new String[] { IControllerProperties.class.getName() }, null); - - c.add(createServiceDependency() - .setService(IClusterGlobalServices.class) - .setCallbacks("setClusterService", "unsetClusterService") - .setRequired(true)); - } - } -} diff --git a/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/ControllerProperties.java b/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/ControllerProperties.java deleted file mode 100644 index 4b319b87cb..0000000000 --- a/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/ControllerProperties.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.switchmanager.internal; - -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.EnumSet; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.sal.core.MacAddress; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class ControllerProperties - * provides implementation for the ControllerProperties API - */ -public class ControllerProperties implements IControllerProperties { - - private IClusterGlobalServices clusterService = null; - private final Logger log = LoggerFactory - .getLogger(ControllerProperties.class); - private static final String controllerGlobalPropertiesCacheName = "switchmanager.controllerGlobalProperties"; - - private ConcurrentMap controllerGlobalProperties; - - private void allocateCaches() { - if (this.clusterService == null) { - this.nonClusterObjectCreate(); - log.warn("un-initialized clusterService, can't create cache"); - return; - } - try { - this.clusterService.createCache(controllerGlobalPropertiesCacheName, - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheConfigException cce) { - log.error("\nCache configuration invalid - check cache mode"); - } catch (CacheExistException ce) { - log.error("\nCache already exits - destroy and recreate if needed"); - } - } - - private void nonClusterObjectCreate() { - controllerGlobalProperties = new ConcurrentHashMap(); - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - if (this.clusterService == null) { - log.warn("un-initialized clusterService, can't create cache"); - return; - } - controllerGlobalProperties = (ConcurrentMap) this.clusterService - .getCache(controllerGlobalPropertiesCacheName); - if (controllerGlobalProperties == null) { - log.error("\nFailed to get cache for controllerGlobalProperties"); - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - * @param c Component - */ - void init(Component c) { - // Instantiate cluster synced variables - allocateCaches(); - retrieveCaches(); - } - - private void initializeProperties() { - byte controllerMac[] = getHardwareMAC(); - if (controllerMac != null) { - Property existing = controllerGlobalProperties.putIfAbsent(MacAddress.name, new MacAddress(controllerMac)); - if (existing == null && log.isTraceEnabled()) { - log.trace("Setting controller MAC address in the cluster: {}", HexEncode.bytesToHexStringFormat(controllerMac)); - } - } - } - - private byte[] getHardwareMAC() { - Enumeration nis; - byte[] macAddress = null; - - try { - nis = NetworkInterface.getNetworkInterfaces(); - } catch (SocketException e) { - log.error("Failed to acquire controller MAC: ", e); - return macAddress; - } - - while (nis.hasMoreElements()) { - NetworkInterface ni = nis.nextElement(); - try { - macAddress = ni.getHardwareAddress(); - } catch (SocketException e) { - log.error("Failed to acquire controller MAC: ", e); - } - if (macAddress != null && macAddress.length != 0) { - break; - } - } - if (macAddress == null) { - log.warn("Failed to acquire controller MAC: No physical interface found"); - // This happens when running controller on windows VM, for example - // TODO: Try parsing the OS command output - // For now provide a quick fix for the release - macAddress = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x0c, (byte) 0x60, (byte) 0x0D, (byte) 0x10 }; - log.debug("Assigning custom MAC address to controller"); - } - return macAddress; - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - // initialize required properties if first node in the cluster - if(this.clusterService.amICoordinator()) { - initializeProperties(); - } - } - - /** - * Function called after registered the service in OSGi service registry. - */ - void started() { - // nothing to do - } - - /** - * Function called before services of the component are removed - * from OSGi service registry. - */ - void stopping() { - // nothing to do - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - // nothing to do - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - // nothing to do - } - - /** - * {@inheritDoc} - */ - @Override - public Map getControllerProperties() { - return new HashMap(this.controllerGlobalProperties); - } - - /** - * {@inheritDoc} - */ - @Override - public Property getControllerProperty(String propertyName) { - if (propertyName != null) { - return this.controllerGlobalProperties.get(propertyName); - } - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Status setControllerProperty(Property property) { - if (property != null) { - this.controllerGlobalProperties.put(property.getName(), property); - return new Status(StatusCode.SUCCESS); - } - return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property"); - } - - /** - * {@inheritDoc} - */ - @Override - public Status removeControllerProperty(String propertyName) { - if (propertyName != null) { - this.controllerGlobalProperties.remove(propertyName); - return new Status(StatusCode.SUCCESS); - } - return new Status(StatusCode.BADREQUEST, "Invalid property provided when removing property"); - } - - /** - * setClusterService - * @param s - */ - public void setClusterService(IClusterGlobalServices s) { - this.clusterService = s; - } - - /** - * unsetClusterServices - * @param s - */ - public void unsetClusterServices(IClusterGlobalServices s) { - if (this.clusterService == s) { - this.clusterService = null; - } - } - -} diff --git a/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/IControllerProperties.java b/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/IControllerProperties.java deleted file mode 100644 index f9301e26c8..0000000000 --- a/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/IControllerProperties.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.internal; - -import java.util.Map; - -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.utils.Status; - -/** - * The class ControllerProperties is a global store - * for controller properties. Use this api to store/retrieve properties - * that are container independent. - * - * This is visible only to switch manager. Hence its a part of - * switch manager internal bundle. - */ -public interface IControllerProperties { - - /** - * Return all the global properties of the controller - * - * @return map of {@link org.opendaylight.controller.sal.core.Property} such - * as {@link org.opendaylight.controller.sal.core.Description} - * and/or {@link org.opendaylight.controller.sal.core.Tier} etc. - */ - public Map getControllerProperties(); - - /** - * Return a specific property of the controller given the property name - * - * @param propertyName - * the property name specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * @return {@link org.opendaylight.controller.sal.core.Property} - */ - public Property getControllerProperty(String propertyName); - - /** - * Set a specific property of the controller - * - * @param property - * {@link org.opendaylight.controller.sal.core.Property} - * @return Status - */ - public Status setControllerProperty(Property property); - - /** - * Remove a property of a node - * - * @param propertyName - * the property name specified by - * {@link org.opendaylight.controller.sal.core.Property} and its - * extended classes - * @return success or failed reason - */ - public Status removeControllerProperty(String propertyName); - -} diff --git a/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManager.java b/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManager.java deleted file mode 100644 index 8372f88e7d..0000000000 --- a/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManager.java +++ /dev/null @@ -1,2180 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.internal; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Dictionary; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; - -import org.apache.felix.dm.Component; -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.Config; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Description; -import org.opendaylight.controller.sal.core.ForwardingMode; -import org.opendaylight.controller.sal.core.MacAddress; -import org.opendaylight.controller.sal.core.Name; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.Tier; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.inventory.IInventoryService; -import org.opendaylight.controller.sal.inventory.IListenInventoryUpdates; -import org.opendaylight.controller.sal.reader.NodeDescription; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.IObjectReader; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.statisticsmanager.IStatisticsManager; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISpanAware; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.ISwitchManagerAware; -import org.opendaylight.controller.switchmanager.SpanConfig; -import org.opendaylight.controller.switchmanager.Subnet; -import org.opendaylight.controller.switchmanager.SubnetConfig; -import org.opendaylight.controller.switchmanager.Switch; -import org.opendaylight.controller.switchmanager.SwitchConfig; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The class describes SwitchManager which is the central repository of all the - * inventory data including nodes, node connectors, properties attached, Layer3 - * configurations, Span configurations, node configurations, network device - * representations viewed by Controller Web applications. One SwitchManager - * instance per container of the network. All the node/nodeConnector properties - * are maintained in the default container only. - */ -public class SwitchManager implements ISwitchManager, IConfigurationContainerAware, - IObjectReader, IListenInventoryUpdates, CommandProvider { - private static Logger log = LoggerFactory.getLogger(SwitchManager.class); - private static final String SUBNETS_FILE_NAME = "subnets.conf"; - private static final String SPAN_FILE_NAME = "spanPorts.conf"; - private static final String SWITCH_CONFIG_FILE_NAME = "switchConfig.conf"; - private final List spanNodeConnectors = new CopyOnWriteArrayList(); - // Collection of Subnets keyed by the InetAddress - private ConcurrentMap subnets; - private ConcurrentMap subnetsConfigList; - private ConcurrentMap spanConfigList; - // manually configured parameters for the node such as name, tier, mode - private ConcurrentMap nodeConfigList; - private ConcurrentMap> nodeProps; - private ConcurrentMap> nodeConnectorProps; - private ConcurrentMap> nodeConnectorNames; - private ConcurrentMap controllerProps; - private IInventoryService inventoryService; - private IStatisticsManager statisticsManager; - private IControllerProperties controllerProperties; - private IConfigurationContainerService configurationService; - private final Set switchManagerAware = Collections - .synchronizedSet(new HashSet()); - private final Set inventoryListeners = Collections - .synchronizedSet(new HashSet()); - private final Set spanAware = Collections.synchronizedSet(new HashSet()); - private IClusterContainerServices clusterContainerService = null; - private String containerName = null; - private boolean isDefaultContainer = true; - private static final int REPLACE_RETRY = 1; - - /* Information about the default subnet. If there have been no configured subnets, i.e., - * subnets.size() == 0 or subnetsConfigList.size() == 0, then this subnet will be the - * only subnet returned. As soon as a user-configured subnet is created this one will - * vanish. - */ - private static final String DISABLE_DEFAULT_SUBNET_PROP = "switchmanager.disableDefaultSubnetGateway"; - private static final String DISABLE_DEFAULT_SUBNET_PROP_VAL = System.getProperty(DISABLE_DEFAULT_SUBNET_PROP); - private static final boolean USE_DEFAULT_SUBNET_GW = !Boolean.valueOf(DISABLE_DEFAULT_SUBNET_PROP_VAL); - protected static final SubnetConfig DEFAULT_SUBNETCONFIG; - protected static final Subnet DEFAULT_SUBNET; - protected static final String DEFAULT_SUBNET_NAME = "default (cannot be modifed)"; - static{ - DEFAULT_SUBNETCONFIG = new SubnetConfig(DEFAULT_SUBNET_NAME, "0.0.0.0/0", new ArrayList()); - DEFAULT_SUBNET = new Subnet(DEFAULT_SUBNETCONFIG); - } - - public void notifySubnetChange(Subnet sub, boolean add) { - synchronized (switchManagerAware) { - for (Object subAware : switchManagerAware) { - try { - ((ISwitchManagerAware) subAware).subnetNotify(sub, add); - } catch (Exception e) { - log.error("Failed to notify Subnet change {}", - e.getMessage()); - } - } - } - } - - public void notifySpanPortChange(Node node, List ports, boolean add) { - synchronized (spanAware) { - for (Object sa : spanAware) { - try { - ((ISpanAware) sa).spanUpdate(node, ports, add); - } catch (Exception e) { - log.error("Failed to notify Span Interface change {}", - e.getMessage()); - } - } - } - } - - private void notifyModeChange(Node node, boolean proactive) { - synchronized (switchManagerAware) { - for (ISwitchManagerAware service : switchManagerAware) { - try { - service.modeChangeNotify(node, proactive); - } catch (Exception e) { - log.error("Failed to notify Subnet change {}", - e.getMessage()); - } - } - } - } - - public void startUp() { - // Instantiate cluster synced variables - allocateCaches(); - retrieveCaches(); - - // Add controller MAC, if first node in the cluster - if ((!controllerProps.containsKey(MacAddress.name)) && (controllerProperties != null)) { - Property controllerMac = controllerProperties.getControllerProperty(MacAddress.name); - if (controllerMac != null) { - Property existing = controllerProps.putIfAbsent(MacAddress.name, controllerMac); - if (existing == null && log.isTraceEnabled()) { - log.trace("Container {}: Setting controller MAC address in the cluster: {}", getContainerName(), - controllerMac); - } - } - } - } - - public void shutDown() { - } - - private void allocateCaches() { - if (this.clusterContainerService == null) { - this.nonClusterObjectCreate(); - log.warn("un-initialized clusterContainerService, can't create cache"); - return; - } - - try { - clusterContainerService.createCache( - "switchmanager.subnetsConfigList", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache("switchmanager.spanConfigList", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache("switchmanager.nodeConfigList", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache("switchmanager.subnets", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache("switchmanager.nodeProps", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache( - "switchmanager.nodeConnectorProps", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache( - "switchmanager.nodeConnectorNames", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - clusterContainerService.createCache( - "switchmanager.controllerProps", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheConfigException cce) { - log.error("\nCache configuration invalid - check cache mode"); - } catch (CacheExistException ce) { - log.error("\nCache already exits - destroy and recreate if needed"); - } - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - if (this.clusterContainerService == null) { - log.warn("un-initialized clusterContainerService, can't create cache"); - return; - } - - subnetsConfigList = (ConcurrentMap) clusterContainerService - .getCache("switchmanager.subnetsConfigList"); - if (subnetsConfigList == null) { - log.error("\nFailed to get cache for subnetsConfigList"); - } - - spanConfigList = (ConcurrentMap) clusterContainerService - .getCache("switchmanager.spanConfigList"); - if (spanConfigList == null) { - log.error("\nFailed to get cache for spanConfigList"); - } - - nodeConfigList = (ConcurrentMap) clusterContainerService - .getCache("switchmanager.nodeConfigList"); - if (nodeConfigList == null) { - log.error("\nFailed to get cache for nodeConfigList"); - } - - subnets = (ConcurrentMap) clusterContainerService - .getCache("switchmanager.subnets"); - if (subnets == null) { - log.error("\nFailed to get cache for subnets"); - } - - nodeProps = (ConcurrentMap>) clusterContainerService - .getCache("switchmanager.nodeProps"); - if (nodeProps == null) { - log.error("\nFailed to get cache for nodeProps"); - } - - nodeConnectorProps = (ConcurrentMap>) clusterContainerService - .getCache("switchmanager.nodeConnectorProps"); - if (nodeConnectorProps == null) { - log.error("\nFailed to get cache for nodeConnectorProps"); - } - - nodeConnectorNames = (ConcurrentMap>) clusterContainerService - .getCache("switchmanager.nodeConnectorNames"); - if (nodeConnectorNames == null) { - log.error("\nFailed to get cache for nodeConnectorNames"); - } - - controllerProps = (ConcurrentMap) clusterContainerService - .getCache("switchmanager.controllerProps"); - if (controllerProps == null) { - log.error("\nFailed to get cache for controllerProps"); - } - } - - private void nonClusterObjectCreate() { - subnetsConfigList = new ConcurrentHashMap(); - spanConfigList = new ConcurrentHashMap(); - nodeConfigList = new ConcurrentHashMap(); - subnets = new ConcurrentHashMap(); - nodeProps = new ConcurrentHashMap>(); - nodeConnectorProps = new ConcurrentHashMap>(); - nodeConnectorNames = new ConcurrentHashMap>(); - controllerProps = new ConcurrentHashMap(); - } - - @Override - public List getSubnetsConfigList() { - // if there are no subnets, return the default subnet - if (USE_DEFAULT_SUBNET_GW && subnetsConfigList.isEmpty()) { - return Collections.singletonList(DEFAULT_SUBNETCONFIG); - } else { - return new ArrayList(subnetsConfigList.values()); - } - } - - @Override - public SubnetConfig getSubnetConfig(String subnet) { - // if there are no subnets, return the default subnet - if (USE_DEFAULT_SUBNET_GW && subnetsConfigList.isEmpty() && subnet.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) { - return DEFAULT_SUBNETCONFIG; - } else { - return subnetsConfigList.get(subnet); - } - } - - private List getSpanConfigList(Node node) { - List confList = new ArrayList(); - String nodeId = node.toString(); - for (SpanConfig conf : spanConfigList.values()) { - if (conf.matchNode(nodeId)) { - confList.add(conf); - } - } - return confList; - } - - public List getNodeConfigList() { - return new ArrayList(nodeConfigList.values()); - } - - @Override - public SwitchConfig getSwitchConfig(String switchId) { - return nodeConfigList.get(switchId); - } - - public Switch getSwitchByNode(Node node) { - Switch sw = new Switch(node); - sw.setNode(node); - MacAddress mac = (MacAddress) this.getNodeProp(node, - MacAddress.name); - if (mac != null) { - sw.setDataLayerAddress(mac.getMacAddress()); - } - Set ncSet = getPhysicalNodeConnectors(node); - sw.setNodeConnectors(ncSet); - - List ncList = new ArrayList(); - for (NodeConnector nodeConnector : ncSet) { - if (spanNodeConnectors.contains(nodeConnector)) { - ncList.add(nodeConnector); - } - } - sw.addSpanPorts(ncList); - - return sw; - } - - @Override - public List getNetworkDevices() { - List swList = new ArrayList(); - for (Node node : getNodes()) { - swList.add(getSwitchByNode(node)); - } - return swList; - } - - private Status updateConfig(SubnetConfig conf, boolean add) { - if (add) { - if(subnetsConfigList.putIfAbsent(conf.getName(), conf) != null) { - String msg = "Cluster conflict: Subnet with name " + conf.getName() + "already exists."; - return new Status(StatusCode.CONFLICT, msg); - } - } else { - subnetsConfigList.remove(conf.getName()); - } - return new Status(StatusCode.SUCCESS); - } - - private Status updateDatabase(SubnetConfig conf, boolean add) { - if (add) { - Subnet subnetCurr = subnets.get(conf.getIPAddress()); - Subnet subnet; - if (subnetCurr == null) { - subnet = new Subnet(conf); - } else { - subnet = subnetCurr.clone(); - } - // In case of API3 call we may receive the ports along with the - // subnet creation - if (!conf.isGlobal()) { - subnet.addNodeConnectors(conf.getNodeConnectors()); - } - boolean putNewSubnet = false; - if(subnetCurr == null) { - if(subnets.putIfAbsent(conf.getIPAddress(), subnet) == null) { - putNewSubnet = true; - } - } else { - putNewSubnet = subnets.replace(conf.getIPAddress(), subnetCurr, subnet); - } - if(!putNewSubnet) { - String msg = "Cluster conflict: Conflict while adding the subnet " + conf.getIPAddress(); - return new Status(StatusCode.CONFLICT, msg); - } - - // Subnet removal case - } else { - subnets.remove(conf.getIPAddress()); - } - return new Status(StatusCode.SUCCESS); - } - - private Status semanticCheck(SubnetConfig conf) { - Set IPs = subnets.keySet(); - if (IPs == null) { - return new Status(StatusCode.SUCCESS); - } - Subnet newSubnet = new Subnet(conf); - for (InetAddress i : IPs) { - Subnet existingSubnet = subnets.get(i); - if ((existingSubnet != null) && !existingSubnet.isMutualExclusive(newSubnet)) { - return new Status(StatusCode.CONFLICT, "This subnet conflicts with an existing one."); - } - } - return new Status(StatusCode.SUCCESS); - } - - private Status addRemoveSubnet(SubnetConfig conf, boolean isAdding) { - // Valid configuration check - Status status = conf.validate(); - if (!status.isSuccess()) { - log.warn(status.getDescription()); - return status; - } - - if (isAdding) { - // Presence check - if (subnetsConfigList.containsKey(conf.getName())) { - return new Status(StatusCode.CONFLICT, - "Subnet with the specified name already exists."); - } - // Semantic check - status = semanticCheck(conf); - if (!status.isSuccess()) { - return status; - } - } else { - if (conf.getName().equalsIgnoreCase(DEFAULT_SUBNET_NAME)) { - return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed"); - } - } - - // Update Database - status = updateDatabase(conf, isAdding); - - if (status.isSuccess()) { - // Update Configuration - status = updateConfig(conf, isAdding); - if(!status.isSuccess()) { - updateDatabase(conf, (!isAdding)); - } else { - // update the listeners - Subnet subnetCurr = subnets.get(conf.getIPAddress()); - Subnet subnet; - if (subnetCurr == null) { - subnet = new Subnet(conf); - } else { - subnet = subnetCurr.clone(); - } - notifySubnetChange(subnet, isAdding); - } - } - - return status; - } - - /** - * Adds Subnet configured in GUI or API3 - */ - @Override - public Status addSubnet(SubnetConfig conf) { - return this.addRemoveSubnet(conf, true); - } - - @Override - public Status removeSubnet(SubnetConfig conf) { - return this.addRemoveSubnet(conf, false); - } - - @Override - public Status removeSubnet(String name) { - if (name.equalsIgnoreCase(DEFAULT_SUBNET_NAME)) { - return new Status(StatusCode.NOTALLOWED, "The specified subnet gateway cannot be removed"); - } - SubnetConfig conf = subnetsConfigList.get(name); - if (conf == null) { - return new Status(StatusCode.SUCCESS, "Subnet not present"); - } - return this.addRemoveSubnet(conf, false); - } - - @Override - public Status modifySubnet(SubnetConfig conf) { - // Sanity check - if (conf == null) { - return new Status(StatusCode.BADREQUEST, "Invalid Subnet configuration: null"); - } - - // Valid configuration check - Status status = conf.validate(); - if (!status.isSuccess()) { - log.warn(status.getDescription()); - return status; - } - - // If a subnet configuration with this name does not exist, consider this is a creation - SubnetConfig target = subnetsConfigList.get(conf.getName()); - if (target == null) { - return this.addSubnet(conf); - } - - // No change - if (target.equals(conf)) { - return new Status(StatusCode.SUCCESS); - } - - // Check not allowed modifications - if (!target.getSubnet().equals(conf.getSubnet())) { - return new Status(StatusCode.BADREQUEST, "IP address change is not allowed"); - } - - // Derive the set of node connectors that are being removed - Set toRemove = target.getNodeConnectors(); - toRemove.removeAll(conf.getNodeConnectors()); - List nodeConnectorStrings = null; - if (!toRemove.isEmpty()) { - nodeConnectorStrings = new ArrayList(); - for (NodeConnector nc : toRemove) { - nodeConnectorStrings.add(nc.toString()); - } - status = this.removePortsFromSubnet(conf.getName(), nodeConnectorStrings); - if (!status.isSuccess()) { - return status; - } - } - - // Derive the set of node connectors that are being added - Set toAdd = conf.getNodeConnectors(); - toAdd.removeAll(target.getNodeConnectors()); - if (!toAdd.isEmpty()) { - List nodeConnectorStringRemoved = nodeConnectorStrings; - nodeConnectorStrings = new ArrayList(); - for (NodeConnector nc : toAdd) { - nodeConnectorStrings.add(nc.toString()); - } - status = this.addPortsToSubnet(conf.getName(), nodeConnectorStrings); - if (!status.isSuccess()) { - // If any port was removed, add it back as a best recovery effort - if (!toRemove.isEmpty()) { - this.addPortsToSubnet(conf.getName(), nodeConnectorStringRemoved); - } - return status; - } - } - - // Update Configuration - subnetsConfigList.put(conf.getName(), conf); - - return new Status(StatusCode.SUCCESS); - } - - @Override - public Status addPortsToSubnet(String name, List switchPorts) { - if (name == null) { - return new Status(StatusCode.BADREQUEST, "Null subnet name"); - } - SubnetConfig confCurr = subnetsConfigList.get(name); - if (confCurr == null) { - return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); - } - - if (switchPorts == null || switchPorts.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Null or empty port set"); - } - - Subnet subCurr = subnets.get(confCurr.getIPAddress()); - if (subCurr == null) { - log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress()); - return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); - } - - // Update Database - Subnet sub = subCurr.clone(); - Set sp = NodeConnector.fromString(switchPorts); - sub.addNodeConnectors(sp); - boolean subnetsReplaced = subnets.replace(confCurr.getIPAddress(), subCurr, sub); - if (!subnetsReplaced) { - String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name; - return new Status(StatusCode.CONFLICT, msg); - } - - // Update Configuration - SubnetConfig conf = confCurr.clone(); - conf.addNodeConnectors(switchPorts); - boolean configReplaced = subnetsConfigList.replace(name, confCurr, conf); - if (!configReplaced) { - // TODO: recovery using Transactionality - String msg = "Cluster conflict: Conflict while adding ports to the subnet " + name; - return new Status(StatusCode.CONFLICT, msg); - } - - return new Status(StatusCode.SUCCESS); - } - - @Override - public Status removePortsFromSubnet(String name, List switchPorts) { - if (name == null) { - return new Status(StatusCode.BADREQUEST, "Null subnet name"); - } - SubnetConfig confCurr = subnetsConfigList.get(name); - if (confCurr == null) { - return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); - } - - if (switchPorts == null || switchPorts.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Null or empty port set"); - } - - Subnet subCurr = subnets.get(confCurr.getIPAddress()); - if (subCurr == null) { - log.debug("Cluster conflict: Subnet entry {} is not present in the subnets cache.", confCurr.getIPAddress()); - return new Status(StatusCode.NOTFOUND, "Subnet does not exist"); - } - - // Validation check - Status status = SubnetConfig.validatePorts(switchPorts); - if (!status.isSuccess()) { - return status; - } - // Update Database - Subnet sub = subCurr.clone(); - Set sp = NodeConnector.fromString(switchPorts); - sub.deleteNodeConnectors(sp); - boolean subnetsReplace = subnets.replace(confCurr.getIPAddress(), subCurr, sub); - if (!subnetsReplace) { - String msg = "Cluster conflict: Conflict while removing ports from the subnet " + name; - return new Status(StatusCode.CONFLICT, msg); - } - - // Update Configuration - SubnetConfig conf = confCurr.clone(); - conf.removeNodeConnectors(switchPorts); - boolean result = subnetsConfigList.replace(name, confCurr, conf); - if (!result) { - // TODO: recovery using Transactionality - String msg = "Cluster conflict: Conflict while removing ports from " + conf; - return new Status(StatusCode.CONFLICT, msg); - } - - return new Status(StatusCode.SUCCESS); - } - - public String getContainerName() { - if (containerName == null) { - return GlobalConstants.DEFAULT.toString(); - } - return containerName; - } - - @Override - public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) { - // if there are no subnets, return the default subnet - if (subnets.size() == 0) { - return DEFAULT_SUBNET; - } - - for(Map.Entry subnetEntry : subnets.entrySet()) { - if(subnetEntry.getValue().isSubnetOf(networkAddress)) { - return subnetEntry.getValue(); - } - } - return null; - } - - @Override - public Object readObject(ObjectInputStream ois) - throws FileNotFoundException, IOException, ClassNotFoundException { - // Perform the class deserialization locally, from inside the package - // where the class is defined - return ois.readObject(); - } - - private void loadSubnetConfiguration() { - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SUBNETS_FILE_NAME)) { - addSubnet((SubnetConfig) conf); - } - } - - private void loadSpanConfiguration() { - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SPAN_FILE_NAME)) { - addSpanConfig((SpanConfig) conf); - } - } - - private void loadSwitchConfiguration() { - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SWITCH_CONFIG_FILE_NAME)) { - updateNodeConfig((SwitchConfig) conf); - } - } - - @SuppressWarnings("deprecation") - @Override - public void updateSwitchConfig(SwitchConfig cfgObject) { - // update default container only - if (!isDefaultContainer) { - return; - } - - SwitchConfig sc = nodeConfigList.get(cfgObject.getNodeId()); - if (sc == null) { - if (nodeConfigList.putIfAbsent(cfgObject.getNodeId(), cfgObject) != null) { - return; - } - } else { - if (!nodeConfigList.replace(cfgObject.getNodeId(), sc, cfgObject)) { - return; - } - } - - boolean modeChange = false; - - if ((sc == null) || !cfgObject.getMode().equals(sc.getMode())) { - modeChange = true; - } - - String nodeId = cfgObject.getNodeId(); - Node node = Node.fromString(nodeId); - Map propMapCurr = nodeProps.get(node); - if (propMapCurr == null) { - return; - } - Map propMap = new HashMap(propMapCurr); - Property desc = new Description(cfgObject.getNodeDescription()); - propMap.put(desc.getName(), desc); - Property tier = new Tier(Integer.parseInt(cfgObject.getTier())); - propMap.put(tier.getName(), tier); - - if (!nodeProps.replace(node, propMapCurr, propMap)) { - // TODO rollback using Transactionality - return; - } - - log.trace("Set Node {}'s Mode to {}", nodeId, cfgObject.getMode()); - - if (modeChange) { - notifyModeChange(node, cfgObject.isProactive()); - } - } - - @Override - public Status updateNodeConfig(SwitchConfig switchConfig) { - Status status = switchConfig.validate(); - if (!status.isSuccess()) { - return status; - } - - Map updateProperties = switchConfig.getNodeProperties(); - ForwardingMode mode = (ForwardingMode) updateProperties.get(ForwardingMode.name); - if (mode != null) { - if (isDefaultContainer) { - if (!mode.isValid()) { - return new Status(StatusCode.BADREQUEST, "Invalid Forwarding Mode Value"); - } - } else { - return new Status(StatusCode.NOTACCEPTABLE, - "Forwarding Mode modification is allowed only in default container"); - } - } - - Description description = (Description) switchConfig.getProperty(Description.propertyName); - String nodeId = switchConfig.getNodeId(); - Node node = Node.fromString(nodeId); - NodeDescription nodeDesc = (this.statisticsManager == null) ? null : this.statisticsManager - .getNodeDescription(node); - String advertisedDesc = (nodeDesc == null) ? "" : nodeDesc.getDescription(); - if (description != null && description.getValue() != null) { - if (description.getValue().isEmpty() || description.getValue().equals(advertisedDesc)) { - updateProperties.remove(Description.propertyName); - switchConfig = new SwitchConfig(nodeId, updateProperties); - } else { - // check if description is configured or was published by any other node - for (Map.Entry> entry : nodeProps.entrySet()) { - Node n = entry.getKey(); - Description desc = (Description) getNodeProp(n, Description.propertyName); - NodeDescription nDesc = (this.statisticsManager == null) ? null : this.statisticsManager - .getNodeDescription(n); - String advDesc = (nDesc == null) ? "" : nDesc.getDescription(); - if ((description.equals(desc) || description.getValue().equals(advDesc)) && !node.equals(n)) { - return new Status(StatusCode.CONFLICT, "Node name already in use"); - } - } - } - } - - boolean modeChange = false; - SwitchConfig sc = nodeConfigList.get(nodeId); - Map prevNodeProperties = new HashMap(); - if (sc == null) { - if ((mode != null) && mode.isProactive()) { - modeChange = true; - } - if (!updateProperties.isEmpty()) { - if (nodeConfigList.putIfAbsent(nodeId, switchConfig) != null) { - return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); - } - } - } else { - prevNodeProperties = new HashMap(sc.getNodeProperties()); - ForwardingMode prevMode = (ForwardingMode) sc.getProperty(ForwardingMode.name); - if (mode == null) { - if ((prevMode != null) && (prevMode.isProactive())) { - modeChange = true; - } - } else { - if (((prevMode != null) && (prevMode.getValue() != mode.getValue())) - || (prevMode == null && mode.isProactive())) { - modeChange = true; - } - } - if (updateProperties.isEmpty()) { - nodeConfigList.remove(nodeId); - } else { - if (!nodeConfigList.replace(nodeId, sc, switchConfig)) { - return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); - } - } - } - Map propMapCurr = nodeProps.get(node); - if (propMapCurr == null) { - return new Status(StatusCode.SUCCESS); - } - Map propMap = new HashMap(propMapCurr); - for (Map.Entry entry : prevNodeProperties.entrySet()) { - String prop = entry.getKey(); - if (!updateProperties.containsKey(prop)) { - if (prop.equals(Description.propertyName)) { - if (advertisedDesc != null) { - if (!advertisedDesc.isEmpty()) { - Property desc = new Description(advertisedDesc); - propMap.put(Description.propertyName, desc); - } - } - else { - propMap.remove(prop); - } - continue; - } else if (prop.equals(ForwardingMode.name)) { - Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING); - propMap.put(ForwardingMode.name, defaultMode); - continue; - } - propMap.remove(prop); - } - } - propMap.putAll(updateProperties); - if (!nodeProps.replace(node, propMapCurr, propMap)) { - // TODO rollback using Transactionality - return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration"); - } - if (modeChange) { - notifyModeChange(node, (mode == null) ? false : mode.isProactive()); - } - return new Status(StatusCode.SUCCESS); - } - - @Override - public Status removeNodeConfig(String nodeId) { - if ((nodeId == null) || (nodeId.isEmpty())) { - return new Status(StatusCode.BADREQUEST, "nodeId cannot be empty."); - } - Map nodeProperties = getSwitchConfig(nodeId).getNodeProperties(); - Node node = Node.fromString(nodeId); - Map propMapCurr = nodeProps.get(node); - if ((propMapCurr != null) && (nodeProperties != null) && (!nodeProperties.isEmpty())) { - Map propMap = new HashMap(propMapCurr); - for (Map.Entry entry : nodeProperties.entrySet()) { - String prop = entry.getKey(); - if (prop.equals(Description.propertyName)) { - Map> nodeProp = this.inventoryService.getNodeProps(); - if (nodeProp.get(node) != null) { - propMap.put(Description.propertyName, nodeProp.get(node).get(Description.propertyName)); - continue; - } - } - propMap.remove(prop); - } - if (!nodeProps.replace(node, propMapCurr, propMap)) { - return new Status(StatusCode.CONFLICT, "Cluster conflict: Unable to update node configuration."); - } - } - if (nodeConfigList != null) { - nodeConfigList.remove(nodeId); - } - return new Status(StatusCode.SUCCESS); - } - - @Override - public Status saveSwitchConfig() { - return saveSwitchConfigInternal(); - } - - public Status saveSwitchConfigInternal() { - Status status; - short number = 0; - status = configurationService.persistConfiguration( - new ArrayList(subnetsConfigList.values()), SUBNETS_FILE_NAME); - if (status.isSuccess()) { - number++; - } else { - log.warn("Failed to save subnet gateway configurations: " + status.getDescription()); - } - status = configurationService.persistConfiguration(new ArrayList(spanConfigList.values()), - SPAN_FILE_NAME); - if (status.isSuccess()) { - number++; - } else { - log.warn("Failed to save span port configurations: " + status.getDescription()); - } - status = configurationService.persistConfiguration(new ArrayList(nodeConfigList.values()), - SWITCH_CONFIG_FILE_NAME); - if (status.isSuccess()) { - number++; - } else { - log.warn("Failed to save node configurations: " + status.getDescription()); - } - if (number == 0) { - return new Status(StatusCode.INTERNALERROR, "Save failed"); - } - if (number < 3) { - return new Status(StatusCode.INTERNALERROR, "Partial save failure"); - } - return status; - } - - @Override - public List getSpanConfigList() { - return new ArrayList(spanConfigList.values()); - } - - @Override - public Status addSpanConfig(SpanConfig conf) { - // Valid config check - if (!conf.isValidConfig()) { - String msg = "Invalid Span configuration"; - log.warn(msg); - return new Status(StatusCode.BADREQUEST, msg); - } - - // Presence check - if (spanConfigList.containsKey(conf)) { - return new Status(StatusCode.CONFLICT, "Same span config exists"); - } - - // Update configuration - if (spanConfigList.putIfAbsent(conf, conf) == null) { - // Update database and notify clients - addSpanPorts(conf.getNode(), conf.getPortArrayList()); - } - - return new Status(StatusCode.SUCCESS); - } - - @Override - public Status removeSpanConfig(SpanConfig conf) { - removeSpanPorts(conf.getNode(), conf.getPortArrayList()); - - // Update configuration - spanConfigList.remove(conf); - - return new Status(StatusCode.SUCCESS); - } - - @Override - public List getSpanPorts(Node node) { - List ncList = new ArrayList(); - - for (NodeConnector nodeConnector : spanNodeConnectors) { - if (nodeConnector.getNode().equals(node)) { - ncList.add(nodeConnector); - } - } - return ncList; - } - - private void addNode(Node node, Set props) { - log.trace("{} added, props: {}", node, props); - if (nodeProps == null) { - return; - } - - Map propMapCurr = nodeProps.get(node); - Map propMap = (propMapCurr == null) ? new HashMap() - : new HashMap(propMapCurr); - - // copy node properties from plugin - if (props != null) { - for (Property prop : props) { - propMap.put(prop.getName(), prop); - } - } - - boolean forwardingModeChanged = false; - - // copy node properties from config - if (nodeConfigList != null) { - String nodeId = node.toString(); - SwitchConfig conf = nodeConfigList.get(nodeId); - if (conf != null && (conf.getNodeProperties() != null)) { - Map nodeProperties = conf.getNodeProperties(); - propMap.putAll(nodeProperties); - if (nodeProperties.get(ForwardingMode.name) != null) { - ForwardingMode mode = (ForwardingMode) nodeProperties.get(ForwardingMode.name); - forwardingModeChanged = mode.isProactive(); - } - } else if ((conf == null) && !(GlobalConstants.DEFAULT.toString().equals(containerName))) { - ISwitchManager defaultSwitchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, GlobalConstants.DEFAULT.toString(), this); - if (defaultSwitchManager != null) { - Property defaultContainerSwitchDesc = (Description) defaultSwitchManager.getNodeProp(node, Description.propertyName); - if (defaultContainerSwitchDesc != null) { - Map descPropMap = new HashMap(); - descPropMap.put(Description.propertyName, defaultContainerSwitchDesc); - conf = new SwitchConfig(nodeId, descPropMap); - updateNodeConfig(conf); - propMap.put(Description.propertyName, defaultContainerSwitchDesc); - } - } - } - } - - if (!propMap.containsKey(ForwardingMode.name)) { - Property defaultMode = new ForwardingMode(ForwardingMode.REACTIVE_FORWARDING); - propMap.put(ForwardingMode.name, defaultMode); - } - - boolean propsAdded = false; - // Attempt initial add - if (nodeProps.putIfAbsent(node, propMap) == null) { - propsAdded = true; - - /* Notify listeners only for initial node addition - * to avoid expensive tasks triggered by redundant notifications - */ - notifyNode(node, UpdateType.ADDED, propMap); - } else { - - propsAdded = nodeProps.replace(node, propMapCurr, propMap); - - // check whether forwarding mode changed - if (propMapCurr.get(ForwardingMode.name) != null) { - ForwardingMode mode = (ForwardingMode) propMapCurr.get(ForwardingMode.name); - forwardingModeChanged ^= mode.isProactive(); - } - } - if (!propsAdded) { - log.debug("Cluster conflict while adding node {}. Overwriting with latest props: {}", node.getID(), props); - addNodeProps(node, propMap); - } - - // check if span ports are configured - addSpanPorts(node); - // notify proactive mode forwarding - if (forwardingModeChanged) { - notifyModeChange(node, true); - } - } - - private void removeNode(Node node) { - log.trace("{} removed", node); - if (nodeProps == null) { - return; - } - - if (nodeProps.remove(node) == null) { - log.debug("Received redundant node REMOVED udate for {}. Skipping..", node); - return; - } - - nodeConnectorNames.remove(node); - Set removeNodeConnectorSet = new HashSet(); - for (Map.Entry> entry : nodeConnectorProps.entrySet()) { - NodeConnector nodeConnector = entry.getKey(); - if (nodeConnector.getNode().equals(node)) { - removeNodeConnectorSet.add(nodeConnector); - } - } - for (NodeConnector nc : removeNodeConnectorSet) { - nodeConnectorProps.remove(nc); - } - - // check if span ports need to be cleaned up - removeSpanPorts(node); - - /* notify node listeners */ - notifyNode(node, UpdateType.REMOVED, null); - } - - private void updateNode(Node node, Set props) { - log.trace("{} updated, props: {}", node, props); - if (nodeProps == null || props == null) { - return; - } - - Map propMapCurr = nodeProps.get(node); - Map propMap = (propMapCurr == null) ? new HashMap() - : new HashMap(propMapCurr); - - // copy node properties from plugin - String nodeId = node.toString(); - for (Property prop : props) { - if (nodeConfigList != null) { - SwitchConfig conf = nodeConfigList.get(nodeId); - if (conf != null && (conf.getNodeProperties() != null) - && conf.getNodeProperties().containsKey(prop.getName())) { - continue; - } - } - propMap.put(prop.getName(), prop); - } - - if (propMapCurr == null) { - if (nodeProps.putIfAbsent(node, propMap) != null) { - log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}", - node.getID(), props); - addNodeProps(node, propMap); - } - } else { - if (!nodeProps.replace(node, propMapCurr, propMap)) { - log.debug("Cluster conflict: Conflict while updating the node. Node: {} Properties: {}", - node.getID(), props); - addNodeProps(node, propMap); - } - } - - /* notify node listeners */ - notifyNode(node, UpdateType.CHANGED, propMap); - } - - @Override - public void updateNode(Node node, UpdateType type, Set props) { - log.debug("updateNode: {} type {} props {} for container {}", - new Object[] { node, type, props, containerName }); - switch (type) { - case ADDED: - addNode(node, props); - break; - case CHANGED: - updateNode(node, props); - break; - case REMOVED: - removeNode(node); - break; - default: - break; - } - } - - @Override - public void updateNodeConnector(NodeConnector nodeConnector, - UpdateType type, Set props) { - Map propMap = new HashMap(); - boolean update = true; - - log.debug("updateNodeConnector: {} type {} props {} for container {}", - new Object[] { nodeConnector, type, props, containerName }); - - if (nodeConnectorProps == null) { - return; - } - - switch (type) { - case ADDED: - // Skip redundant ADDED update (e.g. cluster switch-over) - if (nodeConnectorProps.containsKey(nodeConnector)) { - log.debug("Redundant nodeconnector ADDED for {}, props {} for container {}", - nodeConnector, props, containerName); - update = false; - } - - if (props != null) { - for (Property prop : props) { - addNodeConnectorProp(nodeConnector, prop); - propMap.put(prop.getName(), prop); - } - } else { - addNodeConnectorProp(nodeConnector, null); - } - - - addSpanPort(nodeConnector); - break; - case CHANGED: - if (!nodeConnectorProps.containsKey(nodeConnector) || (props == null)) { - update = false; - } else { - for (Property prop : props) { - addNodeConnectorProp(nodeConnector, prop); - propMap.put(prop.getName(), prop); - } - } - break; - case REMOVED: - if (!nodeConnectorProps.containsKey(nodeConnector)) { - update = false; - } - removeNodeConnectorAllProps(nodeConnector); - - // clean up span config - removeSpanPort(nodeConnector); - break; - default: - update = false; - break; - } - - if (update) { - notifyNodeConnector(nodeConnector, type, propMap); - } - } - - @Override - public Set getNodes() { - return (nodeProps != null) ? new HashSet(nodeProps.keySet()) : new HashSet(); - } - - @Override - public Map getControllerProperties() { - return new HashMap(this.controllerProps); - } - - @Override - public Property getControllerProperty(String propertyName) { - if (propertyName != null) { - HashMap propertyMap = new HashMap(this.controllerProps); - return propertyMap.get(propertyName); - } - return null; - } - - @Override - public Status setControllerProperty(Property property) { - if (property != null) { - this.controllerProps.put(property.getName(), property); - return new Status(StatusCode.SUCCESS); - } - return new Status(StatusCode.BADREQUEST, "Invalid property provided when setting property"); - } - - @Override - public Status removeControllerProperty(String propertyName) { - if (propertyName != null) { - if (this.controllerProps.containsKey(propertyName)) { - this.controllerProps.remove(propertyName); - if (!this.controllerProps.containsKey(propertyName)) { - return new Status(StatusCode.SUCCESS); - } - } - String msg = "Unable to remove property " + propertyName + " from Controller"; - return new Status(StatusCode.BADREQUEST, msg); - } - String msg = "Invalid property provided when removing property from Controller"; - return new Status(StatusCode.BADREQUEST, msg); - } - - /* - * Returns a copy of a list of properties for a given node - * - * (non-Javadoc) - * - * @see - * org.opendaylight.controller.switchmanager.ISwitchManager#getNodeProps - * (org.opendaylight.controller.sal.core.Node) - */ - @Override - public Map getNodeProps(Node node) { - Map rv = new HashMap(); - if (this.nodeProps != null) { - rv = this.nodeProps.get(node); - if (rv != null) { - /* make a copy of it */ - rv = new HashMap(rv); - } - } - return rv; - } - - @Override - public Property getNodeProp(Node node, String propName) { - Map propMap = getNodeProps(node); - return (propMap != null) ? propMap.get(propName) : null; - } - - @Override - public void setNodeProp(Node node, Property prop) { - - for (int i = 0; i <= REPLACE_RETRY; i++) { - /* Get a copy of the property map */ - Map propMapCurr = getNodeProps(node); - if (propMapCurr == null) { - return; - } - - Map propMap = new HashMap(propMapCurr); - propMap.put(prop.getName(), prop); - - if (nodeProps.replace(node, propMapCurr, propMap)) { - return; - } - } - log.warn("Cluster conflict: Unable to add property {} to node {}.", prop.getName(), node.getID()); - } - - @Override - public Status removeNodeProp(Node node, String propName) { - for (int i = 0; i <= REPLACE_RETRY; i++) { - Map propMapCurr = getNodeProps(node); - if (propMapCurr != null) { - if (!propMapCurr.containsKey(propName)) { - return new Status(StatusCode.SUCCESS); - } - Map propMap = new HashMap(propMapCurr); - propMap.remove(propName); - if (nodeProps.replace(node, propMapCurr, propMap)) { - return new Status(StatusCode.SUCCESS); - } - } else { - return new Status(StatusCode.SUCCESS); - } - } - String msg = "Cluster conflict: Unable to remove property " + propName + " for node " + node.getID(); - return new Status(StatusCode.CONFLICT, msg); - } - - @Override - public Status removeNodeAllProps(Node node) { - this.nodeProps.remove(node); - return new Status(StatusCode.SUCCESS); - } - - @Override - public Set getUpNodeConnectors(Node node) { - if (nodeConnectorProps == null) { - return null; - } - - Set nodeConnectorSet = new HashSet(); - for (Map.Entry> entry : nodeConnectorProps.entrySet()) { - NodeConnector nodeConnector = entry.getKey(); - if (!nodeConnector.getNode().equals(node)) { - continue; - } - if (isNodeConnectorEnabled(nodeConnector)) { - nodeConnectorSet.add(nodeConnector); - } - } - - return nodeConnectorSet; - } - - @Override - public Set getNodeConnectors(Node node) { - if (nodeConnectorProps == null) { - return null; - } - - Set nodeConnectorSet = new HashSet(); - for (Map.Entry> entry : nodeConnectorProps.entrySet()) { - NodeConnector nodeConnector = entry.getKey(); - if (!nodeConnector.getNode().equals(node)) { - continue; - } - nodeConnectorSet.add(nodeConnector); - } - - return nodeConnectorSet; - } - - @Override - public Set getPhysicalNodeConnectors(Node node) { - if (nodeConnectorProps == null) { - return null; - } - - Set nodeConnectorSet = new HashSet(); - for (Map.Entry> entry : nodeConnectorProps.entrySet()) { - NodeConnector nodeConnector = entry.getKey(); - if (!nodeConnector.getNode().equals(node) - || isSpecial(nodeConnector)) { - continue; - } - nodeConnectorSet.add(nodeConnector); - } - - return nodeConnectorSet; - } - - @Override - public Map getNodeConnectorProps(NodeConnector nodeConnector) { - Map rv = new HashMap(); - if (this.nodeConnectorProps != null) { - rv = this.nodeConnectorProps.get(nodeConnector); - if (rv != null) { - rv = new HashMap(rv); - } - } - return rv; - } - - @Override - public Property getNodeConnectorProp(NodeConnector nodeConnector, - String propName) { - Map propMap = getNodeConnectorProps(nodeConnector); - return (propMap != null) ? propMap.get(propName) : null; - } - - @Override - public byte[] getControllerMAC() { - MacAddress macProperty = (MacAddress)controllerProps.get(MacAddress.name); - return (macProperty == null) ? null : macProperty.getMacAddress(); - } - - @Override - public NodeConnector getNodeConnector(Node node, String nodeConnectorName) { - if (nodeConnectorNames == null) { - return null; - } - - Map map = nodeConnectorNames.get(node); - if (map == null) { - return null; - } - - return map.get(nodeConnectorName); - } - - /** - * Adds a node connector and its property if any - * - * @param nodeConnector - * {@link org.opendaylight.controller.sal.core.NodeConnector} - * @param propName - * name of {@link org.opendaylight.controller.sal.core.Property} - * @return success or failed reason - */ - @Override - public Status addNodeConnectorProp(NodeConnector nodeConnector, - Property prop) { - Map propMapCurr = getNodeConnectorProps(nodeConnector); - Map propMap = (propMapCurr == null) ? new HashMap() - : new HashMap(propMapCurr); - - String msg = "Cluster conflict: Unable to add NodeConnector Property."; - // Just add the nodeConnector if prop is not available (in a non-default - // container) - if (prop == null) { - if (propMapCurr == null) { - if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) { - return new Status(StatusCode.CONFLICT, msg); - } - } else { - if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) { - return new Status(StatusCode.CONFLICT, msg); - } - } - return new Status(StatusCode.SUCCESS); - } - - propMap.put(prop.getName(), prop); - if (propMapCurr == null) { - if (nodeConnectorProps.putIfAbsent(nodeConnector, propMap) != null) { - return new Status(StatusCode.CONFLICT, msg); - } - } else { - if (!nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap)) { - return new Status(StatusCode.CONFLICT, msg); - } - } - - if (prop.getName().equals(Name.NamePropName)) { - if (nodeConnectorNames != null) { - Node node = nodeConnector.getNode(); - Map mapCurr = nodeConnectorNames.get(node); - Map map = new HashMap(); - if (mapCurr != null) { - for (Map.Entry entry : mapCurr.entrySet()) { - String s = entry.getKey(); - try { - map.put(s, new NodeConnector(entry.getValue())); - } catch (ConstructionException e) { - log.error("An error occured",e); - } - } - } - - map.put(((Name) prop).getValue(), nodeConnector); - if (mapCurr == null) { - if (nodeConnectorNames.putIfAbsent(node, map) != null) { - // TODO: recovery using Transactionality - return new Status(StatusCode.CONFLICT, msg); - } - } else { - if (!nodeConnectorNames.replace(node, mapCurr, map)) { - // TODO: recovery using Transactionality - return new Status(StatusCode.CONFLICT, msg); - } - } - } - } - - return new Status(StatusCode.SUCCESS); - } - - /** - * Removes one property of a node connector - * - * @param nodeConnector - * {@link org.opendaylight.controller.sal.core.NodeConnector} - * @param propName - * name of {@link org.opendaylight.controller.sal.core.Property} - * @return success or failed reason - */ - @Override - public Status removeNodeConnectorProp(NodeConnector nodeConnector, String propName) { - Map propMapCurr = getNodeConnectorProps(nodeConnector); - - if (propMapCurr == null) { - /* Nothing to remove */ - return new Status(StatusCode.SUCCESS); - } - - Map propMap = new HashMap(propMapCurr); - propMap.remove(propName); - boolean result = nodeConnectorProps.replace(nodeConnector, propMapCurr, propMap); - String msg = "Cluster conflict: Unable to remove NodeConnector property."; - if (!result) { - return new Status(StatusCode.CONFLICT, msg); - } - - if (propName.equals(Name.NamePropName)) { - if (nodeConnectorNames != null) { - Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName)); - if (name != null) { - Node node = nodeConnector.getNode(); - Map mapCurr = nodeConnectorNames.get(node); - if (mapCurr != null) { - Map map = new HashMap(); - for (Map.Entry entry : mapCurr.entrySet()) { - String s = entry.getKey(); - try { - map.put(s, new NodeConnector(entry.getValue())); - } catch (ConstructionException e) { - log.error("An error occured",e); - } - } - map.remove(name.getValue()); - if (!nodeConnectorNames.replace(node, mapCurr, map)) { - // TODO: recovery using Transactionality - return new Status(StatusCode.CONFLICT, msg); - } - } - } - } - } - - return new Status(StatusCode.SUCCESS); - } - - /** - * Removes all the properties of a node connector - * - * @param nodeConnector - * {@link org.opendaylight.controller.sal.core.NodeConnector} - * @return success or failed reason - */ - @Override - public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) { - if (nodeConnectorNames != null) { - Name name = ((Name) getNodeConnectorProp(nodeConnector, Name.NamePropName)); - if (name != null) { - Node node = nodeConnector.getNode(); - Map mapCurr = nodeConnectorNames.get(node); - if (mapCurr != null) { - Map map = new HashMap(); - for (Map.Entry entry : mapCurr.entrySet()) { - String s = entry.getKey(); - try { - map.put(s, new NodeConnector(entry.getValue())); - } catch (ConstructionException e) { - log.error("An error occured",e); - } - } - map.remove(name.getValue()); - if (map.isEmpty()) { - nodeConnectorNames.remove(node); - } else { - if (!nodeConnectorNames.replace(node, mapCurr, map)) { - log.warn("Cluster conflict: Unable remove Name property of nodeconnector {}, skip.", - nodeConnector.getID()); - } - } - } - - } - } - nodeConnectorProps.remove(nodeConnector); - - return new Status(StatusCode.SUCCESS); - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init(Component c) { - Dictionary props = c.getServiceProperties(); - if (props != null) { - this.containerName = (String) props.get("containerName"); - log.trace("Running containerName: {}", this.containerName); - } else { - // In the Global instance case the containerName is empty - this.containerName = ""; - } - isDefaultContainer = containerName.equals(GlobalConstants.DEFAULT - .toString()); - - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - shutDown(); - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - startUp(); - - /* - * Read startup and build database if we are the coordinator - */ - loadSubnetConfiguration(); - loadSpanConfiguration(); - loadSwitchConfiguration(); - - // OSGI console - registerWithOSGIConsole(); - } - - /** - * Function called after registered the service in OSGi service registry. - */ - void started() { - // solicit for existing inventories - getInventories(); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - } - - public void setConfigurationContainerService(IConfigurationContainerService service) { - log.trace("Got configuration service set request {}", service); - this.configurationService = service; - } - - public void unsetConfigurationContainerService(IConfigurationContainerService service) { - log.trace("Got configuration service UNset request"); - this.configurationService = null; - } - - public void setInventoryService(IInventoryService service) { - log.trace("Got inventory service set request {}", service); - this.inventoryService = service; - - // solicit for existing inventories - getInventories(); - } - - public void unsetInventoryService(IInventoryService service) { - log.trace("Got a service UNset request"); - this.inventoryService = null; - - // clear existing inventories - clearInventories(); - } - - public void setStatisticsManager(IStatisticsManager statisticsManager) { - log.trace("Got statistics manager set request {}", statisticsManager); - this.statisticsManager = statisticsManager; - } - - public void unsetStatisticsManager(IStatisticsManager statisticsManager) { - log.trace("Got statistics manager UNset request"); - this.statisticsManager = null; - } - - public void setSwitchManagerAware(ISwitchManagerAware service) { - log.trace("Got inventory service set request {}", service); - if (this.switchManagerAware != null) { - this.switchManagerAware.add(service); - } - - // bulk update for newly joined - switchManagerAwareNotify(service); - } - - public void unsetSwitchManagerAware(ISwitchManagerAware service) { - log.trace("Got a service UNset request"); - if (this.switchManagerAware != null) { - this.switchManagerAware.remove(service); - } - } - - public void setInventoryListener(IInventoryListener service) { - log.trace("Got inventory listener set request {}", service); - if (this.inventoryListeners != null) { - this.inventoryListeners.add(service); - } - - // bulk update for newly joined - bulkUpdateService(service); - } - - public void unsetInventoryListener(IInventoryListener service) { - log.trace("Got a service UNset request"); - if (this.inventoryListeners != null) { - this.inventoryListeners.remove(service); - } - } - - public void setSpanAware(ISpanAware service) { - log.trace("Got SpanAware set request {}", service); - if (this.spanAware != null) { - this.spanAware.add(service); - } - - // bulk update for newly joined - spanAwareNotify(service); - } - - public void unsetSpanAware(ISpanAware service) { - log.trace("Got a service UNset request"); - if (this.spanAware != null) { - this.spanAware.remove(service); - } - } - - void setClusterContainerService(IClusterContainerServices s) { - log.trace("Cluster Service set"); - this.clusterContainerService = s; - } - - void unsetClusterContainerService(IClusterContainerServices s) { - if (this.clusterContainerService == s) { - log.trace("Cluster Service removed!"); - this.clusterContainerService = null; - } - } - - public void setControllerProperties(IControllerProperties controllerProperties) { - log.trace("Got controller properties set request {}", controllerProperties); - this.controllerProperties = controllerProperties; - } - - public void unsetControllerProperties(IControllerProperties controllerProperties) { - log.trace("Got controller properties UNset request"); - this.controllerProperties = null; - } - - private void getInventories() { - if (inventoryService == null) { - log.trace("inventory service not avaiable"); - return; - } - - Map> nodeProp = this.inventoryService.getNodeProps(); - for (Map.Entry> entry : nodeProp.entrySet()) { - Node node = entry.getKey(); - log.debug("getInventories: {} added for container {}", new Object[] { node, containerName }); - Map propMap = entry.getValue(); - Set props = new HashSet(); - for (Property property : propMap.values()) { - props.add(property); - } - addNode(node, props); - } - - Map> nodeConnectorProp = this.inventoryService.getNodeConnectorProps(); - for (Map.Entry> entry : nodeConnectorProp.entrySet()) { - Map propMap = entry.getValue(); - for (Property property : propMap.values()) { - addNodeConnectorProp(entry.getKey(), property); - } - } - } - - private void clearInventories() { - nodeProps.clear(); - nodeConnectorProps.clear(); - nodeConnectorNames.clear(); - spanNodeConnectors.clear(); - } - - private void notifyNode(Node node, UpdateType type, - Map propMap) { - synchronized (inventoryListeners) { - for (IInventoryListener service : inventoryListeners) { - service.notifyNode(node, type, propMap); - } - } - } - - private void notifyNodeConnector(NodeConnector nodeConnector, - UpdateType type, Map propMap) { - synchronized (inventoryListeners) { - for (IInventoryListener service : inventoryListeners) { - service.notifyNodeConnector(nodeConnector, type, propMap); - } - } - } - - /* - * For those joined late, bring them up-to-date. - */ - private void switchManagerAwareNotify(ISwitchManagerAware service) { - for (Subnet sub : subnets.values()) { - service.subnetNotify(sub, true); - } - - for (Node node : getNodes()) { - SwitchConfig sc = getSwitchConfig(node.toString()); - if ((sc != null) && isDefaultContainer) { - ForwardingMode mode = (ForwardingMode) sc.getProperty(ForwardingMode.name); - service.modeChangeNotify(node, (mode == null) ? false : mode.isProactive()); - } - } - } - - private void bulkUpdateService(IInventoryListener service) { - Map propMap; - UpdateType type = UpdateType.ADDED; - - for (Node node : getNodes()) { - propMap = nodeProps.get(node); - service.notifyNode(node, type, propMap); - } - - for (Map.Entry> entry : nodeConnectorProps.entrySet()) { - NodeConnector nodeConnector = entry.getKey(); - propMap = nodeConnectorProps.get(nodeConnector); - service.notifyNodeConnector(nodeConnector, type, propMap); - } - } - - private void spanAwareNotify(ISpanAware service) { - for (Node node : getNodes()) { - for (SpanConfig conf : getSpanConfigList(node)) { - service.spanUpdate(node, conf.getPortArrayList(), true); - } - } - } - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, - null); - } - - @Override - public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) { - if (nodeConnector == null) { - return false; - } - - Config config = (Config) getNodeConnectorProp(nodeConnector, - Config.ConfigPropName); - State state = (State) getNodeConnectorProp(nodeConnector, - State.StatePropName); - return ((config != null) && (config.getValue() == Config.ADMIN_UP) - && (state != null) && (state.getValue() == State.EDGE_UP)); - } - - @Override - public boolean doesNodeConnectorExist(NodeConnector nc) { - return (nc != null && nodeConnectorProps != null - && nodeConnectorProps.containsKey(nc)); - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---Switch Manager---\n"); - help.append("\t pencs - Print enabled node connectors for a given node\n"); - help.append("\t pdm - Print switch ports in device map\n"); - return help.toString(); - } - - public void _pencs(CommandInterpreter ci) { - String st = ci.nextArgument(); - if (st == null) { - ci.println("Please enter node id"); - return; - } - - Node node = Node.fromString(st); - if (node == null) { - ci.println("Please enter node id"); - return; - } - - Set nodeConnectorSet = getUpNodeConnectors(node); - if (nodeConnectorSet == null) { - return; - } - for (NodeConnector nodeConnector : nodeConnectorSet) { - if (nodeConnector == null) { - continue; - } - ci.println(nodeConnector); - } - ci.println("Total number of NodeConnectors: " + nodeConnectorSet.size()); - } - - public void _pdm(CommandInterpreter ci) { - String st = ci.nextArgument(); - if (st == null) { - ci.println("Please enter node id"); - return; - } - - Node node = Node.fromString(st); - if (node == null) { - ci.println("Please enter node id"); - return; - } - - Switch sw = getSwitchByNode(node); - - ci.println(" NodeConnector Name"); - - Set nodeConnectorSet = sw.getNodeConnectors(); - String nodeConnectorName; - if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) { - for (NodeConnector nodeConnector : nodeConnectorSet) { - Map propMap = getNodeConnectorProps(nodeConnector); - nodeConnectorName = (propMap == null) ? null : ((Name) propMap - .get(Name.NamePropName)).getValue(); - if (nodeConnectorName != null) { - Node nd = nodeConnector.getNode(); - if (!nd.equals(node)) { - log.debug("node not match {} {}", nd, node); - } - Map map = nodeConnectorNames - .get(node); - if (map != null) { - NodeConnector nc = map.get(nodeConnectorName); - if (nc == null) { - log.debug("no nodeConnector named {}", - nodeConnectorName); - } else if (!nc.equals(nodeConnector)) { - log.debug("nodeConnector not match {} {}", nc, - nodeConnector); - } - } - } - - ci.println(nodeConnector - + " " - + ((nodeConnectorName == null) ? "" : nodeConnectorName) - + "(" + nodeConnector.getID() + ")"); - } - ci.println("Total number of NodeConnectors: " - + nodeConnectorSet.size()); - } - } - - @Override - public byte[] getNodeMAC(Node node) { - MacAddress mac = (MacAddress) this.getNodeProp(node, - MacAddress.name); - return (mac != null) ? mac.getMacAddress() : null; - } - - @Override - public boolean isSpecial(NodeConnector p) { - if (p.getType().equals(NodeConnectorIDType.CONTROLLER) - || p.getType().equals(NodeConnectorIDType.ALL) - || p.getType().equals(NodeConnectorIDType.SWSTACK) - || p.getType().equals(NodeConnectorIDType.HWPATH)) { - return true; - } - return false; - } - - /* - * Add span configuration to local cache and notify clients - */ - private void addSpanPorts(Node node, List nodeConnectors) { - List ncLists = new ArrayList(); - - for (NodeConnector nodeConnector : nodeConnectors) { - if (!spanNodeConnectors.contains(nodeConnector)) { - ncLists.add(nodeConnector); - } - } - - if (ncLists.size() > 0) { - spanNodeConnectors.addAll(ncLists); - notifySpanPortChange(node, ncLists, true); - } - } - - private void addSpanPorts(Node node) { - for (SpanConfig conf : getSpanConfigList(node)) { - addSpanPorts(node, conf.getPortArrayList()); - } - } - - private void addSpanPort(NodeConnector nodeConnector) { - // only add if span is configured on this nodeConnector - for (SpanConfig conf : getSpanConfigList(nodeConnector.getNode())) { - if (conf.getPortArrayList().contains(nodeConnector)) { - List ncList = new ArrayList(); - ncList.add(nodeConnector); - addSpanPorts(nodeConnector.getNode(), ncList); - return; - } - } - } - - /* - * Remove span configuration to local cache and notify clients - */ - private void removeSpanPorts(Node node, List nodeConnectors) { - List ncLists = new ArrayList(); - - for (NodeConnector nodeConnector : nodeConnectors) { - if (spanNodeConnectors.contains(nodeConnector)) { - ncLists.add(nodeConnector); - } - } - - if (ncLists.size() > 0) { - spanNodeConnectors.removeAll(ncLists); - notifySpanPortChange(node, ncLists, false); - } - } - - private void removeSpanPorts(Node node) { - for (SpanConfig conf : getSpanConfigList(node)) { - addSpanPorts(node, conf.getPortArrayList()); - } - } - - private void removeSpanPort(NodeConnector nodeConnector) { - if (spanNodeConnectors.contains(nodeConnector)) { - List ncLists = new ArrayList(); - ncLists.add(nodeConnector); - removeSpanPorts(nodeConnector.getNode(), ncLists); - } - } - - private void addNodeProps(Node node, Map propMap) { - if (propMap == null) { - propMap = new HashMap(); - } - nodeProps.put(node, propMap); - } - - @Override - public Status saveConfiguration() { - return saveSwitchConfig(); - } - - /** - * Creates a Name/Tier/Bandwidth/MacAddress(controller property) Property - * object based on given property name and value. Other property types are - * not supported yet. - * - * @param propName - * Name of the Property - * @param propValue - * Value of the Property - * @return {@link org.opendaylight.controller.sal.core.Property} - */ - @Override - public Property createProperty(String propName, String propValue) { - if (propName == null) { - log.debug("propName is null"); - return null; - } - if (propValue == null) { - log.debug("propValue is null"); - return null; - } - - try { - if (propName.equalsIgnoreCase(Description.propertyName)) { - return new Description(propValue); - } else if (propName.equalsIgnoreCase(Tier.TierPropName)) { - int tier = Integer.parseInt(propValue); - return new Tier(tier); - } else if (propName.equalsIgnoreCase(Bandwidth.BandwidthPropName)) { - long bw = Long.parseLong(propValue); - return new Bandwidth(bw); - } else if (propName.equalsIgnoreCase(ForwardingMode.name)) { - int mode = Integer.parseInt(propValue); - return new ForwardingMode(mode); - } else if (propName.equalsIgnoreCase(MacAddress.name)){ - return new MacAddress(propValue); - } - else { - log.debug("Not able to create {} property", propName); - } - } catch (Exception e) { - log.debug("createProperty caught exception {}", e.getMessage()); - } - - return null; - } - - - @SuppressWarnings("deprecation") - @Override - public String getNodeDescription(Node node) { - // Check first if user configured a name - SwitchConfig config = getSwitchConfig(node.toString()); - if (config != null) { - String configuredDesc = config.getNodeDescription(); - if (configuredDesc != null && !configuredDesc.isEmpty()) { - return configuredDesc; - } - } - - // No name configured by user, get the node advertised name - Description desc = (Description) getNodeProp(node, - Description.propertyName); - return (desc == null /* || desc.getValue().equalsIgnoreCase("none") */) ? "" - : desc.getValue(); - } - - @Override - public Set getConfiguredNotConnectedSwitches() { - Set configuredNotConnectedSwitches = new HashSet(); - if (this.inventoryService == null) { - log.trace("inventory service not available"); - return configuredNotConnectedSwitches; - } - - Set configuredNotConnectedNodes = this.inventoryService.getConfiguredNotConnectedNodes(); - if (configuredNotConnectedNodes != null) { - for (Node node : configuredNotConnectedNodes) { - Switch sw = getSwitchByNode(node); - configuredNotConnectedSwitches.add(sw); - } - } - return configuredNotConnectedSwitches; - } - -} diff --git a/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerCLI.java b/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerCLI.java deleted file mode 100644 index 268e45ad85..0000000000 --- a/opendaylight/adsal/switchmanager/implementation/src/main/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerCLI.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.internal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.felix.service.command.Descriptor; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.osgi.framework.ServiceRegistration; - -/** - * This class provides osgi cli commands for developers to debug Switch Manager - * functionality - */ -public class SwitchManagerCLI { - @SuppressWarnings("rawtypes") - private ServiceRegistration sr = null; - - public void init() { - } - - public void destroy() { - } - - public void start() { - final Dictionary props = new Hashtable(); - props.put("osgi.command.scope", "odpcontroller"); - props.put("osgi.command.function", new String[] { "showNodes", "showNodeConnectors" }); - this.sr = ServiceHelper.registerGlobalServiceWReg(SwitchManagerCLI.class, this, props); - } - - public void stop() { - if (this.sr != null) { - this.sr.unregister(); - this.sr = null; - } - } - - @Descriptor("Retrieves the nodes information present in Switch Manager DB") - public void showNodes( - @Descriptor("Container in which to query Switch Manager") String container) { - final ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, container, this); - - if (sm == null) { - System.out.println("Cannot find the switch manager instance on container: " + container); - return; - } - - Set nodes = sm.getNodes(); - if (nodes == null || nodes.isEmpty()) { - return; - } - - Set propertyList = new HashSet(); - for (Node node : nodes) { - Map propList = sm.getNodeProps(node); - propertyList.addAll(propList.keySet()); - } - List sortedProps = new ArrayList(propertyList); - Collections.sort(sortedProps); - String properties = String.format("%-26s ", "Node"); - for (String s : sortedProps) { - properties = properties.concat(String.format("%-18s ", s)); - } - System.out.println(properties); - for (Node node : nodes) { - String nodeProp = String.format("%-26s ", node); - Map propList = sm.getNodeProps(node); - for (String s : sortedProps) { - if (propList.containsKey(s)) { - nodeProp = nodeProp.concat(String.format("%-18s ", propList.get(s).getStringValue())); - } else { - nodeProp = nodeProp.concat(String.format("%-18s ", "null")); - } - } - System.out.println(nodeProp); - } - System.out.println("Total number of Nodes: " + nodes.size()); - } - - @Descriptor("Retrieves the node connectors information present in Switch Manager DB for the specified node") - public void showNodeConnectors(@Descriptor("Container in which to query Switch Manager") String container, - @Descriptor("String representation of the Node, this need to be consumable from Node.fromString()") String node) { - final String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - final ISwitchManager sm = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this); - - if (sm == null) { - System.out.println("Cannot find the switch manager instance on container: " + containerName); - return; - } - - Node target = Node.fromString(node); - if (target == null) { - System.out.println("Please enter a valid node id"); - return; - } - - Set nodeConnectorSet = sm.getNodeConnectors(target); - if (nodeConnectorSet == null || nodeConnectorSet.isEmpty()) { - return; - } - - Set propertyList = new HashSet(); - for (NodeConnector nodeConnector : nodeConnectorSet) { - Map propList = sm.getNodeConnectorProps(nodeConnector); - propertyList.addAll(propList.keySet()); - } - List sortedProps = new ArrayList(propertyList); - Collections.sort(sortedProps); - String properties = String.format("%-33s ", "NodeConnector"); - for (String s : sortedProps) { - properties = properties.concat(String.format("%-18s ", s)); - } - System.out.println(properties); - for (NodeConnector nodeConnector : nodeConnectorSet) { - String ncProp = String.format("%-33s ", nodeConnector); - Map ncProperties = sm.getNodeConnectorProps(nodeConnector); - for (String s : sortedProps) { - if (ncProperties.containsKey(s)) { - ncProp = ncProp.concat(String.format("%-18s ", ncProperties.get(s).getStringValue())); - } else { - ncProp = ncProp.concat(String.format("%-18s ", "null")); - } - } - System.out.println(ncProp); - } - System.out.println("Total number of NodeConnectors: " + nodeConnectorSet.size()); - } -} diff --git a/opendaylight/adsal/switchmanager/implementation/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerTest.java b/opendaylight/adsal/switchmanager/implementation/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerTest.java deleted file mode 100644 index e7dac9c143..0000000000 --- a/opendaylight/adsal/switchmanager/implementation/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerTest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.internal; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Latency; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.switchmanager.SubnetConfig; - -public class SwitchManagerTest { - - @Test - public void testSwitchManagerAddRemoveSubnet() throws ConstructionException { - SwitchManager switchmgr = new SwitchManager(); - switchmgr.startUp(); - - // Create the node connector string list - Node node1 = new Node(Node.NodeIDType.OPENFLOW, 1L); - Node node2 = new Node(Node.NodeIDType.OPENFLOW, 2L); - NodeConnector nc1 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)1, node1); - NodeConnector nc2 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)2, node2); - NodeConnector nc3 = new NodeConnector(NodeConnector.NodeConnectorIDType.OPENFLOW, (short)3, node1); - List portList = new ArrayList(); - portList.add(nc1.toString()); - portList.add(nc2.toString()); - portList.add(nc3.toString()); - - - SubnetConfig subnet = new SubnetConfig("subnet", "10.0.0.254/16", portList); - Status addResult = (switchmgr.addSubnet(subnet)); - Assert.assertTrue(addResult.isSuccess()); - - Status removeResult = (switchmgr.removeSubnet(subnet.getName())); - Assert.assertTrue(removeResult.isSuccess()); - - SubnetConfig subnetConfigResult = switchmgr.getSubnetConfig(subnet.getName()); - Assert.assertNull(subnetConfigResult); - - subnet = new SubnetConfig("hr", "0.0.0.0", portList); - Status status = switchmgr.addSubnet(subnet); - Assert.assertFalse(status.isSuccess()); - - subnet = new SubnetConfig("hr", "12.12.12.254/16", null); - status = switchmgr.addSubnet(subnet); - Assert.assertTrue(status.isSuccess()); - - } - - @Test - public void testSwitchManagerAddRemovePortsToSubnet() { - SwitchManager switchmgr = new SwitchManager(); - switchmgr.startUp(); - - List portList = new ArrayList(); - portList.add("OF|1@OF|1"); - portList.add("OF|2@OF|00:00:00:00:00:00:00:02"); - portList.add("OF|3@OF|00:00:00:00:00:00:00:01"); - - SubnetConfig subnet = new SubnetConfig("eng", "11.1.1.254/16", portList); - Status status = (switchmgr.addSubnet(subnet)); - Assert.assertTrue(status.isSuccess()); - - - // Empty port set - List badPortSet = new ArrayList(); - status = switchmgr.addPortsToSubnet("eng", badPortSet); - Assert.assertFalse(status.isSuccess()); - - // Non existant subnet - status = switchmgr.removePortsFromSubnet("hr", badPortSet); - Assert.assertFalse(status.isSuccess()); - - // Port set containing non conventional but parsable port - badPortSet.add("1/1"); - status = switchmgr.addPortsToSubnet("eng", badPortSet); - Assert.assertTrue(status.isSuccess()); - - // Port set containing non parsable port - badPortSet.add("OF1/1"); - status = switchmgr.addPortsToSubnet("eng", badPortSet); - Assert.assertTrue(status.isSuccess()); - } - - @Test - public void testSwitchManagerNodeConnectors() { - SwitchManager switchmgr = new SwitchManager(); - switchmgr.startUp(); - - State state; - Bandwidth bw; - Latency l; - - NodeConnector[] headnc = new NodeConnector[5]; - NodeConnector[] tailnc = new NodeConnector[5]; - - Set props = new HashSet(); - state = new State(State.EDGE_UP); - bw = new Bandwidth(Bandwidth.BW100Gbps); - l = new Latency(Latency.LATENCY100ns); - props.add(state); - props.add(bw); - props.add(l); - - for (short i = 1; i < 6; i = (short) (i + 1)) { - - headnc[i - 1] = NodeConnectorCreator.createOFNodeConnector(i, - NodeCreator.createOFNode((long) i)); - tailnc[i - 1] = NodeConnectorCreator - .createOFNodeConnector((short) (i + 10), - NodeCreator.createOFNode((long) (i + 10))); - switchmgr.updateNode(headnc[i - 1].getNode(), UpdateType.ADDED, - props); - switchmgr.updateNode(tailnc[i - 1].getNode(), UpdateType.ADDED, - props); - - Assert.assertFalse(switchmgr.doesNodeConnectorExist(headnc[i - 1])); - switchmgr.updateNodeConnector(headnc[i - 1], UpdateType.ADDED, - props); - Assert.assertTrue(switchmgr.doesNodeConnectorExist(headnc[i - 1])); - - Assert.assertFalse(switchmgr.doesNodeConnectorExist(tailnc[i - 1])); - switchmgr.updateNodeConnector(tailnc[i - 1], UpdateType.ADDED, - props); - Assert.assertTrue(switchmgr.doesNodeConnectorExist(tailnc[i - 1])); - } - - for (int i = 0; i < 5; i++) { - Property bwProp = switchmgr.getNodeConnectorProp(headnc[i], - Bandwidth.BandwidthPropName); - Assert.assertTrue(bwProp.equals(bw)); - Property latencyProp = switchmgr.getNodeConnectorProp(tailnc[i], - Latency.LatencyPropName); - Assert.assertEquals(latencyProp, l); - } - - Set nodes = switchmgr.getNodes(); - for (int i = 0; i < 5; i++) { - if (nodes.contains(headnc[i].getNode()) == true) { - nodes.remove(headnc[i].getNode()); - } - - if (nodes.contains(tailnc[i].getNode()) == true) { - nodes.remove(tailnc[i].getNode()); - } - - } - Assert.assertTrue(nodes.isEmpty()); - } - -} diff --git a/opendaylight/adsal/switchmanager/integrationtest/pom.xml b/opendaylight/adsal/switchmanager/integrationtest/pom.xml deleted file mode 100644 index bfaf52c8a8..0000000000 --- a/opendaylight/adsal/switchmanager/integrationtest/pom.xml +++ /dev/null @@ -1,150 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.integrationtest - 0.7.0-SNAPSHOT - ../../commons/integrationtest - - - switchmanager.integrationtest - 0.6.0-SNAPSHOT - - ../../implementation/target/jacoco-it.exec - - ../../implementation/target/jacoco.exec - - - - - ch.qos.logback - logback-classic - - - ch.qos.logback - logback-core - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - clustering.stub - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - configuration.implementation - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.it.implementation - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - hosttracker.implementation - - - org.opendaylight.controller - protocol_plugins.stub - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.implementation - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - switchmanager.implementation - - - org.opendaylight.controller - topologymanager - - - org.slf4j - log4j-over-slf4j - - - - org.ops4j.pax.exam - pax-exam-container-native - test - - - org.ops4j.pax.exam - pax-exam-junit4 - test - - - org.ops4j.pax.exam - pax-exam-link-mvn - test - - - org.ops4j.pax.url - pax-url-aether - test - - - - - - - org.jacoco - jacoco-maven-plugin - - ../../implementation/target/jacoco-it.exec - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - true - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - - diff --git a/opendaylight/adsal/switchmanager/integrationtest/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerIT.java b/opendaylight/adsal/switchmanager/integrationtest/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerIT.java deleted file mode 100644 index 3963abf265..0000000000 --- a/opendaylight/adsal/switchmanager/integrationtest/src/test/java/org/opendaylight/controller/switchmanager/internal/SwitchManagerIT.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.switchmanager.internal; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; -import static org.ops4j.pax.exam.CoreOptions.options; -import static org.ops4j.pax.exam.CoreOptions.systemPackages; -import static org.ops4j.pax.exam.CoreOptions.systemProperty; - -import java.net.UnknownHostException; -import java.util.Map; - -import javax.inject.Inject; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.sal.core.Actions; -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.Buffers; -import org.opendaylight.controller.sal.core.Capabilities; -import org.opendaylight.controller.sal.core.Capabilities.CapabilitiesType; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.TimeStamp; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.util.PathUtils; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(PaxExam.class) -public class SwitchManagerIT { - private final Logger log = LoggerFactory.getLogger(SwitchManagerIT.class); - // get the OSGI bundle context - @Inject - private BundleContext bc; - - private ISwitchManager switchManager = null; - - // Configure the OSGi container - @Configuration - public Option[] config() { - return options( - systemProperty("logback.configurationFile").value( - "file:" + PathUtils.getBaseDir() - + "/src/test/resources/logback.xml"), - // To start OSGi console for inspection remotely - systemProperty("osgi.console").value("2401"), - // Set the systemPackages (used by clustering) - systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"), - // List framework bundles - mavenBundle("equinoxSDK381", "org.eclipse.equinox.console").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.util").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.osgi.services").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell").versionAsInProject(), - // List logger bundles - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), - mavenBundle("org.slf4j", "log4j-over-slf4j") - .versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-core") - .versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-classic") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "clustering.stub") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "configuration") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "configuration.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "containermanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "containermanager.it.implementation").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "clustering.services").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "protocol_plugins.stub").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "switchmanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "topologymanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "hosttracker").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "forwardingrulesmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", "statisticsmanager").versionAsInProject(), - mavenBundle("org.opendaylight.controller", - "switchmanager.implementation").versionAsInProject(), - mavenBundle("org.jboss.spec.javax.transaction", - "jboss-transaction-api_1.1_spec").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3") - .versionAsInProject(), - mavenBundle("org.apache.felix", - "org.apache.felix.dependencymanager") - .versionAsInProject(), junitBundles()); - } - - private String stateToString(int state) { - switch (state) { - case Bundle.ACTIVE: - return "ACTIVE"; - case Bundle.INSTALLED: - return "INSTALLED"; - case Bundle.RESOLVED: - return "RESOLVED"; - case Bundle.UNINSTALLED: - return "UNINSTALLED"; - default: - return "Not CONVERTED"; - } - } - - @Before - public void areWeReady() { - assertNotNull(bc); - boolean debugit = false; - Bundle b[] = bc.getBundles(); - for (int i = 0; i < b.length; i++) { - int state = b[i].getState(); - if (state != Bundle.ACTIVE && state != Bundle.RESOLVED) { - log.debug("Bundle:" + b[i].getSymbolicName() + " state:" - + stateToString(state)); - debugit = true; - } - } - if (debugit) { - log.debug("Do some debugging because some bundle is " - + "unresolved"); - } - - // Assert if true, if false we are good to go! - assertFalse(debugit); - - // Now lets create a hosttracker for testing purpose - ServiceReference s = bc.getServiceReference(ISwitchManager.class - .getName()); - if (s != null) { - this.switchManager = (ISwitchManager) bc.getService(s); - } - - // If StatisticsManager is null, cannot run tests. - assertNotNull(this.switchManager); - } - - @Test - public void testNodeProp() throws UnknownHostException { - assertNotNull(this.switchManager); - - Node node; - try { - node = new Node("STUB", new Integer(0xCAFE)); - } catch (ConstructionException e) { - // test failed if node cannot be created. - node = null; - Assert.assertTrue(false); - } - Map propMap = this.switchManager.getNodeProps(node); - Assert.assertFalse(propMap.isEmpty()); - - Assert.assertTrue(this.switchManager.getNodeProp(node, - Capabilities.CapabilitiesPropName).equals( - new Capabilities(3))); - Assert.assertTrue(this.switchManager.getNodeProp(node, - Actions.ActionsPropName).equals(new Actions(2))); - Assert.assertTrue(this.switchManager.getNodeProp(node, - Buffers.BuffersPropName).equals(new Buffers(1))); - Assert.assertTrue(this.switchManager.getNodeProp(node, - TimeStamp.TimeStampPropName).equals( - new TimeStamp(100000L, "connectedSince"))); - } - - @Test - public void testNodeConnectorProp() throws UnknownHostException { - assertNotNull(this.switchManager); - Node node; - NodeConnector nc; - try { - node = new Node("STUB", 0xCAFE); - nc = new NodeConnector("STUB", 0xCAFE, node); - } catch (ConstructionException e) { - node = null; - nc = null; - Assert.assertTrue(false); - } - Map propMap = this.switchManager - .getNodeConnectorProps(nc); - Assert.assertFalse(propMap.isEmpty()); - - Assert.assertTrue(this.switchManager.getNodeConnectorProp(nc, - Capabilities.CapabilitiesPropName).equals( - new Capabilities(CapabilitiesType.FLOW_STATS_CAPABILITY - .getValue()))); - Assert.assertTrue(this.switchManager.getNodeConnectorProp(nc, - Bandwidth.BandwidthPropName).equals( - new Bandwidth(Bandwidth.BW1Gbps))); - Assert.assertTrue(this.switchManager.getNodeConnectorProp(nc, - State.StatePropName).equals(new State(State.EDGE_UP))); - } -} diff --git a/opendaylight/adsal/switchmanager/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/switchmanager/integrationtest/src/test/resources/logback.xml deleted file mode 100644 index 2d63ce5744..0000000000 --- a/opendaylight/adsal/switchmanager/integrationtest/src/test/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/opendaylight/adsal/topologymanager/implementation/pom.xml b/opendaylight/adsal/topologymanager/implementation/pom.xml deleted file mode 100644 index 9a056df439..0000000000 --- a/opendaylight/adsal/topologymanager/implementation/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - topologymanager - 0.6.0-SNAPSHOT - bundle - - - equinoxSDK381 - org.eclipse.osgi - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - junit - junit - test - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.topologymanager - javax.xml.bind.annotation, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.topology, - org.opendaylight.controller.configuration, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.switchmanager, - org.osgi.service.component, - org.slf4j, - org.apache.felix.dm, - org.apache.commons.lang3.builder, - org.apache.commons.lang3.tuple, - org.eclipse.osgi.framework.console, - org.osgi.framework - org.opendaylight.controller.topologymanager.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManager.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManager.java deleted file mode 100644 index 1f377593bb..0000000000 --- a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManager.java +++ /dev/null @@ -1,125 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topologymanager; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Host; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.utils.Status; - -/** - * The Interface provides methods to interact with network topology database. - */ -public interface ITopologyManager { - /** - * Query to determine if the specified NodeConnector is connected - * to another Node or is a leaf for the network - * @param p The node connector - * @return true if the NodeConnector is connected to another - * switch false otherwise - */ - public boolean isInternal(NodeConnector p); - - /** - * Retrieves a map of all known link connections between nodes - * including their properties - * @return the map as specified - */ - public Map> getEdges(); - - /** - * Returns an unmodifiable map indexed by the Node and reporting - * all the edges getting out/in from/to the Node - * @return the map as specified - */ - public Map> getNodeEdges(); - - /** - * Add or Update an Host port in the topology manager DB - * - * @param p NodeConnector to which an host is connected - * @param h the Host connected to the NodeConnector - * @param t type of update if Add/Delete/Update - */ - public void updateHostLink(NodeConnector p, Host h, UpdateType t, - Set props); - - /** - * Return a set of NodeConnector that have hosts attached to them - * - * @return A set with all the NodeConnectors known to have an host - * attached - */ - public Set getNodeConnectorWithHost(); - - /** - * Return the Host attached to a NodeConnector with Host. - * Multiple hosts maybe attached to a node connector. - * This method returns the first one only. Hence it has been - * deprecated. Use the new method getHostsAttachedToNodeConnector - * that returns the complete list of hosts. - * @return The Host attached to a NodeConnector - */ - @Deprecated - public Host getHostAttachedToNodeConnector(NodeConnector p); - - /** - * Returns a list of hosts attached to a NodeConnector - * @param p NodeConnector - * @return The list of hosts attached to a NodeConnector - */ - public List getHostsAttachedToNodeConnector(NodeConnector p); - - /** - * Returns a copy map which associates every node with all the - * NodeConnectors of the node that have an Host attached to it - * - * @return A map of all the Nodes with NodeConnectors - */ - public Map> getNodesWithNodeConnectorHost(); - - /** - * Adds user configured link - * - * @param link User configured link - * @return "Success" or error reason - */ - public Status addUserLink(TopologyUserLinkConfig link); - - /** - * Deletes user configured link - * - * @param linkName The name of the user configured link - * @return "Success" or error reason - */ - public Status deleteUserLink(String linkName); - - /** - * Saves user configured links into config file - * - * @return "Success" or error reason - */ - public Status saveConfig(); - - /** - * Gets all the user configured links - * - * @return The map of the user configured links - */ - public ConcurrentMap getUserLinks(); -} diff --git a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerAware.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerAware.java deleted file mode 100644 index a79da60f66..0000000000 --- a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerAware.java +++ /dev/null @@ -1,20 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topologymanager; - -import org.opendaylight.controller.sal.topology.IListenTopoUpdates; - -/** - * Interface for all the listener of topology updates created by - * Topology Manager, effectively speaking the updates are an extension - * of the IListenTopoUpdates coming from SAL. - */ -public interface ITopologyManagerAware extends IListenTopoUpdates { -} diff --git a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerClusterWideAware.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerClusterWideAware.java deleted file mode 100644 index aa47b5fa95..0000000000 --- a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerClusterWideAware.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.topologymanager; - -public interface ITopologyManagerClusterWideAware extends ITopologyManagerAware { -} diff --git a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java deleted file mode 100644 index 22bd9c0512..0000000000 --- a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java +++ /dev/null @@ -1,17 +0,0 @@ -/** -* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. -* -* This program and the accompanying materials are made available under the -* terms of the Eclipse Public License v1.0 which accompanies this distribution, -* and is available at http://www.eclipse.org/legal/epl-v10.html -*/ -package org.opendaylight.controller.topologymanager; - -import java.util.List; - -public interface ITopologyManagerShell { - public List printUserLink(); - public List addUserLink(String name, String ncStr1, String ncStr2); - public List deleteUserLinkShell(String name); - public List printNodeEdges(); -} diff --git a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/TopologyUserLinkConfig.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/TopologyUserLinkConfig.java deleted file mode 100644 index 3532ab78e0..0000000000 --- a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/TopologyUserLinkConfig.java +++ /dev/null @@ -1,187 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topologymanager; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The Interface provides methods to manipulate user configured link. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class TopologyUserLinkConfig extends ConfigurationObject implements Serializable { - private static final long serialVersionUID = 1L; - private static final Logger logger = LoggerFactory.getLogger(TopologyUserLinkConfig.class); - - public enum STATUS { - SUCCESS("Success"), LINKDOWN("Link Down"), INCORRECT( - "Incorrect Connection"); - private STATUS(String name) { - this.name = name; - } - - private String name; - - @Override - public String toString() { - return name; - } - - public static STATUS fromString(String str) { - if (str == null) { - return LINKDOWN; - } - if (str.equals(SUCCESS.toString())) { - return SUCCESS; - } - if (str.equals(LINKDOWN.toString())) { - return LINKDOWN; - } - if (str.equals(INCORRECT.toString())) { - return INCORRECT; - } - return LINKDOWN; - } - } - - @XmlElement - private String status; - @XmlElement - private String name; - @XmlElement - private String srcNodeConnector; - @XmlElement - private String dstNodeConnector; - - public TopologyUserLinkConfig() { - super(); - status = STATUS.LINKDOWN.toString(); - } - - public TopologyUserLinkConfig(String name, String srcNodeConnector, String dstNodeConnector) { - super(); - this.name = name; - this.srcNodeConnector = srcNodeConnector; - this.dstNodeConnector = dstNodeConnector; - } - - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - public STATUS getStatus() { - return STATUS.fromString(status); - } - - public void setStatus(STATUS s) { - this.status = s.toString(); - } - - public String getSrcNodeConnector() { - return srcNodeConnector; - } - - public void setSrcNodeConnector(String srcNodeConnector) { - this.srcNodeConnector = srcNodeConnector; - } - - public String getDstNodeConnector() { - return dstNodeConnector; - } - - public void setDstNodeConnector(String dstNodeConnector) { - this.dstNodeConnector = dstNodeConnector; - } - - public boolean isValidNodeConnector(String nodeConnectorStr) { - return (NodeConnector.fromString(nodeConnectorStr) != null); - } - - public boolean isValid() { - if (!isValidResourceName(name)) { - logger.debug("Invalid name in user link: {}", name); - return false; - } - - if (!isValidNodeConnector(srcNodeConnector) || - !isValidNodeConnector(dstNodeConnector)) { - logger.debug("Invalid NodeConnector in user link: {}", name); - return false; - } - - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime - * result - + ((dstNodeConnector == null) ? 0 : dstNodeConnector.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime - * result - + ((srcNodeConnector == null) ? 0 : srcNodeConnector.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - TopologyUserLinkConfig other = (TopologyUserLinkConfig) obj; - if (dstNodeConnector == null) { - if (other.dstNodeConnector != null) { - return false; - } - } else if (!dstNodeConnector.equals(other.dstNodeConnector)) { - return false; - } - if (srcNodeConnector == null) { - if (other.srcNodeConnector != null) { - return false; - } - } else if (!srcNodeConnector.equals(other.srcNodeConnector)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "TopologyUserLinkConfig [status=" + status + ", name=" + name - + ", srcNodeConnector=" + srcNodeConnector - + ", dstNodeConnector=" + dstNodeConnector + "]"; - } -} diff --git a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java deleted file mode 100644 index 8c422a52ea..0000000000 --- a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topologymanager.internal; - -import java.util.Dictionary; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.Set; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.sal.topology.IListenTopoUpdates; -import org.opendaylight.controller.sal.topology.ITopologyService; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.opendaylight.controller.topologymanager.ITopologyManagerAware; -import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware; -import org.opendaylight.controller.topologymanager.ITopologyManagerShell; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - Object[] res = { TopologyManagerImpl.class }; - return res; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - if (imp.equals(TopologyManagerImpl.class)) { - // export the service needed to listen to topology updates - Dictionary> props = new Hashtable>(); - Set propSet = new HashSet(); - propSet.add(TopologyManagerImpl.TOPOEDGESDB); - props.put("cachenames", propSet); - - c.setInterface(new String[] { IListenTopoUpdates.class.getName(), - IInventoryListener.class.getName(), - ITopologyManager.class.getName(), - ITopologyManagerShell.class.getName(), - IConfigurationContainerAware.class.getName(), - ICacheUpdateAware.class.getName() }, props); - - c.add(createContainerServiceDependency(containerName).setService( - ITopologyService.class).setCallbacks("setTopoService", - "unsetTopoService").setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - ISwitchManager.class).setCallbacks("setSwitchManager", - "unsetSwitchManager").setRequired(true)); - - // These are all the listeners for a topology manager - // updates, there could be many or none - c.add(createContainerServiceDependency(containerName).setService( - ITopologyManagerAware.class).setCallbacks( - "setTopologyManagerAware", "unsetTopologyManagerAware") - .setRequired(false)); - - // These are all the listeners for a topology manager for the - // cluster wide events - // updates, there could be many or none - c.add(createContainerServiceDependency(containerName).setService(ITopologyManagerClusterWideAware.class) - .setCallbacks("setTopologyManagerClusterWideAware", "unsetTopologyManagerClusterWideAware") - .setRequired(false)); - - c.add(createContainerServiceDependency(containerName).setService( - IClusterContainerServices.class).setCallbacks( - "setClusterContainerService", - "unsetClusterContainerService").setRequired(true)); - - c.add(createContainerServiceDependency(containerName).setService( - IConfigurationContainerService.class).setCallbacks( - "setConfigurationContainerService", - "unsetConfigurationContainerService").setRequired(true)); - } - } -} diff --git a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java b/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java deleted file mode 100644 index e1a0ca1e76..0000000000 --- a/opendaylight/adsal/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java +++ /dev/null @@ -1,1309 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topologymanager.internal; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.felix.dm.Component; -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.ICacheUpdateAware; -import org.opendaylight.controller.clustering.services.IClusterContainerServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.configuration.IConfigurationContainerAware; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Host; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.TimeStamp; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.topology.IListenTopoUpdates; -import org.opendaylight.controller.sal.topology.ITopologyService; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; -import org.opendaylight.controller.sal.utils.IObjectReader; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.switchmanager.IInventoryListener; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.topologymanager.ITopologyManager; -import org.opendaylight.controller.topologymanager.ITopologyManagerAware; -import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware; -import org.opendaylight.controller.topologymanager.ITopologyManagerShell; -import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.util.ArrayList; -import java.util.Dictionary; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.LinkedBlockingQueue; - -/** - * The class describes TopologyManager which is the central repository of the - * network topology. It provides service for applications to interact with - * topology database and notifies all the listeners of topology changes. - */ -public class TopologyManagerImpl implements - ICacheUpdateAware, - ITopologyManager, - ITopologyManagerShell, - IConfigurationContainerAware, - IListenTopoUpdates, - IObjectReader, - IInventoryListener, - CommandProvider { - protected static final String TOPOEDGESDB = "topologymanager.edgesDB"; - protected static final String TOPOHOSTSDB = "topologymanager.hostsDB"; - protected static final String TOPONODECONNECTORDB = "topologymanager.nodeConnectorDB"; - protected static final String TOPOUSERLINKSDB = "topologymanager.userLinksDB"; - private static final String USER_LINKS_FILE_NAME = "userTopology.conf"; - private static final Logger log = LoggerFactory.getLogger(TopologyManagerImpl.class); - private static final long PENDING_UPDATE_TIMEOUT = 5000L; - - private ITopologyService topoService; - private IClusterContainerServices clusterContainerService; - private IConfigurationContainerService configurationService; - private ISwitchManager switchManager; - // DB of all the Edges with properties which constitute our topology - private ConcurrentMap> edgesDB; - // DB of all NodeConnector which are part of ISL Edges, meaning they - // are connected to another NodeConnector on the other side of an ISL link. - // NodeConnector of a Production Edge is not part of this DB. - private ConcurrentMap> nodeConnectorsDB; - // DB of all the NodeConnectors with an Host attached to it - private ConcurrentMap>>> hostsDB; - // Topology Manager Aware listeners - private Set topologyManagerAware = new CopyOnWriteArraySet(); - // Topology Manager Aware listeners - for clusterwide updates - private Set topologyManagerClusterWideAware = - new CopyOnWriteArraySet(); - private ConcurrentMap userLinksDB; - private BlockingQueue notifyQ = new LinkedBlockingQueue(); - private volatile Boolean shuttingDown = false; - private Thread notifyThread; - private final Map> pendingUpdates = - new HashMap>(); - private final BlockingQueue updateQ = - new LinkedBlockingQueue(); - private Timer pendingTimer; - private Thread updateThread; - - private class PendingEdgeUpdate extends TopoEdgeUpdate { - private PendingEdgeUpdate(Edge e, Set p, UpdateType t) { - super(e, p, t); - } - } - - private class UpdateTopology implements Runnable { - @Override - public void run() { - log.trace("Start topology update thread"); - - while (!shuttingDown) { - try { - List list = new ArrayList(); - TopoEdgeUpdate teu = updateQ.take(); - for (; teu != null; teu = updateQ.poll()) { - list.add(teu); - } - - if (!list.isEmpty()) { - log.trace("Update edges: {}", list); - doEdgeUpdate(list); - } - } catch (InterruptedException e) { - if (shuttingDown) { - break; - } - log.warn("Topology update thread interrupted", e); - } catch (Exception e) { - log.error("Exception on topology update thread", e); - } - } - - log.trace("Exit topology update thread"); - } - } - - private class PendingUpdateTask extends TimerTask { - private final Edge edge; - private final Set props; - private final UpdateType type; - - private PendingUpdateTask(Edge e, Set p, UpdateType t) { - edge = e; - props = p; - type = t; - } - - private NodeConnector getHeadNodeConnector() { - return edge.getHeadNodeConnector(); - } - - private void flush() { - log.info("Flush pending topology update: edge {}, type {}", - edge, type); - updateQ.add(new PendingEdgeUpdate(edge, props, type)); - } - - @Override - public void run() { - if (removePendingEvent(this)) { - log.warn("Pending topology update timed out: edge{}, type {}", - edge, type); - } - } - } - - void nonClusterObjectCreate() { - edgesDB = new ConcurrentHashMap>(); - hostsDB = new ConcurrentHashMap>>>(); - nodeConnectorsDB = new ConcurrentHashMap>(); - userLinksDB = new ConcurrentHashMap(); - } - - void setTopologyManagerAware(ITopologyManagerAware s) { - if (this.topologyManagerAware != null) { - log.debug("Adding ITopologyManagerAware: {}", s); - this.topologyManagerAware.add(s); - } - } - - void unsetTopologyManagerAware(ITopologyManagerAware s) { - if (this.topologyManagerAware != null) { - log.debug("Removing ITopologyManagerAware: {}", s); - this.topologyManagerAware.remove(s); - } - } - - void setTopologyManagerClusterWideAware(ITopologyManagerClusterWideAware s) { - if (this.topologyManagerClusterWideAware != null) { - log.debug("Adding ITopologyManagerClusterWideAware: {}", s); - this.topologyManagerClusterWideAware.add(s); - } - } - - void unsetTopologyManagerClusterWideAware(ITopologyManagerClusterWideAware s) { - if (this.topologyManagerClusterWideAware != null) { - log.debug("Removing ITopologyManagerClusterWideAware: {}", s); - this.topologyManagerClusterWideAware.remove(s); - } - } - - void setTopoService(ITopologyService s) { - log.debug("Adding ITopologyService: {}", s); - this.topoService = s; - } - - void unsetTopoService(ITopologyService s) { - if (this.topoService == s) { - log.debug("Removing ITopologyService: {}", s); - this.topoService = null; - } - } - - void setClusterContainerService(IClusterContainerServices s) { - log.debug("Cluster Service set"); - this.clusterContainerService = s; - } - - void unsetClusterContainerService(IClusterContainerServices s) { - if (this.clusterContainerService == s) { - log.debug("Cluster Service removed!"); - this.clusterContainerService = null; - } - } - - public void setConfigurationContainerService(IConfigurationContainerService service) { - log.trace("Got configuration service set request {}", service); - this.configurationService = service; - } - - public void unsetConfigurationContainerService(IConfigurationContainerService service) { - log.trace("Got configuration service UNset request"); - this.configurationService = null; - } - - void setSwitchManager(ISwitchManager s) { - log.debug("Adding ISwitchManager: {}", s); - this.switchManager = s; - } - - void unsetSwitchManager(ISwitchManager s) { - if (this.switchManager == s) { - log.debug("Removing ISwitchManager: {}", s); - this.switchManager = null; - } - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init(Component c) { - allocateCaches(); - retrieveCaches(); - String containerName = null; - Dictionary props = c.getServiceProperties(); - if (props != null) { - containerName = (String) props.get("containerName"); - } else { - // In the Global instance case the containerName is empty - containerName = "UNKNOWN"; - } - - registerWithOSGIConsole(); - loadConfiguration(); - - // Restore the shuttingDown status on init of the component - shuttingDown = false; - notifyThread = new Thread(new TopologyNotify(notifyQ)); - pendingTimer = new Timer("Topology Pending Update Timer"); - updateThread = new Thread(new UpdateTopology(), "Topology Update"); - } - - @SuppressWarnings({ "unchecked" }) - private void allocateCaches() { - this.edgesDB = - (ConcurrentMap>) allocateCache(TOPOEDGESDB,EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - this.hostsDB = - (ConcurrentMap>>>) allocateCache(TOPOHOSTSDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - this.nodeConnectorsDB = - (ConcurrentMap>) allocateCache( - TOPONODECONNECTORDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - this.userLinksDB = - (ConcurrentMap) allocateCache( - TOPOUSERLINKSDB, EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } - - private ConcurrentMap allocateCache(String cacheName, Set cacheModes) { - ConcurrentMap cache = null; - try { - cache = this.clusterContainerService.createCache(cacheName, cacheModes); - } catch (CacheExistException e) { - log.debug(cacheName + " cache already exists - destroy and recreate if needed"); - } catch (CacheConfigException e) { - log.error(cacheName + " cache configuration invalid - check cache mode"); - } - return cache; - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - if (this.clusterContainerService == null) { - log.error("Cluster Services is null, can't retrieve caches."); - return; - } - - this.edgesDB = (ConcurrentMap>) this.clusterContainerService.getCache(TOPOEDGESDB); - if (edgesDB == null) { - log.error("Failed to get cache for " + TOPOEDGESDB); - } - - this.hostsDB = - (ConcurrentMap>>>) this.clusterContainerService.getCache(TOPOHOSTSDB); - if (hostsDB == null) { - log.error("Failed to get cache for " + TOPOHOSTSDB); - } - - this.nodeConnectorsDB = - (ConcurrentMap>) this.clusterContainerService.getCache(TOPONODECONNECTORDB); - if (nodeConnectorsDB == null) { - log.error("Failed to get cache for " + TOPONODECONNECTORDB); - } - - this.userLinksDB = - (ConcurrentMap) this.clusterContainerService.getCache(TOPOUSERLINKSDB); - if (userLinksDB == null) { - log.error("Failed to get cache for " + TOPOUSERLINKSDB); - } - } - - /** - * Function called after the topology manager has registered the service in - * OSGi service registry. - * - */ - void started() { - updateThread.start(); - - // Start the batcher thread for the cluster wide topology updates - notifyThread.start(); - // SollicitRefresh MUST be called here else if called at init - // time it may sollicit refresh too soon. - log.debug("Sollicit topology refresh"); - topoService.sollicitRefresh(); - } - - void stop() { - shuttingDown = true; - updateThread.interrupt(); - notifyThread.interrupt(); - pendingTimer.cancel(); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - updateQ.clear(); - updateThread = null; - pendingTimer = null; - notifyQ.clear(); - notifyThread = null; - } - - private void loadConfiguration() { - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, USER_LINKS_FILE_NAME)) { - addUserLink((TopologyUserLinkConfig) conf); - } - } - - @Override - public Status saveConfig() { - return saveConfigInternal(); - } - - public Status saveConfigInternal() { - Status saveStatus = configurationService.persistConfiguration( - new ArrayList(userLinksDB.values()), USER_LINKS_FILE_NAME); - - if (!saveStatus.isSuccess()) { - return new Status(StatusCode.INTERNALERROR, "Topology save failed: " + saveStatus.getDescription()); - } - return saveStatus; - } - - @Override - public Map> getNodeEdges() { - if (this.edgesDB == null) { - return null; - } - - Map> res = new HashMap>(); - for (Edge edge : this.edgesDB.keySet()) { - // Lets analyze the tail - Node node = edge.getTailNodeConnector().getNode(); - Set nodeEdges = res.get(node); - if (nodeEdges == null) { - nodeEdges = new HashSet(); - res.put(node, nodeEdges); - } - nodeEdges.add(edge); - - // Lets analyze the head - node = edge.getHeadNodeConnector().getNode(); - nodeEdges = res.get(node); - if (nodeEdges == null) { - nodeEdges = new HashSet(); - res.put(node, nodeEdges); - } - nodeEdges.add(edge); - } - - return res; - } - - @Override - public boolean isInternal(NodeConnector p) { - if (this.nodeConnectorsDB == null) { - return false; - } - - // This is an internal NodeConnector if is connected to - // another Node i.e it's part of the nodeConnectorsDB - return (this.nodeConnectorsDB.get(p) != null); - } - - /** - * This method returns true if the edge is an ISL link. - * - * @param e - * The edge - * @return true if it is an ISL link - */ - public boolean isISLink(Edge e) { - return (!isProductionLink(e)); - } - - /** - * This method returns true if the edge is a production link. - * - * @param e - * The edge - * @return true if it is a production link - */ - public boolean isProductionLink(Edge e) { - return (e.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION) - || e.getTailNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)); - } - - /** - * This method cross checks the determination of nodeConnector type by Discovery Service - * against the information in SwitchManager and updates it accordingly. - * @param e - * The edge - */ - private void crossCheckNodeConnectors(Edge e) { - NodeConnector nc; - if (e.getHeadNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) { - nc = updateNCTypeFromSwitchMgr(e.getHeadNodeConnector()); - if (nc != null) { - e.setHeadNodeConnector(nc); - } - } - if (e.getTailNodeConnector().getType().equals(NodeConnector.NodeConnectorIDType.PRODUCTION)) { - nc = updateNCTypeFromSwitchMgr(e.getTailNodeConnector()); - if (nc != null) { - e.setTailNodeConnector(nc); - } - } - } - - /** - * A NodeConnector may have been categorized as of type Production by Discovery Service. - * But at the time when this determination was made, only OF nodes were known to Discovery - * Service. This method checks if the node of nodeConnector is known to SwitchManager. If - * so, then it returns a new NodeConnector with correct type. - * - * @param nc - * NodeConnector as passed on in the edge - * @return - * If Node of the NodeConnector is in SwitchManager, then return a new NodeConnector - * with correct type, null otherwise - */ - - private NodeConnector updateNCTypeFromSwitchMgr(NodeConnector nc) { - - for (Node node : switchManager.getNodes()) { - String nodeName = node.getNodeIDString(); - log.trace("Switch Manager Node Name: {}, NodeConnector Node Name: {}", nodeName, - nc.getNode().getNodeIDString()); - if (nodeName.equals(nc.getNode().getNodeIDString())) { - NodeConnector nodeConnector = NodeConnectorCreator - .createNodeConnector(node.getType(), nc.getID(), node); - return nodeConnector; - } - } - return null; - } - - /** - * The Map returned is a copy of the current topology hence if the topology - * changes the copy doesn't - * - * @return A Map representing the current topology expressed as edges of the - * network - */ - @Override - public Map> getEdges() { - if (this.edgesDB == null) { - return null; - } - - Map> edgeMap = new HashMap>(); - Set props; - for (Map.Entry> edgeEntry : edgesDB.entrySet()) { - // Sets of props are copied because the composition of - // those properties could change with time - props = new HashSet(edgeEntry.getValue()); - // We can simply reuse the key because the object is - // immutable so doesn't really matter that we are - // referencing the only owned by a different table, the - // meaning is the same because doesn't change with time. - edgeMap.put(edgeEntry.getKey(), props); - } - - return edgeMap; - } - - @Override - public Set getNodeConnectorWithHost() { - if (this.hostsDB == null) { - return null; - } - - return (new HashSet(this.hostsDB.keySet())); - } - - @Override - public Map> getNodesWithNodeConnectorHost() { - if (this.hostsDB == null) { - return null; - } - HashMap> res = new HashMap>(); - Node node; - Set portSet; - for (NodeConnector nc : this.hostsDB.keySet()) { - node = nc.getNode(); - portSet = res.get(node); - if (portSet == null) { - // Create the HashSet if null - portSet = new HashSet(); - res.put(node, portSet); - } - - // Keep updating the HashSet, given this is not a - // clustered map we can just update the set without - // worrying to update the hashmap. - portSet.add(nc); - } - - return (res); - } - - @Override - public Host getHostAttachedToNodeConnector(NodeConnector port) { - List hosts = getHostsAttachedToNodeConnector(port); - if(hosts != null && !hosts.isEmpty()){ - return hosts.get(0); - } - return null; - } - - @Override - public List getHostsAttachedToNodeConnector(NodeConnector p) { - Set>> hosts; - if (this.hostsDB == null || (hosts = this.hostsDB.get(p)) == null) { - return null; - } - // create a list of hosts - List retHosts = new LinkedList(); - for(ImmutablePair> host : hosts) { - retHosts.add(host.getLeft()); - } - return retHosts; - } - - @Override - public synchronized void updateHostLink(NodeConnector port, Host h, UpdateType t, Set props) { - - // Clone the property set in case non null else just - // create an empty one. Caches allocated via infinispan - // don't allow null values - if (props == null) { - props = new HashSet(); - } else { - props = new HashSet(props); - } - ImmutablePair> thisHost = new ImmutablePair>(h, props); - - // get the host list - Set>> hostSet = this.hostsDB.get(port); - if(hostSet == null) { - hostSet = new HashSet>>(); - } - switch (t) { - case ADDED: - case CHANGED: - hostSet.add(thisHost); - this.hostsDB.put(port, hostSet); - break; - case REMOVED: - hostSet.remove(thisHost); - if(hostSet.isEmpty()) { - //remove only if hasn't been concurrently modified - this.hostsDB.remove(port, hostSet); - } else { - this.hostsDB.put(port, hostSet); - } - break; - } - } - - private boolean headNodeConnectorExist(Edge e) { - /* - * Only check the head end point which is supposed to be part of a - * network node we control (present in our inventory). If we checked the - * tail end point as well, we would not store the edges that connect to - * a non sdn enable port on a non sdn capable production switch. We want - * to be able to see these switches on the topology. - */ - NodeConnector head = e.getHeadNodeConnector(); - return (switchManager.doesNodeConnectorExist(head)); - } - - private void addPendingEvent(Edge e, Set p, UpdateType t) { - NodeConnector head = e.getHeadNodeConnector(); - PendingUpdateTask task = new PendingUpdateTask(e, p, t); - synchronized (pendingUpdates) { - List list = pendingUpdates.get(head); - if (list == null) { - list = new LinkedList(); - pendingUpdates.put(head, list); - } - list.add(task); - pendingTimer.schedule(task, PENDING_UPDATE_TIMEOUT); - } - } - - private boolean enqueueEventIfPending(Edge e, Set p, UpdateType t) { - NodeConnector head = e.getHeadNodeConnector(); - synchronized (pendingUpdates) { - List list = pendingUpdates.get(head); - if (list != null) { - log.warn("Enqueue edge update: edge {}, type {}", e, t); - PendingUpdateTask task = new PendingUpdateTask(e, p, t); - list.add(task); - pendingTimer.schedule(task, PENDING_UPDATE_TIMEOUT); - return true; - } - } - - return false; - } - - private boolean removePendingEvent(PendingUpdateTask t) { - t.cancel(); - NodeConnector head = t.getHeadNodeConnector(); - boolean removed = false; - - synchronized (pendingUpdates) { - List list = pendingUpdates.get(head); - if (list != null) { - removed = list.remove(t); - if (list.isEmpty()) { - pendingUpdates.remove(head); - } - } - } - - return removed; - } - - private void removePendingEvent(NodeConnector head, boolean doFlush) { - List list; - synchronized (pendingUpdates) { - list = pendingUpdates.remove(head); - } - - if (list != null) { - for (PendingUpdateTask task : list) { - if (task.cancel() && doFlush) { - task.flush(); - } - } - pendingTimer.purge(); - } - } - - private TopoEdgeUpdate edgeUpdate(Edge e, UpdateType type, Set props) { - return edgeUpdate(e, type, props, false); - } - - private TopoEdgeUpdate edgeUpdate(Edge e, UpdateType type, Set props, boolean isPending) { - if (!type.equals(UpdateType.ADDED) && - enqueueEventIfPending(e, props, type)) { - return null; - } - - switch (type) { - case ADDED: - if (this.edgesDB.containsKey(e)) { - // Avoid redundant updates (e.g. cluster switch-over) as notifications trigger expensive tasks - log.trace("Skipping redundant edge addition: {}", e); - return null; - } - - // Ensure that head node connector exists - if (!isPending) { - if (headNodeConnectorExist(e)) { - removePendingEvent(e.getHeadNodeConnector(), true); - } else { - log.warn("Ignore edge that contains invalid node connector: {}", - e); - addPendingEvent(e, props, type); - return null; - } - } - - // Make sure the props are non-null or create a copy - if (props == null) { - props = new HashSet(); - } else { - props = new HashSet(props); - } - - // Check if nodeConnectors of the edge were correctly categorized - // by protocol plugin - crossCheckNodeConnectors(e); - - // Now make sure there is the creation timestamp for the - // edge, if not there, stamp with the first update - boolean found_create = false; - for (Property prop : props) { - if (prop instanceof TimeStamp) { - TimeStamp t = (TimeStamp) prop; - if (t.getTimeStampName().equals("creation")) { - found_create = true; - break; - } - } - } - - if (!found_create) { - TimeStamp t = new TimeStamp(System.currentTimeMillis(), "creation"); - props.add(t); - } - - // Now add this in the database eventually overriding - // something that may have been already existing - this.edgesDB.put(e, props); - - // Now populate the DB of NodeConnectors - // NOTE WELL: properties are empty sets, not really needed - // for now. - // The DB only contains ISL ports - if (isISLink(e)) { - this.nodeConnectorsDB.put(e.getHeadNodeConnector(), new HashSet(1)); - this.nodeConnectorsDB.put(e.getTailNodeConnector(), new HashSet(1)); - } - log.trace("Edge {} {}", e.toString(), type.name()); - break; - case REMOVED: - // Now remove the edge from edgesDB - this.edgesDB.remove(e); - - // Now lets update the NodeConnectors DB, the assumption - // here is that two NodeConnector are exclusively - // connected by 1 and only 1 edge, this is reasonable in - // the same plug (virtual of phisical) we can assume two - // cables won't be plugged. This could break only in case - // of devices in the middle that acts as hubs, but it - // should be safe to assume that won't happen. - this.nodeConnectorsDB.remove(e.getHeadNodeConnector()); - this.nodeConnectorsDB.remove(e.getTailNodeConnector()); - log.trace("Edge {} {}", e.toString(), type.name()); - break; - case CHANGED: - Set oldProps = this.edgesDB.get(e); - - // When property(s) changes lets make sure we can change it - // all except the creation time stamp because that should - // be set only when the edge is created - TimeStamp timeStamp = null; - if (oldProps != null) { - for (Property prop : oldProps) { - if (prop instanceof TimeStamp) { - TimeStamp tsProp = (TimeStamp) prop; - if (tsProp.getTimeStampName().equals("creation")) { - timeStamp = tsProp; - break; - } - } - } - } - - // Now lets make sure new properties are non-null - if (props == null) { - props = new HashSet(); - } else { - // Copy the set so noone is going to change the content - props = new HashSet(props); - } - - // Now lets remove the creation property if exist in the - // new props - for (Iterator i = props.iterator(); i.hasNext();) { - Property prop = i.next(); - if (prop instanceof TimeStamp) { - TimeStamp t = (TimeStamp) prop; - if (t.getTimeStampName().equals("creation")) { - if (timeStamp != null) { - i.remove(); - } - break; - } - } - } - - // Now lets add the creation timestamp in it - if (timeStamp != null) { - props.add(timeStamp); - } - - // Finally update - this.edgesDB.put(e, props); - log.trace("Edge {} {}", e.toString(), type.name()); - break; - } - return new TopoEdgeUpdate(e, props, type); - } - - private void doEdgeUpdate(List topoedgeupdateList) { - List teuList = new ArrayList(); - for (TopoEdgeUpdate teu : topoedgeupdateList) { - boolean isPending = (teu instanceof PendingEdgeUpdate); - Edge e = teu.getEdge(); - Set p = teu.getProperty(); - UpdateType type = teu.getUpdateType(); - TopoEdgeUpdate update = edgeUpdate(e, type, p, isPending); - if (update != null) { - teuList.add(update); - } - } - - if (!teuList.isEmpty()) { - // Now update the listeners - for (ITopologyManagerAware s : this.topologyManagerAware) { - try { - s.edgeUpdate(teuList); - } catch (Exception exc) { - log.error("Exception on edge update:", exc); - } - } - } - } - - @Override - public void edgeUpdate(List topoedgeupdateList) { - updateQ.addAll(topoedgeupdateList); - } - - private Edge getReverseLinkTuple(TopologyUserLinkConfig link) { - TopologyUserLinkConfig rLink = new TopologyUserLinkConfig( - link.getName(), link.getDstNodeConnector(), link.getSrcNodeConnector()); - return getLinkTuple(rLink); - } - - - private Edge getLinkTuple(TopologyUserLinkConfig link) { - NodeConnector srcNodeConnector = NodeConnector.fromString(link.getSrcNodeConnector()); - NodeConnector dstNodeConnector = NodeConnector.fromString(link.getDstNodeConnector()); - try { - return new Edge(srcNodeConnector, dstNodeConnector); - } catch (Exception e) { - return null; - } - } - - @Override - public ConcurrentMap getUserLinks() { - return new ConcurrentHashMap(userLinksDB); - } - - @Override - public Status addUserLink(TopologyUserLinkConfig userLink) { - if (!userLink.isValid()) { - return new Status(StatusCode.BADREQUEST, - "User link configuration invalid."); - } - userLink.setStatus(TopologyUserLinkConfig.STATUS.LINKDOWN); - - //Check if this link already configured - //NOTE: infinispan cache doesn't support Map.containsValue() - // (which is linear time in most ConcurrentMap impl anyway) - for (TopologyUserLinkConfig existingLink : userLinksDB.values()) { - if (existingLink.equals(userLink)) { - return new Status(StatusCode.CONFLICT, "Link configuration exists"); - } - } - //attempt put, if mapping for this key already existed return conflict - if (userLinksDB.putIfAbsent(userLink.getName(), userLink) != null) { - return new Status(StatusCode.CONFLICT, "Link with name : " + userLink.getName() - + " already exists. Please use another name"); - } - - Edge linkTuple = getLinkTuple(userLink); - if (linkTuple != null) { - if (!isProductionLink(linkTuple)) { - TopoEdgeUpdate teu = edgeUpdate(linkTuple, UpdateType.ADDED, - new HashSet()); - if (teu == null) { - userLinksDB.remove(userLink.getName()); - return new Status(StatusCode.NOTFOUND, - "Link configuration contains invalid node connector: " - + userLink); - } - } - - linkTuple = getReverseLinkTuple(userLink); - if (linkTuple != null) { - userLink.setStatus(TopologyUserLinkConfig.STATUS.SUCCESS); - if (!isProductionLink(linkTuple)) { - edgeUpdate(linkTuple, UpdateType.ADDED, new HashSet()); - } - } - } - return new Status(StatusCode.SUCCESS); - } - - @Override - public Status deleteUserLink(String linkName) { - if (linkName == null) { - return new Status(StatusCode.BADREQUEST, "User link name cannot be null."); - } - - TopologyUserLinkConfig link = userLinksDB.remove(linkName); - Edge linkTuple; - if ((link != null) && ((linkTuple = getLinkTuple(link)) != null)) { - if (! isProductionLink(linkTuple)) { - edgeUpdate(linkTuple, UpdateType.REMOVED, null); - } - - linkTuple = getReverseLinkTuple(link); - if (! isProductionLink(linkTuple)) { - edgeUpdate(linkTuple, UpdateType.REMOVED, null); - } - } - return new Status(StatusCode.SUCCESS); - } - - private void registerWithOSGIConsole() { - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) - .getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, - null); - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - help.append("---Topology Manager---\n"); - help.append("\t addUserLink \n"); - help.append("\t deleteUserLink \n"); - help.append("\t printUserLink\n"); - help.append("\t printNodeEdges\n"); - return help.toString(); - } - - public void _printUserLink(CommandInterpreter ci) { - for (String name : this.userLinksDB.keySet()) { - TopologyUserLinkConfig linkConfig = userLinksDB.get(name); - ci.println("Name : " + name); - ci.println(linkConfig); - ci.println("Edge " + getLinkTuple(linkConfig)); - ci.println("Reverse Edge " + getReverseLinkTuple(linkConfig)); - } - } - - public void _addUserLink(CommandInterpreter ci) { - String name = ci.nextArgument(); - if ((name == null)) { - ci.println("Please enter a valid Name"); - return; - } - - String ncStr1 = ci.nextArgument(); - if (ncStr1 == null) { - ci.println("Please enter two node connector strings"); - return; - } - String ncStr2 = ci.nextArgument(); - if (ncStr2 == null) { - ci.println("Please enter second node connector string"); - return; - } - - NodeConnector nc1 = NodeConnector.fromString(ncStr1); - if (nc1 == null) { - ci.println("Invalid input node connector 1 string: " + ncStr1); - return; - } - NodeConnector nc2 = NodeConnector.fromString(ncStr2); - if (nc2 == null) { - ci.println("Invalid input node connector 2 string: " + ncStr2); - return; - } - - TopologyUserLinkConfig config = new TopologyUserLinkConfig(name, ncStr1, ncStr2); - ci.println(this.addUserLink(config)); - } - - public void _deleteUserLink(CommandInterpreter ci) { - String name = ci.nextArgument(); - if ((name == null)) { - ci.println("Please enter a valid Name"); - return; - } - this.deleteUserLink(name); - } - - public void _printNodeEdges(CommandInterpreter ci) { - Map> nodeEdges = getNodeEdges(); - if (nodeEdges == null) { - return; - } - Set nodeSet = nodeEdges.keySet(); - if (nodeSet == null) { - return; - } - ci.println(" Node Edge"); - for (Node node : nodeSet) { - Set edgeSet = nodeEdges.get(node); - if (edgeSet == null) { - continue; - } - for (Edge edge : edgeSet) { - ci.println(node + " " + edge); - } - } - } - - @Override - public Object readObject(ObjectInputStream ois) - throws FileNotFoundException, IOException, ClassNotFoundException { - return ois.readObject(); - } - - @Override - public Status saveConfiguration() { - return saveConfig(); - } - - @Override - public void edgeOverUtilized(Edge edge) { - log.warn("Link Utilization above normal: {}", edge); - } - - @Override - public void edgeUtilBackToNormal(Edge edge) { - log.warn("Link Utilization back to normal: {}", edge); - } - - private void edgeUpdateClusterWide(Edge e, UpdateType type, Set props, boolean isLocal) { - TopoEdgeUpdate upd = new TopoEdgeUpdate(e, props, type); - upd.setLocal(isLocal); - notifyQ.add(upd); - } - - @Override - public void notifyNode(Node node, UpdateType type, Map propMap) { - // NOP - } - - @Override - public void notifyNodeConnector(NodeConnector nc, UpdateType type, Map propMap) { - // Remove pending edge updates for the given node connector. - // Pending events should be notified if the node connector exists. - boolean doFlush = !type.equals(UpdateType.REMOVED); - removePendingEvent(nc, doFlush); - } - - @Override - public void entryCreated(final Object key, final String cacheName, final boolean originLocal) { - if (cacheName.equals(TOPOEDGESDB)) { - // This is the case of an Edge being added to the topology DB - final Edge e = (Edge) key; - log.trace("Edge {} CREATED isLocal:{}", e, originLocal); - edgeUpdateClusterWide(e, UpdateType.ADDED, null, originLocal); - } - } - - @Override - public void entryUpdated(final Object key, final Object new_value, final String cacheName, final boolean originLocal) { - if (cacheName.equals(TOPOEDGESDB)) { - final Edge e = (Edge) key; - log.trace("Edge {} UPDATED isLocal:{}", e, originLocal); - final Set props = (Set) new_value; - edgeUpdateClusterWide(e, UpdateType.CHANGED, props, originLocal); - } - } - - @Override - public void entryDeleted(final Object key, final String cacheName, final boolean originLocal) { - if (cacheName.equals(TOPOEDGESDB)) { - final Edge e = (Edge) key; - log.trace("Edge {} DELETED isLocal:{}", e, originLocal); - edgeUpdateClusterWide(e, UpdateType.REMOVED, null, originLocal); - } - } - - class TopologyNotify implements Runnable { - private final BlockingQueue notifyQ; - private TopoEdgeUpdate entry; - private List teuList = new ArrayList(); - private boolean notifyListeners; - - TopologyNotify(BlockingQueue notifyQ) { - this.notifyQ = notifyQ; - } - - @Override - public void run() { - while (true) { - try { - log.trace("New run of TopologyNotify"); - notifyListeners = false; - // First we block waiting for an element to get in - entry = notifyQ.take(); - // Then we drain the whole queue if elements are - // in it without getting into any blocking condition - for (; entry != null; entry = notifyQ.poll()) { - teuList.add(entry); - notifyListeners = true; - } - - // Notify listeners only if there were updates drained else - // give up - if (notifyListeners) { - log.trace("Notifier thread, notified a listener"); - // Now update the listeners - for (ITopologyManagerClusterWideAware s : topologyManagerClusterWideAware) { - try { - s.edgeUpdate(teuList); - } catch (Exception exc) { - log.error("Exception on edge update:", exc); - } - } - } - teuList.clear(); - - // Lets sleep for sometime to allow aggregation of event - Thread.sleep(100); - } catch (InterruptedException e1) { - if (shuttingDown) { - return; - } - log.warn("TopologyNotify interrupted {}", e1.getMessage()); - } catch (Exception e2) { - log.error("", e2); - } - } - } - } - - public List printUserLink() { - List result = new ArrayList(); - for (String name : this.userLinksDB.keySet()) { - TopologyUserLinkConfig linkConfig = userLinksDB.get(name); - result.add("Name : " + name); - result.add(linkConfig.toString()); - result.add("Edge " + getLinkTuple(linkConfig)); - result.add("Reverse Edge " + getReverseLinkTuple(linkConfig)); - } - return result; - } - - public List addUserLink(String name, String ncStr1, String ncStr2) { - List result = new ArrayList(); - if ((name == null)) { - result.add("Please enter a valid Name"); - return result; - } - - if (ncStr1 == null) { - result.add("Please enter two node connector strings"); - return result; - } - if (ncStr2 == null) { - result.add("Please enter second node connector string"); - return result; - } - - NodeConnector nc1 = NodeConnector.fromString(ncStr1); - if (nc1 == null) { - result.add("Invalid input node connector 1 string: " + ncStr1); - return result; - } - NodeConnector nc2 = NodeConnector.fromString(ncStr2); - if (nc2 == null) { - result.add("Invalid input node connector 2 string: " + ncStr2); - return result; - } - - TopologyUserLinkConfig config = new TopologyUserLinkConfig(name, ncStr1, ncStr2); - result.add(this.addUserLink(config).toString()); - return result; - } - - public List deleteUserLinkShell(String name) { - List result = new ArrayList(); - if ((name == null)) { - result.add("Please enter a valid Name"); - return result; - } - this.deleteUserLink(name); - return result; - } - - public List printNodeEdges() { - List result = new ArrayList(); - Map> nodeEdges = getNodeEdges(); - if (nodeEdges == null) { - return result; - } - Set nodeSet = nodeEdges.keySet(); - if (nodeSet == null) { - return result; - } - result.add(" Node Edge"); - for (Node node : nodeSet) { - Set edgeSet = nodeEdges.get(node); - if (edgeSet == null) { - continue; - } - for (Edge edge : edgeSet) { - result.add(node + " " + edge); - } - } - return result; - } - - // Only for unit test. - void startTest() { - pendingTimer = new Timer("Topology Pending Update Timer"); - updateThread = new Thread(new UpdateTopology(), "Topology Update"); - updateThread.start(); - } - - void stopTest() { - shuttingDown = true; - updateThread.interrupt(); - pendingTimer.cancel(); - } - - boolean flushUpdateQueue(long timeout) { - long limit = System.currentTimeMillis() + timeout; - long cur; - do { - if (updateQ.peek() == null) { - return true; - } - - try { - Thread.sleep(100); - } catch (InterruptedException e) { - break; - } - cur = System.currentTimeMillis(); - } while (cur < limit); - - return false; - } -} diff --git a/opendaylight/adsal/topologymanager/implementation/src/test/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImplTest.java b/opendaylight/adsal/topologymanager/implementation/src/test/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImplTest.java deleted file mode 100644 index 2c5727070c..0000000000 --- a/opendaylight/adsal/topologymanager/implementation/src/test/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImplTest.java +++ /dev/null @@ -1,885 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topologymanager.internal; - -import java.net.InetAddress; -import java.net.UnknownHostException; -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.concurrent.ConcurrentMap; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.controller.sal.core.Bandwidth; -import org.opendaylight.controller.sal.core.ConstructionException; -import org.opendaylight.controller.sal.core.Description; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Host; -import org.opendaylight.controller.sal.core.Latency; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.Node.NodeIDType; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.TimeStamp; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.packet.address.EthernetAddress; -import org.opendaylight.controller.sal.topology.TopoEdgeUpdate; -import org.opendaylight.controller.sal.utils.NodeConnectorCreator; -import org.opendaylight.controller.sal.utils.NodeCreator; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.SpanConfig; -import org.opendaylight.controller.switchmanager.Subnet; -import org.opendaylight.controller.switchmanager.SubnetConfig; -import org.opendaylight.controller.switchmanager.Switch; -import org.opendaylight.controller.switchmanager.SwitchConfig; -import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig; - -public class TopologyManagerImplTest { - private TopologyManagerImpl topoManagerImpl; - - /** - * Mockup of switch manager that only maintains existence of node - * connector. - */ - private final class TestSwitchManager implements ISwitchManager { - private final Set nodeSet = new HashSet(); - private final Set nodeConnectorSet = - new HashSet(); - - private void addNodeConnectors(NodeConnector ... connectors) { - for (NodeConnector nc: connectors) { - if (nc != null) { - nodeSet.add(nc.getNode()); - nodeConnectorSet.add(nc); - } - } - } - - private void addNodeConnectors(TopologyUserLinkConfig ... links) { - for (TopologyUserLinkConfig link: links) { - NodeConnector src = - NodeConnector.fromString(link.getSrcNodeConnector()); - NodeConnector dst = - NodeConnector.fromString(link.getDstNodeConnector()); - addNodeConnectors(src, dst); - } - } - - private void clear() { - nodeSet.clear(); - nodeConnectorSet.clear(); - } - - @Override - public Status addSubnet(SubnetConfig configObject) { - return null; - } - - @Override - public Status removeSubnet(SubnetConfig configObject) { - return null; - } - - @Override - public Status modifySubnet(SubnetConfig configObject) { - return null; - } - - @Override - public Status removeSubnet(String name) { - return null; - } - - @Override - public List getNetworkDevices() { - return null; - } - - @Override - public List getSubnetsConfigList() { - return null; - } - - @Override - public SubnetConfig getSubnetConfig(String subnet) { - return null; - } - - @Override - public Subnet getSubnetByNetworkAddress(InetAddress networkAddress) { - return null; - } - - @Override - public Status saveSwitchConfig() { - return null; - } - - @Override - public Status addSpanConfig(SpanConfig configObject) { - return null; - } - - @Override - public Status removeSpanConfig(SpanConfig cfgObject) { - return null; - } - - @Override - public List getSpanConfigList() { - return null; - } - - @Override - public List getSpanPorts(Node node) { - return null; - } - - @Override - public void updateSwitchConfig(SwitchConfig cfgObject) { - } - - @Override - public Status updateNodeConfig(SwitchConfig switchConfig) { - return null; - } - - @Override - public Status removeNodeConfig(String nodeId) { - return null; - } - - @Override - public SwitchConfig getSwitchConfig(String nodeId) { - return null; - } - - @Override - public Status addPortsToSubnet(String name, List nodeConnectors) { - return null; - } - - @Override - public Status removePortsFromSubnet(String name, List nodeConnectors) { - return null; - } - - @Override - public Set getNodes() { - return new HashSet(nodeSet); - } - - @Override - public Map getNodeProps(Node node) { - return new HashMap(); - } - - @Override - public Property getNodeProp(Node node, String propName) { - return null; - } - - @Override - public void setNodeProp(Node node, Property prop) { - } - - @Override - public Status removeNodeProp(Node node, String propName) { - return null; - } - - @Override - public Status removeNodeAllProps(Node node) { - return null; - } - - @Override - public Set getUpNodeConnectors(Node node) { - return getNodeConnectors(node); - } - - @Override - public Set getNodeConnectors(Node node) { - Set set = new HashSet(); - for (NodeConnector nc: nodeConnectorSet) { - if (nc.getNode().equals(node)) { - set.add(nc); - } - } - - return set; - } - - @Override - public Set getPhysicalNodeConnectors(Node node) { - return getNodeConnectors(node); - } - - @Override - public Map getNodeConnectorProps(NodeConnector nodeConnector) { - return new HashMap(); - } - - @Override - public Property getNodeConnectorProp(NodeConnector nodeConnector, String propName) { - return null; - } - - @Override - public Status addNodeConnectorProp(NodeConnector nodeConnector, Property prop) { - return null; - } - - @Override - public Status removeNodeConnectorProp(NodeConnector nc, String propName) { - return null; - } - - @Override - public Status removeNodeConnectorAllProps(NodeConnector nodeConnector) { - return null; - } - - @Override - public NodeConnector getNodeConnector(Node node, String nodeConnectorName) { - return null; - } - - @Override - public boolean isSpecial(NodeConnector p) { - String type = p.getType(); - return (type.equals(NodeConnectorIDType.CONTROLLER) - || type.equals(NodeConnectorIDType.ALL) - || type.equals(NodeConnectorIDType.SWSTACK) - || type.equals(NodeConnectorIDType.HWPATH)); - } - - @Override - public Boolean isNodeConnectorEnabled(NodeConnector nodeConnector) { - if (doesNodeConnectorExist(nodeConnector)) { - return Boolean.TRUE; - } - return Boolean.FALSE; - } - - @Override - public boolean doesNodeConnectorExist(NodeConnector nc) { - return (nc != null && nodeConnectorSet.contains(nc)); - } - - @Override - public byte[] getControllerMAC() { - return new byte[6]; - } - - @Override - public byte[] getNodeMAC(Node node) { - return new byte[6]; - } - - @Override - public Property createProperty(String propName, String propValue) { - return null; - } - - @Override - public String getNodeDescription(Node node) { - return null; - } - - @Override - public Status removeControllerProperty(String propertyName){ - return null; - } - - @Override - public Set getConfiguredNotConnectedSwitches() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getControllerProperties() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Property getControllerProperty(String propertyName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Status setControllerProperty(Property property) { - // TODO Auto-generated method stub - return null; - } - } - - @Before - public void setUp() { - topoManagerImpl = new TopologyManagerImpl(); - topoManagerImpl.startTest(); - } - - @After - public void tearDown() { - if (topoManagerImpl != null) { - topoManagerImpl.stopTest(); - topoManagerImpl = null; - } - } - - /* - * Sets the node, edges and properties for edges here: Edge : <1:1>--><11:11>; <1:2>--><11:12>; <3:3>--><13:13>; - * <3:4>--><13:14>; <5:5>--><15:15>; <5:6>--><15:16>; Method used by two - * tests: testGetNodeEdges and testGetEdges - * - * @param topoManagerImpl - * - * @throws ConstructionException - */ - public void setNodeEdges(TopologyManagerImpl topoManagerImpl, TestSwitchManager swMgr) - throws ConstructionException { - topoManagerImpl.nonClusterObjectCreate(); - - State state; - Bandwidth bw; - Latency l; - - Set props = new HashSet(); - state = new State(State.EDGE_UP); - bw = new Bandwidth(Bandwidth.BW100Gbps); - l = new Latency(Latency.LATENCY100ns); - props.add(state); - props.add(bw); - props.add(l); - - for (short i = 1; i < 6; i = (short) (i + 2)) { - List topoedgeupdateList = new ArrayList(); - NodeConnector headnc1 = NodeConnectorCreator.createOFNodeConnector( - i, NodeCreator.createOFNode((long) i)); - NodeConnector tailnc1 = NodeConnectorCreator - .createOFNodeConnector((short) (i + 10), - NodeCreator.createOFNode((long) (i + 10))); - swMgr.addNodeConnectors(tailnc1, headnc1); - Edge e1 = new Edge(tailnc1, headnc1); - TopoEdgeUpdate teu1 = new TopoEdgeUpdate(e1, props, - UpdateType.ADDED); - topoedgeupdateList.add(teu1); - - NodeConnector tailnc2 = NodeConnectorCreator.createOFNodeConnector( - (short) (i + 1), headnc1.getNode()); - NodeConnector headnc2 = NodeConnectorCreator.createOFNodeConnector( - (short) (i + 11), tailnc1.getNode()); - swMgr.addNodeConnectors(tailnc1, headnc2); - Edge e2 = new Edge(tailnc2, headnc2); - TopoEdgeUpdate teu2 = new TopoEdgeUpdate(e2, props, - UpdateType.ADDED); - topoedgeupdateList.add(teu2); - topoManagerImpl.edgeUpdate(topoedgeupdateList); - } - - Assert.assertTrue(topoManagerImpl.flushUpdateQueue(5000)); - } - - @Test - public void testGetNodeEdges() throws ConstructionException { - TestSwitchManager swMgr = new TestSwitchManager(); - topoManagerImpl.setSwitchManager(swMgr); - setNodeEdges(topoManagerImpl, swMgr); - - Map> nodeEdgeMap = topoManagerImpl.getNodeEdges(); - for (Iterator>> i = nodeEdgeMap.entrySet() - .iterator(); i.hasNext();) { - Map.Entry> entry = i.next(); - Node node = entry.getKey(); - Long nodeId = ((Long) node.getID()).longValue(); - Assert.assertTrue((node.getType().equals(NodeIDType.OPENFLOW))); - - Set edges = entry.getValue(); - for (Edge edge : edges) { - Long headNcId = ((Short) edge.getHeadNodeConnector().getID()) - .longValue(); - Long tailNcId = ((Short) edge.getTailNodeConnector().getID()) - .longValue(); - Assert.assertTrue( - (headNcId.equals(nodeId) && tailNcId.equals(nodeId + 10)) - || (headNcId.equals(nodeId + 11) && tailNcId.equals(nodeId + 1)) - || (headNcId.equals(nodeId + 1) && tailNcId.equals(nodeId - 9)) - || (headNcId.equals(nodeId - 10) && tailNcId.equals(nodeId)) - ); - } - i.remove(); - } - Assert.assertTrue(nodeEdgeMap.isEmpty()); - } - - @Test - public void testGetEdges() throws ConstructionException { - TestSwitchManager swMgr = new TestSwitchManager(); - topoManagerImpl.setSwitchManager(swMgr); - setNodeEdges(topoManagerImpl, swMgr); - - Map> edgeProperty = topoManagerImpl.getEdges(); - - for (Iterator>> i = edgeProperty - .entrySet().iterator(); i.hasNext();) { - Map.Entry> entry = i.next(); - Edge e = entry.getKey(); - NodeConnector headnc = e.getHeadNodeConnector(); - NodeConnector tailnc = e.getTailNodeConnector(); - - Long headNodeId = (Long) headnc.getNode().getID(); - - Long headNcId = ((Short) headnc.getID()).longValue(); - Long tailNcId = ((Short) tailnc.getID()).longValue(); - - if (headNodeId == 1 || headNodeId == 3 || headNodeId == 5) { - Assert.assertTrue((headNcId.equals(headNodeId) && tailNcId - .equals(headNodeId + 10)) - || (headNcId.equals(headNodeId + 10) && tailNcId - .equals(headNodeId)) - || (headNcId.equals(headNodeId + 1) && tailNcId - .equals(headNodeId + 11)) - || (headNcId.equals(headNodeId + 11) && tailNcId - .equals(headNodeId + 1))); - } else if (headNodeId == 11 || headNodeId == 13 || headNodeId == 15) { - Assert.assertTrue((headNcId.equals(headNodeId) && tailNcId - .equals(headNodeId - 10)) - || (headNcId.equals(headNodeId) && tailNcId - .equals(headNodeId - 10)) - || (headNcId.equals(headNodeId - 9) && tailNcId - .equals(headNodeId + 1)) - || (headNcId.equals(headNodeId + 1) && tailNcId - .equals(headNodeId - 9))); - } - - Set prop = entry.getValue(); - for (Property p : prop) { - String pName; - long pValue; - if (p instanceof Bandwidth) { - Bandwidth b = (Bandwidth) p; - pName = Bandwidth.BandwidthPropName; - pValue = b.getValue(); - Assert.assertTrue(pName.equals(p.getName()) - && pValue == Bandwidth.BW100Gbps); - continue; - } - if (p instanceof Latency) { - Latency l = (Latency) p; - pName = Latency.LatencyPropName; - pValue = l.getValue(); - Assert.assertTrue(pName.equals(p.getName()) - && pValue == Latency.LATENCY100ns); - continue; - } - if (p instanceof State) { - State state = (State) p; - pName = State.StatePropName; - pValue = state.getValue(); - Assert.assertTrue(pName.equals(p.getName()) - && pValue == State.EDGE_UP); - continue; - } - } - i.remove(); - } - Assert.assertTrue(edgeProperty.isEmpty()); - } - - @Test - public void testAddDeleteUserLink() { - TopologyUserLinkConfig link1 = new TopologyUserLinkConfig("default1", - "OF|1@OF|2", "OF|1@OF|3"); - TopologyUserLinkConfig link2 = new TopologyUserLinkConfig("default1", - "OF|10@OF|20", "OF|10@OF|30"); - TopologyUserLinkConfig link3 = new TopologyUserLinkConfig("default2", - "OF|1@OF|2", "OF|1@OF|3"); - TopologyUserLinkConfig link4 = new TopologyUserLinkConfig("default20", - "OF|10@OF|20", "OF|10@OF|30"); - - TestSwitchManager swMgr = new TestSwitchManager(); - topoManagerImpl.setSwitchManager(swMgr); - topoManagerImpl.nonClusterObjectCreate(); - - swMgr.addNodeConnectors(link1, link2, link3, link4); - - Assert.assertTrue(topoManagerImpl.addUserLink(link1).isSuccess()); - Assert.assertTrue(topoManagerImpl.addUserLink(link2).getCode() == StatusCode.CONFLICT); - Assert.assertTrue(topoManagerImpl.addUserLink(link3).getCode() == StatusCode.CONFLICT); - Assert.assertTrue(topoManagerImpl.addUserLink(link4).isSuccess()); - - Assert.assertTrue(topoManagerImpl.deleteUserLink(null).getCode() == StatusCode.BADREQUEST); - Assert.assertTrue(topoManagerImpl.deleteUserLink(link1.getName()) - .isSuccess()); - Assert.assertTrue(topoManagerImpl.deleteUserLink(link4.getName()) - .isSuccess()); - Assert.assertTrue(topoManagerImpl.getUserLinks().isEmpty()); - - TopologyUserLinkConfig badlink1 = - new TopologyUserLinkConfig("bad1", "OF|1@OF|4", "OF|1@OF|5"); - TopologyUserLinkConfig badlink2 = - new TopologyUserLinkConfig("bad2", "OF|10@OF|7", "OF|7@OF|13"); - Assert.assertEquals(StatusCode.NOTFOUND, - topoManagerImpl.addUserLink(badlink1).getCode()); - Assert.assertEquals(StatusCode.NOTFOUND, - topoManagerImpl.addUserLink(badlink2).getCode()); - } - - @Test - public void testGetUserLink() { - TopologyUserLinkConfig[] link = new TopologyUserLinkConfig[5]; - TopologyUserLinkConfig[] reverseLink = new TopologyUserLinkConfig[5]; - TestSwitchManager swMgr = new TestSwitchManager(); - topoManagerImpl.setSwitchManager(swMgr); - topoManagerImpl.nonClusterObjectCreate(); - - String name = "Test"; - String srcSwitchId = null; - String srcNodeConnectorIDType = null; - String srcPort = null; - String srcNodeIDType = null; - String dstNodeIDType = null; - String dstSwitchId = null; - String dstNodeConnectorIDType = null; - String dstPort = null; - String srcNodeConnector = null; - String dstNodeConnector = null; - - /* Creating userlinks and checking for their validity */ - link[0] = new TopologyUserLinkConfig(name, srcNodeConnector, dstNodeConnector); - Assert.assertTrue(link[0].isValid() == false); - - srcNodeConnector = "OF|1@OF|1"; - link[0] = new TopologyUserLinkConfig(name, srcNodeConnector, dstNodeConnector); - Assert.assertTrue(link[0].isValid() == false); - - dstNodeConnector = "OF|1@OF|2"; - link[0] = new TopologyUserLinkConfig(name, srcNodeConnector, dstNodeConnector); - Assert.assertTrue(link[0].isValid() == true); - - Integer i; - - for (i = 0; i < 5; i++) { - link[i] = new TopologyUserLinkConfig(); - - name = Integer.toString(i + 1); - srcSwitchId = Integer.toString(i + 1); - srcPort = Integer.toString(i + 1); - dstSwitchId = Integer.toString((i + 1) * 10); - dstPort = Integer.toString((i + 1) * 10); - - link[i].setName(name); - srcNodeConnectorIDType = dstNodeConnectorIDType = "INCORRECT"; - srcNodeConnector = srcNodeConnectorIDType+"|"+srcSwitchId+"@"+srcNodeConnectorIDType+"|"+srcPort; - dstNodeConnector = dstNodeConnectorIDType+"|"+dstSwitchId+"@"+dstNodeConnectorIDType+"|"+dstPort; - - link[i].setSrcNodeConnector(srcNodeConnector); - Assert.assertTrue(link[i].isValid() == false); - - srcNodeConnectorIDType = "OF"; - srcNodeConnector = srcNodeConnectorIDType+"|"+srcSwitchId+"@"+srcNodeConnectorIDType+"|"+srcPort; - link[i].setSrcNodeConnector(srcNodeConnector); - Assert.assertTrue(link[i].isValid() == false); - - dstNodeConnectorIDType = "OF"; - dstNodeConnector = dstNodeConnectorIDType+"|"+dstSwitchId+"@"+dstNodeConnectorIDType+"|"+dstPort; - link[i].setDstNodeConnector(dstNodeConnector); - Assert.assertTrue(link[i].isValid() == true); - - reverseLink[i] = new TopologyUserLinkConfig(name, dstNodeConnector, srcNodeConnector); - - Assert.assertEquals(StatusCode.NOTFOUND, - topoManagerImpl.addUserLink(link[i]).getCode()); - swMgr.addNodeConnectors(link[i]); - Assert.assertTrue(topoManagerImpl.addUserLink(link[i]).isSuccess()); - } - - ConcurrentMap userLinks = topoManagerImpl - .getUserLinks(); - TopologyUserLinkConfig resultLink; - - for (i = 0; i < 5; i++) { - resultLink = userLinks.get(((Integer) (i + 1)).toString()); - - Assert.assertTrue(resultLink.getName().equals( - reverseLink[i].getName())); - Assert.assertTrue(resultLink.getDstNodeConnector().equals( - reverseLink[i].getSrcNodeConnector())); - Assert.assertTrue(resultLink.getSrcNodeConnector().equals( - reverseLink[i].getDstNodeConnector())); - } - } - - @Test - public void testHostLinkMethods() throws ConstructionException, - UnknownHostException { - TestSwitchManager swMgr = new TestSwitchManager(); - topoManagerImpl.setSwitchManager(swMgr); - topoManagerImpl.nonClusterObjectCreate(); - int hostCounter = 0; - - State state; - Bandwidth bw; - Latency l; - Set props = new HashSet(); - state = new State(State.EDGE_UP); - bw = new Bandwidth(Bandwidth.BW100Gbps); - l = new Latency(Latency.LATENCY100ns); - props.add(state); - props.add(bw); - props.add(l); - - EthernetAddress ea; - InetAddress ip; - Host[] h = new Host[5]; - NodeConnector[] nc = new NodeConnector[5]; - - /* - * Adding host, nodeConnector to hostsDB for the i = 0,1,2,3. No host - * added for i = 4 - */ - for (int i = 0; i < 5; i++) { - if (hostCounter < 4) { - ea = new EthernetAddress(new byte[] { (byte) 0x0, (byte) 0x0, - (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) i }); - String stringIP = new StringBuilder().append(i + 1).append(".") - .append(i + 10).append(".").append(i + 20).append(".") - .append(i + 30).toString(); - ip = InetAddress.getByName(stringIP); - h[hostCounter] = new Host(ea, ip); - } else { - h[hostCounter] = null; - } - hostCounter++; - nc[i] = NodeConnectorCreator.createOFNodeConnector((short) (i + 1), - NodeCreator.createOFNode((long) (i + 1))); - topoManagerImpl - .updateHostLink(nc[i], h[i], UpdateType.ADDED, props); - } - - for (int i = 0; i < 5; i++) { - Host host = topoManagerImpl.getHostAttachedToNodeConnector(nc[i]); - if (i == 4) { - Assert.assertTrue(host == null); - } else { - Assert.assertTrue(host.equals(h[i])); - } - } - - Set ncSet = topoManagerImpl.getNodeConnectorWithHost(); - for (int i = 0; i < 5; i++) { - Assert.assertTrue(ncSet.remove(nc[i])); - } - Assert.assertTrue(ncSet.isEmpty()); - } - - @Test - public void testGetNodesWithNodeConnectorHost() - throws ConstructionException, UnknownHostException { - TestSwitchManager swMgr = new TestSwitchManager(); - topoManagerImpl.setSwitchManager(swMgr); - topoManagerImpl.nonClusterObjectCreate(); - int hostCounter = 0; - - State state; - Bandwidth bw; - Latency l; - Set props = new HashSet(); - state = new State(State.EDGE_UP); - bw = new Bandwidth(Bandwidth.BW100Gbps); - l = new Latency(Latency.LATENCY100ns); - props.add(state); - props.add(bw); - props.add(l); - - EthernetAddress ea; - InetAddress ip; - Host[] h = new Host[5]; - NodeConnector[] nc = new NodeConnector[5]; - - /* - * Adding host, nodeconnector, properties of edge to hostsDB for the - * first three nodes only - */ - for (int i = 1; i < 6; i++) { - if (i < 4) { - ea = new EthernetAddress(new byte[] { (byte) 0x0, (byte) 0x0, - (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) i }); - String stringIP = new StringBuilder().append(i).append(".") - .append(i + 10).append(".").append(i + 20).append(".") - .append(i + 30).toString(); - ip = InetAddress.getByName(stringIP); - h[hostCounter] = new Host(ea, ip); - } else { - h[hostCounter] = null; - } - hostCounter++; - nc[i - 1] = NodeConnectorCreator.createOFNodeConnector((short) i, - NodeCreator.createOFNode((long) i)); - topoManagerImpl.updateHostLink(nc[i - 1], h[i - 1], - UpdateType.ADDED, props); - } - - /* Get the nodes which have host connected to its nodeConnector */ - Map> nodeNCmap = topoManagerImpl - .getNodesWithNodeConnectorHost(); - for (int i = 1; i < 6; i++) { - Node node = nc[i - 1].getNode(); - Set ncSet = nodeNCmap.get(nc[i - 1].getNode()); - - Assert.assertTrue(ncSet == nodeNCmap.remove(node)); - } - - Assert.assertTrue(nodeNCmap.isEmpty()); - } - - @Test - public void bug1348FixTest() throws ConstructionException, - InterruptedException { - TestSwitchManager swMgr = new TestSwitchManager(); - topoManagerImpl.setSwitchManager(swMgr); - topoManagerImpl.nonClusterObjectCreate(); - - NodeConnector headnc1 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, NodeCreator.createOFNode(1000L)); - NodeConnector tailnc1 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, NodeCreator.createOFNode(2000L)); - Edge edge = new Edge(headnc1, tailnc1); - List updatedEdges = new ArrayList<>(); - Set edgeProps = new HashSet<>(); - edgeProps.add(new TimeStamp(System.currentTimeMillis(), "creation")); - edgeProps.add(new Latency(Latency.LATENCY100ns)); - edgeProps.add(new State(State.EDGE_UP)); - edgeProps.add(new Bandwidth(Bandwidth.BW100Gbps)); - edgeProps.add(new Description("Test edge")); - updatedEdges.add(new TopoEdgeUpdate(edge, edgeProps, UpdateType.CHANGED)); - - try { - topoManagerImpl.edgeUpdate(updatedEdges); - } catch (Exception e) { - Assert.fail("Exception was raised when trying to update edge properties: " + e.getMessage()); - } - - Assert.assertTrue(topoManagerImpl.flushUpdateQueue(5000)); - verifyEdgesSize(1); - Assert.assertNotNull(topoManagerImpl.getEdges().get(edge)); - } - - private void verifyEdgesSize(int expSize) throws InterruptedException { - int timeout = 5000; - for(int i = 0; i < timeout / 50; i++) { - if(topoManagerImpl.getEdges().size() == expSize) { - return; - } - - Thread.sleep(50); - } - - Assert.fail(String.format("Expected edges size %d. Actual was %d", - topoManagerImpl.getEdges().size(), expSize)); - } - - @Test - public void testNotifyNodeConnector() throws Exception { - TestSwitchManager swMgr = new TestSwitchManager(); - topoManagerImpl.setSwitchManager(swMgr); - topoManagerImpl.nonClusterObjectCreate(); - - // Test NodeConnector notification in the case that there are no - // related edge updates. - NodeConnector nc1 = NodeConnectorCreator.createOFNodeConnector( - (short) 1, NodeCreator.createOFNode(1000L)); - Map propMap = new HashMap<>(); - swMgr.addNodeConnectors(nc1); - topoManagerImpl.notifyNodeConnector(nc1, UpdateType.ADDED, propMap); - verifyEdgesSize(0); - - topoManagerImpl.notifyNodeConnector(nc1, UpdateType.CHANGED, propMap); - verifyEdgesSize(0); - - swMgr.clear(); - topoManagerImpl.notifyNodeConnector(nc1, UpdateType.REMOVED, propMap); - verifyEdgesSize(0); - - // Test NodeConnector notification in the case that there is a related - // edge update just before the notification. - NodeConnector nc2 = NodeConnectorCreator.createOFNodeConnector( - (short) 2, NodeCreator.createOFNode(2000L)); - Edge edge1 = new Edge(nc1, nc2); - Edge edge2 = new Edge(nc2, nc1); - Set props = new HashSet(); - TopoEdgeUpdate teu1 = new TopoEdgeUpdate(edge1, props, UpdateType.ADDED); - TopoEdgeUpdate teu2 = new TopoEdgeUpdate(edge2, props, UpdateType.ADDED); - List topoedgeupdateList = new ArrayList(); - topoedgeupdateList.add(teu1); - topoedgeupdateList.add(teu2); - topoManagerImpl.edgeUpdate(topoedgeupdateList); - swMgr.addNodeConnectors(nc1); - topoManagerImpl.notifyNodeConnector(nc1, UpdateType.ADDED, propMap); - swMgr.addNodeConnectors(nc2); - topoManagerImpl.notifyNodeConnector(nc2, UpdateType.CHANGED, propMap); - Assert.assertTrue(topoManagerImpl.flushUpdateQueue(5000)); - verifyEdgesSize(2); - - teu1 = new TopoEdgeUpdate(edge1, props, UpdateType.REMOVED); - teu2 = new TopoEdgeUpdate(edge2, props, UpdateType.REMOVED); - topoedgeupdateList = new ArrayList(); - topoedgeupdateList.add(teu1); - topoedgeupdateList.add(teu2); - topoManagerImpl.edgeUpdate(topoedgeupdateList); - Assert.assertTrue(topoManagerImpl.flushUpdateQueue(5000)); - verifyEdgesSize(0); - topoManagerImpl.notifyNodeConnector(nc1, UpdateType.REMOVED, propMap); - topoManagerImpl.notifyNodeConnector(nc2, UpdateType.REMOVED, propMap); - - swMgr.clear(); - - // Test NodeConnector notification in the case that there are multiple - // edge updates related to the NodeConnector just before the notification. - teu1 = new TopoEdgeUpdate(edge1, props, UpdateType.ADDED); - teu2 = new TopoEdgeUpdate(edge2, props, UpdateType.ADDED); - TopoEdgeUpdate teu3 = new TopoEdgeUpdate(edge1, props, UpdateType.CHANGED); - TopoEdgeUpdate teu4 = new TopoEdgeUpdate(edge2, props, UpdateType.CHANGED); - TopoEdgeUpdate teu5 = new TopoEdgeUpdate(edge1, props, UpdateType.REMOVED); - TopoEdgeUpdate teu6 = new TopoEdgeUpdate(edge2, props, UpdateType.REMOVED); - topoedgeupdateList = new ArrayList(); - topoedgeupdateList.add(teu1); - topoedgeupdateList.add(teu2); - topoedgeupdateList.add(teu3); - topoedgeupdateList.add(teu4); - topoedgeupdateList.add(teu5); - topoedgeupdateList.add(teu6); - topoManagerImpl.edgeUpdate(topoedgeupdateList); - swMgr.addNodeConnectors(nc1); - topoManagerImpl.notifyNodeConnector(nc1, UpdateType.ADDED, propMap); - swMgr.addNodeConnectors(nc2); - topoManagerImpl.notifyNodeConnector(nc2, UpdateType.CHANGED, propMap); - Assert.assertTrue(topoManagerImpl.flushUpdateQueue(5000)); - verifyEdgesSize(0); - topoManagerImpl.notifyNodeConnector(nc1, UpdateType.REMOVED, propMap); - topoManagerImpl.notifyNodeConnector(nc2, UpdateType.REMOVED, propMap); - Assert.assertTrue(topoManagerImpl.flushUpdateQueue(5000)); - verifyEdgesSize(0); - } -} diff --git a/opendaylight/adsal/topologymanager/integrationtest/pom.xml b/opendaylight/adsal/topologymanager/integrationtest/pom.xml deleted file mode 100644 index 20fdc0b1ae..0000000000 --- a/opendaylight/adsal/topologymanager/integrationtest/pom.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.integrationtest - 0.7.0-SNAPSHOT - ../../commons/integrationtest - - - topologymanager.integrationtest - 0.6.0-SNAPSHOT - - ../../implementaiton/target/jacoco-it.exec - - ../../implementation/target/jacoco.exec - - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - clustering.stub - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - configuration.implementation - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - containermanager.it.implementation - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - hosttracker - - - org.opendaylight.controller - protocol_plugins.stub - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - sal.implementation - - - org.opendaylight.controller - statisticsmanager - - - org.opendaylight.controller - statisticsmanager.implementation - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - switchmanager.implementation - - - org.opendaylight.controller - topologymanager - - - org.ops4j.pax.exam - pax-exam-container-native - test - - - - - - org.jacoco - jacoco-maven-plugin - - ../../implementation/target/jacoco-it.exec - - org.opendaylight.controller.* - - - - - pre-test - - prepare-agent - - - - post-test - - true - - - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/topologymanager/integrationtest/src/test/java/org/opendaylight/controller/topologymanager/TopologyManagerIT.java b/opendaylight/adsal/topologymanager/integrationtest/src/test/java/org/opendaylight/controller/topologymanager/TopologyManagerIT.java deleted file mode 100644 index c2fc8aaa8e..0000000000 --- a/opendaylight/adsal/topologymanager/integrationtest/src/test/java/org/opendaylight/controller/topologymanager/TopologyManagerIT.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.topologymanager; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.opendaylight.controller.protocol_plugins.stub.internal.TopologyServices; -import org.opendaylight.controller.sal.core.Edge; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.UpdateType; -import org.opendaylight.controller.sal.topology.IPluginInTopologyService; -import org.ops4j.pax.exam.Option; -import org.ops4j.pax.exam.Configuration; -import org.ops4j.pax.exam.junit.PaxExam; -import org.ops4j.pax.exam.util.PathUtils; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import java.util.HashSet; -import java.util.Set; - -import static org.ops4j.pax.exam.CoreOptions.junitBundles; -import static org.ops4j.pax.exam.CoreOptions.mavenBundle; -import static org.ops4j.pax.exam.CoreOptions.options; -import static org.ops4j.pax.exam.CoreOptions.systemPackages; -import static org.ops4j.pax.exam.CoreOptions.systemProperty; - - -@RunWith(PaxExam.class) -public class TopologyManagerIT { - private Logger log = LoggerFactory - .getLogger(TopologyManagerIT.class); - // get the OSGI bundle context - @Inject - private BundleContext bc; - @Inject - private ITopologyManager manager = null; - - // Configure the OSGi container - @Configuration - public Option[] config() { - return options( - // - systemProperty("logback.configurationFile").value( - "file:" + PathUtils.getBaseDir() - + "/src/test/resources/logback.xml"), - // To start OSGi console for inspection remotely - systemProperty("osgi.console").value("2401"), - // Set the systemPackages (used by clustering) - systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"), - // List framework bundles - mavenBundle("equinoxSDK381", "org.eclipse.equinox.console").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.util").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.osgi.services").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime").versionAsInProject(), - mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell").versionAsInProject(), - // List logger bundles - mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), - mavenBundle("org.slf4j", "log4j-over-slf4j") - .versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-core") - .versionAsInProject(), - mavenBundle("ch.qos.logback", "logback-classic") - .versionAsInProject(), - // needed by statisticsmanager - mavenBundle("org.opendaylight.controller", "containermanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "containermanager.it.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "clustering.services") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "clustering.stub") - .versionAsInProject(), - // needed by forwardingrulesmanager - mavenBundle("org.opendaylight.controller", "configuration") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "configuration.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "hosttracker") - .versionAsInProject(), - - // List all the bundles on which the test case depends - mavenBundle("org.opendaylight.controller", "sal") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "sal.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "protocol_plugins.stub") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "switchmanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "switchmanager.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "statisticsmanager") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "statisticsmanager.implementation") - .versionAsInProject(), - mavenBundle("org.opendaylight.controller", "forwardingrulesmanager") - .versionAsInProject(), - - // needed by hosttracker - mavenBundle("org.opendaylight.controller", "topologymanager") - .versionAsInProject(), - mavenBundle("org.jboss.spec.javax.transaction", - "jboss-transaction-api_1.1_spec").versionAsInProject(), - mavenBundle("org.apache.commons", "commons-lang3") - .versionAsInProject(), - mavenBundle("org.apache.felix", - "org.apache.felix.dependencymanager") - .versionAsInProject(), junitBundles()); - } - - private String stateToString(int state) { - switch (state) { - case Bundle.ACTIVE: - return "ACTIVE"; - case Bundle.INSTALLED: - return "INSTALLED"; - case Bundle.RESOLVED: - return "RESOLVED"; - case Bundle.UNINSTALLED: - return "UNINSTALLED"; - default: - return "Not CONVERTED"; - } - } - - /** - * This test verifies that the isInternal method of the TopologyManager returns true when a node is internal and - * not otherwise - * - * To make a node interval we add a node using the plugin interface (TopologyServices.addEdge) this is to ensure - * that when TopologyManager sees the edge is via it's dependency on the SAL ITopologyService. - * - * @throws Exception - */ - @Test - public void testIsInternal() throws Exception{ - Node node1 = new Node("STUB", 0xCAFE); - Node node2 = new Node("STUB", 0XFACE); - - NodeConnector head = new NodeConnector("STUB", node1.getID(), node1); - NodeConnector tail = new NodeConnector("STUB", node2.getID(), node2); - - assert(this.manager.isInternal(head)); - - Set properties = new HashSet(); - - ServiceReference r = bc.getServiceReference(IPluginInTopologyService.class - .getName()); - TopologyServices topologyServices = null; - if (r != null) { - if(bc.getService(r) instanceof TopologyServices) { - topologyServices = (TopologyServices) bc.getService(r); - } else { - throw new RuntimeException("topology service registered is not from the stub plugin implementation"); - } - } - - topologyServices.addEdge(new Edge(tail, head), properties, UpdateType.ADDED); - - assert(this.manager.isInternal(head)); - } - -} diff --git a/opendaylight/adsal/topologymanager/integrationtest/src/test/resources/logback.xml b/opendaylight/adsal/topologymanager/integrationtest/src/test/resources/logback.xml deleted file mode 100644 index 2d63ce5744..0000000000 --- a/opendaylight/adsal/topologymanager/integrationtest/src/test/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - diff --git a/opendaylight/adsal/topologymanager/shell/pom.xml b/opendaylight/adsal/topologymanager/shell/pom.xml deleted file mode 100644 index bc9d63078c..0000000000 --- a/opendaylight/adsal/topologymanager/shell/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - topologymanager.shell - ${topologymanager.shell.version} - bundle - - - junit - junit - - - org.apache.karaf.shell - org.apache.karaf.shell.console - ${karaf.shell.version} - - - org.mockito - mockito-all - - - org.opendaylight.controller - topologymanager - - - - - - - org.apache.felix - maven-bundle-plugin - - - org.apache.felix.service.command, - org.apache.karaf.shell.commands, - org.apache.karaf.shell.console, - * - - - - - - - diff --git a/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java b/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java deleted file mode 100644 index 92467c9344..0000000000 --- a/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java +++ /dev/null @@ -1,39 +0,0 @@ -/** -* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. -* -* This program and the accompanying materials are made available under the -* terms of the Eclipse Public License v1.0 which accompanies this distribution, -* and is available at http://www.eclipse.org/legal/epl-v10.html -*/ -package org.opendaylight.controller.topologymanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.topologymanager.ITopologyManagerShell; - -@Command(scope = "topologymanager", name = "addUserLink", description="Adds user link") -public class AddUserLink extends OsgiCommandSupport{ - private ITopologyManagerShell topologyManager; - - @Argument(index=0, name="name", description="name", required=true, multiValued=false) - String name = null; - - @Argument(index=1, name="ncStr1", description="ncStr1", required=true, multiValued=false) - String ncStr1 = null; - - @Argument(index=2, name="ncStr2", description="ncStr2", required=true, multiValued=false) - String ncStr2 = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : topologyManager.addUserLink(name, ncStr1, ncStr2)) { - System.out.println(p); - } - return null; - } - - public void setTopologyManager(ITopologyManagerShell topologyManager){ - this.topologyManager = topologyManager; - } -} diff --git a/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java b/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java deleted file mode 100644 index 2c3e93c26a..0000000000 --- a/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java +++ /dev/null @@ -1,33 +0,0 @@ -/** -* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. -* -* This program and the accompanying materials are made available under the -* terms of the Eclipse Public License v1.0 which accompanies this distribution, -* and is available at http://www.eclipse.org/legal/epl-v10.html -*/ -package org.opendaylight.controller.topologymanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.commands.Argument; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.topologymanager.ITopologyManagerShell; - -@Command(scope = "topologymanager", name = "deleteUserLink", description="deletes user link") -public class DeleteUserLink extends OsgiCommandSupport{ - private ITopologyManagerShell topologyManager; - - @Argument(index=0, name="name", description="name", required=true, multiValued=false) - String name = null; - - @Override - protected Object doExecute() throws Exception { - for(String p : topologyManager.deleteUserLinkShell(name)) { - System.out.println(p); - } - return null; - } - - public void setTopologyManager(ITopologyManagerShell topologyManager){ - this.topologyManager = topologyManager; - } -} diff --git a/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java b/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java deleted file mode 100644 index 4a65a45351..0000000000 --- a/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. -* -* This program and the accompanying materials are made available under the -* terms of the Eclipse Public License v1.0 which accompanies this distribution, -* and is available at http://www.eclipse.org/legal/epl-v10.html -*/ -package org.opendaylight.controller.topologymanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.topologymanager.ITopologyManagerShell; - -@Command(scope = "topologymanager", name = "printNodeEdges", description="Prints node edges") -public class PrintNodeEdges extends OsgiCommandSupport{ - private ITopologyManagerShell topologyManager; - - @Override - protected Object doExecute() throws Exception { - for(String p : topologyManager.printNodeEdges()) { - System.out.println(p); - } - return null; - } - - public void setTopologyManager(ITopologyManagerShell topologyManager){ - this.topologyManager = topologyManager; - } -} diff --git a/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java b/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java deleted file mode 100644 index e0976b0cf2..0000000000 --- a/opendaylight/adsal/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java +++ /dev/null @@ -1,29 +0,0 @@ -/** -* Copyright (c) 2014 Inocybe Technologies, and others. All rights reserved. -* -* This program and the accompanying materials are made available under the -* terms of the Eclipse Public License v1.0 which accompanies this distribution, -* and is available at http://www.eclipse.org/legal/epl-v10.html -*/ -package org.opendaylight.controller.topologymanager.shell; - -import org.apache.karaf.shell.commands.Command; -import org.apache.karaf.shell.console.OsgiCommandSupport; -import org.opendaylight.controller.topologymanager.ITopologyManagerShell; - -@Command(scope = "topologymanager", name = "printUserLink", description="Prints user link") -public class PrintUserLink extends OsgiCommandSupport{ - private ITopologyManagerShell topologyManager; - - @Override - protected Object doExecute() throws Exception { - for(String p : topologyManager.printUserLink()) { - System.out.println(p); - } - return null; - } - - public void setTopologyManager(ITopologyManagerShell topologyManager){ - this.topologyManager = topologyManager; - } -} diff --git a/opendaylight/adsal/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/opendaylight/adsal/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml deleted file mode 100644 index 96b0b10f10..0000000000 --- a/opendaylight/adsal/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/usermanager/api/pom.xml b/opendaylight/adsal/usermanager/api/pom.xml deleted file mode 100644 index a1dcca44ac..0000000000 --- a/opendaylight/adsal/usermanager/api/pom.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - usermanager - 0.6.0-SNAPSHOT - bundle - - - equinoxSDK381 - javax.servlet - - - junit - junit - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - sal - - - - org.springframework.security - spring-security-core - - - org.springframework.security - spring-security-web - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.configuration, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.utils, - org.slf4j, - org.eclipse.osgi.framework.console, - org.osgi.framework, - org.apache.felix.dm, - org.apache.commons.logging, - javax.servlet, - javax.servlet.http, - org.springframework.security.web.context, - org.springframework.security.core, - org.springframework.security.core.context, - org.springframework.security.authentication, - org.springframework.security.core.authority, - org.springframework.security.core.userdetails, - javax.xml.bind.annotation - org.opendaylight.controller.usermanager, - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthResponse.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthResponse.java deleted file mode 100644 index 062c3585be..0000000000 --- a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthResponse.java +++ /dev/null @@ -1,69 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -import java.io.Serializable; -import java.util.LinkedList; -import java.util.List; - -import org.opendaylight.controller.sal.authorization.AuthResultEnum; - -/** - * The class describes AAA response status and payload data - */ -public class AuthResponse implements Serializable { - private static final long serialVersionUID = 1L; - private List data; - private AuthResultEnum status; - private AuthResultEnum authorStatus; - - public AuthResponse() { - this.data = new LinkedList(); - this.status = AuthResultEnum.AUTH_NONE; - this.authorStatus = AuthResultEnum.AUTH_NONE; - } - - public void setData(List data) { - this.data = data; - } - - public void addData(String data) { - this.data.add(data); - } - - public List getData() { - return data; - } - - public void setStatus(AuthResultEnum status) { - this.status = status; - } - - public AuthResultEnum getStatus() { - return status; - } - - public void setAuthorizationStatus(AuthResultEnum authorStatus) { - this.authorStatus = authorStatus; - } - - public AuthResultEnum getAuthorizationStatus() { - return authorStatus; - } - - public String toString() { - return ("\nReceived messages: " + data.toString() + "\nStatus: " + status); - } - - public void resetData(String rolesData) { - // TODO Auto-generated method stub - - } -} \ No newline at end of file diff --git a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthenticatedUser.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthenticatedUser.java deleted file mode 100644 index 809ca134f7..0000000000 --- a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthenticatedUser.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; - -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; - -/** - * Represents a user that was successfully authenticated and authorized - * It contains the user role for which the user was authorized and the - * date on which it was authenticated and authorized - */ -public class AuthenticatedUser implements Serializable { - private static final long serialVersionUID = 1L; - private List userRoles; - private Date accessDate; - - public AuthenticatedUser(String name) { - userRoles = null; - accessDate = new Date(); - } - - public void setRoleList(List roleList) { - this.userRoles = roleList; - } - - public void setRoleList(String[] roleArray) { - userRoles = new ArrayList(roleArray.length); - for (String role : roleArray) { - String target = role.trim(); - if (!target.isEmpty()) { - userRoles.add(target); - } - } - } - - public List getUserRoles() { - return userRoles == null ? Collections. emptyList() : new ArrayList(userRoles); - } - - public void addUserRole(String string) { - userRoles.add(string); - } - - public String getAccessDate() { - return accessDate.toString(); - } - - public List getGrantedAuthorities(UserLevel usrLvl) { - List roles = new ArrayList(); - roles.add(new SimpleGrantedAuthority(new ODLUserLevel(usrLvl) - .getAuthority())); - return roles; - } - -} diff --git a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthorizationConfig.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthorizationConfig.java deleted file mode 100644 index a484943380..0000000000 --- a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/AuthorizationConfig.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -import java.util.ArrayList; -import java.util.List; - -import org.opendaylight.controller.sal.utils.Status; - -/** - * Configuration Java Object which represents a Local configured Authorization - * for a remote authenticated user for User Manager. - */ -public class AuthorizationConfig extends UserConfig { - private static final long serialVersionUID = 1L; - - public AuthorizationConfig() { - super(); - } - - // Constructor may be needed for autocontainer logic - public AuthorizationConfig(String user, List roles) { - super(); - this.user = user; - this.roles = (roles == null) ? new ArrayList() - : new ArrayList(roles); - } - - @Override - public Status validate() { - Status status = validateUsername(); - if (status.isSuccess()) { - status = validateRoles(); - } - return status; - } - - @Override - public String toString() { - return "AuthorizationConfig=[user: " + user + ", roles: " + roles + "]"; - } - - @Override - public String getRolesString() { - return super.getRolesString(); - } - -} diff --git a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java deleted file mode 100644 index 36a2c06bf6..0000000000 --- a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IAAAProvider.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -/** - * IAAAProvider exposes a pluggable interface for 3rd party Authentication and - * Authorization providers to support the UserManager with AAA management. - */ - -public interface IAAAProvider { - - /** - * Authenticate user with AAA server and return authentication and - * authorization info using the Provider's mechanism - * - * @param userName - * the username - * @param password - * the password - * @param server - * AAA server ip address in string form - * @param secretKey - * shared secret between the AAA client and AAA server - * @return {@link org.opendaylight.controller.usermanager.AuthResponse} - * Authentication and Authorization Response - */ - public AuthResponse authService(String userName, String password, - String server, String secretKey); - - /** - * Returns the Name of the Provider - * - * @return Name of the AAA provider - */ - public String getName(); -} diff --git a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java deleted file mode 100644 index 372462eaae..0000000000 --- a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ISessionManager.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -import javax.servlet.http.HttpSessionListener; - -/** - * - * This interface defines method(s) to invalidate a session. - */ -public interface ISessionManager extends HttpSessionListener { - - /** - * Invalidates the session for a given user and a session Id - * - * @param username - * the username - * @param sessionId - * the session Id - */ - public void invalidateSessions(String username, String sessionId); - -} diff --git a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java deleted file mode 100644 index aaf5cbd7cf..0000000000 --- a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/IUserManager.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.opendaylight.controller.sal.authorization.AuthResultEnum; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.utils.Status; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.web.context.SecurityContextRepository; - -/** - * The Interface which describes the methods exposed by User Manager. - */ -public interface IUserManager extends UserDetailsService { - - /** - * Returns the list of roles associated to the passed user name - * - * @param userName - * @return the role associated to the user name - */ - public List getUserRoles(String userName); - - /** - * Authenticate user with AAA server and return authentication and - * authorization info - * - * @param username - * the username - * @param password - * the password - * @return {@link org.opendaylight.controller.sal.authorization.AuthResultEnum} - * authentication result - */ - public AuthResultEnum authenticate(String username, String password); - - /** - * Add/remove AAA server - * - * @param configObject - * {@link org.opendaylight.controller.usermanager.internal.ServerConfig} - * Server Configuration - * @return {@link org.opendaylight.controller.sal.utils.Status} - * status of this action - */ - public Status addAAAServer(ServerConfig configObject); - - /** - * Remove AAA server - * - * @param configObject - * refer to - * {@link org.opendaylight.controller.usermanager.internal.ServerConfig} - * Server Configuration - * @return {@link org.opendaylight.controller.sal.utils.Status} - * status of this action - */ - public Status removeAAAServer(ServerConfig configObject); - - /** - * Add a local user - * - * @param configObject - * {@link org.opendaylight.controller.usermanager.internal.UserConfig} - * User Configuration - * @return refer to {@link org.opendaylight.controller.sal.utils.Status} - * status code - */ - public Status addLocalUser(UserConfig configObject); - - /** - * Modify a local user - * - * @param configObject - * {@link org.opendaylight.controller.usermanager.internal.UserConfig} - * The new User Configuration - * @return refer to {@link org.opendaylight.controller.sal.utils.Status} - * status code - */ - public Status modifyLocalUser(UserConfig configObject); - - /** - * Remove a local user - * - * @param configObject - * {@link org.opendaylight.controller.usermanager.internal.UserConfig} - * UserConfig - * @return {@link org.opendaylight.controller.sal.utils.Status} - * status of this action - */ - public Status removeLocalUser(UserConfig configObject); - - /** - * Remove a local user - * - * @param userName - * the user name - * @return {@link org.opendaylight.controller.sal.utils.Status} - * status of this action - */ - public Status removeLocalUser(String userName); - - /** - * Add the authorization information for a user that gets authenticated - * remotely - * - * @param AAAconf - * {@link org.opendaylight.controller.usermanager.internal.AuthorizationConfig} - * Authorization Resources - * @return {@link org.opendaylight.controller.sal.utils.Status} - * status of this action - */ - public Status addAuthInfo(AuthorizationConfig AAAconf); - - /** - * Remove the authorization information for a user that gets authenticated - * remotely - * - * @param AAAconf - * {@link org.opendaylight.controller.usermanager.internal.AuthorizationConfig} - * Authorization Resource - * @return {@link org.opendaylight.controller.sal.utils.Status} - * status of this action - */ - public Status removeAuthInfo(AuthorizationConfig AAAconf); - - /** - * Return the list of authorization resources - * - * @return {@link org.opendaylight.controller.usermanager.internal.AuthorizationConfig} - * List of Authorization Resource - */ - public List getAuthorizationList(); - - /** - * Returns a list of AAA Providers. - * - * @return Set of provider names. - */ - public Set getAAAProviderNames(); - - /** - * Change the current password for a locally configured user - * - * @param user - * the username - * @param curPasssword - * the current password - * @param newPassword - * the new password - * @return {@link org.opendaylight.controller.sal.utils.Status} - * status of this action - */ - public Status changeLocalUserPassword(String user, String curPassword, - String newPassword); - - /** - * Return a list of AAA servers currently configured - * - * @return {@link org.opendaylight.controller.usermanager.internal.ServerConfig} - * List of ServerConfig - */ - public List getAAAServerList(); - - /** - * Return a list of local users - * - * @return {@link org.opendaylight.controller.usermanager.internal.UserConfig} - * List of UserConfig - */ - public List getLocalUserList(); - - /** - * Save the local users to disk - * - * @return {@link org.opendaylight.controller.sal.utils.Status} - * status of this action - */ - public Status saveLocalUserList(); - - /** - * Save the AAA server configurations to disk - * - * @return {@link org.opendaylight.controller.sal.utils.Status} - * status of this action - */ - public Status saveAAAServerList(); - - /** - * Save the Authorization configurations to disk - * - * @return {@link org.opendaylight.controller.sal.utils.Status} - * status code - */ - public Status saveAuthorizationList(); - - /** - * Remove user profile when user logs out - * - * @param username - * the user name - */ - public void userLogout(String username); - - /** - * Remove user profile when user times out - * - * @param username - * the user name - */ - public void userTimedOut(String username); - - /** - * Get the list of users currently logged in - * - * @return the list of users along with their administrative roles - */ - public Map> getUserLoggedIn(); - - /** - * Get date and time user was successfully authenticated - * - * @param user - * @return Date in String format - */ - public String getAccessDate(String user); - - /** - * Returns the highest user level for the passed user name. It checks the roles - * assigned to this user and checks against the well known Controller user - * roles to determines the highest user level associated with the user - * - * @param userName - * the user name - * @return {@link org.opendaylight.controller.sal.authorization.UserLevel} - * the highest user level for this user - */ - public UserLevel getUserLevel(String userName); - - /** - * Returns the list of user level for the passed user name. It checks the roles - * assigned to this user and checks against the well known Controller user - * roles to determines the corresponding list of user level associated with the user - * - * @param userName - * the user name - * @return - * the list of user level for this user - */ - public List getUserLevels(String userName); - - /** - * Returns the Security Context - * - * @returns {@link org.springframework.security.web.context.SecurityContextRepository} - * Security Context - */ - public SecurityContextRepository getSecurityContextRepo(); - - /** - * Returns the Session Manager Interface Handler - * - * @return {@link org.opendaylight.controller.usermanager.ISessionManager} - * session manager interface handler - */ - public ISessionManager getSessionManager(); - - /** - * Checks if the specified role belongs to any application. Usually an - * application will call this function when configuring a role, to check if - * that role is already being used by another application. - * - * @param role - * The role to check - * @return true if the specified role belongs to any application or if the - * role is a well-known controller role, false otherwise. - */ - public boolean isRoleInUse(String role); - - /* non-Javadoc - * Returns the password for a given user - * - * @param username - * the user name - * @return password for the username - */ - public String getPassword(String username); - -} diff --git a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java deleted file mode 100644 index 045002e6a7..0000000000 --- a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ODLUserLevel.java +++ /dev/null @@ -1,30 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -import java.util.Locale; - -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.springframework.security.core.GrantedAuthority; - -public class ODLUserLevel implements GrantedAuthority { - private static final long serialVersionUID = 1L; - UserLevel userLevel; - - public ODLUserLevel(UserLevel userLevel) { - this.userLevel = userLevel; - } - - @Override - public String getAuthority() { - return "ROLE_" + this.userLevel.toString().toUpperCase(Locale.ENGLISH); - } - -} diff --git a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ServerConfig.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ServerConfig.java deleted file mode 100644 index 3145f2095f..0000000000 --- a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/ServerConfig.java +++ /dev/null @@ -1,100 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -import java.io.Serializable; - -import org.opendaylight.controller.configuration.ConfigurationObject; - -/** - * Configuration Java Object which represents a Remote AAA server configuration - * information for User Manager. - */ -public class ServerConfig extends ConfigurationObject implements Serializable { - private static final long serialVersionUID = 1L; - - // Order matters: JSP file expects following fields in the following order - private String ip; - private String secret; - private String protocol; - - public ServerConfig() { - } - - public ServerConfig(String ip, String secret, String protocol) { - this.ip = ip; - this.secret = secret; - this.protocol = protocol; - } - - public String getAddress() { - return ip; - } - - public String getSecret() { - return secret; - } - - public String getProtocol() { - return protocol; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((ip == null) ? 0 : ip.hashCode()); - result = prime * result - + ((protocol == null) ? 0 : protocol.hashCode()); - result = prime * result + ((secret == null) ? 0 : secret.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - ServerConfig other = (ServerConfig) obj; - if (ip == null) { - if (other.ip != null) { - return false; - } - } else if (!ip.equals(other.ip)) { - return false; - } - if (protocol == null) { - if (other.protocol != null) { - return false; - } - } else if (!protocol.equals(other.protocol)) { - return false; - } - if (secret == null) { - if (other.secret != null) { - return false; - } - } else if (!secret.equals(other.secret)) { - return false; - } - return true; - } - - public boolean isValid() { - return (ip != null && !ip.isEmpty() && secret != null && !secret - .isEmpty()); - } -} diff --git a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/UserConfig.java b/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/UserConfig.java deleted file mode 100644 index 8298f5b76a..0000000000 --- a/opendaylight/adsal/usermanager/api/src/main/java/org/opendaylight/controller/usermanager/UserConfig.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -import java.io.Serializable; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.sal.authorization.AuthResultEnum; -import org.opendaylight.controller.sal.packet.BitBufferHelper; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Configuration Java Object which represents a Local AAA user configuration - * information for User Manager. - */ -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class UserConfig extends ConfigurationObject implements Serializable { - private static final long serialVersionUID = 1L; - private static Logger log = LoggerFactory.getLogger(UserConfig.class); - private static final boolean strongPasswordCheck = Boolean.getBoolean("enableStrongPasswordCheck"); - private static final String DIGEST_ALGORITHM = "SHA-384"; - private static final String BAD_PASSWORD = "Bad Password"; - private static final int USERNAME_MAXLENGTH = 32; - protected static final String PASSWORD_REGEX = "(?=.*[^a-zA-Z0-9])(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,256}$"; - private static final Pattern INVALID_USERNAME_CHARACTERS = Pattern.compile("([/\\s\\.\\?#%;\\\\]+)"); - private static MessageDigest oneWayFunction; - private static SecureRandom randomGenerator; - - static { - try { - UserConfig.oneWayFunction = MessageDigest.getInstance(DIGEST_ALGORITHM); - } catch (NoSuchAlgorithmException e) { - log.error(String.format("Implementation of %s digest algorithm not found: %s", DIGEST_ALGORITHM, - e.getMessage())); - } - UserConfig.randomGenerator = new SecureRandom(BitBufferHelper.toByteArray(System.currentTimeMillis())); - } - - /** - * User Id - */ - @XmlElement - protected String user; - - /** - * List of roles a user can have - * example - * System-Admin - * Network-Admin - * Network-Operator - */ - @XmlElement - protected List roles; - - /** - * Password - * Should be 8 to 256 characters long, - * contain both upper and lower case letters, at least one number, - * and at least one non alphanumeric character. - */ - @XmlElement - private String password; - - private byte[] salt; - - - - public UserConfig() { - } - - /** - * Construct a UserConfig object and takes care of hashing the user password - * - * @param user - * the user name - * @param password - * the plain text password - * @param roles - * the list of roles - */ - public UserConfig(String user, String password, List roles) { - this.user = user; - - /* - * Password validation to be done on clear text password. If fails, mark - * the password with a well known label, so that object validation can - * report the proper error. Only if password is a valid one, generate - * salt, concatenate it with clear text password and hash the - * resulting string. Hash result is going to be our stored password. - */ - if (validateClearTextPassword(password).isSuccess()) { - this.salt = BitBufferHelper.toByteArray(randomGenerator.nextLong()); - this.password = hash(salt, password); - } else { - this.salt = null; - this.password = BAD_PASSWORD; - } - - this.roles = (roles == null) ? Collections.emptyList() : new ArrayList(roles); - } - - public String getUser() { - return user; - } - - public String getPassword() { - return password; - } - - public List getRoles() { - return new ArrayList(roles); - } - - public byte[] getSalt() { - return (salt == null) ? null : salt.clone(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((password == null) ? 0 : password.hashCode()); - result = prime * result + ((roles == null) ? 0 : roles.hashCode()); - result = prime * result + ((user == null) ? 0 : user.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - UserConfig other = (UserConfig) obj; - if (password == null) { - if (other.password != null) { - return false; - } - } else if (!password.equals(other.password)) { - return false; - } - if (roles == null) { - if (other.roles != null) { - return false; - } - } else if (!roles.equals(other.roles)) { - return false; - } - if (user == null) { - if (other.user != null) { - return false; - } - } else if (!user.equals(other.user)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "UserConfig[user=" + user + ", password=" + password + ", roles=" + roles +"]"; - } - - public Status validate() { - Status validCheck = validateUsername(); - if (validCheck.isSuccess()) { - // Password validation was run at object construction time - validCheck = (!password.equals(BAD_PASSWORD)) ? new Status(StatusCode.SUCCESS) : new Status( - StatusCode.BADREQUEST, - "Password should be 8 to 256 characters long, contain both upper and lower case letters, " - + "at least one number and at least one non alphanumeric character"); - } - if (validCheck.isSuccess()) { - validCheck = validateRoles(); - } - return validCheck; - } - - protected Status validateUsername() { - if (user == null || user.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Username cannot be empty"); - } - - Matcher mUser = UserConfig.INVALID_USERNAME_CHARACTERS.matcher(user); - if (user.length() > UserConfig.USERNAME_MAXLENGTH || mUser.find() == true) { - return new Status(StatusCode.BADREQUEST, - "Username can have 1-32 non-whitespace " - + "alphanumeric characters and any special " - + "characters except ./#%;?\\"); - } - - return new Status(StatusCode.SUCCESS); - } - - public static Status validateClearTextPassword(String password) { - if (password == null || password.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Password cannot be empty"); - } - - if (strongPasswordCheck && !password.matches(UserConfig.PASSWORD_REGEX)) { - return new Status(StatusCode.BADREQUEST, "Password should be 8 to 256 characters long, " - + "contain both upper and lower case letters, at least one number " - + "and at least one non alphanumeric character"); - } - return new Status(StatusCode.SUCCESS); - } - - protected Status validateRoles() { - if (roles == null || roles.isEmpty()) { - return new Status(StatusCode.BADREQUEST, "No role specified"); - } - return new Status(StatusCode.SUCCESS); - } - - public Status update(String currentPassword, String newPassword, List newRoles) { - - // To make any changes to a user configured profile, current password - // must always be provided - if (!isPasswordMatch(currentPassword)) { - return new Status(StatusCode.BADREQUEST, "Current password is incorrect"); - } - - // Create a new object with the proposed modifications - UserConfig proposed = new UserConfig(); - proposed.user = this.user; - proposed.password = (newPassword == null)? this.password : hash(this.salt, newPassword); - proposed.roles = (newRoles == null)? this.roles : newRoles; - - // Validate it - Status status = proposed.validate(); - if (!status.isSuccess()) { - return status; - } - - // Accept the modifications - this.user = proposed.user; - this.password = proposed.password; - this.roles = new ArrayList(proposed.roles); - - return status; - } - - public boolean isPasswordMatch(String otherPass) { - return this.password.equals(hash(this.salt, otherPass)); - } - - public AuthResponse authenticate(String clearTextPassword) { - AuthResponse locResponse = new AuthResponse(); - if (isPasswordMatch(clearTextPassword)) { - locResponse.setStatus(AuthResultEnum.AUTH_ACCEPT_LOC); - locResponse.addData(getRolesString()); - } else { - locResponse.setStatus(AuthResultEnum.AUTH_REJECT_LOC); - } - return locResponse; - } - - protected String getRolesString() { - StringBuffer buffer = new StringBuffer(); - if (!roles.isEmpty()) { - Iterator iter = roles.iterator(); - buffer.append(iter.next()); - while (iter.hasNext()) { - buffer.append(" "); - buffer.append(iter.next()); - } - } - return buffer.toString(); - } - - private static byte[] concatenate(byte[] salt, String password) { - byte[] messageArray = password.getBytes(); - byte[] concatenation = new byte[salt.length + password.length()]; - System.arraycopy(salt, 0, concatenation, 0, salt.length); - System.arraycopy(messageArray, 0, concatenation, salt.length, messageArray.length); - return concatenation; - } - - private static String hash(byte[] salt, String message) { - if (message == null) { - log.warn("Password hash requested but empty or no password provided"); - return message; - } - if (salt == null || salt.length == 0) { - log.warn("Password hash requested but empty or no salt provided"); - return message; - } - - // Concatenate salt and password - byte[] messageArray = message.getBytes(); - byte[] concatenation = new byte[salt.length + message.length()]; - System.arraycopy(salt, 0, concatenation, 0, salt.length); - System.arraycopy(messageArray, 0, concatenation, salt.length, messageArray.length); - - UserConfig.oneWayFunction.reset(); - return HexEncode.bytesToHexString(UserConfig.oneWayFunction.digest(concatenate(salt, message))); - } - - /** - * Returns UserConfig instance populated with the passed parameters. It does - * not run any checks on the passed parameters. - * - * @param userName - * the user name - * @param password - * the plain text password - * @param roles - * the list of roles - * @return the UserConfig object populated with the passed parameters. No - * validity check is run on the input parameters. - */ - public static UserConfig getUncheckedUserConfig(String userName, String password, List roles) { - UserConfig config = new UserConfig(); - config.user = userName; - config.salt = BitBufferHelper.toByteArray(randomGenerator.nextLong()); - config.password = hash(config.salt, password); - config.roles = roles; - return config; - } -} diff --git a/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthResponseTest.java b/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthResponseTest.java deleted file mode 100644 index af68be6cef..0000000000 --- a/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthResponseTest.java +++ /dev/null @@ -1,14 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -public class AuthResponseTest{ - -} \ No newline at end of file diff --git a/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthenticatedUserTest.java b/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthenticatedUserTest.java deleted file mode 100644 index d32799e3eb..0000000000 --- a/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthenticatedUserTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager; - -import java.util.Arrays; -import java.util.List; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.springframework.security.core.GrantedAuthority; - -public class AuthenticatedUserTest { - - static String[] roleArray; - static AuthenticatedUser user; - - @BeforeClass - public static void testSetup() { - roleArray = new String[] { UserLevel.NETWORKOPERATOR.toString(), - UserLevel.APPUSER.toString() }; - } - - @Test - public void testAuthenticatedUser() { - user = new AuthenticatedUser("auser"); - - Assert.assertFalse(user.getAccessDate().isEmpty()); - Assert.assertNotNull(user.getUserRoles()); - } - - @Test - public void testSetUserRoleList() { - List retrievedRoleList = null; - List roleList = Arrays.asList(roleArray); - - // list arg - user = new AuthenticatedUser("auser"); - user.setRoleList(roleList); - retrievedRoleList = user.getUserRoles(); - Assert.assertTrue(roleList.equals(retrievedRoleList)); - - // array arg - user = new AuthenticatedUser("auser"); - user.setRoleList(roleArray); - retrievedRoleList = user.getUserRoles(); - for (int i = 0; i < roleArray.length; i++) - Assert.assertTrue(roleArray[i].equals(retrievedRoleList.get(i))); - - // test addUserRole - user.addUserRole("AnotherRole"); - Assert.assertTrue(user.getUserRoles().lastIndexOf("AnotherRole") != -1); - - } - - @Test - public void testGetGrantedAuthorities() { - user = new AuthenticatedUser("auser"); - List gaList = user - .getGrantedAuthorities(UserLevel.NETWORKOPERATOR); - Assert.assertTrue(gaList.get(0).getAuthority() - .equals("ROLE_NETWORK-OPERATOR")); - } - -} diff --git a/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthorizationUserConfigTest.java b/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthorizationUserConfigTest.java deleted file mode 100644 index 8fc7f07df1..0000000000 --- a/opendaylight/adsal/usermanager/api/src/test/java/org/opendaylight/controller/usermanager/AuthorizationUserConfigTest.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.usermanager; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; -import org.opendaylight.controller.sal.authorization.AuthResultEnum; -import org.opendaylight.controller.sal.authorization.UserLevel; -/* - * This test case includes tests for UserConfig and the extending class AuthorizationConfig - */ -public class AuthorizationUserConfigTest { - - @Test - public void authorizationConfigTest() { - AuthorizationConfig authConfig; - List roles = new ArrayList(); - - // test isValid - roles.add(UserLevel.SYSTEMADMIN.toString()); - authConfig = new AuthorizationConfig(null, roles); - assertFalse(authConfig.validate().isSuccess()); - authConfig = new AuthorizationConfig("admin", new ArrayList()); - assertFalse(authConfig.validate().isSuccess()); - authConfig = new AuthorizationConfig("admin", roles); - assertTrue(authConfig.validate().isSuccess()); - } - - @Test - public void userConfigTest() { - UserConfig userConfig; - List roles = new ArrayList(); - - roles.add(UserLevel.SYSTEMADMIN.toString()); - userConfig = new UserConfig(null, "cisco", roles); - assertFalse(userConfig.validate().isSuccess()); - - roles.clear(); - roles.add("cisco"); - userConfig = new UserConfig("uname", "", roles); - assertFalse(userConfig.validate().isSuccess()); - - roles.clear(); - roles.add(UserLevel.NETWORKOPERATOR.toString()); - userConfig = new UserConfig("uname", "ciscocisco", roles); - assertTrue(userConfig.validate().isSuccess()); - - // currentPassword mismatch - assertFalse(userConfig.update("Cisco", "cisco123", roles).isSuccess()); - - // Role change only - roles.clear(); - roles.add(UserLevel.NETWORKADMIN.toString()); - assertTrue(userConfig.update("ciscocisco", null, roles).isSuccess()); - - // Role change and same new password - roles.clear(); - roles.add(UserLevel.NETWORKOPERATOR.toString()); - assertTrue(userConfig.update("ciscocisco", "ciscocisco", roles) - .isSuccess()); - - // New Password = null, No change in password - assertTrue(userConfig.authenticate("ciscocisco").getStatus().equals(AuthResultEnum.AUTH_ACCEPT_LOC)); - - // Password changed successfully, no change in user role - assertTrue(userConfig.update("ciscocisco", "cisco123", roles) - .isSuccess()); - assertTrue(userConfig.authenticate("cisco123").getStatus().equals(AuthResultEnum.AUTH_ACCEPT_LOC)); - assertTrue(userConfig.getRoles().get(0).equals( - UserLevel.NETWORKOPERATOR.toString())); - - // Password not changed, role changed successfully - roles.clear(); - roles.add(UserLevel.SYSTEMADMIN.toString()); - assertTrue(userConfig.update("cisco123", "cisco123", roles) - .isSuccess()); - assertTrue(userConfig.authenticate("cisco123").getStatus().equals(AuthResultEnum.AUTH_ACCEPT_LOC)); - assertTrue(userConfig.getRoles().get(0) - .equals(UserLevel.SYSTEMADMIN.toString())); - - // Password and role changed successfully - assertTrue(userConfig.update("cisco123", "ciscocisco", roles) - .isSuccess()); - assertTrue(userConfig.authenticate("ciscocisco").getStatus().equals(AuthResultEnum.AUTH_ACCEPT_LOC)); - assertTrue(userConfig.getRoles().get(0) - .equals(UserLevel.SYSTEMADMIN.toString())); - - String username = userConfig.getUser(); - assertTrue(username.equals("uname")); - - // test authenticate - AuthResponse authresp = userConfig.authenticate("ciscocisco"); - assertTrue(authresp.getStatus().equals(AuthResultEnum.AUTH_ACCEPT_LOC)); - authresp = userConfig.authenticate("wrongPassword"); - assertTrue(authresp.getStatus().equals(AuthResultEnum.AUTH_REJECT_LOC)); - } - - @Test - public void userConfigPasswordTest() { - - String regex = UserConfig.PASSWORD_REGEX; - String password = null; - - // Good password - password = "aBc@eF#h9"; - assertTrue(password.matches(regex)); - password = "^aBc@eF#h9$88ad*o&"; - assertTrue(password.matches(regex)); - password = "_^aBc@\":eF#h;9$\\8|8ad*o&-(){}/,.> - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - usermanager.implementation - 0.6.0-SNAPSHOT - bundle - - - equinoxSDK381 - org.eclipse.osgi - - - junit - junit - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - usermanager - - - org.slf4j - jcl-over-slf4j - - - org.springframework.security - spring-security-web - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.configuration, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.packet, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.slf4j, - org.eclipse.osgi.framework.console, - org.osgi.framework, - org.apache.felix.dm, - org.apache.commons.lang3.builder, - org.apache.commons.logging, - javax.servlet, - javax.servlet.http, - org.springframework.security.web.context, - org.springframework.security.core, - org.springframework.security.core.context, - org.apache.commons.lang3, - org.springframework.security.authentication, - org.springframework.security.core.authority, - org.springframework.security.core.userdetails, - org.opendaylight.controller.usermanager - - - - org.opendaylight.controller.usermanager.internal.Activator - - ${project.basedir}/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/Activator.java b/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/Activator.java deleted file mode 100644 index 26e10a6b04..0000000000 --- a/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/Activator.java +++ /dev/null @@ -1,126 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager.internal; - -import org.apache.felix.dm.Component; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.configuration.IConfigurationAware; -import org.opendaylight.controller.configuration.IConfigurationService; -import org.opendaylight.controller.containermanager.IContainerAuthorization; -import org.opendaylight.controller.sal.authorization.IResourceAuthorization; -import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase; -import org.opendaylight.controller.usermanager.IAAAProvider; -import org.opendaylight.controller.usermanager.IUserManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * UserManager Bundle Activator - * - * - */ -public class Activator extends ComponentActivatorAbstractBase { - protected static final Logger logger = LoggerFactory - .getLogger(Activator.class); - - - /** - * Function that is used to communicate to dependency manager the - * list of known implementations for services inside a container - * - * - * @return An array containing all the CLASS objects that will be - * instantiated in order to get an fully working implementation - * Object - */ - @Override - public Object[] getImplementations() { - return new Object[]{}; - } - - /** - * Function that is called when configuration of the dependencies - * is required. - * - * @param c dependency manager Component object, used for - * configuring the dependencies exported and imported - * @param imp Implementation class that is being configured, - * needed as long as the same routine can configure multiple - * implementations - * @param containerName The containerName being configured, this allow - * also optional per-container different behavior if needed, usually - * should not be the case though. - */ - @Override - public void configureInstance(Component c, Object imp, String containerName) { - } - - /** - * Method which tells how many global implementations are - * supported by the bundle. This way we can tune the number of - * components created. This components will be created ONLY at the - * time of bundle startup and will be destroyed only at time of - * bundle destruction, this is the major difference with the - * implementation retrieved via getImplementations where all of - * them are assumed to be in a container ! - * - * - * @return The list of implementations the bundle will support, - * in Global version - */ - @Override - protected Object[] getGlobalImplementations() { - Object[] res = { UserManager.class }; - return res; - } - - /** - * Configure the dependency for a given instance Global - * - * @param c Component assigned for this instance, this will be - * what will be used for configuration - * @param imp implementation to be configured - * @param containerName container on which the configuration happens - */ - @Override - protected void configureGlobalInstance(Component c, Object imp) { - if (imp.equals(UserManager.class)) { - - // export the service - c.setInterface(new String[] { - IUserManager.class.getName(), - IConfigurationAware.class.getName() }, null); - - c.add(createServiceDependency().setService( - IClusterGlobalServices.class).setCallbacks( - "setClusterGlobalService", "unsetClusterGlobalService") - .setRequired(true)); - - c.add(createServiceDependency().setService( - IConfigurationService.class).setCallbacks( - "setConfigurationService", - "unsetConfigurationService").setRequired(true)); - - c.add(createServiceDependency().setService(IAAAProvider.class) - .setCallbacks("addAAAProvider", "removeAAAProvider") - .setRequired(false)); - - c.add(createServiceDependency().setService( - IContainerAuthorization.class).setCallbacks( - "setContainerAuthClient", "unsetContainerAuthClient") - .setRequired(false)); - - c.add(createServiceDependency().setService( - IResourceAuthorization.class).setCallbacks( - "setAppAuthClient", "unsetAppAuthClient") - .setRequired(false)); - } - } -} diff --git a/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/UserManager.java b/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/UserManager.java deleted file mode 100644 index e7394f9262..0000000000 --- a/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/internal/UserManager.java +++ /dev/null @@ -1,1192 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager.internal; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.apache.commons.lang3.StringUtils; -import org.eclipse.osgi.framework.console.CommandInterpreter; -import org.eclipse.osgi.framework.console.CommandProvider; -import org.opendaylight.controller.clustering.services.CacheConfigException; -import org.opendaylight.controller.clustering.services.CacheExistException; -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.clustering.services.IClusterServices; -import org.opendaylight.controller.configuration.ConfigurationObject; -import org.opendaylight.controller.configuration.IConfigurationAware; -import org.opendaylight.controller.configuration.IConfigurationService; -import org.opendaylight.controller.containermanager.IContainerAuthorization; -import org.opendaylight.controller.sal.authorization.AuthResultEnum; -import org.opendaylight.controller.sal.authorization.IResourceAuthorization; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.utils.IObjectReader; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.usermanager.AuthResponse; -import org.opendaylight.controller.usermanager.AuthenticatedUser; -import org.opendaylight.controller.usermanager.AuthorizationConfig; -import org.opendaylight.controller.usermanager.IAAAProvider; -import org.opendaylight.controller.usermanager.ISessionManager; -import org.opendaylight.controller.usermanager.IUserManager; -import org.opendaylight.controller.usermanager.ServerConfig; -import org.opendaylight.controller.usermanager.UserConfig; -import org.opendaylight.controller.usermanager.security.SessionManager; -import org.opendaylight.controller.usermanager.security.UserSecurityContextRepository; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.FrameworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.AuthenticationServiceException; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.web.context.SecurityContextRepository; - -/** - * The internal implementation of the User Manager. - */ -public class UserManager implements IUserManager, IObjectReader, - IConfigurationAware, CommandProvider, AuthenticationProvider { - private static final Logger logger = LoggerFactory.getLogger(UserManager.class); - private static final String DEFAULT_ADMIN = "admin"; - private static final String DEFAULT_ADMIN_PASSWORD = "admin"; - private static final String DEFAULT_ADMIN_ROLE = UserLevel.NETWORKADMIN.toString(); - private static final String USERS_FILE_NAME = "users.conf"; - private static final String SERVERS_FILE_NAME = "servers.conf"; - private static final String AUTH_FILE_NAME = "authorization.conf"; - private static final String RECOVERY_FILE = "NETWORK_ADMIN_PASSWORD_RECOVERY"; - private static final boolean DISALLOW_DEFAULT_ADMIN_PASSWORD = - Boolean.getBoolean("usermanager.disable-default-admin-password"); - private ConcurrentMap localUserConfigList; - private ConcurrentMap remoteServerConfigList; - // local authorization info for remotely authenticated users - private ConcurrentMap authorizationConfList; - private ConcurrentMap activeUsers; - private ConcurrentMap authProviders; - private IClusterGlobalServices clusterGlobalService = null; - private IConfigurationService configurationService; - private SecurityContextRepository securityContextRepo = new UserSecurityContextRepository(); - private IContainerAuthorization containerAuthorizationClient; - private Set applicationAuthorizationClients; - private ISessionManager sessionMgr = new SessionManager(); - protected enum Command { - ADD("add", "added"), - MODIFY("modify", "modified"), - REMOVE("remove", "removed"); - private final String action; - private final String postAction; - private Command(String action, String postAction) { - this.action = action; - this.postAction = postAction; - } - - public String getAction() { - return action; - } - - public String getPostAction() { - return postAction; - } - } - - public boolean addAAAProvider(IAAAProvider provider) { - if (provider == null || provider.getName() == null - || provider.getName().trim().isEmpty()) { - return false; - } - if (authProviders.get(provider.getName()) != null) { - return false; - } - - authProviders.put(provider.getName(), provider); - return true; - } - - public void removeAAAProvider(IAAAProvider provider) { - authProviders.remove(provider.getName()); - } - - public IAAAProvider getAAAProvider(String name) { - return authProviders.get(name); - } - - @Override - public Set getAAAProviderNames() { - return authProviders.keySet(); - } - - private void allocateCaches() { - this.applicationAuthorizationClients = Collections.synchronizedSet(new HashSet()); - if (clusterGlobalService == null) { - logger.error("un-initialized clusterGlobalService, can't create cache"); - return; - } - - try { - clusterGlobalService.createCache("usermanager.localUserConfigList", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterGlobalService.createCache( - "usermanager.remoteServerConfigList", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterGlobalService.createCache( - "usermanager.authorizationConfList", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - - clusterGlobalService.createCache("usermanager.activeUsers", - EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL)); - } catch (CacheConfigException cce) { - logger.error("Cache configuration invalid - check cache mode"); - } catch (CacheExistException ce) { - logger.debug("Skipping cache creation as already present"); - } - } - - @SuppressWarnings({ "unchecked" }) - private void retrieveCaches() { - if (clusterGlobalService == null) { - logger.error("un-initialized clusterService, can't retrieve cache"); - return; - } - - activeUsers = (ConcurrentMap) clusterGlobalService - .getCache("usermanager.activeUsers"); - if (activeUsers == null) { - logger.error("Failed to get cache for activeUsers"); - } - - localUserConfigList = (ConcurrentMap) clusterGlobalService - .getCache("usermanager.localUserConfigList"); - if (localUserConfigList == null) { - logger.error("Failed to get cache for localUserConfigList"); - } - - remoteServerConfigList = (ConcurrentMap) clusterGlobalService - .getCache("usermanager.remoteServerConfigList"); - if (remoteServerConfigList == null) { - logger.error("Failed to get cache for remoteServerConfigList"); - } - - authorizationConfList = (ConcurrentMap) clusterGlobalService - .getCache("usermanager.authorizationConfList"); - if (authorizationConfList == null) { - logger.error("Failed to get cache for authorizationConfList"); - } - } - - private void loadConfigurations() { - // To encode and decode user and server configuration objects - loadSecurityKeys(); - /* - * Do not load local startup file if we are not the coordinator - */ - loadUserConfig(); - loadServerConfig(); - loadAuthConfig(); - } - - private void loadSecurityKeys() { - - } - - private void checkDefaultNetworkAdmin(String newPass) { - boolean usingFactoryPassword = false; - // network admin already configured. - if (localUserConfigList.containsKey(DEFAULT_ADMIN)) { - UserConfig uc = localUserConfigList.get(DEFAULT_ADMIN); - if (!uc.isPasswordMatch(DEFAULT_ADMIN_PASSWORD)) { - return; - } else { - usingFactoryPassword = true; - } - } - - List defaultRoles = new ArrayList(1); - defaultRoles.add(DEFAULT_ADMIN_ROLE); - if (newPass == null) { - if (!localUserConfigList.containsKey(DEFAULT_ADMIN)) { - // Need to skip the strong password check for the default admin - UserConfig defaultAdmin = UserConfig.getUncheckedUserConfig( - UserManager.DEFAULT_ADMIN, UserManager.DEFAULT_ADMIN_PASSWORD, - defaultRoles); - localUserConfigList.put(UserManager.DEFAULT_ADMIN, defaultAdmin); - usingFactoryPassword = true; - } - } else { - // use new password for admin - Status status = UserConfig.validateClearTextPassword(newPass); - if (status.isSuccess()) { - localUserConfigList.put(UserManager.DEFAULT_ADMIN, - new UserConfig(UserManager.DEFAULT_ADMIN, newPass, defaultRoles)); - logger.trace("Network Adminstrator password is reset."); - if (newPass.equals(DEFAULT_ADMIN_PASSWORD)) { - usingFactoryPassword = true; - } - } else { - logger.warn("Password is invalid - {}. Network Adminstrator password " + - "cannot be set.", status.getDescription()); - } - } - - if (usingFactoryPassword) { - if (DISALLOW_DEFAULT_ADMIN_PASSWORD) { - logger.warn("Network Administrator factory default password " + - "is disallowed. Please set the password prior to starting " + - "the controller. Shutting down now."); - // shutdown osgi - try { - BundleContext bundleContext = FrameworkUtil.getBundle( - getClass()).getBundleContext(); - bundleContext.getBundle(0).stop(); - } catch (BundleException e) { - logger.warn("Cannot stop framework ", e); - } - } else { - logger.warn("Network Administrator password is set to factory default. " + - "Please change the password as soon as possible."); - } - } - } - - private String checkPasswordRecovery() { - final String fileDescription = "Default Network Administrator password recovery file"; - File recoveryFile = new File(UserManager.RECOVERY_FILE); - if (!recoveryFile.exists()) { - return null; - } - // read the recovery file - String pwd = null; - try { - BufferedReader reader = new BufferedReader(new FileReader(recoveryFile)); - // read password from recovery file if it has one - pwd = reader.readLine(); - if (pwd != null && pwd.trim().length() == 0) { - pwd = null; - } - reader.close(); - /* - * Recovery file detected, remove current default network - * administrator entry from local users configuration list. - * Warn user and delete recovery file. - */ - this.localUserConfigList.remove(UserManager.DEFAULT_ADMIN); - if (!recoveryFile.delete()) { - logger.warn("Failed to delete {}", fileDescription); - } else { - logger.trace("{} deleted", fileDescription); - } - } catch (IOException e) { - logger.warn("Failed to process file {}", fileDescription); - } - return pwd; - } - - @Override - public AuthResultEnum authenticate(String userName, String password) { - IAAAProvider aaaClient; - AuthResponse rcResponse = null; - AuthenticatedUser result; - boolean remotelyAuthenticated = false; - boolean authorizationInfoIsPresent = false; - boolean authorized = false; - - /* - * Attempt remote authentication first if server is configured - */ - for (ServerConfig aaaServer : remoteServerConfigList.values()) { - String protocol = aaaServer.getProtocol(); - aaaClient = this.getAAAProvider(protocol); - if (aaaClient != null) { - rcResponse = aaaClient.authService(userName, password, - aaaServer.getAddress(), aaaServer.getSecret()); - if (rcResponse.getStatus() == AuthResultEnum.AUTH_ACCEPT) { - logger.trace( - "Remote Authentication Succeeded for User: \"{}\", by Server: {}", - userName, aaaServer.getAddress()); - remotelyAuthenticated = true; - break; - } else if (rcResponse.getStatus() == AuthResultEnum.AUTH_REJECT) { - logger.trace( - "Remote Authentication Rejected User: \"{}\", from Server: {}, Reason:{}", - new Object[] { userName, aaaServer.getAddress(), - rcResponse.getStatus().toString() }); - } else { - logger.trace( - "Remote Authentication Failed for User: \"{}\", from Server: {}, Reason:{}", - new Object[] { userName, aaaServer.getAddress(), - rcResponse.getStatus().toString() }); - } - } - } - - if (!remotelyAuthenticated) { - UserConfig localUser = this.localUserConfigList.get(userName); - if (localUser == null) { - logger.trace( - "Local Authentication Failed for User:\"{}\", Reason: " - + "user not found in Local Database", userName); - return (AuthResultEnum.AUTH_INVALID_LOC_USER); - } - rcResponse = localUser.authenticate(password); - if (rcResponse.getStatus() != AuthResultEnum.AUTH_ACCEPT_LOC) { - logger.trace( - "Local Authentication Failed for User: \"{}\", Reason: {}", - userName, rcResponse.getStatus().toString()); - - return (rcResponse.getStatus()); - } - logger.trace("Local Authentication Succeeded for User: \"{}\"", - userName); - } - - /* - * Authentication succeeded - */ - result = new AuthenticatedUser(userName); - - /* - * Extract attributes from response All the information we are - * interested in is in the first Cisco VSA (vendor specific attribute). - * Just process the first VSA and return - */ - String attributes = (rcResponse.getData() != null && !rcResponse - .getData().isEmpty()) ? rcResponse.getData().get(0) : null; - - /* - * Check if the authorization information is present - */ - authorizationInfoIsPresent = checkAuthorizationInfo(attributes); - - /* - * The AAA server was only used to perform the authentication Look for - * locally stored authorization info for this user If found, add the - * data to the rcResponse - */ - if (remotelyAuthenticated && !authorizationInfoIsPresent) { - logger.trace( - "No Remote Authorization Info provided by Server for User: \"{}\"", - userName); - logger.trace( - "Looking for Local Authorization Info for User: \"{}\"", - userName); - - AuthorizationConfig resource = authorizationConfList.get(userName); - if (resource != null) { - logger.trace("Found Local Authorization Info for User: \"{}\"", - userName); - attributes = resource.getRolesString(); - - } - authorizationInfoIsPresent = checkAuthorizationInfo(attributes); - } - - /* - * Common response parsing for local & remote authenticated user Looking - * for authorized resources, detecting attributes' validity - */ - if (authorizationInfoIsPresent) { - // Identifying the administrative role - result.setRoleList(attributes.split(" ")); - authorized = true; - } else { - logger.trace("Not able to find Authorization Info for User: \"{}\"", - userName); - } - - /* - * Add profile for authenticated user - */ - putUserInActiveList(userName, result); - if (authorized) { - logger.trace("User \"{}\" authorized for the following role(s): {}", - userName, result.getUserRoles()); - } else { - logger.trace("User \"{}\" Not Authorized for any role ", userName); - } - - return rcResponse.getStatus(); - } - - // Check in the attributes string whether or not authorization information - // is present - private boolean checkAuthorizationInfo(String attributes) { - return (attributes != null && !attributes.isEmpty()); - } - - private void putUserInActiveList(String user, AuthenticatedUser result) { - activeUsers.put(user, result); - } - - private void removeUserFromActiveList(String user) { - if (!activeUsers.containsKey(user)) { - // as cookie persists in cache, we can get logout for unexisting - // active users - return; - } - activeUsers.remove(user); - } - - @Override - public Status saveLocalUserList() { - return saveLocalUserListInternal(); - } - - private Status saveLocalUserListInternal() { - return configurationService.persistConfiguration( - new ArrayList(localUserConfigList.values()), USERS_FILE_NAME); - } - - @Override - public Status saveAAAServerList() { - return saveAAAServerListInternal(); - } - - private Status saveAAAServerListInternal() { - return configurationService.persistConfiguration( - new ArrayList(remoteServerConfigList.values()), SERVERS_FILE_NAME); - } - - @Override - public Status saveAuthorizationList() { - return saveAuthorizationListInternal(); - } - - private Status saveAuthorizationListInternal() { - return configurationService.persistConfiguration( - new ArrayList(authorizationConfList.values()), AUTH_FILE_NAME); - } - - @Override - public Object readObject(ObjectInputStream ois) - throws FileNotFoundException, IOException, ClassNotFoundException { - // Perform the class deserialization locally, from inside the package - // where the class is defined - return ois.readObject(); - } - - private void loadUserConfig() { - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, USERS_FILE_NAME)) { - addRemoveLocalUserInternal((UserConfig) conf, false); - } - } - - private void loadServerConfig() { - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, SERVERS_FILE_NAME)) { - addAAAServer((ServerConfig) conf); - } - } - - private void loadAuthConfig() { - for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, AUTH_FILE_NAME)) { - addAuthInfo((AuthorizationConfig) conf); - } - } - - /* - * Interaction with GUI START - */ - private Status changeLocalUser(UserConfig AAAconf, Command command) { - // UserConfig Validation check - Status validCheck = AAAconf.validate(); - if (!validCheck.isSuccess()) { - return validCheck; - } - - String user = AAAconf.getUser(); - - // Check default admin user - if (user.equals(UserManager.DEFAULT_ADMIN)) { - String msg = String.format("Invalid Request: Default Network Admin User cannot be %s", command.getPostAction()); - logger.debug(msg); - return new Status(StatusCode.NOTALLOWED, msg); - } - - // Check user presence/conflict - UserConfig currentAAAconf = localUserConfigList.get(user); - StatusCode statusCode = null; - String reason = null; - switch (command) { - case ADD: - if (currentAAAconf != null) { - reason = "already present"; - statusCode = StatusCode.CONFLICT; - } - break; - case MODIFY: - case REMOVE: - if (currentAAAconf == null) { - reason = "not found"; - statusCode = StatusCode.NOTFOUND; - } - break; - default: - break; - - } - if (statusCode != null) { - String action = String.format("Failed to %s user %s: ", command.getAction(), user); - String msg = String.format("User %s %s in configuration database", user, reason); - logger.debug(action + msg); - return new Status(statusCode, msg); - } - - switch (command) { - case ADD: - return addRemoveLocalUserInternal(AAAconf, false); - case MODIFY: - addRemoveLocalUserInternal(currentAAAconf, true); - return addRemoveLocalUserInternal(AAAconf, false); - case REMOVE: - return addRemoveLocalUserInternal(AAAconf, true); - default: - return new Status(StatusCode.INTERNALERROR, "Unknown action"); - } - } - - private Status addRemoveLocalUserInternal(UserConfig AAAconf, boolean delete) { - // Update Config database - if (delete) { - localUserConfigList.remove(AAAconf.getUser()); - /* - * A user account has been removed form local database, we assume - * admin does not want this user to stay connected, in case he has - * an open session. So we clean the active list as well. - */ - removeUserFromActiveList(AAAconf.getUser()); - } else { - localUserConfigList.put(AAAconf.getUser(), AAAconf); - } - - return new Status(StatusCode.SUCCESS); - } - - private Status addRemoveAAAServer(ServerConfig AAAconf, boolean delete) { - // Validation check - if (!AAAconf.isValid()) { - String msg = "Invalid Server configuration"; - logger.warn(msg); - return new Status(StatusCode.BADREQUEST, msg); - } - - // Update configuration database - if (delete) { - remoteServerConfigList.remove(AAAconf.getAddress()); - } else { - remoteServerConfigList.put(AAAconf.getAddress(), AAAconf); - } - - return new Status(StatusCode.SUCCESS); - } - - private Status addRemoveAuthInfo(AuthorizationConfig AAAconf, boolean delete) { - Status configCheck = AAAconf.validate(); - if (!configCheck.isSuccess()) { - String msg = "Invalid Authorization configuration: " - + configCheck.getDescription(); - logger.warn(msg); - return new Status(StatusCode.BADREQUEST, msg); - } - - // Update configuration database - if (delete) { - authorizationConfList.remove(AAAconf.getUser()); - } else { - authorizationConfList.put(AAAconf.getUser(), AAAconf); - } - - return new Status(StatusCode.SUCCESS); - } - - @Override - public Status addLocalUser(UserConfig AAAconf) { - return changeLocalUser(AAAconf, Command.ADD); - } - - @Override - public Status modifyLocalUser(UserConfig AAAconf) { - return changeLocalUser(AAAconf, Command.MODIFY); - } - - @Override - public Status removeLocalUser(UserConfig AAAconf) { - return changeLocalUser(AAAconf, Command.REMOVE); - } - - @Override - public Status removeLocalUser(String userName) { - if (userName == null || userName.trim().isEmpty()) { - return new Status(StatusCode.BADREQUEST, "Invalid user name"); - } - - if (!localUserConfigList.containsKey(userName)) { - return new Status(StatusCode.NOTFOUND, "User does not exist"); - } - - return changeLocalUser(localUserConfigList.get(userName), Command.REMOVE); - } - - @Override - public Status addAAAServer(ServerConfig AAAconf) { - return addRemoveAAAServer(AAAconf, false); - } - - @Override - public Status removeAAAServer(ServerConfig AAAconf) { - return addRemoveAAAServer(AAAconf, true); - } - - @Override - public Status addAuthInfo(AuthorizationConfig AAAconf) { - return addRemoveAuthInfo(AAAconf, false); - } - - @Override - public Status removeAuthInfo(AuthorizationConfig AAAconf) { - return addRemoveAuthInfo(AAAconf, true); - } - - @Override - public List getLocalUserList() { - return new ArrayList(localUserConfigList.values()); - } - - @Override - public List getAAAServerList() { - return new ArrayList(remoteServerConfigList.values()); - } - - @Override - public List getAuthorizationList() { - return new ArrayList( - authorizationConfList.values()); - } - - @Override - public Status changeLocalUserPassword(String user, String curPassword, String newPassword) { - UserConfig targetConfigEntry = null; - - // update configuration entry - targetConfigEntry = localUserConfigList.get(user); - if (targetConfigEntry == null) { - return new Status(StatusCode.NOTFOUND, "User not found"); - } - Status status = targetConfigEntry.update(curPassword, newPassword, null); - if (!status.isSuccess()) { - return status; - } - // Trigger cluster update - localUserConfigList.put(user, targetConfigEntry); - - logger.trace("Password changed for User \"{}\"", user); - - return status; - } - - @Override - public void userLogout(String userName) { - // TODO: if user was authenticated through AAA server, send - // Acct-Status-Type=stop message to server with logout as reason - removeUserFromActiveList(userName); - logger.trace("User \"{}\" logged out", userName); - } - - /* - * This function will get called by http session mgr when session times out - */ - @Override - public void userTimedOut(String userName) { - // TODO: if user was authenticated through AAA server, send - // Acct-Status-Type=stop message to server with timeout as reason - removeUserFromActiveList(userName); - logger.trace("User \"{}\" timed out", userName); - } - - @Override - public String getAccessDate(String user) { - return this.activeUsers.get(user).getAccessDate(); - } - - @Override - public synchronized Map> getUserLoggedIn() { - Map> loggedInList = new HashMap>(); - for (Map.Entry user : activeUsers.entrySet()) { - String userNameShow = user.getKey(); - loggedInList.put(userNameShow, user.getValue().getUserRoles()); - } - return loggedInList; - } - - public void _umAddUser(CommandInterpreter ci) { - String userName = ci.nextArgument(); - String password = ci.nextArgument(); - String role = ci.nextArgument(); - - List roles = new ArrayList(); - while (role != null) { - if (!role.trim().isEmpty()) { - roles.add(role); - } - role = ci.nextArgument(); - } - - if (userName == null || userName.trim().isEmpty() || password == null || password.trim().isEmpty() - || roles.isEmpty()) { - ci.println("Invalid Arguments"); - ci.println("umAddUser "); - return; - } - ci.print(this.addLocalUser(new UserConfig(userName, password, roles))); - } - - public void _umRemUser(CommandInterpreter ci) { - String userName = ci.nextArgument(); - - if (userName == null || userName.trim().isEmpty()) { - ci.println("Invalid Arguments"); - ci.println("umRemUser "); - return; - } - UserConfig target = localUserConfigList.get(userName); - if (target == null) { - ci.println("User not found"); - return; - } - ci.println(this.removeLocalUser(target)); - } - - public void _umGetUsers(CommandInterpreter ci) { - for (UserConfig conf : this.getLocalUserList()) { - ci.println(conf.getUser() + " " + conf.getRoles()); - } - } - - public void _addAAAServer(CommandInterpreter ci) { - String server = ci.nextArgument(); - String secret = ci.nextArgument(); - String protocol = ci.nextArgument(); - - if (server == null || secret == null || protocol == null) { - ci.println("Usage : addAAAServer "); - return; - } - ServerConfig s = new ServerConfig(server, secret, protocol); - addAAAServer(s); - } - - public void _removeAAAServer(CommandInterpreter ci) { - String server = ci.nextArgument(); - String secret = ci.nextArgument(); - String protocol = ci.nextArgument(); - - if (server == null || secret == null || protocol == null) { - ci.println("Usage : addAAAServer "); - return; - } - ServerConfig s = new ServerConfig(server, secret, protocol); - removeAAAServer(s); - } - - public void _printAAAServers(CommandInterpreter ci) { - for (ServerConfig aaaServer : remoteServerConfigList.values()) { - ci.println(aaaServer.getAddress() + "-" + aaaServer.getProtocol()); - } - } - - @Override - public String getHelp() { - StringBuffer help = new StringBuffer(); - return help.toString(); - } - - void setClusterGlobalService(IClusterGlobalServices s) { - logger.debug("Cluster Service Global set"); - this.clusterGlobalService = s; - } - - void unsetClusterGlobalService(IClusterGlobalServices s) { - if (this.clusterGlobalService == s) { - logger.debug("Cluster Service Global removed!"); - this.clusterGlobalService = null; - } - } - - public void setConfigurationService(IConfigurationService service) { - logger.trace("Got configuration service set request {}", service); - this.configurationService = service; - } - - public void unsetConfigurationService(IConfigurationService service) { - logger.trace("Got configuration service UNset request"); - this.configurationService = null; - } - - void unsetContainerAuthClient(IContainerAuthorization s) { - if (this.containerAuthorizationClient == s) { - this.containerAuthorizationClient = null; - } - } - - void setContainerAuthClient(IContainerAuthorization s) { - this.containerAuthorizationClient = s; - } - - void setAppAuthClient(IResourceAuthorization s) { - this.applicationAuthorizationClients.add(s); - } - - void unsetAppAuthClient(IResourceAuthorization s) { - this.applicationAuthorizationClients.remove(s); - } - - /** - * Function called by the dependency manager when all the required - * dependencies are satisfied - * - */ - void init() { - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - void destroy() { - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - void start() { - authProviders = new ConcurrentHashMap(); - // Instantiate cluster synced variables - allocateCaches(); - retrieveCaches(); - - // Read startup configuration and populate databases - loadConfigurations(); - - // Check if a password recovery was triggered for default network admin user - String pwd = checkPasswordRecovery(); - - // Make sure default Network Admin account is there - checkDefaultNetworkAdmin(pwd); - - BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); - bundleContext.registerService(CommandProvider.class.getName(), this, null); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - void stop() { - } - - @Override - public List getUserRoles(String userName) { - List roles = null; - if (userName != null) { - /* - * First look in active users then in local configured users, - * finally in local authorized users - */ - if (activeUsers.containsKey(userName)) { - roles = activeUsers.get(userName).getUserRoles(); - } else if (localUserConfigList.containsKey(userName)) { - roles = localUserConfigList.get(userName).getRoles(); - } else if (authorizationConfList.containsKey(userName)) { - roles = authorizationConfList.get(userName).getRoles(); - } - } - return (roles == null) ? new ArrayList(0) : roles; - } - - @Override - public UserLevel getUserLevel(String username) { - // Returns the highest controller user level for the passed user - List rolesNames = getUserRoles(username); - - if (rolesNames.isEmpty()) { - return UserLevel.NOUSER; - } - - // Check against the well known controller roles first - if (rolesNames.contains(UserLevel.SYSTEMADMIN.toString())) { - return UserLevel.SYSTEMADMIN; - } - if (rolesNames.contains(UserLevel.NETWORKADMIN.toString())) { - return UserLevel.NETWORKADMIN; - } - if (rolesNames.contains(UserLevel.NETWORKOPERATOR.toString())) { - return UserLevel.NETWORKOPERATOR; - } - // Check if container user now - if (containerAuthorizationClient != null) { - for (String roleName : rolesNames) { - if (containerAuthorizationClient.isApplicationRole(roleName)) { - return UserLevel.CONTAINERUSER; - } - } - } - // Finally check if application user - if (applicationAuthorizationClients != null) { - for (String roleName : rolesNames) { - for (IResourceAuthorization client : this.applicationAuthorizationClients) { - if (client.isApplicationRole(roleName)) { - return UserLevel.APPUSER; - } - } - } - } - return UserLevel.NOUSER; - } - - - @Override - public List getUserLevels(String username) { - // Returns the controller user levels for the passed user - List rolesNames = getUserRoles(username); - List levels = new ArrayList(); - - if (rolesNames.isEmpty()) { - return levels; - } - - // Check against the well known controller roles first - if (rolesNames.contains(UserLevel.SYSTEMADMIN.toString())) { - levels.add(UserLevel.SYSTEMADMIN); - } - if (rolesNames.contains(UserLevel.NETWORKADMIN.toString())) { - levels.add(UserLevel.NETWORKADMIN); - } - if (rolesNames.contains(UserLevel.NETWORKOPERATOR.toString())) { - levels.add(UserLevel.NETWORKOPERATOR); - } - // Check if container user now - if (containerAuthorizationClient != null) { - for (String roleName : rolesNames) { - if (containerAuthorizationClient.isApplicationRole(roleName)) { - levels.add(UserLevel.CONTAINERUSER); - break; - } - } - } - // Finally check if application user - if (applicationAuthorizationClients != null) { - for (String roleName : rolesNames) { - for (IResourceAuthorization client : this.applicationAuthorizationClients) { - if (client.isApplicationRole(roleName)) { - levels.add(UserLevel.APPUSER); - break; - } - } - } - } - return levels; - } - - @Override - public Status saveConfiguration() { - boolean success = true; - Status ret = saveLocalUserList(); - if (!ret.isSuccess()) { - success = false; - } - ret = saveAAAServerList(); - if (!ret.isSuccess()) { - success = false; - } - ret = saveAuthorizationList(); - if (!ret.isSuccess()) { - success = false; - } - - if (success) { - return new Status(StatusCode.SUCCESS); - } - - return new Status(StatusCode.INTERNALERROR, "Failed to save user configurations"); - } - - @Override - public UserDetails loadUserByUsername(String username) - throws UsernameNotFoundException { - AuthenticatedUser user = activeUsers.get(username); - - if (user != null) { - boolean enabled = true; - boolean accountNonExpired = true; - boolean credentialsNonExpired = true; - boolean accountNonLocked = true; - - return new User(username, localUserConfigList.get(username) - .getPassword(), enabled, accountNonExpired, - credentialsNonExpired, accountNonLocked, - user.getGrantedAuthorities(getUserLevel(username))); - } else { - throw new UsernameNotFoundException("User not found " + username); - } - } - - @Override - public boolean supports(Class authentication) { - return UsernamePasswordAuthenticationToken.class - .isAssignableFrom(authentication); - - } - - @Override - public SecurityContextRepository getSecurityContextRepo() { - return securityContextRepo; - } - - public void setSecurityContextRepo( - SecurityContextRepository securityContextRepo) { - this.securityContextRepo = securityContextRepo; - } - - @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { - - if (StringUtils.isBlank((String) authentication.getCredentials()) - || StringUtils.isBlank((String) authentication.getPrincipal())) { - throw new BadCredentialsException( - "Username or credentials did not match"); - } - - AuthResultEnum result = authenticate( - (String) authentication.getPrincipal(), - (String) authentication.getCredentials()); - if (result.equals(AuthResultEnum.AUTHOR_PASS) - || result.equals(AuthResultEnum.AUTH_ACCEPT_LOC) - || result.equals(AuthResultEnum.AUTH_ACCEPT)) { - - AuthenticatedUser user = activeUsers.get(authentication - .getPrincipal().toString()); - - if (user == null) { - throw new AuthenticationServiceException( - "Authentication Failure"); - } - - authentication = new UsernamePasswordAuthenticationToken( - authentication.getPrincipal(), - authentication.getCredentials(), - user.getGrantedAuthorities(getUserLevel(authentication - .getName()))); - return authentication; - - } else { - throw new BadCredentialsException( - "Username or credentials did not match"); - } - - } - - // Following are setters for use in unit testing - void setLocalUserConfigList(ConcurrentMap ucl) { - if (ucl != null) { - this.localUserConfigList = ucl; - } - } - - void setRemoteServerConfigList(ConcurrentMap scl) { - if (scl != null) { - this.remoteServerConfigList = scl; - } - } - - void setAuthorizationConfList(ConcurrentMap acl) { - if (acl != null) { - this.authorizationConfList = acl; - } - } - - void setActiveUsers(ConcurrentMap au) { - if (au != null) { - this.activeUsers = au; - } - } - - void setAuthProviders(ConcurrentMap ap) { - if (ap != null) { - this.authProviders = ap; - } - } - - @Override - public ISessionManager getSessionManager() { - return this.sessionMgr; - } - - public void setSessionMgr(ISessionManager sessionMgr) { - this.sessionMgr = sessionMgr; - } - - @Override - public String getPassword(String username) { - return localUserConfigList.get(username).getPassword(); - } - - @Override - public boolean isRoleInUse(String role) { - if (role == null || role.isEmpty()) { - return false; - } - // Check against controller roles - if (role.equals(UserLevel.SYSTEMADMIN.toString()) - || role.equals(UserLevel.NETWORKADMIN.toString()) - || role.equals(UserLevel.NETWORKOPERATOR.toString())) { - return true; - } - // Check if container roles - if (containerAuthorizationClient != null) { - if (containerAuthorizationClient.isApplicationRole(role)) { - return true; - } - } - // Finally if application role - if (applicationAuthorizationClients != null) { - for (IResourceAuthorization client : this.applicationAuthorizationClients) { - if (client.isApplicationRole(role)) { - return true; - } - } - } - return false; - } -} diff --git a/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/SessionManager.java b/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/SessionManager.java deleted file mode 100644 index 5201a6dc6d..0000000000 --- a/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/SessionManager.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager.security; - -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.Map.Entry; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionEvent; - -import org.opendaylight.controller.usermanager.ISessionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SessionManager implements ISessionManager { - - private static final Logger logger = LoggerFactory - .getLogger(SessionManager.class); - - private Map> sessionMap = new HashMap>(); - - @Override - public void sessionCreated(HttpSessionEvent se) { - - ServletContext ctx = se.getSession().getServletContext(); - String path = ctx.getContextPath(); - - logger.debug("Servlet Context Path created {}", path); - logger.debug("Session Id created for ctxt path {}", - se.getSession().getId()); - - synchronized (sessionMap) { - Set set = sessionMap.get(ctx); - if (set == null) { - set = new HashSet(); - sessionMap.put(ctx, set); - } - set.add(se.getSession()); - } - } - - @Override - public void sessionDestroyed(HttpSessionEvent se) { - ServletContext ctx = se.getSession().getServletContext(); - String path = ctx.getContextPath(); - logger.debug("Servlet Context Path of destroyed session - {}", path); - logger.debug("Session Id destroyed {}", se.getSession().getId()); - - synchronized (sessionMap) { - Set set = sessionMap.get(ctx); - if (set != null) { - set.remove(se.getSession()); - } - } - } - - @Override - public void invalidateSessions(String username, String sessionId) { - - synchronized (sessionMap) { - List sessionsList = new ArrayList(); - Iterator>> sessMapIterator = sessionMap - .entrySet().iterator(); - while (sessMapIterator.hasNext()) { - - Entry> val = sessMapIterator - .next(); - Iterator sessIterator = val.getValue().iterator(); - - while (sessIterator.hasNext()) { - HttpSession session = sessIterator.next(); - if (session != null && sessionId != null && session.getId() != null && !session.getId().equals(sessionId)) { - sessionsList.add(session); - sessIterator.remove(); - } - else { - logger.debug(" session or sessionId is null "); - } - } - } - - Iterator sessionIt = sessionsList.iterator(); - while (sessionIt.hasNext()) { - HttpSession session = sessionIt.next(); - sessionIt.remove(); - session.invalidate(); - } - } - } - -} diff --git a/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/UserSecurityContextRepository.java b/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/UserSecurityContextRepository.java deleted file mode 100644 index 655f77da56..0000000000 --- a/opendaylight/adsal/usermanager/implementation/src/main/java/org/opendaylight/controller/usermanager/security/UserSecurityContextRepository.java +++ /dev/null @@ -1,42 +0,0 @@ - -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager.security; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.web.context.HttpRequestResponseHolder; -import org.springframework.security.web.context.HttpSessionSecurityContextRepository; -import org.springframework.security.web.context.SecurityContextRepository; - -public class UserSecurityContextRepository implements - SecurityContextRepository { - - HttpSessionSecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository(); - - @Override - public SecurityContext loadContext( - HttpRequestResponseHolder requestResponseHolder) { - return securityContextRepository.loadContext(requestResponseHolder); - } - - @Override - public void saveContext(SecurityContext context, - HttpServletRequest request, HttpServletResponse response) { - securityContextRepository.saveContext(context, request, response); - } - - @Override - public boolean containsContext(HttpServletRequest request) { - return securityContextRepository.containsContext(request); - } - -} diff --git a/opendaylight/adsal/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java b/opendaylight/adsal/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java deleted file mode 100644 index f2cbe784fc..0000000000 --- a/opendaylight/adsal/usermanager/implementation/src/test/java/org/opendaylight/controller/usermanager/internal/UserManagerImplTest.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.usermanager.internal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.opendaylight.controller.sal.authorization.AuthResultEnum; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.usermanager.AuthResponse; -import org.opendaylight.controller.usermanager.AuthenticatedUser; -import org.opendaylight.controller.usermanager.IAAAProvider; -import org.opendaylight.controller.usermanager.IUserManager; -import org.opendaylight.controller.usermanager.ServerConfig; -import org.opendaylight.controller.usermanager.UserConfig; -import org.opendaylight.controller.usermanager.AuthorizationConfig; - -/** - * Unit Tests for UserManager - */ -public class UserManagerImplTest { - - private static UserManager um; - - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, new Object()); - if (userManager instanceof UserManager) { - um = (UserManager) userManager; - } else { - um = new UserManager(); - um.setAuthProviders(new ConcurrentHashMap()); - - // mock up a remote server list with a dummy server - um.setRemoteServerConfigList(new ConcurrentHashMap() { - static final long serialVersionUID = 1L; - { - put("dummyServerConfig", new ServerConfig() { - // Server config can't be empty - static final long serialVersionUID = 8645L; - - @Override - public String getAddress() { - return "1.1.1.1"; - } - - @Override - public String getSecret() { - return "secret"; - } - - @Override - public String getProtocol() { - return "IPv4"; - } - }); - } - }); - - // mock up a localUserConfigList with an admin user - um.setLocalUserConfigList(new ConcurrentHashMap() { - static final long serialVersionUID = 2L; - { - List roles = new ArrayList(1); - roles.add(UserLevel.SYSTEMADMIN.toString()); - put("admin", new UserConfig("admin", - "7029,7455,8165,7029,7881", roles)); - } - }); - - um.setAuthorizationConfList(new ConcurrentHashMap() { - static final long serialVersionUID = 2L; - { - List roles = new ArrayList(3); - roles.add(UserLevel.NETWORKOPERATOR.toString()); - roles.add("Container1-Admin"); - roles.add("Application2-User"); - - put("Andrew", new AuthorizationConfig("Andrew", roles)); - } - }); - // instantiate an empty activeUser collection - um.setActiveUsers(new ConcurrentHashMap()); - } - } - - private IAAAProvider getAnonymousAAAProvider(final String providerName) { - // instantiate an anonymous AAAProvider - return new IAAAProvider() { - - @Override - public AuthResponse authService(String userName, String password, - String server, String secretKey) { - return new AuthResponse(); - }; - - @Override - public String getName() { - return providerName; - } - }; - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#addAAAProvider(org.opendaylight.controller.usermanager.IAAAProvider)} - * and for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#removeAAAProvider(org.opendaylight.controller.usermanager.IAAAProvider)} - * and - * {@link org.opendaylight.controller.usermanager.internal.UserManager#getAAAProvider(java.lang.String)} - */ - @Test - public void testAddGetRemoveAAAProvider() { - final String providerName = "dummyAAAProvider"; - IAAAProvider a3p = getAnonymousAAAProvider(providerName); - um.addAAAProvider(a3p); - assertEquals(a3p, um.getAAAProvider(providerName)); - um.removeAAAProvider(um.getAAAProvider(providerName)); - assertTrue(um.getAAAProviderNames().isEmpty()); - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#authenticate(java.lang.String, java.lang.String)} - * . - */ - @Test - public void testAuthenticateStringString() { - List roles = new ArrayList(1); - roles.add(UserLevel.SYSTEMADMIN.toString()); - UserConfig uc = new UserConfig("administrator", "admin", roles); - um.addLocalUser(uc); - AuthResultEnum authResult = um.authenticate("administrator", "admin"); - assertEquals(authResult, AuthResultEnum.AUTH_ACCEPT_LOC); - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#addRemoveLocalUser(org.opendaylight.controller.usermanager.org.opendaylight.controller.usermanager.internal.UserConfig, boolean)} - * . - */ - @Test - public void testAddRemoveLocalUser() { - List roles = new ArrayList(1); - roles.add(UserLevel.SYSTEMADMIN.toString()); - UserConfig uc = new UserConfig("sysadmin", "7029,7455,8165,7029,7881", - roles); - um.addLocalUser(uc); - assertTrue(um.getLocalUserList().contains(uc)); - um.removeLocalUser(uc); - assertFalse(um.getLocalUserList().contains(uc)); - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#changeLocalUserPassword(java.lang.String, java.lang.String, java.lang.String)} - * . - */ - @Test - public void testChangeLocalUserPassword() { - // fail("Not yet implemented"); - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#userLogout(java.lang.String)} - * . - */ - @Test - public void testUserLogout() { - // fail("Not yet implemented"); - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#userTimedOut(java.lang.String)} - * . - */ - @Test - public void testUserTimedOut() { - // fail("Not yet implemented"); - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#authenticate(org.springframework.security.core.Authentication)} - * . - */ - @Test - public void testAuthenticateAuthentication() { - // fail("Not yet implemented"); - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#saveLocalUserList()} - * . - */ - @Test - public void testSaveLocalUserList() { - // fail("Not yet implemented"); - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#saveAAAServerList()} - * . - */ - @Test - public void testSaveAAAServerList() { - // fail("Not yet implemented"); - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#saveAuthorizationList()} - * . - */ - @Test - public void testSaveAuthorizationList() { - // fail("Not yet implemented"); - } - - /** - * Test method for - * {@link org.opendaylight.controller.usermanager.internal.UserManager#readObject(java.io.ObjectInputStream)} - * . - */ - @Test - public void testReadObject() { - // fail("Not yet implemented"); - } - - @Test - public void testGetUserLevel() { - List roles = new ArrayList(2); - roles.add(UserLevel.SYSTEMADMIN.toString()); - roles.add("App1_supervisor"); - um.addLocalUser(new UserConfig("Jack", "password", roles)); - um.authenticate("Jack", "password"); - - roles.clear(); - roles.add("App2Admin"); - roles.add(UserLevel.NETWORKOPERATOR.toString()); - um.addLocalUser(new UserConfig("John", "password", roles)); - - // Run the check on authenticated user - Assert.assertTrue(um.getUserLevel("Jack") == UserLevel.SYSTEMADMIN); - // Run the check on configured users - Assert.assertTrue(um.getUserLevel("John") == UserLevel.NETWORKOPERATOR); - // Run the check on local authorized users - Assert.assertTrue(um.getUserLevel("Andrew") == UserLevel.NETWORKOPERATOR); - // Non locally known user - Assert.assertTrue(um.getUserLevel("Tom") == UserLevel.NOUSER); - } -} diff --git a/opendaylight/adsal/web/brandfragment/pom.xml b/opendaylight/adsal/web/brandfragment/pom.xml deleted file mode 100644 index 171ac3f47f..0000000000 --- a/opendaylight/adsal/web/brandfragment/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - - org.opendaylight.controller - web.brandfragment - 0.6.0-SNAPSHOT - bundle - - - - - org.apache.felix - maven-bundle-plugin - ${bundle.plugin.version} - true - - - org.opendaylight.controller.web - / - - - - - - diff --git a/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/customerror.jsp b/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/customerror.jsp deleted file mode 100644 index 47de972a87..0000000000 --- a/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/customerror.jsp +++ /dev/null @@ -1,3 +0,0 @@ -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - diff --git a/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/customlogin.jsp b/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/customlogin.jsp deleted file mode 100644 index f2adf1f39c..0000000000 --- a/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/customlogin.jsp +++ /dev/null @@ -1,3 +0,0 @@ -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - diff --git a/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/custommain.jsp b/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/custommain.jsp deleted file mode 100644 index f079c82635..0000000000 --- a/opendaylight/adsal/web/brandfragment/src/main/resources/WEB-INF/jsp/custommain.jsp +++ /dev/null @@ -1,4 +0,0 @@ -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - - diff --git a/opendaylight/adsal/web/brandfragment/src/main/resources/css/customlogin.less b/opendaylight/adsal/web/brandfragment/src/main/resources/css/customlogin.less deleted file mode 100644 index cdaba2385f..0000000000 --- a/opendaylight/adsal/web/brandfragment/src/main/resources/css/customlogin.less +++ /dev/null @@ -1,53 +0,0 @@ -.reset { - padding: 0; - margin: 0; -} - -html , body { - .reset; - height: 100%; - width: 100%; - background-color: #eee; -} - -html { - display: table; -} - -body { - display: table-cell; - vertical-align: middle; - padding-bottom: 10%; -} - -.container { - width: 650px; - .content { - padding: 25px; - background-color: #fff; - -webkit-border-radius: 10px; - -moz-border-radius: 10px; - border-radius: 10px; - -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .15); - -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, .15); - box-shadow: 0 1px 2px rgba(0, 0, 0, .15); - text-align: center; - .login-form { - #logo { - background-repeat: no-repeat; - background-position: center; - background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAADQCAMAAADGQmMsAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpBQ0I5NEY2RjhBM0QxMUUyOUMzMUNFMzQ4NjM5NUNFRiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpBQ0I5NEY3MDhBM0QxMUUyOUMzMUNFMzQ4NjM5NUNFRiI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkFDQjk0RjZEOEEzRDExRTI5QzMxQ0UzNDg2Mzk1Q0VGIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkFDQjk0RjZFOEEzRDExRTI5QzMxQ0UzNDg2Mzk1Q0VGIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+EBgRdAAAAwBQTFRFrKus/sxW8VIj////Y2Nk/s9gysrL+qMY/tl//uWp+6wW9ogeW1pco6Ok8E4jzc3N/b8p/chJ//jp/tZ2/tyJ/cZC+Pj48vLy//Xd8lwi7Ozs820hbGts/bscxcXF4eDh//LV/tFke3t8U1JU//DN/b0l6enp9fX1/s5d/+3E3t3etrW2u7q7/uzA/cAt/t2P/uq5/LIV/tRx//bi/uOh/bUU/cExTEtN5ubm/clM9oQfwcHC//fl/ui09Hkh/tmA/cI0/cQ8/bgU/+/K2tra/td61dXW/tNs8Vgj//vzmpqb/uy//uGd8mUi/cM5+qUX9YUg/bkWdXR2/tqE0tLS8Ewj//z2/uSk/uiy/tJo9HEh/r8S8mAi9Hgh//789HYi/t6T9X4g//34hYSF/bwh//bg/uCY+6wa//HQcXBx/bwi/Pz88mIi//vw//z0vb29//Ta/r8R/stS9YIf/boa9HkilpaX//PX/sER/bcT/+7HkZGS/s1Y/cdF+vr6//rviYmKnZ2e9vb2/cU99YIg2NjY+JQbgYCCjYyN/um28Eoj/uSm//76V1ZYsbGx9Xsf/t6Q/uu88WAi/t+V/tuI+Zwa/uas/boT/tBi/bgT/cQ694sdRkVH9HMh/uCW/bwV9oIg828h+Zgb/tl59Xsh/rgT9YAgQkFD/r0S/t2N9X0h/ueu/uevj46Q/bwfx8fI//PY/rwS/boZ+Z4Z9Hwhb25wi4uMxMPE/tyM//LT//ns/chH//rt//jn///+//HS/bkT/b0SR0ZI9YEg/bkYQ0JE/uau/v7+/s5b/b4RSUhKh4aIRENFv7/AdHN0/s1anJuc/b4S9H0hd3Z3/LAV7+/wUE9R/stU/tRv09PUeHd59Hwg8WIiXl1f/uewqKeos7O0/bkSt7e3/r0R4+Pjc3J029vc8mMiYWBhmJeZiIeIl5eY/rsS+Z0ZhIOFTk1P9Xwg9X0goJ+g9oEgZ2Zo/b0R0M/Q/r0UcG9x/tuGvLu89X4h/rwTlJOUg4OE9H8hK2JASQAAFM5JREFUeNrsnXtAVVW+x8WlJop6BEFASRRQaRQNFIRB0oMIiiDkIx+ASmioaIoPEjVrtGt1oxS91kq9k43DYsZHaZniA80081VZaJMzjl6vDU5Ttxmv13vNW87a57kfa629z0F8nPP7/gV7r/04+7N/6/Fbv9/aTRDI69QEHgFABwF0EEAHAXQQQAcBdBBABwF0EEAHAXQQQAcBdBBABwF0EEAHAXQQQAfoIIAOAugggA4C6CCADgLoIIAOAugggA4C6CCADgLoIIAOAugggA4C6AAdBNBBAB0E0EEAHQTQQQAdBNBBAB0E0EEAHQTQQQAdBNBBAB10D6DPWffxFpbWTYXn7rHQ1+Ry9AQ8d4+F3gdz1A+eu8dCn8yDDpYO0EEA3ZhCb1x88fHOu3Z1nv5BkxahrBIzv27XQq3RZ1WFzrbTFrJpiKNQ9478+5g5ul0PgH5XoO9+MoHIdOLn09oyHX8gWiV0u3RMXug04crPUejVZs9y7yToBBnqzdC3FrsHPXWgq8inUyadF19ud6V79wHtei3uTP+9rsHew4+sXLxNrsUrO58i5Oo7skIPk4htykJ2PddEVugkH7ofGeLF0H2xaY470IuL8DhXrjNgJSHn2jwi3/RCkwhCzg9QQa8g2mp/wKULhAyXQ39c/4rvENIEoLOZYxwf5zr0sii6xQVbH1JBDn9+VlOXX0wgFe3U0B9hHN/jmpz6w2S6IeikHUBnM6fU57gKvdgkbck1TH3oOdLsL6wdXT4lh28YgI7Qj4S8esw16IdJxIBagM5krrR1I9DDo2zbDFLvkkC6cXrLx06SDaONQEdtSEKoa9BfHE6uBwF0NnOFrRuAftBk32bM1n91lfwfvyf9LYk4awQ6uk7+5hr0hagZWQnQOcwp9anGoTvsXNKfDVzoA+InGDNTmN0MQd9NEjq6BP05dCWBtAHoHOYYDwo2Cj08Rr419yXdC71AyA3R/isnyC+NQEcXyNMuQe8mlSSnATqHObX1YGPQa6JU27fqXWk6+VZc4CK5MNMI9IXkJ5eg75IeFTncBaBzmDtsXQe60s6N2PoQcrS7uMSzEU5TF0HvZR+euwAdnSQXOgJ0SbVa5tgcE6wPvWYG48Atwmu9SLbp3c41Z39LBP0GaeY69JmdyZcAnW3nFlufqge9LIa1J7ev4FJBEfrPd8CGw6EGoH/tDnTUPULuzPNa6LVs5tTW54ihHyxi78oV2PoN4jdT94522btod97SERpNyCWAvo7HFQ+KE0Fn27lFfFtvoteNszpefjIA/bQ7bTrVJXLqL94O/QnMV4w/943oHVfEP878Me9qJ8mr+rc0mnQ2AH24G713ixaTilDvhr4OixQY+7/sHTt+s1x4IMfWaT/qhv49XSERM3WhH/MjvdyDjr4knWd6M/QnhOjw6yNbnWFtn9hq5OvCAzm2Th/vI/o3dfaE3a8ugN6CJPSwQ3/cNej0LrZ5MfSBYua4+u0Vjx7Xbp5bd/v7ap1De7Ou1yPiVEf9u6IQXtCFfv3oQmSHXjH8+eEM/XU3Gzp6YYOilfEy6GWDdaC/Nynp0bkaO697a9JDOtADg1nXCyUJMw1BH6oH/Zp8lo2jo9040NFuQlp4b/Uel60D/fcLctTU59bN27xZB3rgXublOp7bYMTSL+ha+mXitNWHyYVeT/di6BdDedDR5yQi1Hs7cvsDdaBXpaioH6+bl1KlA739MK4NG3i8HX843F0IfebzhHyOnNBdbNMl/SybXPe+IZvQ1iXoKuqSnVfpQOfYOaV1nRuzJHfJkYggex/gqLZmuHLpqpy56713C+ir5Gcvds7sDdSBXpWS9OhEZ7+d2rkOdJ6dUz1JDNzt10ev2zt+fuT8k0p1a0Zb6wvKaFg3oKMB5xyT697oe0/O1oEu2fpxuZ2LoXPtHEnzpk8a+EHkOTv0q4z+2blPf6EIe3IPOmpx1D657pUTLnxbt0GXbP2M1c7fSqnSgb5vluBSRnzvx7rZ3S6Spbe5rFCvFkPVFb6b0Om7dcI6uR5U4Y3z6QeydaBL1I9Ldr5ic5UO9KX7hX20c+RrXd9MgmPKnbbp+glH7kJH35Jmlirj2WZeGUThH6gDndbwdRMddi6ALrRzS6N+Uu9mLjp74yLfe8OhH5tuu1I37wyX8n9TB/pHKUmH+r9ls3M+9KXLdC7Ujhy9olPkqqN2b2ToKDTiqGUUcN5LAyMPBIqhV31U9dprVVU60Pct073QN3pduUukIuguQafjBMsL5q3Q0d7BYug5+RkZKTli6Hp1u6ShRJwiejbCmbvS6NBRL8vdeC10dGC5CHpOfkheZWV+kgi6uA9n138RP1Hn7Lx83rPRoaOFpOIs+tJ705r2LudDp8xL6rPyHNRZ0NvPNnQZasqf8vf+lWyQBSk3PnTaiTt/7GcvTmAcW3poh1JzH7q9QlJOfl5JFlVlZUqOZcOtkc+oih7yqTV4maGHyXNBXObkMrqr0Hv4kZ9Wegf0sj1rO2g0ImDk2/+m0HutO0na1KlphlVNM+g/klq/97284PdvP5U2TXvGtR1YrfzDp8g3zNVGfrWNKBOP7gJ0NOQwObzBK6CzI2C/q8uZ9L5ctzrlUWWFtH25rU0vt62sl7Z1uqUoOKn1o98xT8lcZLDFCVLxI2NzM/XKAXcDujQff9groG85wkT0P/1bL6iSacWmvHralLcd09ahMW3zsurr8yaskJdbsH7RDrazJo5tXdMJ+eaXCn9q0I1uhPip5uAMQv+yQdDRNXLKO6DvZDM60791igq6krkkSl0JPWX9ojOcWLk4zg20+YGQiL/92MXSke/R5fQ1aWploXp1CoPQr+5+eDdTTw8xAt1beu886Pi4gjqFrmUu2boCesp6zPPEc6Gj0IsXLFNmV69fbxYh/VXxeRdNV7AjMYDjaf7qUs5xwmnZSlMaBe16x6uhK219xaZ6DXOLrdc7od/m27kIutSGD+/mZ2VT8fhPLVizb0HPLw7V/S2PLF78AUcvXnYWEj2mAQO8G7pk6452fcWEEBbzMW0rNzqg5/PtXAe6RLV7lytXugwIQqB7Cl2ydTv1nE4s5hL1TTaP7O0FAjvXhw66T6Dj44ts1HPyM5jM6cgtIyXJ1m/Homg5gP6gQJdsPV9iPikvoy1HGZWW2Rdq5x9igO4J0K19+JxJIVk86GNCSiQ/fP76Q+L4d4D+4EDH1f1b384PKRFAz8qrTLm1fpFOogtAf4Cg4+PVUzLy6kXQs/Iy5s2tXgTQPQf63P5TQiqzxNBD5i06jgG6x0Cf2Gre7b9X5omgV/5pyq2kuokA3VOgW3IaklIq80K40Cv/9H6SLTIaoHsCdFusc85r9U25Q7b6fyRZ4uHrzgB0T4A+t+4ja6xz0h8zXuY4Z0KmJMmyIAD6gw59rjOngeuGbTohx5kFAW7YBx76RLudWyZcKpuyJlya5jkmXD4S2vqDD70wOTg8OjI4ucCToctylyxTqyVa6mOa1pfI5tOljCeD0Av7BCj1O99iI09zTUDATWW5ZfTgVcIDYh0B2b4BAeIVa/sFBGQydxRPTg+Mmk9/R5hp3x9GaLNxD6QFtPTnnXVEQMBq619lAUKtKb7H0CfWOXOXrEEUGuqUuSKIQmTrKuhjtYvPhcV3HThM527LpILKdSgLS0WLFEoLKC0Za//PB+N04fnbY9xSu3VZv31hils1NY9WvxR0aw3npLWBjrNuEY9rY/rdW+jUzjerw6VU1CXm6nAprq2robNXn3tzTaHwbgMsqRTKbWMHUQqcTPhZJvokHcxROpOpTM0x7qM1/0HWm9u+vLTUJ9D2tn5SrigTHoa3v8s76xKMf2f96yUx9OXr7g70j3M5dj5vszYwUkF9TNMSRmCkLX9dLzBSgj5+Wh+7Jo9qHmj9GEi26Hf7z8e59H5VZlaOuQYsvSSyCt0d6ME+0m0V+UwLj5tdW4vGJkdOK5Xs/sjaAteh+48b6FTfdTH0Iax2bvhzdPLdgc4Ogf7/VlMm/V6u25YQ6PpKeQh0iTUE+rai4KT/brXDQAi0BF21wFyy73jLC5jGb9sfwzh2FLUy1eY/8Fary6Q7YlGDoGdK72LRKOVH6sLTJOyJyS5DV2kwxtPuRUcuedzHWzWKbNnqvZEKtVq/aePGjRMmTQjJCLEoI4T+Szd1+pdWypIPPdWhXHvGLVvHaqBrv+5Tlm6mD7M5717HUsuIPEBLhCu376XbBzHahYJsWrnPahB0S32crh15BNNT4ai4hkEfls17GxoZOvtNGPx6tVLP2NOa/lhfaUlryppiTWv6YuQzqqKvG0lfZENHKFpqP3u+wulbYxyIUE+MA1Q7+tKDHtOWH6Ws3N2AHi31ePox07QGRuHsAx4EvXg7P4Ex6bXKvKysvJJ/rOAnMMbMcRs62luqqpJlhrscm2n3Nhqbw9Sjo670oEh1+VRabXRFDYHuL9XtvE5Gefp+5DnQi02iVOWklMrKypK/C1OV44Pdho6G0WET+3ut1J5Nw6wjoLXqHl6RpRJQviO0XNH+BkHvKWCO3Om937fQI8PEixIkfZERMmWFcFECs6nMbehobzw2x7AWskjEeJStlo9RJ0NvpVfdo9y0R0vMRejSIH8U8gboB006y4/cvtU65wu95Uf0bF0AHfWl1fJNxstIh0mW/nJhjFn71fZPMN6pGCC8ewTjN1BDoBcsN+PsAm+AzrRzBfT89dXfObMgeAsNmcLdho7eoB1jrbcl3dHWd6B1uRrGgRkYf6WqF4oONAh6X+H3SDwIOtvOZdClnIYPZVkQ3CXF4qe6DX0OHa9rHJJTd2Kz7UU6QF/M1RoHN73mCNW/tQ2C3lXbT/BI6Bw7l0FfsP4/KOX/tGdBCBYPFNq6ELr07BMZzrVEmTemVOPhpt3+MIe7JG4+xp+xKgvj0JeZGK+eB0KvMektE2rPabBlQQiXCY2Pcxf6OIxzVR7JYVGyA4rpfs2EVHCYzK/zGX0D4hoGvZz2EpI9H3rqdr0FgfMtdi6J2nqK3oLApho3oSdv13S8p2E8WNFtG8/y3WBfp3N5BGoY9FW0aqn1eOh8O7dDz5flNFRb23Xh0t98WxdDl6Y4lWOlgkEKin2ZhryUvmcWb+9eE6N9cBW6VNjTodemFukt8q/MXbKuWiBe5J9r6zrQx6s98L6KKVJUMBibtX7Xsp02FxxllxvcUOiJFv+fZ0PXfAtbAz1flbtksXWdz3nExLkFfa26p0aNOE3VV48aqzmsj3W6TZol6YMaCn2QUW+cDXrRMMEQ9P6EXl6k8+Ge9/PX/7ZandO6foHeh3s4tq4DnY7E28uq1tpojOcrTHesiTkrSc8ajxCncncZ+hHVxP3Urs2V2iOHnvtVc45M9yn06DDdT3QxcpE/7N96o94nuqIOumfpCl/YG5qO2yiMBxWwvHZ4z01u6JKL0MNUzuRUTaSLHLpQ9yX03rnim97xduvfVrPy13P0PsYXFukG9D1KWw3WTqJJDpotzLdF0lrUcOjxmm+BF8sfkjTz7/NgQ0eZ4rs+9FR/JtwP61odEh5YlOpO9Z5mVkAPwHifpq9nZtXhBZbl6gML7gD0NzVt+uzyaKeK96igh/lGRrOUmrrvvu3ICTvvuOfNX7N3fLdqibBJn+NWR+4zbJbNhPuHMSZbI82aYDlbO2UO40USuwR9iU4sU28V9CKuJ6fn/TtO7z1f8K0t9K+8XasLBJ9VnpHq1pBNOqWs+72K2X4nsgOrfATxVi5BjzVzgjlsGqiC/mA6Z1Jn8NglDkOTefHs/dDepa7auR708Fz5jIoUGsewOTowMzPO35XlrHMHej9+M+FB0FE0x9YTZyMudGlmez/H1qMi3XTDUtOOcgY00komG7FtOo3JresdgV5Df0GZ50OvTWU6aBKl5y+CzrF1kyBUTgi9YJC8Sa+lRbMfS9OoZXv6avg3HvTCbHHcjIdAt0V/qplbPF9C6GjZcrMrdq4D3VcRxbpa1FHs0HjQUUuMYwq9ADoq19h6e2s9K4bO+J6bOExOBL0wHuP4QnktLnDzjm086O/mcry5ngZdY+uJtqevAx3NCnTBzsXQWyrmRaXUwNg1exia3BIzHDR3DrrkB5wR5w3QVbbe3h6WqgddZes6IXIi6OuUOYrjFRPpmgFwYCNCD56PzYncsi95EHRUvlNr5wagK2w9Si/Rmg9dCmY2O1+Z4O0CH4mUq7a68aBboqi5Y/VoT4KOymdo7NwIdOTvGLmZDiJ3oT8h+bdl89iPYbOJ+2U/Ke/BpxGh1/LTbdCwN+S+4Qc/ral8vtrODUFHw2y2HlWD3ISeHCsd/+/ODbNMZlYMvGwInxveeNCtX6grZcX1li9X5M95QAKjdXK9vTwnyAh0lGyxdZOBRTQodLMmpjx4j6U/MVlmav0w3imIr3wlRmOJOtBHuQQdJUsJlVFr1J65uJZShSR7gTwAOkqdr7Rzg9Attm6qQYagyxNKC5cl10wutSCfIe+P18YLnKo23912/wZbegEXOprV07JUQtpBZxuzrDxdiibcKQ+m8gToKDp3sDKdzBh0lBwfFokMQg9s7mPTkqWD7DO76Qo33jjaqSsXnUeagLvpCvT4z3y0Kk17hQcdoT7WW8uOXeO7enWm7+R062ok7VORp0FHkSoHp0HoKLkGGYXOcNYHqFqGRF7gk0MBtGqZ5QJ0tuxLGjDXnAmO1c46Z6tiJj0DulpGoRvUbE24dVRiej+1J13KJhsoPlGZOiwlkZH9Ytcn3FjtQsfBrEY/eG3pEXlObldfdYli7foYTi1lLplAm44ozg4PhV6QmqlQ74Os7low3aNbJWVmKqqH8MxM7tMvy+QossBxMCcF792X1sYuSSxN/Cp2VSZjwbjZvTOjud+SPsg5q/QQpnoRdNCdEkAH6HdUfXjQ+8Fz91jo04o48oXn7rHQQQAdBNBBAB0E0EEAHQTQQQAdBNBBAB0E0EEAHaCDADoIoIMAOgiggwA6CKCDADoIoIMAOgiggwA6CKCDADoIoIMAOgigA3QQQAcBdBBABwF0EEAHAXQQQAcBdBBABwF0EEAHAXQQQAcBdBBABwF0gA4C6CCADgLoIIAOAuig+13/FGAApyIqjoQlf2EAAAAASUVORK5CYII='); - width: 400px; - height: 175px; - margin: 0 auto 20px; - } - .icon-login { - width: 20px; - height: 16px; - background-position: left center; - background-repeat: no-repeat; - background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc5JREFUeNpi3NLKAAKMQBwNxP5AbM0AAUeBeCMQLwXi/95V/xmwARao5nphGeN6KTUPBlF5S7DE64fHQ57d2hHy9slZFSC3EWQILgOiQZqVjRMY3r+4zHBqYx5YQlLVhQEkBjIcaMgdIL0EmwFMIGeDbAZpvn1yVtGXd/cEQRjEBomB5KBeY8BlgDXI2c9v7wHx53vnnf0AwiA2SAzqJWt8BlAEQAYcBQYY2M9AkLh1krEACIPYIDGQHDRGcBqwERjaDIISugyq5ml9PEJK70EYxAaJgeTYWTRDcBnACEwHuKIRrPnLi28MipZBDF+f7WJQcpoAUsvAI2qFYgDOhASy+cXDzwx6dpIgzQz39hWADQHRIKAXfoqB8f///zgD6NJKMxD1/9Kh5yiGQC0EG0AwFm6f/sAI0gwyBOoCBuRUSVQ0ggyRkOfFaggLIc2qpgIM7558/K/jW8Lw7PwMsCEMDAUMYloxDIcm6U7FGwYwcKBX/b+0liqDoHIQw4UNPQyggJVTF2Cwy7vMyOgizMj4W4iDkZGZhYmdmZGBi/E/Cws7IzMDCwvLPyZGlvdf/nK+//qHuy9L6gbIsNTex/oT8xWKvCuug3Ldd4AAAwBj/b+B1P2YnAAAAABJRU5ErkJggg=='); - } - } - } -} \ No newline at end of file diff --git a/opendaylight/adsal/web/brandfragment/src/main/resources/css/custommain.less b/opendaylight/adsal/web/brandfragment/src/main/resources/css/custommain.less deleted file mode 100644 index cb6fbc54fc..0000000000 --- a/opendaylight/adsal/web/brandfragment/src/main/resources/css/custommain.less +++ /dev/null @@ -1,260 +0,0 @@ -// properties -@mainTop: 43px; -@mainBottom: 41px; - -@minWidth: 640px; -@minHeight: 480px; - -@topologyOffset: -4px; // ensure calibration - -// mixins -.dash-size (@width, @height) { - width: @width; - height: @height; -} -.position (@type, @top, @right, @bottom, @left) { - position: @type; - top: @top; - right: @right; - bottom: @bottom; - left: @left; -} -.dash-position (@top, @right, @bottom, @left) { - .position(absolute, @top, @right, @bottom, @left); -} -.icon { - width: 22px; - height: 16px; - background-position: left center; - background-repeat: no-repeat; -} -.dashlet-elements { - width: 98%; - margin: 5px auto; -} - -// header -#menu { - .navbar-inner { - .brand { - font-size: 1.4em; - font-variant: small-caps; - margin: 0 12px; - padding: 10px 0 10px 45px; - background-image: url('../img/logo.png'); - background-position: left center; - background-repeat: no-repeat; - } - ul { - margin-top: 10px; - border-bottom: transparent; - li { - a { - padding: 5px 15px; - &:hover { - border-color: transparent; - } - } - } - .active { - a { - border-radius: 1px; - background: #f6f6f6; - &:hover { - border-top: 1px solid #ddd; - border-right: 1px solid #ddd; - border-left: 1px solid #ddd; - } - } - } - } - #toolbar { - position: absolute; - right: 10px; - .dropdown-menu { - right: 0; - left: auto; - min-width: 120px; - } - .icon-user { - .icon; - background-image: url('../img/user_0020_16.png'); - } - .icon-users { - .icon; - background-image: url('../img/user_group_0107_16.png'); - } - .icon-save { - .icon; - background-image: url('../img/save_as_0106_16.png'); - } - .icon-logout { - .icon; - background-image: url('../img/open_1054_16.png'); - } - } - } -} - -// footer -#footer { - #alert { - margin: 0; - p { - padding: 0; - margin: 0; - } - } -} - -// main -#main { - position: fixed; - top: @mainTop; - right: 0; - bottom: @mainBottom; - left: 0; - min-width: @minWidth; - min-height: @minHeight; - - // topology - #topology { - position: absolute; - top: @topologyOffset; - right: 0; - bottom: @topologyOffset; - left: 0; - background: #ddd; - } - - // left - #left { - .dash-size(30%, 100%); - float: left; - - #left-top { - .dash-size(100%, 60%); - - .dash { - .dash-position(5px, 5px, 5px, 5px); - } - } - - #left-bottom { - .dash-size(100%, 40%); - - .dash { - .dash-position(0, 5px, 5px, 5px); - } - } - } - - // right - #right { - .dash-size(70%, 100%); - float: right; - - #right-top { - .dash-size(100%, 60%); - - .dash { - .dash-position(5px, 5px, 5px, 0); - } - } - - #right-bottom { - .dash-size(100%, 40%); - - .dash { - .dash-position(0, 5px, 5px, 0); - } - } - } - - #left-top, #left-bottom, - #right-top, #right-bottom { - position: relative; - } - - // dashentries - .dash { - border-radius: 1px; - background: #fff; - border: 1px solid #ddd; - - .nav { - padding: 2px; - padding-bottom: 0; - margin: 0; - } - - .nav-tabs { - background: #eee; - li { - a { - background: #ddd; - padding: 4px 8px; - margin-right: 3px; - border-radius: 1px; - &:hover { - border-color: transparent; - } - } - } - .active { - a { - background: #fff; - border-radius: 1px; - &:hover { - border-top: 1px solid #ddd; - border-left: 1px solid #ddd; - border-right: 1px solid #ddd; - } - } - } - } - - .dashlet { - overflow: auto; - .dash-position(45px,0,0,0); - - h4 { - .dashlet-elements; - } - - p { - .dashlet-elements; - } - - table { - .dashlet-elements; - } - - .btn-group { - margin: 5px; - } - - .none { - margin: 0 auto; - padding-top: 128px; - background-position: center; - background-repeat: no-repeat; - background-image: url('../img/alert_unreachable_2008_128.png'); - text-align: center; - p { - cursor: default; - } - } - } - } - - // defaults for visual topology - #right-top .dash { - background: #ddd; - overflow: hidden; - } -} - -.table-cursor tr:hover { - cursor: pointer; -} diff --git a/opendaylight/adsal/web/brandfragment/src/main/resources/img/logo.png b/opendaylight/adsal/web/brandfragment/src/main/resources/img/logo.png deleted file mode 100644 index 46c02e2aeb..0000000000 Binary files a/opendaylight/adsal/web/brandfragment/src/main/resources/img/logo.png and /dev/null differ diff --git a/opendaylight/adsal/web/devices/pom.xml b/opendaylight/adsal/web/devices/pom.xml deleted file mode 100644 index 56ad7e7a39..0000000000 --- a/opendaylight/adsal/web/devices/pom.xml +++ /dev/null @@ -1,122 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - devices.web - 0.6.0-SNAPSHOT - bundle - - - com.fasterxml.jackson.core - jackson-databind - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - forwarding.staticrouting - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - web - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.forwardingrulesmanager, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.connection, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.connectionmanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.forwarding.staticrouting, - org.opendaylight.controller.usermanager, - org.opendaylight.controller.web, - com.google.gson, - com.google.gson.reflect, - javax.annotation, - javax.naming, - javax.servlet, - javax.servlet.annotation, - javax.servlet.http, - javax.servlet.jsp, - javax.servlet.jsp.el, - javax.servlet.jsp.jstl.core, - javax.servlet.jsp.jstl.fmt, - javax.servlet.jsp.jstl.tlv, - javax.servlet.jsp.tagext, - javax.servlet.resources, - javax.xml.parsers, - javax.xml.transform, - org.apache.commons.logging, - org.apache.taglibs.standard.functions, - org.apache.taglibs.standard.resources, - org.apache.taglibs.standard.tag.common.core, - org.apache.taglibs.standard.tag.common.fmt, - org.apache.taglibs.standard.tag.rt.core, - org.apache.taglibs.standard.tag.rt.fmt, - org.apache.taglibs.standard.tei, - org.apache.taglibs.standard.tlv, - com.fasterxml.jackson.databind, - com.fasterxml.jackson.annotation, - org.osgi.framework, - org.slf4j, - org.springframework.beans, - org.springframework.beans.factory.xml, - org.springframework.context.config, - org.springframework.stereotype, - org.springframework.web, - org.springframework.web.bind.annotation, - org.springframework.web.servlet, - org.springframework.web.servlet.config, - org.springframework.web.servlet.view, - org.springframework.web.filter, - org.springframework.web.context - /controller/web/devices - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/Devices.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/Devices.java deleted file mode 100644 index a9f11fafb5..0000000000 --- a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/Devices.java +++ /dev/null @@ -1,869 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.devices.web; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentMap; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.forwarding.staticrouting.IForwardingStaticRouting; -import org.opendaylight.controller.forwarding.staticrouting.StaticRouteConfig; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.connection.ConnectionConstants; -import org.opendaylight.controller.sal.core.Config; -import org.opendaylight.controller.sal.core.Description; -import org.opendaylight.controller.sal.core.ForwardingMode; -import org.opendaylight.controller.sal.core.Name; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.core.Property; -import org.opendaylight.controller.sal.core.State; -import org.opendaylight.controller.sal.core.Tier; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.HexEncode; -import org.opendaylight.controller.sal.utils.NetUtils; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.sal.utils.TierHelper; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.SpanConfig; -import org.opendaylight.controller.switchmanager.SubnetConfig; -import org.opendaylight.controller.switchmanager.Switch; -import org.opendaylight.controller.switchmanager.SwitchConfig; -import org.opendaylight.controller.web.DaylightWebUtil; -import org.opendaylight.controller.web.IDaylightWeb; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -@Controller -@RequestMapping("/") -public class Devices implements IDaylightWeb { - private static final UserLevel AUTH_LEVEL = UserLevel.CONTAINERUSER; - private static final String WEB_NAME = "Devices"; - private static final String WEB_ID = "devices"; - private static final short WEB_ORDER = 1; - - public Devices() { - ServiceHelper.registerGlobalService(IDaylightWeb.class, this, null); - } - - @Override - public String getWebName() { - return WEB_NAME; - } - - @Override - public String getWebId() { - return WEB_ID; - } - - @Override - public short getWebOrder() { - return WEB_ORDER; - } - - @Override - public boolean isAuthorized(UserLevel userLevel) { - return userLevel.ordinal() <= AUTH_LEVEL.ordinal(); - } - - @RequestMapping(value = "/nodesLearnt", method = RequestMethod.GET) - @ResponseBody - public DevicesJsonBean getNodesLearnt(HttpServletRequest request, @RequestParam(required = false) String container) { - Gson gson = new Gson(); - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Derive the privilege this user has on the current container - String userName = request.getUserPrincipal().getName(); - Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this); - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - List> nodeData = new ArrayList>(); - if (switchManager != null && privilege != Privilege.NONE) { - for (Switch device : switchManager.getNetworkDevices()) { - HashMap nodeDatum = new HashMap(); - Node node = device.getNode(); - Tier tier = (Tier) switchManager.getNodeProp(node, Tier.TierPropName); - nodeDatum.put("containerName", containerName); - Description description = (Description) switchManager.getNodeProp(node, Description.propertyName); - String desc = (description == null) ? "" : description.getValue(); - nodeDatum.put("nodeName", desc); - nodeDatum.put("nodeId", node.toString()); - int tierNumber = (tier == null) ? TierHelper.unknownTierNumber : tier.getValue(); - nodeDatum.put("tierName", TierHelper.getTierName(tierNumber) + " (Tier-" + tierNumber + ")"); - nodeDatum.put("tier", tierNumber + ""); - String modeStr = "0"; - ForwardingMode mode = null; - if (!containerName.equals(GlobalConstants.DEFAULT.toString())) { - ISwitchManager switchManagerDefault = (ISwitchManager) ServiceHelper.getInstance( - ISwitchManager.class, GlobalConstants.DEFAULT.toString(), this); - mode = (ForwardingMode) switchManagerDefault.getNodeProp(node, ForwardingMode.name); - } else { - mode = (ForwardingMode) switchManager.getNodeProp(node, ForwardingMode.name); - } - if (mode != null) { - modeStr = String.valueOf(mode.getValue()); - } - nodeDatum.put("mode", modeStr); - - nodeDatum.put("json", gson.toJson(nodeDatum)); - nodeDatum.put("mac", HexEncode.bytesToHexStringFormat(device.getDataLayerAddress())); - StringBuffer sb1 = new StringBuffer(); - Set nodeConnectorSet = device.getNodeConnectors(); - if (nodeConnectorSet != null && nodeConnectorSet.size() > 0) { - Map portList = new HashMap(); - List intfList = new ArrayList(); - for (NodeConnector nodeConnector : nodeConnectorSet) { - String nodeConnectorNumberToStr = nodeConnector.getID().toString(); - Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector, Name.NamePropName)); - Config portConfig = ((Config) switchManager.getNodeConnectorProp(nodeConnector, - Config.ConfigPropName)); - State portState = ((State) switchManager.getNodeConnectorProp(nodeConnector, - State.StatePropName)); - String nodeConnectorName = (ncName != null) ? ncName.getValue() : ""; - nodeConnectorName += " (" + nodeConnector.getID() + ")"; - - if (portConfig != null) { - if (portConfig.getValue() == Config.ADMIN_UP) { - if (portState != null && portState.getValue() == State.EDGE_UP) { - nodeConnectorName = "" + nodeConnectorName + ""; - } else if (portState == null || portState.getValue() == State.EDGE_DOWN) { - nodeConnectorName = "" + nodeConnectorName + ""; - } - } else if (portConfig.getValue() == Config.ADMIN_DOWN) { - nodeConnectorName = "" + nodeConnectorName + ""; - } - } - - Class idClass = nodeConnector.getID().getClass(); - if (idClass.equals(Short.class)) { - portList.put(Short.parseShort(nodeConnectorNumberToStr), nodeConnectorName); - } else { - intfList.add(nodeConnectorName); - } - } - - if (portList.size() > 0) { - Map sortedPortList = new TreeMap(portList); - - for (Entry e : sortedPortList.entrySet()) { - sb1.append(e.getValue()); - sb1.append("
"); - } - } else if (intfList.size() > 0) { - for (String intf : intfList) { - sb1.append(intf); - sb1.append("
"); - } - } - } - nodeDatum.put("ports", sb1.toString()); - nodeData.add(nodeDatum); - } - } - - DevicesJsonBean result = new DevicesJsonBean(); - result.setNodeData(nodeData); - result.setPrivilege(privilege); - List columnNames = new ArrayList(); - columnNames.add("Node ID"); - columnNames.add("Node Name"); - columnNames.add("Tier"); - columnNames.add("Mac Address"); - columnNames.add("Ports"); - columnNames.add("Port Status"); - - result.setColumnNames(columnNames); - return result; - } - - @RequestMapping(value = "/tiers", method = RequestMethod.GET) - @ResponseBody - public List getTiers() { - return TierHelper.getTiers(); - } - - @RequestMapping(value = "/nodesLearnt/update", method = RequestMethod.GET) - @ResponseBody - public StatusJsonBean updateLearntNode(@RequestParam("nodeName") String nodeName, - @RequestParam("nodeId") String nodeId, @RequestParam("tier") String tier, - @RequestParam("operationMode") String operationMode, HttpServletRequest request, - @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return unauthorizedMessage(); - } - - StatusJsonBean resultBean = new StatusJsonBean(); - try { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - containerName, this); - Map nodeProperties = new HashMap(); - Property desc = new Description(nodeName); - nodeProperties.put(desc.getName(), desc); - Property nodeTier = new Tier(Integer.parseInt(tier)); - nodeProperties.put(nodeTier.getName(), nodeTier); - if (containerName.equals(GlobalConstants.DEFAULT.toString())) { - Property mode = new ForwardingMode(Integer.parseInt(operationMode)); - nodeProperties.put(mode.getName(), mode); - } - SwitchConfig cfg = new SwitchConfig(nodeId, nodeProperties); - Status result = switchManager.updateNodeConfig(cfg); - if (!result.isSuccess()) { - resultBean.setStatus(false); - resultBean.setMessage(result.getDescription()); - } else { - resultBean.setStatus(true); - resultBean.setMessage("Updated node information successfully"); - DaylightWebUtil.auditlog("Property", userName, "updated", - "of Node " + DaylightWebUtil.getNodeDesc(Node.fromString(nodeId), switchManager)); - } - } catch (Exception e) { - resultBean.setStatus(false); - resultBean.setMessage("Error updating node information. " + e.getMessage()); - } - return resultBean; - } - - @RequestMapping(value = "/staticRoutes", method = RequestMethod.GET) - @ResponseBody - public DevicesJsonBean getStaticRoutes(HttpServletRequest request, @RequestParam(required = false) String container) { - Gson gson = new Gson(); - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Derive the privilege this user has on the current container - String userName = request.getUserPrincipal().getName(); - Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this); - - IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper.getInstance( - IForwardingStaticRouting.class, containerName, this); - if (staticRouting == null) { - return null; - } - List> staticRoutes = new ArrayList>(); - ConcurrentMap routeConfigs = staticRouting.getStaticRouteConfigs(); - if (routeConfigs == null) { - return null; - } - if (privilege != Privilege.NONE) { - for (StaticRouteConfig conf : routeConfigs.values()) { - Map staticRoute = new HashMap(); - staticRoute.put("name", conf.getName()); - staticRoute.put("staticRoute", conf.getStaticRoute()); - staticRoute.put("nextHopType", conf.getNextHopType()); - staticRoute.put("nextHop", conf.getNextHop()); - staticRoute.put("json", gson.toJson(conf)); - staticRoutes.add(staticRoute); - } - } - DevicesJsonBean result = new DevicesJsonBean(); - result.setPrivilege(privilege); - result.setColumnNames(StaticRouteConfig.getGuiFieldsNames()); - result.setNodeData(staticRoutes); - return result; - } - - @RequestMapping(value = "/staticRoute/add", method = RequestMethod.GET) - @ResponseBody - public StatusJsonBean addStaticRoute(@RequestParam("routeName") String routeName, - @RequestParam("staticRoute") String staticRoute, @RequestParam("nextHop") String nextHop, - HttpServletRequest request, @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return unauthorizedMessage(); - } - - StatusJsonBean result = new StatusJsonBean(); - try { - IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper.getInstance( - IForwardingStaticRouting.class, containerName, this); - StaticRouteConfig config = new StaticRouteConfig(); - config.setName(routeName); - config.setStaticRoute(staticRoute); - config.setNextHop(nextHop); - Status addStaticRouteResult = staticRouting.addStaticRoute(config); - if (addStaticRouteResult.isSuccess()) { - result.setStatus(true); - result.setMessage("Static Route saved successfully"); - DaylightWebUtil.auditlog("Static Route", userName, "added", routeName, containerName); - } else { - result.setStatus(false); - result.setMessage(addStaticRouteResult.getDescription()); - } - } catch (Exception e) { - result.setStatus(false); - result.setMessage("Error - " + e.getMessage()); - } - return result; - } - - @RequestMapping(value = "/staticRoute/delete", method = RequestMethod.GET) - @ResponseBody - public StatusJsonBean deleteStaticRoute(@RequestParam("routesToDelete") String routesToDelete, - HttpServletRequest request, @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return unauthorizedMessage(); - } - - StatusJsonBean resultBean = new StatusJsonBean(); - try { - IForwardingStaticRouting staticRouting = (IForwardingStaticRouting) ServiceHelper.getInstance( - IForwardingStaticRouting.class, containerName, this); - String[] routes = routesToDelete.split(","); - Status result; - resultBean.setStatus(true); - resultBean.setMessage("Successfully deleted selected static routes"); - for (String route : routes) { - result = staticRouting.removeStaticRoute(route); - if (!result.isSuccess()) { - resultBean.setStatus(false); - resultBean.setMessage(result.getDescription()); - break; - } - DaylightWebUtil.auditlog("Static Route", userName, "removed", route, containerName); - } - } catch (Exception e) { - resultBean.setStatus(false); - resultBean.setMessage("Error occurred while deleting static routes. " + e.getMessage()); - } - return resultBean; - } - - @RequestMapping(value = "/subnets", method = RequestMethod.GET) - @ResponseBody - public DevicesJsonBean getSubnetGateways(HttpServletRequest request, - @RequestParam(required = false) String container) { - Gson gson = new Gson(); - List> subnets = new ArrayList>(); - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Derive the privilege this user has on the current container - String userName = request.getUserPrincipal().getName(); - Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this); - - if (privilege != Privilege.NONE) { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - containerName, this); - if (switchManager != null) { - for (SubnetConfig conf : switchManager.getSubnetsConfigList()) { - Map subnet = new HashMap(); - subnet.put("name", conf.getName()); - subnet.put("subnet", conf.getSubnet()); - List portsList = new ArrayList(); - Iterator itor = conf.getNodeConnectors().iterator(); - while (itor.hasNext()) { - SubnetGatewayPortBean bean = new SubnetGatewayPortBean(); - NodeConnector nodeConnector = itor.next(); - String nodeName = getNodeDesc(nodeConnector.getNode().toString(), containerName); - Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector, Name.NamePropName)); - String nodeConnectorName = (ncName != null) ? ncName.getValue() : ""; - bean.setNodeName(nodeName); - bean.setNodePortName(nodeConnectorName); - bean.setNodeId(nodeConnector.getNode().toString()); - bean.setNodePortId(nodeConnector.toString()); - portsList.add(bean); - } - subnet.put("nodePorts", gson.toJson(portsList)); - subnets.add(subnet); - } - } - } - DevicesJsonBean result = new DevicesJsonBean(); - result.setPrivilege(privilege); - result.setColumnNames(SubnetConfig.getGuiFieldsNames()); - result.setNodeData(subnets); - return result; - } - - @RequestMapping(value = "/subnetGateway/add", method = RequestMethod.GET) - @ResponseBody - public StatusJsonBean addSubnetGateways(@RequestParam("gatewayName") String gatewayName, - @RequestParam("gatewayIPAddress") String gatewayIPAddress, HttpServletRequest request, - @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return unauthorizedMessage(); - } - - StatusJsonBean resultBean = new StatusJsonBean(); - try { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - containerName, this); - SubnetConfig cfgObject = new SubnetConfig(gatewayName, gatewayIPAddress, new ArrayList()); - Status result = switchManager.addSubnet(cfgObject); - if (result.isSuccess()) { - resultBean.setStatus(true); - resultBean.setMessage("Added gateway address successfully"); - DaylightWebUtil.auditlog("Subnet Gateway", userName, "added", gatewayName, containerName); - } else { - resultBean.setStatus(false); - resultBean.setMessage(result.getDescription()); - } - } catch (Exception e) { - resultBean.setStatus(false); - resultBean.setMessage(e.getMessage()); - } - return resultBean; - } - - @RequestMapping(value = "/subnetGateway/delete", method = RequestMethod.GET) - @ResponseBody - public StatusJsonBean deleteSubnetGateways(@RequestParam("gatewaysToDelete") String gatewaysToDelete, - HttpServletRequest request, @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, container, this) != Privilege.WRITE) { - return unauthorizedMessage(); - } - - StatusJsonBean resultBean = new StatusJsonBean(); - try { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - containerName, this); - String[] subnets = gatewaysToDelete.split(","); - resultBean.setStatus(true); - resultBean.setMessage("Added gateway address successfully"); - for (String subnet : subnets) { - Status result = switchManager.removeSubnet(subnet); - if (!result.isSuccess()) { - resultBean.setStatus(false); - resultBean.setMessage(result.getDescription()); - break; - } - DaylightWebUtil.auditlog("Subnet Gateway", userName, "removed", subnet, containerName); - } - } catch (Exception e) { - resultBean.setStatus(false); - resultBean.setMessage(e.getMessage()); - } - return resultBean; - } - - @RequestMapping(value = "/subnetGateway/ports/add", method = RequestMethod.GET) - @ResponseBody - public StatusJsonBean addSubnetGatewayPort(@RequestParam("portsName") String portsName, - @RequestParam("ports") String ports, @RequestParam("nodeId") String nodeId, HttpServletRequest request, - @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return unauthorizedMessage(); - } - - StatusJsonBean resultBean = new StatusJsonBean(); - try { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - containerName, this); - List toAdd = new ArrayList(); - for (String port : ports.split(",")) { - toAdd.add(port); - } - Status result = switchManager.addPortsToSubnet(portsName, toAdd); - - if (result.isSuccess()) { - resultBean.setStatus(true); - resultBean.setMessage("Added ports to subnet gateway address successfully"); - for (String port : toAdd) { - DaylightWebUtil.auditlog("Port", userName, "added", - DaylightWebUtil.getPortName(NodeConnector.fromString(port), switchManager) - + " to Subnet Gateway " + portsName, containerName); - } - } else { - resultBean.setStatus(false); - resultBean.setMessage(result.getDescription()); - } - } catch (Exception e) { - resultBean.setStatus(false); - resultBean.setMessage(e.getMessage()); - } - return resultBean; - } - - @RequestMapping(value = "/subnetGateway/ports/delete", method = RequestMethod.GET) - @ResponseBody - public StatusJsonBean deleteSubnetGatewayPort(@RequestParam("gatewayName") String gatewayName, - @RequestParam("nodePort") String nodePort, HttpServletRequest request, - @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return unauthorizedMessage(); - } - - StatusJsonBean resultBean = new StatusJsonBean(); - try { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - containerName, this); - List toRemove = new ArrayList(); - for (String port : nodePort.split(",")) { - toRemove.add(port); - } - Status result = switchManager.removePortsFromSubnet(gatewayName, toRemove); - - if (result.isSuccess()) { - resultBean.setStatus(true); - resultBean.setMessage("Deleted port from subnet gateway address successfully"); - for (String port : toRemove) { - DaylightWebUtil.auditlog("Port", userName, "removed", - DaylightWebUtil.getPortName(NodeConnector.fromString(port), switchManager) - + " from Subnet Gateway " + gatewayName, containerName); - } - } else { - resultBean.setStatus(false); - resultBean.setMessage(result.getDescription()); - } - } catch (Exception e) { - resultBean.setStatus(false); - resultBean.setMessage(e.getMessage()); - } - return resultBean; - } - - @RequestMapping(value = "/spanPorts", method = RequestMethod.GET) - @ResponseBody - public DevicesJsonBean getSpanPorts(HttpServletRequest request, @RequestParam(required = false) String container) { - Gson gson = new Gson(); - List> spanConfigs = new ArrayList>(); - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Derive the privilege this user has on the current container - String userName = request.getUserPrincipal().getName(); - Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this); - - if (privilege != Privilege.NONE) { - List spanConfigs_json = new ArrayList(); - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - containerName, this); - if (switchManager != null) { - for (SpanConfig conf : switchManager.getSpanConfigList()) { - spanConfigs_json.add(gson.toJson(conf)); - } - } - ObjectMapper mapper = new ObjectMapper(); - - for (String config_json : spanConfigs_json) { - try { - @SuppressWarnings("unchecked") - Map config_data = mapper.readValue(config_json, HashMap.class); - Map config = new HashMap(); - for (String name : config_data.keySet()) { - config.put(name, config_data.get(name)); - // Add switch portName value (non-configuration field) - config.put("nodeName", getNodeDesc(config_data.get("nodeId"), containerName)); - NodeConnector spanPortNodeConnector = NodeConnector.fromString(config_data.get("spanPort")); - Name ncName = ((Name) switchManager.getNodeConnectorProp(spanPortNodeConnector, - Name.NamePropName)); - String spanPortName = (ncName != null) ? ncName.getValue() : ""; - config.put("spanPortName", spanPortName); - } - config.put("json", config_json); - spanConfigs.add(config); - } catch (Exception e) { - // TODO: Handle the exception. - } - } - } - - DevicesJsonBean result = new DevicesJsonBean(); - result.setPrivilege(privilege); - result.setColumnNames(SpanConfig.getGuiFieldsNames()); - result.setNodeData(spanConfigs); - return result; - } - - @RequestMapping(value = "/nodeports") - @ResponseBody - public String getNodePorts(HttpServletRequest request, @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Derive the privilege this user has on the current container - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) { - return null; - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - if (switchManager == null) { - return null; - } - List nodeJsonBeans = new ArrayList(); - - for (Switch node : switchManager.getNetworkDevices()) { - NodeJsonBean nodeJsonBean = new NodeJsonBean(); - List port = new ArrayList(); - Set nodeConnectorSet = node.getNodeConnectors(); - if (nodeConnectorSet != null) { - for (NodeConnector nodeConnector : nodeConnectorSet) { - String nodeConnectorName = ((Name) switchManager.getNodeConnectorProp(nodeConnector, - Name.NamePropName)).getValue(); - port.add(new PortJsonBean(nodeConnector.getID().toString(), nodeConnectorName, nodeConnector - .toString())); - } - } - nodeJsonBean.setNodeId(node.getNode().toString()); - nodeJsonBean.setNodeName(getNodeDesc(node.getNode().toString(), containerName)); - nodeJsonBean.setNodePorts(port); - nodeJsonBeans.add(nodeJsonBean); - } - - return new Gson().toJson(nodeJsonBeans); - } - - @RequestMapping(value = "/spanPorts/add", method = RequestMethod.GET) - @ResponseBody - public StatusJsonBean addSpanPort(@RequestParam("jsonData") String jsonData, HttpServletRequest request, - @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return unauthorizedMessage(); - } - - StatusJsonBean resultBean = new StatusJsonBean(); - try { - Gson gson = new Gson(); - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - containerName, this); - SpanConfig cfgObject = gson.fromJson(jsonData, SpanConfig.class); - Status result = switchManager.addSpanConfig(cfgObject); - if (result.isSuccess()) { - resultBean.setStatus(true); - resultBean.setMessage("SPAN Port added successfully"); - DaylightWebUtil.auditlog("SPAN Port", userName, "added", - DaylightWebUtil.getPortName(NodeConnector.fromString(cfgObject.getSpanPort()), switchManager), - containerName); - } else { - resultBean.setStatus(false); - resultBean.setMessage(result.getDescription()); - } - } catch (Exception e) { - resultBean.setStatus(false); - resultBean.setMessage("Error occurred while adding span port. " + e.getMessage()); - } - return resultBean; - } - - @RequestMapping(value = "/spanPorts/delete", method = RequestMethod.GET) - @ResponseBody - public StatusJsonBean deleteSpanPorts(@RequestParam("spanPortsToDelete") String spanPortsToDelete, - HttpServletRequest request, @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return unauthorizedMessage(); - } - - StatusJsonBean resultBean = new StatusJsonBean(); - try { - Gson gson = new Gson(); - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - containerName, this); - Type collectionType = new TypeToken>() { - }.getType(); - List jsonBeanList = gson.fromJson(spanPortsToDelete, collectionType); - for (SpanPortJsonBean jsonBean : jsonBeanList) { - SpanConfig cfgObject = gson.fromJson(gson.toJson(jsonBean), SpanConfig.class); - Status result = switchManager.removeSpanConfig(cfgObject); - if (!result.isSuccess()) { - resultBean.setStatus(false); - resultBean.setMessage(result.getDescription()); - break; - } - DaylightWebUtil.auditlog("SPAN Port", userName, "removed", - DaylightWebUtil.getPortName(NodeConnector.fromString(cfgObject.getSpanPort()), switchManager), - containerName); - } - resultBean.setStatus(true); - resultBean.setMessage("SPAN Port(s) deleted successfully"); - } catch (Exception e) { - resultBean.setStatus(false); - resultBean.setMessage("Error occurred while deleting span port. " + e.getMessage()); - } - return resultBean; - } - - @RequestMapping(value = "/connect/nodes", method = RequestMethod.GET) - @ResponseBody - public List getNodes(HttpServletRequest request) { - IConnectionManager connectionManager = (IConnectionManager) ServiceHelper.getGlobalInstance( - IConnectionManager.class, this); - if (connectionManager == null) { - return null; - } - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - GlobalConstants.DEFAULT.toString(), this); - if (switchManager == null) { - return null; - } - - Set nodes = connectionManager.getLocalNodes(); - List result = new LinkedList(); - if (nodes == null) { - return result; - } - for (Node node : nodes) { - Description descriptionProperty = (Description) switchManager.getNodeProp(node, "description"); - String description = node.toString(); - if (descriptionProperty != null) { - description = descriptionProperty.getValue(); - } - NodeJsonBean nodeBean = new NodeJsonBean(); - nodeBean.setNodeId(node.getNodeIDString()); - nodeBean.setNodeType(node.getType()); - if (description.equals("None")) { - nodeBean.setNodeName(node.toString()); - } else { - nodeBean.setNodeName(description); - } - result.add(nodeBean); - } - - return result; - } - - @RequestMapping(value = "/connect/{nodeId:.+}", method = RequestMethod.POST) - @ResponseBody - public Status addNode(HttpServletRequest request, @PathVariable("nodeId") String nodeId, - @RequestParam(required = true) String ipAddress, @RequestParam(required = true) String port, - @RequestParam(required = false) String nodeType) { - IConnectionManager connectionManager = (IConnectionManager) ServiceHelper.getGlobalInstance( - IConnectionManager.class, this); - if (connectionManager == null) { - return new Status(StatusCode.NOTFOUND, "Service not found"); - } - - if (!NetUtils.isIPv4AddressValid(ipAddress)) { - return new Status(StatusCode.NOTACCEPTABLE, "Invalid IP Address: " + ipAddress); - } - - try { - Integer.parseInt(port); - } catch (Exception e) { - return new Status(StatusCode.NOTACCEPTABLE, "Invalid Layer 4 Port: " + port); - } - - Map params = new HashMap(); - params.put(ConnectionConstants.ADDRESS, ipAddress); - params.put(ConnectionConstants.PORT, port); - - Node node = null; - if (nodeType != null) { - node = connectionManager.connect(nodeType, nodeId, params); - } else { - node = connectionManager.connect(nodeId, params); - } - if (node == null) { - return new Status(StatusCode.NOTFOUND, "Failed to connect to Node at " + ipAddress + ":" + port); - } - return new Status(StatusCode.SUCCESS); - } - - @RequestMapping(value = "/disconnect/{nodeId:.+}", method = RequestMethod.POST) - @ResponseBody - public Status removeNode(HttpServletRequest request, @PathVariable("nodeId") String nodeId, - @RequestParam(required = true) String nodeType) { - IConnectionManager connectionManager = (IConnectionManager) ServiceHelper.getGlobalInstance( - IConnectionManager.class, this); - if (connectionManager == null) { - return new Status(StatusCode.NOTFOUND, "Service not found"); - } - - try { - Node node = new Node(nodeType, nodeId); - return connectionManager.disconnect(node); - } catch (Exception e) { - return new Status(StatusCode.NOTFOUND, "Resource not found"); - } - } - - private String getNodeDesc(String nodeId, String containerName) { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - String description = ""; - if (switchManager != null) { - Description desc = (Description) switchManager.getNodeProp(Node.fromString(nodeId), - Description.propertyName); - if (desc != null) { - description = desc.getValue(); - } - } - return (description.isEmpty() || description.equalsIgnoreCase("none")) ? nodeId : description; - } - - private StatusJsonBean unauthorizedMessage() { - StatusJsonBean message = new StatusJsonBean(); - message.setStatus(false); - message.setMessage("Operation not authorized"); - return message; - } - - @RequestMapping(value = "login") - public String login(final HttpServletRequest request, final HttpServletResponse response) { - /* - * IUserManager userManager = (IUserManager) ServiceHelper - * .getGlobalInstance(IUserManager.class, this); if (userManager == - * null) { return "User Manager is not available"; } - * - * String username = request.getUserPrincipal().getName(); - * - * - * model.addAttribute("username", username); model.addAttribute("role", - * userManager.getUserLevel(username).toNumber()); - */ - return "forward:" + "/"; - } - -} diff --git a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/DevicesJsonBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/DevicesJsonBean.java deleted file mode 100644 index ce0b3763e0..0000000000 --- a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/DevicesJsonBean.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.devices.web; - -import java.util.List; -import java.util.Map; - -import org.opendaylight.controller.sal.authorization.Privilege; - -public class DevicesJsonBean { - private List columnNames; - private List> nodeData; - private Privilege privilege; - - public List getColumnNames() { - return columnNames; - } - - public void setColumnNames(List columnNames) { - this.columnNames = columnNames; - } - - public List> getNodeData() { - return nodeData; - } - - public void setNodeData(List> nodeData) { - this.nodeData = nodeData; - } - - public void setPrivilege(Privilege privilege) { - this.privilege = privilege; - } - - public Privilege getPrivilege() { - return privilege; - } -} diff --git a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/NodeJsonBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/NodeJsonBean.java deleted file mode 100644 index e5f2b6a2c0..0000000000 --- a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/NodeJsonBean.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.devices.web; - -import java.util.List; - -public class NodeJsonBean { - String nodeId; - String nodeName; - String nodeType; - List nodePorts; - - public String getNodeId() { - return nodeId; - } - - public String getNodeName() { - return nodeName; - } - - public String getNodeType() { - return nodeType; - } - - public List getNodePorts() { - return nodePorts; - } - - public void setNodeId(String nodeId) { - this.nodeId = nodeId; - } - - public void setNodeName(String nodeName) { - this.nodeName = nodeName; - } - - public void setNodeType(String nodeType) { - this.nodeType = nodeType; - } - - public void setNodePorts(List port) { - this.nodePorts = port; - } - -} diff --git a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/PortJsonBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/PortJsonBean.java deleted file mode 100644 index 09b90d0254..0000000000 --- a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/PortJsonBean.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.devices.web; - -public class PortJsonBean { - String portId; - String portName; - String internalPortName; - - public PortJsonBean() { - this.portId = null; - this.portName = null; - this.internalPortName = null; - } - - public PortJsonBean(String id, String name, String internalName) { - this.portId = id; - this.portName = (name == null) ? internalName : name; - this.internalPortName = internalName; - } -} diff --git a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/SpanPortJsonBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/SpanPortJsonBean.java deleted file mode 100644 index b9be40b3d3..0000000000 --- a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/SpanPortJsonBean.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.devices.web; - -public class SpanPortJsonBean { - - private String nodeId; - private String spanPort; - - public String getNodeId() { - return nodeId; - } - - public void setNodeId(String nodeId) { - this.nodeId = nodeId; - } - - public String getSpanPort() { - return spanPort; - } - - public void setSpanPort(String spanPort) { - this.spanPort = spanPort; - } - -} diff --git a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/StatusJsonBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/StatusJsonBean.java deleted file mode 100644 index a3546030b4..0000000000 --- a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/StatusJsonBean.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.devices.web; - -public class StatusJsonBean { - private boolean status; - private String message; - - public boolean isStatus() { - return status; - } - - public void setStatus(boolean status) { - this.status = status; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} diff --git a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/SubnetGatewayPortBean.java b/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/SubnetGatewayPortBean.java deleted file mode 100644 index ba0d2a22f1..0000000000 --- a/opendaylight/adsal/web/devices/src/main/java/org/opendaylight/controller/devices/web/SubnetGatewayPortBean.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.devices.web; - -public class SubnetGatewayPortBean { - private String nodeName; - private String nodeId; - private PortJsonBean port; - private String nodePortId; - private String nodePortName; - - public String getNodeName() { - return nodeName; - } - public void setNodeName(String nodeName) { - this.nodeName = nodeName; - } - public String getNodeId() { - return nodeId; - } - public void setNodeId(String nodeId) { - this.nodeId = nodeId; - } - public String getNodePortId() { - return nodePortId; - } - public void setNodePortId(String nodePortId) { - this.nodePortId = nodePortId; - } - public String getNodePortName() { - return nodePortName; - } - public void setNodePortName(String nodePortName) { - this.nodePortName = nodePortName; - } -} diff --git a/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/web/devices/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/Devices-servlet.xml b/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/Devices-servlet.xml deleted file mode 100644 index af5cd8d456..0000000000 --- a/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/Devices-servlet.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/autherror.jsp b/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/autherror.jsp deleted file mode 100644 index 127a5a09dd..0000000000 --- a/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/autherror.jsp +++ /dev/null @@ -1,55 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@ page import="java.net.URL" %> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - - - - - - - - - - - - -<% - String filePath = "/WEB-INF/jsp/customerror.jsp"; - URL fileURL = pageContext.getServletContext().getResource(filePath); - if(fileURL!=null) { -%> - -<% } %> - ${title} - - - - - - - - -
- -
-
- -
-
-
- <% if (session != null) session.invalidate(); %> - - diff --git a/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/error.jsp b/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/error.jsp deleted file mode 100644 index 270d793e5c..0000000000 --- a/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/error.jsp +++ /dev/null @@ -1,8 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> -<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> - - - - - \ No newline at end of file diff --git a/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/login.jsp b/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/login.jsp deleted file mode 100644 index 270d793e5c..0000000000 --- a/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/jsp/login.jsp +++ /dev/null @@ -1,8 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> -<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> - - - - - \ No newline at end of file diff --git a/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 6294a9fb5b..0000000000 --- a/opendaylight/adsal/web/devices/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - free access - /js/* - /images/* - /css/* - /favicon.ico - - - - - DevicesApp - - DevicesGUI - /* - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - FORM - - /WEB-INF/jsp/login.jsp - /WEB-INF/jsp/error.jsp - - - - - 403 - /WEB-INF/jsp/autherror.jsp - - - - Devices - org.springframework.web.servlet.DispatcherServlet - 1 - - - - Devices - / - - - - org.opendaylight.controller.web.ControllerUISessionManager - - - - / - - - - diff --git a/opendaylight/adsal/web/devices/src/main/resources/js/page.js b/opendaylight/adsal/web/devices/src/main/resources/js/page.js deleted file mode 100644 index 935354e304..0000000000 --- a/opendaylight/adsal/web/devices/src/main/resources/js/page.js +++ /dev/null @@ -1,1814 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -//PAGE Devices -one.f = {}; - -// specify dashlets and layouts - -one.f.dashlet = { - nodesLearnt : { - id : 'nodesLearnt', - name : 'Nodes Learned' - }, - staticRouteConfig : { - id : 'staticRouteConfig', - name : 'Static Route Configuration' - }, - subnetGatewayConfig : { - id : 'subnetGatewayConfig', - name : 'Subnet Gateway Configuration' - }, - spanPortConfig : { - id : 'spanPortConfig', - name : 'SPAN Port Configuration' - }, - connection : { - id : 'connection', - name : 'Connection Manager' - } -}; - -one.f.menu = { - left : { - top : [ - one.f.dashlet.nodesLearnt - ], - bottom : [ - one.f.dashlet.staticRouteConfig, - one.f.dashlet.connection - ] - }, - right : { - top : [], - bottom : [ - one.f.dashlet.subnetGatewayConfig, - one.f.dashlet.spanPortConfig - ] - } -}; - -/**Devices Modules */ -one.f.switchmanager = { - rootUrl: "controller/web/devices", - createTable: function(columnNames, body) { - var tableAttributes = ["table-striped", "table-bordered", "table-condensed"]; - var $table = one.lib.dashlet.table.table(tableAttributes); - var tableHeaders = columnNames; - var $thead = one.lib.dashlet.table.header(tableHeaders); - var $tbody = one.lib.dashlet.table.body(body, tableHeaders); - $table.append($thead) - .append($tbody); - return $table; - }, - validateName: function(name) { - return (name.length < 256); - } -}; - -one.f.switchmanager.nodesLearnt = { - id: { - dashlet: { - popout: "one_f_switchmanager_nodesLearnt_id_dashlet_popout", - datagrid: "one_f_switchmanager_nodesLearnt_id_dashlet_datagrid" - }, - modal: { - modal: "one_f_switchmanager_nodesLearnt_id_modal_modal", - configure: "one_f_switchmanager_nodesLearnt_id_modal_configure", - ports: "one_f_switchmanager_nodesLearnt_id_modal_ports", - save: "one_f_switchmanager_nodesLearnt_id_modal_save", - datagrid: "one_f_switchmanager_nodesLearnt_id_modal_datagrid", - portsDatagrid: "one_f_switchmanager_nodesLearnt_id_modal_portsDatagrid", - form: { - nodeId: "one_f_switchmanager_nodesLearnt_id_modal_form_nodeid", - nodeName : "one_f_switchmanager_nodesLearnt_id_modal_form_nodename", - portStatus : "one_f_switchmanager_nodesLearnt_id_modal_form_portstatus", - tier: "one_f_switchmanager_nodesLearnt_id_modal_form_tier", - operationMode: "one_f_switchmanager_nodesLearnt_id_modal_form_opmode" - } - } - }, - dashlet: function($dashlet) { - var url = one.f.switchmanager.rootUrl + "/nodesLearnt"; - one.lib.dashlet.empty($dashlet); - $dashlet.append(one.lib.dashlet.header(one.f.dashlet.nodesLearnt.name)); - - one.f.switchmanager.nodesLearnt.ajax.main(url, function(content) { - var $gridHTML = one.lib.dashlet.datagrid.init(one.f.switchmanager.nodesLearnt.id.dashlet.datagrid, { - searchable: true, - filterable: false, - pagination: true, - flexibleRowsPerPage: true - }, "table-striped table-condensed"); - $dashlet.append($gridHTML); - var dataSource = one.f.switchmanager.nodesLearnt.data.gridDataSource.abridged(content); - $("#" + one.f.switchmanager.nodesLearnt.id.dashlet.datagrid).datagrid({dataSource: dataSource}).on("loaded", function() { - $(this).find("tbody a").click(one.f.switchmanager.nodesLearnt.modal.initialize.updateNode); - }); - - $("#" + one.f.switchmanager.nodesLearnt.id.dashlet.datagrid).datagrid({dataSource: dataSource}).on("loaded", function() { - $(this).find("tbody span").click(function(){ - one.f.switchmanager.nodesLearnt.modal.initialize.displayPorts($(this)); - }); - }); - - }); - }, - ajax : { - main : function(url, callback) { - $.getJSON(url, function(data) { - callback(data); - }); - } - }, - modal : { - registry : { callback:undefined }, - initialize: { - updateNode: function(evt) { - one.f.switchmanager.nodesLearnt.ajax.main(one.f.switchmanager.rootUrl + "/tiers", function(tiers) { - - var nodeId = decodeURIComponent(evt.target.id); - var h3; - var footer = []; - var $body = one.f.switchmanager.nodesLearnt.modal.body.updateNode(nodeId, JSON.parse(decodeURIComponent(evt.target.getAttribute("switchDetails"))), tiers); - if (evt.target.getAttribute("privilege") == 'WRITE'){ - h3 = "Update Node Information"; - footer = one.f.switchmanager.nodesLearnt.modal.footer.updateNode(); - } else { //disable node edit - $body.find('*').attr('disabled', 'disabled'); - h3 = 'Node Information'; - } - - var $modal = one.lib.modal.spawn(one.f.switchmanager.nodesLearnt.id.modal.configure, h3, "", footer); - // bind save button - $('#' + one.f.switchmanager.nodesLearnt.id.modal.save, $modal).click(function() { - one.f.switchmanager.nodesLearnt.modal.save($modal); - }); - - // inject body (nodePorts) - one.lib.modal.inject.body($modal, $body); - - $modal.modal().on("shown",function() { - var callback = one.f.switchmanager.nodesLearnt.modal.registry.callback; - if( callback !== undefined && $.isFunction(callback)) { - callback(); - } - }); - }); - }, - popout: function() { - var h3 = "Nodes Learned"; - var footer = one.f.switchmanager.nodesLearnt.modal.footer.popout(); - var $modal = one.lib.modal.spawn(one.f.switchmanager.nodesLearnt.id.modal.modal, h3, "", footer); - var $body = one.f.switchmanager.nodesLearnt.modal.body.popout($modal); - return $modal; - }, - displayPorts: function(ports) { - var content = JSON.parse(decodeURIComponent(ports.attr("ports"))); - - var h3 = ((ports.attr("nodeName") == "None")? ports.attr("nodeId") : ports.attr("nodeName")) - var footer = []; - var $modal = one.lib.modal.spawn(one.f.switchmanager.nodesLearnt.id.modal.ports, h3, "", footer); - - var $gridHTML = one.lib.dashlet.datagrid.init(one.f.switchmanager.nodesLearnt.id.modal.portsDatagrid, { - searchable: true, - filterable: false, - pagination: true, - flexibleRowsPerPage: true, - popout: true - }, "table-striped table-condensed"); - one.lib.modal.inject.body($modal, $gridHTML); - $modal.on("shown", function() { - var dataSource = one.f.switchmanager.nodesLearnt.data.gridDataSource.displayPorts(content); - $("#" + one.f.switchmanager.nodesLearnt.id.modal.portsDatagrid).datagrid({ - dataSource: dataSource, - stretchHeight: false - }); - }); - $modal.modal(); - } - }, - body: { - updateNode: function(nodeId, switchDetails, tiers) { - var $form = $(document.createElement('form')); - var $fieldset = $(document.createElement('fieldset')); - // node ID. not editable. - var $label = one.lib.form.label("Node ID"); - var $input = one.lib.form.input("node id"); - $input.attr('id', one.f.switchmanager.nodesLearnt.id.modal.form.nodeId); - $input.attr("disabled", true); - $input.attr("value", nodeId); - $fieldset.append($label).append($input); - // node name - var $label = one.lib.form.label("Node Name"); - var $input = one.lib.form.input("Node Name"); - $input.attr('id', one.f.switchmanager.nodesLearnt.id.modal.form.nodeName); - if(switchDetails["nodeName"] != null) { - $input.attr('value', switchDetails["nodeName"]); - } - $fieldset.append($label).append($input); - // node tier - var $label = one.lib.form.label("Tier"); - var $select = one.lib.form.select.create(tiers); - $select.attr('id', one.f.switchmanager.nodesLearnt.id.modal.form.tier); - $select.val(switchDetails["tier"]); - $fieldset.append($label).append($select); - // operation mode - var $label = one.lib.form.label("Operation Mode"); - var $select = one.lib.form.select.create( - ["Allow reactive forwarding", "Proactive forwarding only"]); - $select.attr('id', one.f.switchmanager.nodesLearnt.id.modal.form.operationMode); - if ((one.main.registry != undefined) && (one.main.registry.container != 'default')) { - $select.attr("disabled", true); - } - $select.val(switchDetails["mode"]); - $fieldset.append($label).append($select); - $form.append($fieldset); - return $form; - }, - popout: function($modal) { - var $gridHTML = one.lib.dashlet.datagrid.init(one.f.switchmanager.nodesLearnt.id.modal.datagrid, { - searchable: true, - filterable: false, - pagination: true, - flexibleRowsPerPage: true, - popout: true - }, "table-striped table-condensed"); - one.lib.modal.inject.body($modal, $gridHTML); - // attach to shown event of modal - $modal.on("shown", function() { - var url = one.f.switchmanager.rootUrl + "/nodesLearnt"; - one.f.switchmanager.nodesLearnt.ajax.main(url, function(content) { - var dataSource = one.f.switchmanager.nodesLearnt.data.gridDataSource.popout(content); - $("#" + one.f.switchmanager.nodesLearnt.id.modal.datagrid).datagrid({ - dataSource: dataSource, - stretchHeight: false - }) - .on("loaded", function() { - $("#" + one.f.switchmanager.nodesLearnt.id.modal.datagrid).find("tbody span").click(function(){ - one.f.switchmanager.nodesLearnt.modal.initialize.displayPorts($(this)); - }); - }); - }); - }); - } - }, - save: function($modal) { - var result = {}; - result['nodeName'] = $('#' + one.f.switchmanager.nodesLearnt.id.modal.form.nodeName, $modal).val(); - if(!one.f.switchmanager.validateName(result['nodeName'])) { - alert("Node name can contain upto 255 characters"); - return; - } - result['nodeId'] = $('#' + one.f.switchmanager.nodesLearnt.id.modal.form.nodeId, $modal).val(); - result['tier'] = $('#' + one.f.switchmanager.nodesLearnt.id.modal.form.tier, $modal).val(); - result['operationMode'] = $('#' + one.f.switchmanager.nodesLearnt.id.modal.form.operationMode, $modal).val(); - one.f.switchmanager.nodesLearnt.modal.ajax(result, - function(response) { - if(response.status == true) { - $modal.modal('hide'); - one.topology.update(); // refresh visual topology with new name - // TODO: Identify dashlet by inserting a nodesLearnt div - // in the dashlet() instead - one.f.switchmanager.nodesLearnt.dashlet($("#left-top .dashlet")); - } else { - alert(response.message); - } - - }); - }, - ajax: function(requestData, callback) { - $.getJSON(one.f.switchmanager.rootUrl + "/nodesLearnt/update", requestData, function(response) { - callback(response); - }); - }, - footer: { - updateNode: function() { - var footer = []; - var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.nodesLearnt.id.modal.save, "btn-primary", ""); - var $saveButton = one.lib.dashlet.button.button(saveButton); - footer.push($saveButton); - - return footer; - }, - popout: function() { - // TODO: Maybe put a close button in the footer? - return []; - } - } - }, - // data functions - data : { - gridDataSource: { - abridged: function(data) { - var source = new StaticDataSource({ - columns: [ - { - property: 'nodeName', - label: 'Node Name', - sortable: true - }, - { - property: 'nodeId', - label: 'Node ID', - sortable: true - }, - { - property: 'ports', - label: 'Ports', - sortable: true - } - ], - data: data.nodeData, - formatter: function(items) { - $.each(items, function (index, item) { - var nodeName = item.nodeName; - var nodeNameEntry = item.nodeName ? item.nodeName : "Click to update"; - item.nodeName = '' + nodeNameEntry + ''; - - var ports = item.ports; - var portsMatch = ports.match(/<\/span>/g); - var portsLength = 0; - if (portsMatch != null) { - portsLength = portsMatch.length; - } - item.ports = '' + portsLength +''; - }); - }, - delay: 0 - }); - return source; - - }, - popout: function(data) { - var source = new StaticDataSource({ - columns: [ - { - property: 'nodeName', - label: 'Node Name', - sortable: true - }, - { - property: 'nodeId', - label: 'Node ID', - sortable: true - }, - { - property: 'tierName', - label: 'Tier Name', - sortable: true - }, - { - property: 'mac', - label: 'MAC Address', - sortable: true - }, - { - property: 'ports', - label: 'Ports', - sortable: true - } - ], - data: data.nodeData, - formatter: function(items) { - $.each(items, function (index, item) { - var ports = item.ports; - var portsMatch = ports.match(/<\/span>/g); - var portsLength = 0; - if (portsMatch != null) { - portsLength = portsMatch.length; - } - item.ports = '' + portsLength +''; - }); - }, - delay: 0 - }); - return source; - }, - displayPorts: function(content){ - var data=[]; - var start=0;; - var finish=content.indexOf("
",start); - while(finish != -1){ - data.push({"ports":content.substring(start,finish)}); - start=finish+4 - finish=content.indexOf("
",start); - } - var source = new StaticDataSource({ - columns: [ - { - property: 'ports', - label: 'Ports', - sortable: true - } - ], - data:data, - delay: 0 - }); - - return source; - } - }, - abridged : function(data) { - var result = []; - $.each(data.nodeData, function(key, value) { - var tr = {}; - var entry = []; - var nodeNameEntry = value["nodeName"] ? value["nodeName"] : "Click to update"; - - // TODO: Move anchor tag creation to one.lib.form. - var aTag; - aTag = document.createElement("a"); - aTag.privilege = data.privilege; - aTag.addEventListener("click", one.f.switchmanager.nodesLearnt.modal.initialize.updateNode); - aTag.addEventListener("mouseover", function(evt) { - evt.target.style.cursor = "pointer"; - }, false); - aTag.setAttribute("id", encodeURIComponent(value["nodeId"])); - aTag.switchDetails = value; - aTag.innerHTML = nodeNameEntry; - entry.push(aTag); - entry.push(value["nodeId"]); - entry.push(value["ports"]); - tr.entry = entry; - result.push(tr); - }); - return result; - }, - popout : function(data) { - var result = []; - $.each(data.nodeData, function(key, value) { - var tr = {}; - // fill up all the td's - var entry = []; - var nodenameentry = value["nodeName"] ? value["nodeName"] : "No name provided"; - entry.push(nodenameentry); - entry.push(value["nodeId"]); - entry.push(value["tierName"]); - entry.push(value["mac"]); - entry.push(value["ports"]); - tr.entry = entry; - result.push(tr); - }); - return result; - } - } -}; - -one.f.switchmanager.subnetGatewayConfig = { - id: { - dashlet: { - addIPAddress: "one_f_switchmanager_subnetGatewayConfig_id_dashlet_addIP", - addPorts: "one_f_switchmanager_subnetGatewayConfig_id_dashlet_addPorts", - removeIPAddress: "one_f_switchmanager_subnetGatewayConfig_id_dashlet_removeIP", - datagrid: "one_f_switchmanager_subnetGatewayConfig_id_dashlet_datagrid", - selectAll: "one_f_switchmanager_subnetGatewayConfig_id_dashlet_selectAll" - }, - modal: { - modal: "one_f_switchmanager_subnetGatewayConfig_id_modal_modal", - ports : "one_f_switchmanager_subnetGatewayConfig_id_modal_ports", - save: "one_f_switchmanager_subnetGatewayConfig_id_modal_save", - remove: "one_f_switchmanager_subnetGatewayConfig_id_modal_remove", - cancel: "one_f_switchmanager_subnetGatewayConfig_id_modal_cancel", - form: { - name : "one_f_switchmanager_subnetGatewayConfig_id_modal_form_gatewayname", - gatewayIPAddress : "one_f_switchmanager_subnetGatewayConfig_id_modal_form_gatewayipaddress", - nodeId: "one_f_switchmanager_subnetGatewayConfig_id_modal_form_nodeid", - ports: "one_f_switchmanager_subnetGatewayConfig_id_modal_form_ports" - } - } - }, - // device ajax calls - dashlet: function($dashlet) { - one.lib.dashlet.empty($dashlet); - $dashlet.append(one.lib.dashlet.header(one.f.dashlet.subnetGatewayConfig.name)); - // Add gateway IP Address button - var url = one.f.switchmanager.rootUrl + "/subnets"; - one.f.switchmanager.subnetGatewayConfig.ajax.main(url, {}, function(content) { - - if (content.privilege === 'WRITE') { - var button = one.lib.dashlet.button.single("Add Gateway IP Address", - one.f.switchmanager.subnetGatewayConfig.id.dashlet.addIPAddress, "btn-primary", "btn-mini"); - var $button = one.lib.dashlet.button.button(button); - $button.click(function() { - var $modal = one.f.switchmanager.subnetGatewayConfig.modal.initialize.gateway(); - $modal.modal(); - }); - $dashlet.append($button); - - // Delete gateway ip address button - var button = one.lib.dashlet.button.single("Remove Gateway IP Address", - one.f.switchmanager.subnetGatewayConfig.id.dashlet.removeIPAddress, "btn-danger", "btn-mini"); - var $button = one.lib.dashlet.button.button(button); - $button.click(function() { - var gatewaysToDelete = []; - var checkedCheckBoxes = $("#" + one.f.switchmanager.subnetGatewayConfig.id.dashlet.datagrid).find("tbody input:checked") - checkedCheckBoxes.each(function(index, value) { - gatewaysToDelete.push(checkedCheckBoxes[index].id); - }); - if (checkedCheckBoxes.size() === 0) { - return false; - } - one.f.switchmanager.subnetGatewayConfig.modal.removeMultiple.dialog(gatewaysToDelete) - }); - $dashlet.append($button); - - // Add Ports button - var button = one.lib.dashlet.button.single("Add Ports", - one.f.switchmanager.subnetGatewayConfig.id.dashlet.addPorts, "btn-primary", "btn-mini"); - var $button = one.lib.dashlet.button.button(button); - $button.click(function() { - if (one.f.switchmanager.subnetGatewayConfig.registry.gateways.length === 0) { - alert('No Gateways Exist'); - return false; - } - var $modal = one.f.switchmanager.subnetGatewayConfig.modal.initialize.ports(); - $modal.modal(); - }); - $dashlet.append($button); - } - var $gridHTML = one.lib.dashlet.datagrid.init(one.f.switchmanager.subnetGatewayConfig.id.dashlet.datagrid, { - searchable: true, - filterable: false, - pagination: true, - flexibleRowsPerPage: true - }, "table-striped table-condensed"); - $dashlet.append($gridHTML); - var dataSource = one.f.switchmanager.subnetGatewayConfig.data.devicesgrid(content); - $("#" + one.f.switchmanager.subnetGatewayConfig.id.dashlet.datagrid).datagrid({dataSource: dataSource}) - .on("loaded", function() { - $("#"+one.f.switchmanager.subnetGatewayConfig.id.dashlet.selectAll).click(function() { - $("#" + one.f.switchmanager.subnetGatewayConfig.id.dashlet.datagrid).find(':checkbox').prop('checked', - $("#"+one.f.switchmanager.subnetGatewayConfig.id.dashlet.selectAll).is(':checked')); - }); - $(".subnetGatewayConfig").click(function(e){ - if (!$('.subnetGatewayConfig[type=checkbox]:not(:checked)').length) { - $("#"+one.f.switchmanager.subnetGatewayConfig.id.dashlet.selectAll) - .prop("checked", - true); - } else { - $("#"+one.f.switchmanager.subnetGatewayConfig.id.dashlet.selectAll) - .prop("checked", - false); - } - e.stopPropagation(); - }); - }); - }); - }, - ajax : { - main : function(url, requestData, callback) { - $.getJSON(url, requestData, function(data) { - callback(data); - }); - } - }, - registry: {}, - modal : { - initialize: { - gateway: function() { - var h3 = "Add Gateway IP Address"; - var footer = one.f.switchmanager.subnetGatewayConfig.modal.footer(); - var $modal = one.lib.modal.spawn(one.f.switchmanager.subnetGatewayConfig.id.modal.modal, h3, "", footer); - // bind save button - $('#' + one.f.switchmanager.subnetGatewayConfig.id.modal.save, $modal).click(function() { - one.f.switchmanager.subnetGatewayConfig.modal.save.gateway($modal); - }); - var $body = one.f.switchmanager.subnetGatewayConfig.modal.body.gateway(); - one.lib.modal.inject.body($modal, $body); - return $modal; - }, - ports: function() { - var h3 = "Add Ports"; - var footer = one.f.switchmanager.subnetGatewayConfig.modal.footer(); - var $modal = one.lib.modal.spawn(one.f.switchmanager.subnetGatewayConfig.id.modal.ports, h3, "", footer); - // bind save button - $('#' + one.f.switchmanager.subnetGatewayConfig.id.modal.save, $modal).click(function() { - one.f.switchmanager.subnetGatewayConfig.modal.save.ports($modal); - }); - - // TODO: Change to subnetGateway instead. - one.f.switchmanager.spanPortConfig.modal.ajax.nodes(function(nodes, nodeports) { - var $body = one.f.switchmanager.subnetGatewayConfig.modal.body.ports(nodes, nodeports); - one.lib.modal.inject.body($modal, $body); - }); - return $modal; - } - }, - save: { - gateway: function($modal) { - var result = {}; - result['gatewayName'] = $('#' + one.f.switchmanager.subnetGatewayConfig.id.modal.form.name, $modal).val(); - if(!one.f.switchmanager.validateName(result['gatewayName'])) { - alert("Gateway name can contain upto 255 characters"); - return; - } - result['gatewayIPAddress'] = $('#' + one.f.switchmanager.subnetGatewayConfig.id.modal.form.gatewayIPAddress, $modal).val(); - one.f.switchmanager.subnetGatewayConfig.modal.ajax.gateway(result, - function(response) { - if(response.status == true) { - $modal.modal('hide'); - one.f.switchmanager.subnetGatewayConfig.dashlet($("#right-bottom .dashlet")); - } else { - alert(response.message); - } - }); - }, - ports: function($modal) { - var result = {}; - var gatewayRegistryIndex = $('#' + one.f.switchmanager.subnetGatewayConfig.id.modal.form.name, $modal).val(); - result['portsName'] = one.f.switchmanager.subnetGatewayConfig.registry.gateways[gatewayRegistryIndex]; - result['nodeId'] = $('#' + one.f.switchmanager.subnetGatewayConfig.id.modal.form.nodeId, $modal).val(); - result['ports'] = $('#' + one.f.switchmanager.subnetGatewayConfig.id.modal.form.ports, $modal).val(); - if(!result['portsName'] || result['portsName'] == "") { - alert("No gateway chosen. Cannot add port"); - return; - } - if(!result['nodeId'] || result['nodeId'] == "") { - alert("Please select a node."); - return; - } - if(!result['ports'] || result['ports'] == "") { - alert("Please choose a port."); - return; - } - one.f.switchmanager.subnetGatewayConfig.modal.ajax.ports(result, - function(response) { - if(response.status == true) { - $modal.modal('hide'); - one.f.switchmanager.subnetGatewayConfig.dashlet($("#right-bottom .dashlet")); - } else { - alert(response.message); - } - }); - } - }, - body: { - gateway: function() { - var $form = $(document.createElement('form')); - var $fieldset = $(document.createElement('fieldset')); - // gateway name - var $label = one.lib.form.label("Name"); - var $input = one.lib.form.input("Name"); - $input.attr('id', one.f.switchmanager.subnetGatewayConfig.id.modal.form.name); - $fieldset.append($label).append($input); - // gateway IP Mask - var $label = one.lib.form.label("Gateway IP Address/Mask"); - var $input = one.lib.form.input("Gateway IP Address/Mask"); - var $help = one.lib.form.help('Example: 192.168.10.254/16'); - $input.attr('id', one.f.switchmanager.subnetGatewayConfig.id.modal.form.gatewayIPAddress); - $fieldset.append($label).append($input).append($help); - - $form.append($fieldset); - return $form; - }, - ports: function(nodes, nodeports) { - var $form = $(document.createElement('form')); - var $fieldset = $(document.createElement('fieldset')); - // gateways drop down - var $label = one.lib.form.label("Gateway Name"); - var $select = one.lib.form.select.create(one.f.switchmanager.subnetGatewayConfig.registry.gateways); - $select.attr('id', one.f.switchmanager.subnetGatewayConfig.id.modal.form.name); - one.lib.form.select.prepend($select, { '' : 'Please Select a Gateway' }); - $select.val($select.find("option:first").val()); - $fieldset.append($label).append($select); - - // node ID - var $label = one.lib.form.label("Node ID"); - var $select = one.lib.form.select.create(nodes); - $select.attr('id', one.f.switchmanager.subnetGatewayConfig.id.modal.form.nodeId); - one.lib.form.select.prepend($select, { '' : 'Please Select a Node' }); - $select.val($select.find("option:first").val()); - $fieldset.append($label).append($select); - - // bind onchange - $select.change(function() { - // retrieve port value - var node = $(this).find('option:selected').attr('value'); - one.f.switchmanager.subnetGatewayConfig.registry['currentNode'] = node; - var $ports = $('#' + one.f.switchmanager.subnetGatewayConfig.id.modal.form.ports); - var ports = nodeports[node]; - var options = {}; - $(ports).each(function(idx, val) { - options[val.internalPortName] = val.portName+' ('+val.portId+')'; - }); - one.lib.form.select.inject($ports, options); - one.lib.form.select.prepend($ports, { '' : 'Please Select a Port' }); - $ports.val($ports.find("option:first").val()); - }); - - // ports - var $label = one.lib.form.label("Select Port"); - var $select = one.lib.form.select.create(); - one.lib.form.select.prepend($select, { '' : 'Please Select a Port' }); - $select.attr('id', one.f.switchmanager.subnetGatewayConfig.id.modal.form.ports); - $fieldset.append($label).append($select); - - $form.append($fieldset); - return $form; - } - }, - ajax: { - gateway: function(requestData, callback) { - $.getJSON(one.f.switchmanager.rootUrl + "/subnetGateway/add", requestData, function(data) { - callback(data); - }); - }, - ports: function(requestData, callback) { - $.getJSON(one.f.switchmanager.rootUrl + "/subnetGateway/ports/add", requestData, function(data) { - callback(data); - }); - } - }, - footer : function() { - var footer = []; - var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.subnetGatewayConfig.id.modal.save, "btn-primary", ""); - var $saveButton = one.lib.dashlet.button.button(saveButton); - footer.push($saveButton); - return footer; - }, - removeMultiple: { - dialog: function(gatewaysToDelete) { - var h3 = 'Remove Gateway IP Address'; - - var footer = one.f.switchmanager.subnetGatewayConfig.modal.removeMultiple.footer(); - var $body = one.f.switchmanager.subnetGatewayConfig.modal.removeMultiple.body(gatewaysToDelete); - var $modal = one.lib.modal.spawn(one.f.switchmanager.subnetGatewayConfig.id.modal.modal, h3, $body, footer); - - // bind close button - $('#'+one.f.switchmanager.subnetGatewayConfig.id.modal.cancel, $modal).click(function() { - $modal.modal('hide'); - }); - - // bind remove rule button - $('#'+one.f.switchmanager.subnetGatewayConfig.id.modal.remove, $modal).click(this, function(e) { - var requestData = {}; - if (gatewaysToDelete.length > 0) { - requestData["gatewaysToDelete"] = gatewaysToDelete.toString(); - var url = one.f.switchmanager.rootUrl + "/subnetGateway/delete"; - one.f.switchmanager.subnetGatewayConfig.ajax.main(url, requestData, function(response) { - $modal.modal('hide'); - if (response.status == true) { - // refresh dashlet by passing dashlet div as param - one.lib.alert("Gateway IP Address(es) successfully removed"); - } else { - alert(response.message); - } - one.f.switchmanager.subnetGatewayConfig.dashlet($("#right-bottom .dashlet")); - }); - } - }); - $modal.modal(); - }, - footer : function() { - var footer = []; - var remove = one.lib.dashlet.button.single('Remove Gateway IP Address',one.f.switchmanager.subnetGatewayConfig.id.modal.remove, 'btn-danger', ''); - var $remove = one.lib.dashlet.button.button(remove); - footer.push($remove); - - var cancel = one.lib.dashlet.button.single('Cancel', one.f.switchmanager.subnetGatewayConfig.id.modal.cancel, '', ''); - var $cancel = one.lib.dashlet.button.button(cancel); - footer.push($cancel); - - return footer; - }, - body : function (gatewayList) { - var $p = $(document.createElement('p')); - var p = 'Remove the following Gateway IP Address(es)?'; - //creata a BS label for each rule and append to list - $(gatewayList).each(function(){ - var $span = $(document.createElement('span')); - $span.append(this); - p += '
' + $span[0].outerHTML; - }); - $p.append(p); - return $p; - } - } - }, - // data functions - data : { - devicesgrid: function(data) { - one.f.switchmanager.subnetGatewayConfig.registry.gateways = []; - var source = new StaticDataSource({ - columns: [ - { - property: 'selector', - label: "", - sortable: false - }, - { - property: 'name', - label: 'Name', - sortable: true - }, - { - property: 'subnet', - label: 'Gateway IP Address/Mask', - sortable: true - }, - { - property: 'nodePorts', - label: 'Ports', - sortable: false - } - ], - data: data.nodeData, - formatter: function(items) { - $.each(items, function(index, tableRow) { - tableRow["selector"] = ''; - var json = tableRow["nodePorts"]; - var nodePorts = JSON.parse(json); - var nodePortHtml = "
"; - $.each(nodePorts, function(index, nodePort) { - nodePortHtml += nodePort["nodePortName"] + " @ " + nodePort["nodeName"]; - nodePortHtml += " "; - nodePortHtml += 'Remove'; - nodePortHtml += "
"; - }); - nodePortHtml += "
"; - tableRow["nodePorts"] = nodePortHtml; - }); - - }, - delay: 0 - }); - // populate the registry with subnet names - one.f.switchmanager.subnetGatewayConfig.registry.gateways = []; - $.each(data.nodeData, function(key, value) { - one.f.switchmanager.subnetGatewayConfig.registry.gateways.push(value["name"]); - }); - return source; - }, - devices : function(data) { - var result = []; - one.f.switchmanager.subnetGatewayConfig.registry.gateways = []; - $.each(data.nodeData, function(key, value) { - var tr = {}; - // fill up all the td's - var subnetConfigObject = $.parseJSON(value["json"]); - var nodePorts = subnetConfigObject.nodePorts; - var $nodePortsContainer = $(document.createElement("div")); - - for(var i = 0; i < nodePorts.length; i++) { - var nodePort = nodePorts[i]; - $nodePortsContainer.append(nodePort + " "); - // add delete anchor tag to delete ports - var aTag = document.createElement("a"); - aTag.setAttribute("id", encodeURIComponent(nodePort)); - aTag.gatewayName = value["name"]; - aTag.addEventListener("click", function(evt) { - var htmlPortAnchor = evt.target; - var requestData = {}; - requestData["gatewayName"] = evt.target.gatewayName; - requestData["nodePort"] = decodeURIComponent(evt.target.id); - // make ajax call to delete port - var url = one.f.switchmanager.rootUrl + "/subnetGateway/ports/delete"; - one.f.switchmanager.subnetGatewayConfig.ajax.main(url, requestData, function(response) { - if(response.status == true) { - // refresh dashlet by passing dashlet div as param - one.f.switchmanager.subnetGatewayConfig.dashlet($("#right-bottom .dashlet")); - } else { - alert(response.message); - } - }); - - }); - aTag.addEventListener("mouseover", function(evt) { - evt.target.style.cursor = "pointer"; - }, false); - aTag.innerHTML = "Remove"; - $nodePortsContainer.append(aTag); - $nodePortsContainer.append("
"); - } - - // store gateways in the registry so that they can be used in the add ports popup - one.f.switchmanager.subnetGatewayConfig.registry.gateways.push(value["name"]); - var entry = []; - var checkbox = document.createElement("input"); - checkbox.setAttribute("type", "checkbox"); - checkbox.setAttribute("id", value["name"]); - entry.push(checkbox); - entry.push(value["name"]); - entry.push(value["subnet"]); - entry.push($nodePortsContainer); - tr.entry = entry; - result.push(tr); - }); - return result; - } - }, - actions: { - deleteNodePort: function(htmlPortAnchor) { - var requestData = {}; - requestData["gatewayName"] = htmlPortAnchor.getAttribute("gatewayName"); - requestData["nodePort"] = decodeURIComponent(htmlPortAnchor.id); - // make ajax call to delete port - var url = one.f.switchmanager.rootUrl + "/subnetGateway/ports/delete"; - one.f.switchmanager.subnetGatewayConfig.ajax.main(url, requestData, function(response) { - if(response.status == true) { - // refresh dashlet by passing dashlet div as param - one.f.switchmanager.subnetGatewayConfig.dashlet($("#right-bottom .dashlet")); - } else { - alert(response.message); - } - }); - } - } -} - -one.f.switchmanager.staticRouteConfig = { - id: { - dashlet: { - add: "one_f_switchmanager_staticRouteConfig_id_dashlet_add", - remove: "one_f_switchmanager_staticRouteConfig_id_dashlet_remove", - datagrid: "one_f_switchmanager_staticRouteConfig_id_dashlet_datagrid", - selectAll: "one_f_switchmanager_staticRouteConfig_id_dashlet_selectAll" - }, - modal: { - modal: "one_f_switchmanager_staticRouteConfig_id_modal_modal", - save: "one_f_switchmanager_staticRouteConfig_id_modal_save", - cancel: "one_f_switchmanager_staticRouteConfig_id_modal_cancel", - remove: "one_f_switchmanager_staticRouteConfig_id_modal_remove", - form: { - routeName : "one_f_switchmanager_staticRouteConfig_id_modal_form_routename", - staticRoute : "one_f_switchmanager_staticRouteConfig_id_modal_form_staticroute", - nextHop : "one_f_switchmanager_staticRouteConfig_id_modal_form_nexthop", - } - } - }, - dashlet: function($dashlet) { - one.lib.dashlet.empty($dashlet); - var url = one.f.switchmanager.rootUrl + "/staticRoutes"; - one.f.switchmanager.staticRouteConfig.ajax.main(url, {}, function(content) { - - if (content.privilege === 'WRITE') { - // Add static route button - var button = one.lib.dashlet.button.single("Add Static Route", one.f.switchmanager.staticRouteConfig.id.dashlet.add, "btn-primary", "btn-mini"); - var $button = one.lib.dashlet.button.button(button); - $button.click(function() { - var $modal = one.f.switchmanager.staticRouteConfig.modal.initialize(); - $modal.modal(); - }); - $dashlet.append(one.lib.dashlet.header(one.f.dashlet.staticRouteConfig.name)); - $dashlet.append($button); - - // Delete static route button - var button = one.lib.dashlet.button.single("Remove Static Route", one.f.switchmanager.staticRouteConfig.id.dashlet.remove, "btn-danger", "btn-mini"); - var $button = one.lib.dashlet.button.button(button); - $button.click(function() { - var routesToDelete = []; - var checkedCheckBoxes = $("#" + one.f.switchmanager.staticRouteConfig.id.dashlet.datagrid).find("tbody input:checked"); - checkedCheckBoxes.each(function(index, value) { - routesToDelete.push(checkedCheckBoxes[index].id); - }); - if (checkedCheckBoxes.size() === 0) { - return false; - } - one.f.switchmanager.staticRouteConfig.modal.removeMultiple.dialog(routesToDelete); - }); - $dashlet.append($button); - } - var $gridHTML = one.lib.dashlet.datagrid.init(one.f.switchmanager.staticRouteConfig.id.dashlet.datagrid, { - searchable: true, - filterable: false, - pagination: true, - flexibleRowsPerPage: true - }, "table-striped table-condensed"); - $dashlet.append($gridHTML); - var dataSource = one.f.switchmanager.staticRouteConfig.data.staticRouteConfigGrid(content); - $("#" + one.f.switchmanager.staticRouteConfig.id.dashlet.datagrid).datagrid({dataSource: dataSource}) - .on("loaded", function() { - $("#"+one.f.switchmanager.staticRouteConfig.id.dashlet.selectAll).click(function() { - $("#" + one.f.switchmanager.staticRouteConfig.id.dashlet.datagrid).find(':checkbox').prop('checked', - $("#"+one.f.switchmanager.staticRouteConfig.id.dashlet.selectAll).is(':checked')); - }); - $(".staticRoute").click(function(e){ - if (!$('.staticRoute[type=checkbox]:not(:checked)').length) { - $("#"+one.f.switchmanager.staticRouteConfig.id.dashlet.selectAll) - .prop("checked", - true); - } else { - $("#"+one.f.switchmanager.staticRouteConfig.id.dashlet.selectAll) - .prop("checked", - false); - } - e.stopPropagation(); - }); - }); - }); - }, - // device ajax calls - ajax : { - main : function(url, requestData, callback) { - $.getJSON(url, requestData, function(data) { - callback(data); - }); - } - }, - registry: {}, - modal : { - initialize: function() { - var h3 = "Add Static Route"; - var footer = one.f.switchmanager.staticRouteConfig.modal.footer(); - var $modal = one.lib.modal.spawn(one.f.switchmanager.staticRouteConfig.id.modal.modal, h3, "", footer); - // bind save button - $('#' + one.f.switchmanager.staticRouteConfig.id.modal.save, $modal).click(function() { - one.f.switchmanager.staticRouteConfig.modal.save($modal); - }); - var $body = one.f.switchmanager.staticRouteConfig.modal.body(); - one.lib.modal.inject.body($modal, $body); - return $modal; - }, - save: function($modal) { - var result = {}; - result['routeName'] = $('#' + one.f.switchmanager.staticRouteConfig.id.modal.form.routeName, $modal).val(); - result['staticRoute'] = $('#' + one.f.switchmanager.staticRouteConfig.id.modal.form.staticRoute, $modal).val(); - result['nextHop'] = $('#' + one.f.switchmanager.staticRouteConfig.id.modal.form.nextHop, $modal).val(); - one.f.switchmanager.staticRouteConfig.modal.ajax.staticRouteConfig(result, function(response) { - if(response.status == true) { - $modal.modal('hide'); - // refresh dashlet by passing dashlet div as param - one.f.switchmanager.staticRouteConfig.dashlet($("#left-bottom .dashlet")); - } else { - // TODO: Show error message in a error message label instead. - alert(response.message); - } - }); - }, - body: function() { - var $form = $(document.createElement('form')); - var $fieldset = $(document.createElement('fieldset')); - // static route name - var $label = one.lib.form.label("Name"); - var $input = one.lib.form.input("Name"); - $input.attr('id', one.f.switchmanager.staticRouteConfig.id.modal.form.routeName); - $fieldset.append($label).append($input); - // static route IP Mask - var $label = one.lib.form.label("Static Route"); - var $input = one.lib.form.input("Static Route"); - var $help = one.lib.form.help('Example: 53.55.0.0/16'); - $input.attr('id', one.f.switchmanager.staticRouteConfig.id.modal.form.staticRoute); - $fieldset.append($label).append($input).append($help); - // static route IP Mask - var $label = one.lib.form.label("Next Hop"); - var $input = one.lib.form.input("Next Hop"); - var $help = one.lib.form.help('Example: 192.168.10.254'); - $input.attr('id', one.f.switchmanager.staticRouteConfig.id.modal.form.nextHop); - $fieldset.append($label).append($input).append($help); - // return - $form.append($fieldset); - return $form; - }, - ajax: { - staticRouteConfig: function(requestData, callback) { - $.getJSON(one.f.switchmanager.rootUrl + "/staticRoute/add", requestData, function(data) { - callback(data); - }); - } - }, - data : { - - }, - footer : function() { - var footer = []; - var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.staticRouteConfig.id.modal.save, "btn-primary", ""); - var $saveButton = one.lib.dashlet.button.button(saveButton); - footer.push($saveButton); - return footer; - }, - removeMultiple: { - dialog: function(routesToDelete) { - var h3 = 'Remove Static Route'; - - var footer = one.f.switchmanager.staticRouteConfig.modal.removeMultiple.footer(); - var $body = one.f.switchmanager.staticRouteConfig.modal.removeMultiple.body(routesToDelete); - var $modal = one.lib.modal.spawn(one.f.switchmanager.staticRouteConfig.id.modal.modal, h3, $body, footer); - - // bind close button - $('#'+one.f.switchmanager.staticRouteConfig.id.modal.cancel, $modal).click(function() { - $modal.modal('hide'); - }); - - // bind remove rule button - $('#'+one.f.switchmanager.staticRouteConfig.id.modal.remove, $modal).click(this, function(e) { - if (routesToDelete.length > 0) { - var requestData = {}; - requestData["routesToDelete"] = routesToDelete.toString(); - var url = one.f.switchmanager.rootUrl + "/staticRoute/delete"; - one.f.switchmanager.staticRouteConfig.ajax.main(url, requestData, function(response) { - $modal.modal('hide'); - if (response.status == true) { - // refresh dashlet by passing dashlet div as param - one.lib.alert("Static Route(s) successfully removed"); - } else { - alert(response.message); - } - one.f.switchmanager.staticRouteConfig.dashlet($("#left-bottom .dashlet")); - }); - } - }); - $modal.modal(); - }, - footer : function() { - var footer = []; - var remove = one.lib.dashlet.button.single('Remove Static Route',one.f.switchmanager.staticRouteConfig.id.modal.remove, 'btn-danger', ''); - var $remove = one.lib.dashlet.button.button(remove); - footer.push($remove); - - var cancel = one.lib.dashlet.button.single('Cancel', one.f.switchmanager.staticRouteConfig.id.modal.cancel, '', ''); - var $cancel = one.lib.dashlet.button.button(cancel); - footer.push($cancel); - - return footer; - }, - body : function (staticRouteList) { - var $p = $(document.createElement('p')); - var p = 'Remove the following Static Route(s)?'; - //creata a BS label for each rule and append to list - $(staticRouteList).each(function(){ - var $span = $(document.createElement('span')); - $span.append(this); - p += '
' + $span[0].outerHTML; - }); - $p.append(p); - return $p; - } - } - }, - // data functions - data : { - staticRouteConfigGrid: function(data) { - var source = new StaticDataSource({ - columns: [ - { - property: 'selector', - label: "", - sortable: false - }, - { - property: 'name', - label: 'Name', - sortable: true - }, - { - property: 'staticRoute', - label: 'Static Route', - sortable: true - }, - { - property: 'nextHop', - label: 'Next Hop Address', - sortable: true - } - ], - data: data.nodeData, - formatter: function(items) { - $.each(items, function(index, item) { - item["selector"] = ''; - }); - - }, - delay: 0 - }); - return source; - }, - staticRouteConfig : function(data) { - var result = []; - $.each(data.nodeData, function(key, value) { - var tr = {}; - // fill up all the td's - var entry = []; - var checkbox = document.createElement("input"); - checkbox.setAttribute("type", "checkbox"); - checkbox.setAttribute("id", value["name"]); - entry.push(checkbox); - entry.push(value["name"]); - entry.push(value["staticRoute"]); - entry.push(value["nextHop"]); - tr.entry = entry; - result.push(tr); - }); - return result; - } - } -} - -one.f.switchmanager.spanPortConfig = { - id: { - dashlet: { - add: "one_f_switchmanager_spanPortConfig_id_dashlet_add", - remove: "one_f_switchmanager_spanPortConfig_id_dashlet_remove", - datagrid: "one_f_switchmanager_spanPortConfig_id_dashlet_datagrid", - selectAllFlows: "one_f_switchmanager_spanPortConfig_id_dashlet_selectAllFlows" - }, - modal: { - modal: "one_f_switchmanager_spanPortConfig_id_modal_modal", - save: "one_f_switchmanager_spanPortConfig_id_modal_save", - cancel: "one_f_switchmanager_spanPortConfig_id_modal_cancel", - remove: "one_f_switchmanager_spanPortConfig_id_modal_remove", - form: { - name : "one_f_switchmanager_spanPortConfig_id_modal_form_name", - nodes : "one_f_switchmanager_spanPortConfig_id_modal_form_nodes", - port : "one_f_switchmanager_spanPortConfig_id_modal_form_port", - } - } - }, - dashlet: function($dashlet) { - one.lib.dashlet.empty($dashlet); - - //populate table in dashlet - var url = one.f.switchmanager.rootUrl + "/spanPorts"; - one.f.switchmanager.spanPortConfig.ajax.main(url, {}, function(content) { - - if (content.privilege === 'WRITE') { - - // Add span port button - var button = one.lib.dashlet.button.single("Add SPAN Port", one.f.switchmanager.spanPortConfig.id.dashlet.add, "btn-primary", "btn-mini"); - var $button = one.lib.dashlet.button.button(button); - - $button.click(function() { - var $modal = one.f.switchmanager.spanPortConfig.modal.initialize(); - $modal.modal(); - }); - $dashlet.append(one.lib.dashlet.header(one.f.dashlet.spanPortConfig.name)); - $dashlet.append($button); - - // Delete span port button - var button = one.lib.dashlet.button.single("Remove SPAN Port", one.f.switchmanager.spanPortConfig.id.dashlet.remove, "btn-danger", "btn-mini"); - var $button = one.lib.dashlet.button.button(button); - $button.click(function() { - var spanPortsToDelete = []; - var checkedCheckBoxes = $("#" + one.f.switchmanager.spanPortConfig.id.dashlet.datagrid).find("tbody input:checked"); - - if (checkedCheckBoxes.size() === 0) { - return false; - } - checkedCheckBoxes.each(function(index, value) { - var spanPortObj = {}; - spanPortObj['spanPortJson'] = decodeURIComponent(checkedCheckBoxes[index].getAttribute("spanPort")); - spanPortObj['spanPortNodeName'] = checkedCheckBoxes[index].getAttribute("spanPortNode"); - spanPortObj['spanPortPortName'] = checkedCheckBoxes[index].getAttribute("spanPortPort"); - - spanPortsToDelete.push(spanPortObj); - }); - one.f.switchmanager.spanPortConfig.modal.removeMultiple.dialog(spanPortsToDelete); - }); - $dashlet.append($button); - } - var $gridHTML = one.lib.dashlet.datagrid.init(one.f.switchmanager.spanPortConfig.id.dashlet.datagrid, { - searchable: true, - filterable: false, - pagination: true, - flexibleRowsPerPage: true - }, "table-striped table-condensed"); - $dashlet.append($gridHTML); - var dataSource = one.f.switchmanager.spanPortConfig.data.spanPortConfigGrid(content); - $("#" + one.f.switchmanager.spanPortConfig.id.dashlet.datagrid).datagrid({dataSource: dataSource}) - .on("loaded", function() { - $("#"+one.f.switchmanager.spanPortConfig.id.dashlet.selectAll).click(function() { - $("#" + one.f.switchmanager.spanPortConfig.id.dashlet.datagrid).find(':checkbox').prop('checked', - $("#"+one.f.switchmanager.spanPortConfig.id.dashlet.selectAll).is(':checked')); - }); - $(".spanPortConfig").click(function(e){ - if (!$('.spanPortConfig[type=checkbox]:not(:checked)').length) { - $("#"+one.f.switchmanager.spanPortConfig.id.dashlet.selectAll) - .prop("checked", - true); - } else { - $("#"+one.f.switchmanager.spanPortConfig.id.dashlet.selectAll) - .prop("checked", - false); - } - e.stopPropagation(); - }); - }); - }); - }, - // device ajax calls - ajax : { - main : function(url, requestData, callback) { - $.getJSON(url, requestData, function(data) { - callback(data); - }); - } - }, - registry: {}, - modal : { - initialize: function() { - var h3 = "Add SPAN Port"; - var footer = one.f.switchmanager.spanPortConfig.modal.footer(); - var $modal = one.lib.modal.spawn(one.f.switchmanager.spanPortConfig.id.modal.modal, h3, "", footer); - // bind save button - $('#' + one.f.switchmanager.spanPortConfig.id.modal.save, $modal).click(function() { - one.f.switchmanager.spanPortConfig.modal.save($modal); - }); - - one.f.switchmanager.spanPortConfig.modal.ajax.nodes(function(nodes, nodeports) { - var $body = one.f.switchmanager.spanPortConfig.modal.body(nodes, nodeports); - one.lib.modal.inject.body($modal, $body); - }); - return $modal; - }, - save: function($modal) { - var result = {}; - result['nodeId'] = $('#' + one.f.switchmanager.spanPortConfig.id.modal.form.nodes, $modal).val(); - result['spanPort'] = $('#' + one.f.switchmanager.spanPortConfig.id.modal.form.port, $modal).val(); - one.f.switchmanager.spanPortConfig.modal.ajax.saveSpanPortConfig(result, - function(response) { - if(response.status == true) { - $modal.modal('hide'); - one.f.switchmanager.spanPortConfig.dashlet($("#right-bottom .dashlet")); - } else { - alert(response.message); - } - - }); - }, - body: function(nodes, nodeports) { - var $form = $(document.createElement('form')); - var $fieldset = $(document.createElement('fieldset')); - // node - var $label = one.lib.form.label("Node"); - var $select = one.lib.form.select.create(nodes); - one.lib.form.select.prepend($select, { '' : 'Please Select a Node' }); - $select.val($select.find("option:first").val()); - $select.attr('id', one.f.switchmanager.spanPortConfig.id.modal.form.nodes); - - // bind onchange - $select.change(function() { - // retrieve port value - var nodeId = $(this).find('option:selected').attr('value'); - one.f.switchmanager.spanPortConfig.registry['currentNode'] = nodeId; - var $ports = $('#'+one.f.switchmanager.spanPortConfig.id.modal.form.port); - var ports = one.f.switchmanager.spanPortConfig.registry['nodePorts'][nodeId] - var options = {}; - $(ports).each(function(idx, val) { - options[val.internalPortName] = val.portName+' ('+val.portId+')'; - }); - one.lib.form.select.inject($ports, options); - one.lib.form.select.prepend($ports, {'':'Please Select a Port'}); - $ports.val($ports.find('option:first').val()); - }); - - $fieldset.append($label).append($select); - // input port - var $label = one.lib.form.label("Port"); - var $select = one.lib.form.select.create(); - one.lib.form.select.prepend($select, {'':'None'}); - $select.attr('id', one.f.switchmanager.spanPortConfig.id.modal.form.port); - $select.val($select.find('option:first').val()); - $fieldset.append($label).append($select); - - // return - $form.append($fieldset); - return $form; - }, - ajax: { - nodes: function(callback) { - $.getJSON(one.f.switchmanager.rootUrl + "/nodeports", function(data) { - var nodes = {}; - var nodePorts = {}; - $(data).each(function(index, node) { - nodes[node.nodeId] = node.nodeName; - nodePorts[node.nodeId] = node.nodePorts; - }); - one.f.switchmanager.spanPortConfig.registry['nodePorts'] = nodePorts; - callback(nodes, nodePorts); - }); - }, - saveSpanPortConfig: function(requestData, callback) { - var resource = {}; - resource["jsonData"] = JSON.stringify(requestData); - $.getJSON(one.f.switchmanager.rootUrl + "/spanPorts/add", resource, function(data) { - callback(data); - }); - } - }, - footer : function() { - var footer = []; - var saveButton = one.lib.dashlet.button.single("Save", one.f.switchmanager.spanPortConfig.id.modal.save, "btn-primary", ""); - var $saveButton = one.lib.dashlet.button.button(saveButton); - footer.push($saveButton); - return footer; - }, - removeMultiple: { - dialog: function(spanPortsToDelete) { - var h3 = 'Remove SPAN Port'; - - var footer = one.f.switchmanager.spanPortConfig.modal.removeMultiple.footer(); - var $body = one.f.switchmanager.spanPortConfig.modal.removeMultiple.body(spanPortsToDelete); - var $modal = one.lib.modal.spawn(one.f.switchmanager.spanPortConfig.id.modal.modal, h3, $body, footer); - - // bind close button - $('#'+one.f.switchmanager.spanPortConfig.id.modal.cancel, $modal).click(function() { - $modal.modal('hide'); - }); - - // bind remove rule button - $('#'+one.f.switchmanager.spanPortConfig.id.modal.remove, $modal).click(this, function(e) { - var requestData = {}; - var spanPorts = []; - $(spanPortsToDelete).each(function(index, spanPort) { - spanPorts.push(JSON.parse(spanPort.spanPortJson)); - }); - requestData["spanPortsToDelete"] = JSON.stringify(spanPorts); - - var url = one.f.switchmanager.rootUrl + "/spanPorts/delete"; - one.f.switchmanager.spanPortConfig.ajax.main(url, requestData, function(response) { - $modal.modal('hide'); - if (response.status == true) { - // refresh dashlet by passing dashlet div as param - one.lib.alert("Span Port(s) successfully removed"); - } else { - alert(response.message); - } - one.f.switchmanager.spanPortConfig.dashlet($("#right-bottom .dashlet")); - }); - }); - $modal.modal(); - }, - footer : function() { - var footer = []; - var remove = one.lib.dashlet.button.single('Remove SPAN Port',one.f.switchmanager.spanPortConfig.id.modal.remove, 'btn-danger', ''); - var $remove = one.lib.dashlet.button.button(remove); - footer.push($remove); - - var cancel = one.lib.dashlet.button.single('Cancel', one.f.switchmanager.spanPortConfig.id.modal.cancel, '', ''); - var $cancel = one.lib.dashlet.button.button(cancel); - footer.push($cancel); - - return footer; - }, - body : function (spanPortToDelete) { - var $p = $(document.createElement('p')); - var p = 'Remove the following Span Port(s)?'; - //creata a BS label for each rule and append to list - - $(spanPortToDelete).each(function(index, spanPortItem) { - var $span = $(document.createElement('span')); - $span.append(this.spanPortNodeName+"-"+this.spanPortPortName); - p += '
' + $span[0].outerHTML; - }); - $p.append(p); - return $p; - } - } - }, - // data functions - data : { - spanPortConfigGrid: function(data) { - var source = new StaticDataSource({ - columns: [ - { - property: 'selector', - label: "", - sortable: false - }, - { - property: 'nodeName', - label: 'Node', - sortable: true - }, - { - property: 'spanPortName', - label: 'SPAN Port', - sortable: true - }, - ], - data: data.nodeData, - formatter: function(items) { - $.each(items, function(index, item) { - item["selector"] = ''; - }); - }, - delay: 0 - }); - return source; - }, - devices : function(data) { - var result = []; - $.each(data.nodeData, function(key, value) { - var tr = {}; - // fill up all the td's - var entry = []; - var checkbox = document.createElement("input"); - checkbox.setAttribute("type", "checkbox"); - checkbox.spanPort = value.json; - entry.push(checkbox); - entry.push(value["nodeName"]); - entry.push(value["spanPort"]); - tr.entry = entry; - result.push(tr); - }); - return result; - } - } -} - -one.f.connection = { - id : { // one.f.connection.id - datagrid : 'one-f-connection-id-datagrid', - add : 'one-f-connection-id-add' - }, - dashlet: function($dashlet) { - one.lib.dashlet.empty($dashlet); - // heading - $dashlet.append(one.lib.dashlet.header(one.f.dashlet.connection.name)); - // add button - var add = one.lib.dashlet.button.single('Add Node', one.f.connection.id.add, 'btn-primary', 'btn-mini'); - var $add = one.lib.dashlet.button.button(add); - $add.click(function() { - one.f.connection.add.initialize(); - }); - $dashlet.append($add); - // load table - var url = one.f.switchmanager.rootUrl+'/connect/nodes'; - $.getJSON(url, function(data) { - var $gridHTML = one.lib.dashlet.datagrid.init(one.f.connection.id.datagrid, { - searchable: true, - filterable: false, - pagination: true, - flexibleRowsPerPage: true - }, 'table-striped table-condensed table-cursor'); - $dashlet.append($gridHTML); - var dataSource = one.f.connection.data(data); - $('#'+one.f.connection.id.datagrid, $dashlet).datagrid({dataSource:dataSource}) - .on('loaded', function() { - $(this).find('tbody tr').click(function() { - var nodeId = $(this).find('.nodeId').text(); - var nodeType = $(this).find('.nodeType').text(); - var nodeName = $(this).find('.nodeName').text(); - one.f.connection.remove.initialize(nodeId, nodeName, nodeType); - }); - }); - }); - }, - data : function(data) { - var source = new StaticDataSource({ - columns: [ - { - property: 'nodeName', - label: 'Node', - sortable: true - } - ], - data: data, - formatter: function(items) { - $.each(items, function(index, item) { - var $nodeId = $(document.createElement('span')); - $nodeId.css('display', 'none'); - var $nodeType = $nodeId.clone(); - var $nodeName = $nodeId.clone(); - $nodeId.append(item.nodeId).addClass('nodeId'); - $nodeType.append(item.nodeType).addClass('nodeType'); - $nodeName.append(item.nodeName).addClass('nodeName'); - item.nodeName += $nodeId[0].outerHTML+$nodeType[0].outerHTML+$nodeName[0].outerHTML; - }); - }, - delay: 0 - }); - return source; - }, - add : { - id : { // one.f.connection.add.id - modal : 'one-f-connection-add-id-modal', - add : 'one-f-connection-add-id-add', - cancel : 'one-f-connection-add-id-cancel', - form : { - nodeId : 'one-f-connection-add-id-form-nodeId', - ipAddress : 'one-f-connection-add-id-form-ipAddress', - port : 'one-f-connection-add-id-form-port', - nodeType : 'one-f-connection-add-id-form-nodeType' - } - }, - initialize : function() { - var h3 = 'Add Node'; - var footer = one.f.connection.add.footer(); - var $body = one.f.connection.add.body();; - var $modal = one.lib.modal.spawn(one.f.connection.add.id.modal, h3, $body, footer); - // bind add buton - $('#'+one.f.connection.add.id.add, $modal).click(function() { - var nodeId = $('#'+one.f.connection.add.id.form.nodeId, $modal).val(); - if (nodeId === '') { - alert('Please enter a node ID'); - return false; - } - var resources = {}; - resources.ipAddress = $('#'+one.f.connection.add.id.form.ipAddress, $modal).val(); - if (resources.ipAddress === '') { - alert('Please enter an IP Address'); - return false; - } - resources.port = $('#'+one.f.connection.add.id.form.port, $modal).val(); - if (resources.port === '') { - alert('Please enter a port'); - return false; - } - var nodeType = $('#'+one.f.connection.add.id.form.nodeType, $modal).val(); - if (nodeType !== '') { - resources.nodeType = nodeType; - } - var url = one.f.switchmanager.rootUrl+'/connect/'+encodeURI(nodeId); - $.post(url, resources, function(result) { - if (result.success === true) { - $modal.modal('hide'); - one.lib.alert(result.description); - } else { - alert(result.code+': '+result.description); - } - }); - }); - // bind cancel button - $('#'+one.f.connection.add.id.cancel, $modal).click(function() { - $modal.modal('hide'); - }); - $modal.modal(); - }, - body : function() { - var $form = $(document.createElement('form')); - var $fieldset = $(document.createElement('fieldset')); - // node id - var $label = one.lib.form.label('Node ID'); - var $input = one.lib.form.input('Node ID'); - $input.attr('id', one.f.connection.add.id.form.nodeId); - $fieldset.append($label).append($input); - // ip address - $label = one.lib.form.label('IP Address'); - $input = one.lib.form.input('IP Address'); - $input.attr('id', one.f.connection.add.id.form.ipAddress); - $fieldset.append($label).append($input); - // port - $label = one.lib.form.label('Port'); - $input = one.lib.form.input('Port'); - $input.attr('id', one.f.connection.add.id.form.port); - var $help = one.lib.form.help('Enter a number'); - $fieldset.append($label).append($input).append($help); - // node type - $label = one.lib.form.label('Node Type'); - $input = one.lib.form.input('Node Type'); - $input.attr('id', one.f.connection.add.id.form.nodeType); - $help = one.lib.form.help('Optional'); - $fieldset.append($label).append($input).append($help); - $form.append($fieldset); - return $form; - }, - footer : function() { - var footer = []; - var add = one.lib.dashlet.button.single('Submit', one.f.connection.add.id.add, 'btn-primary', ''); - var $add = one.lib.dashlet.button.button(add); - footer.push($add); - var cancel = one.lib.dashlet.button.single('Cancel', one.f.connection.add.id.cancel, '', ''); - var $cancel = one.lib.dashlet.button.button(cancel); - footer.push($cancel); - return footer; - } - }, - remove : { - id : { // one.f.connection.remove.id - modal : 'one-f-connection-remove-id-modal', - remove : 'one-f-connection-remove-id-remove', - cancel : 'one-f-connection-remove-id-cancel' - }, - initialize : function(nodeId, nodeName, nodeType) { - var h3 = 'Remove Node'; - var footer = one.f.connection.remove.footer(); - var $body = one.f.connection.remove.body(nodeName); - var $modal = one.lib.modal.spawn(one.f.connection.remove.id.modal, h3, $body, footer); - // bind remove buton - $('#'+one.f.connection.remove.id.remove, $modal).click(function() { - var resources = {}; - resources.nodeType = nodeType; - var url = one.f.switchmanager.rootUrl+'/disconnect/'+encodeURI(nodeId); - $.post(url, resources, function(result) { - if (result.success === true) { - $modal.modal('hide'); - one.lib.alert(result.description); - } else { - alert(result.code+': '+result.description); - } - }).fail(function() { debugger; }); - }); - // bind cancel button - $('#'+one.f.connection.remove.id.cancel, $modal).click(function() { - $modal.modal('hide'); - }); - $modal.modal(); - }, - body : function(nodeName) { - var $p = $(document.createElement('p')); - $p.append('Remove the following node? '); - var $span = $(document.createElement('span')); - $span.addClass('label label-info'); - $span.append(nodeName); - $p.append($span[0].outerHTML); - return $p; - }, - footer : function() { - var footer = []; - var remove = one.lib.dashlet.button.single('Remove', one.f.connection.remove.id.remove, 'btn-danger', ''); - var $remove = one.lib.dashlet.button.button(remove); - footer.push($remove); - var cancel = one.lib.dashlet.button.single('Cancel', one.f.connection.remove.id.cancel, '', ''); - var $cancel = one.lib.dashlet.button.button(cancel); - footer.push($cancel); - return footer; - } - } -} - -/** INIT **/ -// populate nav tabs -$(one.f.menu.left.top).each(function(index, value) { - var $nav = $(".nav", "#left-top"); - one.main.page.dashlet($nav, value); -}); - -$(one.f.menu.left.bottom).each(function(index, value) { - var $nav = $(".nav", "#left-bottom"); - one.main.page.dashlet($nav, value); -}); - -$(one.f.menu.right.bottom).each(function(index, value) { - var $nav = $(".nav", "#right-bottom"); - one.main.page.dashlet($nav, value); -}); - -one.f.addPopOut = function() { - $img1 = $(document.createElement("img")); - $img1.attr("src", "/img/Expand16T.png"); - $img1.attr("style", "float: right;"); - $img1.hover(function() { - $img1.css("cursor", "pointer"); - }); - $img1.click(function() { - var $modal = one.f.switchmanager.nodesLearnt.modal.initialize.popout(); - $modal.css({ - 'margin-left': '-45%', - 'margin-top': '-3%', - 'width':$(document).width() * 0.8, - 'height':$(document).height() * 0.9 - }); - $(".modal-body", $modal).css({ - "max-height": $(document).height() * 0.75, - }); - $modal.modal(); - }); - $dash1 = $($("#left-top .nav")[0]); - $dash1.append($img1); -}; -one.f.addPopOut(); - -// bind dashlet nav -$('.dash .nav a', '#main').click(function() { - // de/activation - var $li = $(this).parent(); - var $ul = $li.parent(); - one.lib.nav.unfocus($ul); - $li.addClass('active'); - // clear respective dashlet - var $dashlet = $ul.parent().find('.dashlet'); - one.lib.dashlet.empty($dashlet); - - // callback based on menu - var id = $(this).attr('id'); - var menu = one.f.dashlet; - switch (id) { - case menu.nodesLearnt.id: - one.f.switchmanager.nodesLearnt.dashlet($dashlet); - break; - case menu.staticRouteConfig.id: - one.f.switchmanager.staticRouteConfig.dashlet($dashlet); - break; - case menu.subnetGatewayConfig.id: - one.f.switchmanager.subnetGatewayConfig.dashlet($dashlet); - break; - case menu.spanPortConfig.id: - one.f.switchmanager.spanPortConfig.dashlet($dashlet); - break; - case menu.connection.id: - one.f.connection.dashlet($dashlet); - break; - }; -}); - -// activate first tab on each dashlet -$('.dash .nav').each(function(index, value) { - $($(value).find('li')[0]).find('a').click(); -}); diff --git a/opendaylight/adsal/web/flows/pom.xml b/opendaylight/adsal/web/flows/pom.xml deleted file mode 100644 index 14fe753a2f..0000000000 --- a/opendaylight/adsal/web/flows/pom.xml +++ /dev/null @@ -1,112 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - flows.web - 0.6.0-SNAPSHOT - bundle - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - forwardingrulesmanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - usermanager - - - org.opendaylight.controller - web - - - - - - org.apache.felix - maven-bundle-plugin - true - - - - org.opendaylight.controller.forwardingrulesmanager, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.action, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.flowprogrammer, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.switchmanager, - org.opendaylight.controller.usermanager, - org.opendaylight.controller.web, - com.google.gson, - javax.annotation, - javax.naming, - javax.servlet, - javax.servlet.annotation, - javax.servlet.http, - javax.servlet.jsp, - javax.servlet.jsp.el, - javax.servlet.jsp.jstl.core, - javax.servlet.jsp.jstl.fmt, - javax.servlet.jsp.jstl.tlv, - javax.servlet.jsp.tagext, - javax.servlet.resources, - javax.xml.parsers, - javax.xml.transform, - org.apache.commons.logging, - org.apache.taglibs.standard.functions, - org.apache.taglibs.standard.resources, - org.apache.taglibs.standard.tag.common.core, - org.apache.taglibs.standard.tag.common.fmt, - org.apache.taglibs.standard.tag.rt.core, - org.apache.taglibs.standard.tag.rt.fmt, - org.apache.taglibs.standard.tei, - org.apache.taglibs.standard.tlv, - com.fasterxml.jackson.core, - com.fasterxml.jackson.annotation, - com.fasterxml.jackson.databind, - org.osgi.framework, - org.slf4j, - org.springframework.beans, - org.springframework.beans.factory.xml, - org.springframework.context.config, - org.springframework.stereotype, - org.springframework.web, - org.springframework.web.bind.annotation, - org.springframework.web.servlet, - org.springframework.web.servlet.config, - org.springframework.web.servlet.view, - org.springframework.web.filter, - org.springframework.web.context - /controller/web/flows - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/web/flows/src/main/java/org/opendaylight/controller/flows/web/Flows.java b/opendaylight/adsal/web/flows/src/main/java/org/opendaylight/controller/flows/web/Flows.java deleted file mode 100644 index 9c3c895916..0000000000 --- a/opendaylight/adsal/web/flows/src/main/java/org/opendaylight/controller/flows/web/Flows.java +++ /dev/null @@ -1,426 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.flows.web; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -import javax.servlet.http.HttpServletRequest; - -import org.opendaylight.controller.forwardingrulesmanager.FlowConfig; -import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager; -import org.opendaylight.controller.sal.action.Action; -import org.opendaylight.controller.sal.action.ActionType; -import org.opendaylight.controller.sal.action.SupportedFlowActions; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.core.Description; -import org.opendaylight.controller.sal.core.Name; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.switchmanager.Switch; -import org.opendaylight.controller.switchmanager.SwitchConfig; -import org.opendaylight.controller.web.DaylightWebUtil; -import org.opendaylight.controller.web.IDaylightWeb; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.google.gson.Gson; - -@Controller -@RequestMapping("/") -public class Flows implements IDaylightWeb { - private static final UserLevel AUTH_LEVEL = UserLevel.CONTAINERUSER; - private static final String WEB_NAME = "Flows"; - - private static final String WEB_ID = "flows"; - private static final short WEB_ORDER = 2; - - private final Gson gson; - - public Flows() { - ServiceHelper.registerGlobalService(IDaylightWeb.class, this, null); - gson = new Gson(); - } - - @Override - public String getWebName() { - return WEB_NAME; - } - - @Override - public String getWebId() { - return WEB_ID; - } - - @Override - public short getWebOrder() { - return WEB_ORDER; - } - - @Override - public boolean isAuthorized(UserLevel userLevel) { - return userLevel.ordinal() <= AUTH_LEVEL.ordinal(); - } - - @RequestMapping(value = "/main") - @ResponseBody - public Map getFlows(HttpServletRequest request, @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Derive the privilege this user has on the current container - String userName = request.getUserPrincipal().getName(); - Privilege privilege = DaylightWebUtil.getContainerPrivilege(userName, containerName, this); - if (privilege == Privilege.NONE) { - return null; - } - - // fetch frm - IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( - IForwardingRulesManager.class, containerName, this); - if (frm == null) { - return null; - } - - // fetch sm - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - if (switchManager == null) { - return null; - } - - // get static flow list - List staticFlowList = frm.getStaticFlows(); - Set> flowSet = new HashSet>(); - for (FlowConfig flowConfig : staticFlowList) { - Map entry = new HashMap(); - entry.put("flow", flowConfig); - entry.put("name", flowConfig.getName()); - Node node = flowConfig.getNode(); - entry.put("node", getNodeDesc(node, switchManager)); - entry.put("nodeId", node.toString()); - flowSet.add(entry); - } - - Map output = new HashMap(2); - output.put("flows", flowSet); - output.put("privilege", privilege); - return output; - } - - @RequestMapping(value = "/node-ports") - @ResponseBody - public Map getNodePorts(HttpServletRequest request, @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Derive the privilege this user has on the current container - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) { - return null; - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - if (switchManager == null) { - return null; - } - - Map nodes = new HashMap(); - Map port; - - for (Switch node : switchManager.getNetworkDevices()) { - port = new HashMap(); // new port - Set nodeConnectorSet = node.getNodeConnectors(); - - if (nodeConnectorSet != null) { - for (NodeConnector nodeConnector : nodeConnectorSet) { - String nodeConnectorName = ((Name) switchManager.getNodeConnectorProp(nodeConnector, - Name.NamePropName)).getValue(); - port.put( nodeConnector.getID().toString(), - nodeConnectorName + "(" + nodeConnector.getNodeConnectorIDString() + ")"); - } - } - - // add ports - Map entry = new HashMap(); - entry.put("ports", port); - - // add name - entry.put("name", getNodeDesc(node.getNode(), switchManager)); - - // add to the node - nodes.put(node.getNode().toString(), entry); - } - - return nodes; - } - - @RequestMapping(value = "/node-flows") - @ResponseBody - public Map getNodeFlows(HttpServletRequest request, @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Derive the privilege this user has on the current container - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) == Privilege.NONE) { - return null; - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, - this); - if (switchManager == null) { - return null; - } - IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( - IForwardingRulesManager.class, containerName, this); - if (frm == null) { - return null; - } - - Map nodes = new HashMap(); - - for (Switch sw : switchManager.getNetworkDevices()) { - Node node = sw.getNode(); - - List flows = frm.getStaticFlows(node); - - String nodeDesc = node.toString(); - SwitchConfig config = switchManager.getSwitchConfig(node.toString()); - if ((config != null) && (config.getProperty(Description.propertyName) != null)) { - nodeDesc = ((Description) config.getProperty(Description.propertyName)).getValue(); - } - - nodes.put(nodeDesc, flows.size()); - } - - return nodes; - } - - @RequestMapping(value = "/flow", method = RequestMethod.POST) - @ResponseBody - public String actionFlow(@RequestParam(required = true) String action, @RequestParam(required = false) String body, - @RequestParam(required = true) String nodeId, HttpServletRequest request, - @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return "Operation not authorized"; - } - - IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( - IForwardingRulesManager.class, containerName, this); - if (frm == null) { - return null; - } - - FlowConfig flow = gson.fromJson(body, FlowConfig.class); - - Node node = Node.fromString(nodeId); - flow.setNode(node); - - Status result = new Status(StatusCode.BADREQUEST, "Invalid request"); - if (action.equals("add")) { - result = frm.addStaticFlow(flow); - if (result.isSuccess()) { - DaylightWebUtil.auditlog("Flow Entry", userName, "added", flow.getName() + " on Node " - + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName); - } - } else if (action.equals("edit")){ - result = frm.modifyStaticFlow(flow); - if (result.isSuccess()) { - DaylightWebUtil.auditlog("Flow Entry", userName, "updated", flow.getName() + " on Node " - + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName); - } - } - - return (result.isSuccess()) ? StatusCode.SUCCESS.toString() : result.getDescription(); - } - - @RequestMapping(value = "/flow/{nodeId}/{name:.*}", method = RequestMethod.POST) - @ResponseBody - public String removeFlow(@PathVariable("nodeId") String nodeId, @PathVariable("name") String name, - @RequestParam(required = true) String action, HttpServletRequest request, - @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return "Operation not authorized"; - } - - IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( - IForwardingRulesManager.class, containerName, this); - if (frm == null) { - return null; - } - - Status result = null; - Node node = Node.fromString(nodeId); - if (node == null) { - return null; - } - if (action.equals("remove")) { - result = frm.removeStaticFlow(name, node); - if (result.isSuccess()) { - DaylightWebUtil.auditlog("Flow Entry", userName, "removed", - name + " on Node " + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName); - } - } else if (action.equals("toggle")) { - result = frm.toggleStaticFlowStatus(name, node); - if (result.isSuccess()) { - DaylightWebUtil.auditlog("Flow Entry", userName, "toggled", - name + " on Node " + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName); - } - } else { - result = new Status(StatusCode.BADREQUEST, "Unknown action"); - } - - return (result.isSuccess()) ? StatusCode.SUCCESS.toString() : result.getDescription(); - } - - @SuppressWarnings("unchecked") - @RequestMapping(value = "/flow/deleteFlows", method = RequestMethod.POST) - @ResponseBody - public String removeSelectedFlows(@RequestParam(required = false) String body, HttpServletRequest request, - @RequestParam(required = false) String container) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return "Operation not authorized"; - } - IForwardingRulesManager frm = (IForwardingRulesManager) ServiceHelper.getInstance( - IForwardingRulesManager.class, containerName, this); - if (frm == null) { - return "Forwarding Rules Manager is not available"; - } - - List> flowList = new ArrayList>(); - flowList = gson.fromJson(body, flowList.getClass()); - Status result = new Status(StatusCode.BADREQUEST, "Invalid request"); - String status = ""; - for (Map flowEntry : flowList) { - Node node = Node.fromString(flowEntry.get("node")); - result = frm.removeStaticFlow(flowEntry.get("name"), node); - if (result.isSuccess()) { - DaylightWebUtil.auditlog("Flow Entry", userName, "removed", flowEntry.get("name") + " on Node " - + DaylightWebUtil.getNodeDesc(node, containerName, this), containerName); - } else { - status = flowEntry.get("name") + ", " + status; - } - } - if (!status.equals("")) { - return "Could not remove " + status.substring(0, status.length() - 2) + " Flow(s)"; - } else { - return "Success"; - } - } - - @RequestMapping(value = "/valid-flows/{nodeId}") - @ResponseBody - public Object getValidActions(HttpServletRequest request, @RequestParam(required = false) String container, - @PathVariable("nodeId") String nodeId) { - String containerName = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Authorization check - String userName = request.getUserPrincipal().getName(); - if (DaylightWebUtil.getContainerPrivilege(userName, containerName, this) != Privilege.WRITE) { - return "Operation not authorized"; - } - - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, containerName, this); - if (switchManager == null) { - return null; - } - - Map result = new TreeMap(); - - Node node = Node.fromString(nodeId); - SupportedFlowActions supportedFlows = (SupportedFlowActions) switchManager.getNodeProp(node, "supportedFlowActions"); - List> actions = supportedFlows.getActions(); - for (Class action : actions) { - if (action.isAssignableFrom(org.opendaylight.controller.sal.action.Drop.class)) { - result.put(ActionType.DROP.toString(), "Drop"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.Loopback.class)) { - result.put(ActionType.LOOPBACK.toString(), "Loopback"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.Flood.class)) { - result.put(ActionType.FLOOD.toString(), "Flood"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.FloodAll.class)) { - result.put(ActionType.FLOOD_ALL.toString(), "Flood All"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.Controller.class)) { - result.put(ActionType.CONTROLLER.toString(), "Controller"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SwPath.class)) { - result.put(ActionType.SW_PATH.toString(), "Software Path"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.HwPath.class)) { - result.put(ActionType.HW_PATH.toString(), "Hardware Path"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.Output.class)) { - result.put(ActionType.OUTPUT.toString(), "Output"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.Enqueue.class)) { - result.put(ActionType.ENQUEUE.toString(), "Enqueue"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetDlSrc.class)) { - result.put(ActionType.SET_DL_SRC.toString(), "Set Datalayer Source Address"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetDlDst.class)) { - result.put(ActionType.SET_DL_DST.toString(), "Set Datalayer Destination Address"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetVlanId.class)) { - result.put(ActionType.SET_VLAN_ID.toString(), "Set VLAN ID"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetVlanPcp.class)) { - result.put(ActionType.SET_VLAN_PCP.toString(), "Set VLAN Priority"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetVlanCfi.class)) { - result.put(ActionType.SET_VLAN_CFI.toString(), "Set VLAN CFI"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.PopVlan.class)) { - result.put(ActionType.POP_VLAN.toString(), "Pop VLAN"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.PushVlan.class)) { - result.put(ActionType.PUSH_VLAN.toString(), "Push VLAN"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetDlType.class)) { - result.put(ActionType.SET_DL_TYPE.toString(), "Set EtherType"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetNwSrc.class)) { - result.put(ActionType.SET_NW_SRC.toString(), "Set Network Source Address"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetNwDst.class)) { - result.put(ActionType.SET_NW_DST.toString(), "Set Network Destination Address"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetNwTos.class)) { - result.put(ActionType.SET_NW_TOS.toString(), "Modify ToS Bits"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetTpSrc.class)) { - result.put(ActionType.SET_TP_SRC.toString(), "Modify Transport Source Port"); - } else if (action.isAssignableFrom(org.opendaylight.controller.sal.action.SetTpDst.class)) { - result.put(ActionType.SET_TP_DST.toString(), "Modify Transport Destination Port"); - } - } - - return result; - } - - private boolean actionCompare(String name, ActionType type) { - return name.equals(type.getId().toLowerCase()); - } - - private String getNodeDesc(Node node, ISwitchManager switchManager) { - Description desc = (Description) switchManager.getNodeProp(node, Description.propertyName); - String description = (desc == null) ? "" : desc.getValue(); - return (description.isEmpty() || description.equalsIgnoreCase("none")) ? node.toString() : description; - } - -} diff --git a/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/web/flows/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/Flows-servlet.xml b/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/Flows-servlet.xml deleted file mode 100644 index 293fa77ef1..0000000000 --- a/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/Flows-servlet.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/autherror.jsp b/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/autherror.jsp deleted file mode 100644 index 127a5a09dd..0000000000 --- a/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/autherror.jsp +++ /dev/null @@ -1,55 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@ page import="java.net.URL" %> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - - - - - - - - - - - - -<% - String filePath = "/WEB-INF/jsp/customerror.jsp"; - URL fileURL = pageContext.getServletContext().getResource(filePath); - if(fileURL!=null) { -%> - -<% } %> - ${title} - - - - - - - - -
- -
-
- -
-
-
- <% if (session != null) session.invalidate(); %> - - diff --git a/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/error.jsp b/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/error.jsp deleted file mode 100644 index 270d793e5c..0000000000 --- a/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/error.jsp +++ /dev/null @@ -1,8 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> -<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> - - - - - \ No newline at end of file diff --git a/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/login.jsp b/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/login.jsp deleted file mode 100644 index 270d793e5c..0000000000 --- a/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/jsp/login.jsp +++ /dev/null @@ -1,8 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> -<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> - - - - - \ No newline at end of file diff --git a/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index c5d2479f6b..0000000000 --- a/opendaylight/adsal/web/flows/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - Flows - org.springframework.web.servlet.DispatcherServlet - 1 - - - - Flows - / - - - - - - free access - /js/* - /images/* - /css/* - /favicon.ico - - - - - FlowApp - - FlowMgrGUI - /* - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - FORM - - /WEB-INF/jsp/login.jsp - /WEB-INF/jsp/error.jsp - - - - - 403 - /WEB-INF/jsp/autherror.jsp - - - - org.opendaylight.controller.web.ControllerUISessionManager - - - - - / - - - - - - diff --git a/opendaylight/adsal/web/flows/src/main/resources/js/page.js b/opendaylight/adsal/web/flows/src/main/resources/js/page.js deleted file mode 100644 index 5e638cf9cc..0000000000 --- a/opendaylight/adsal/web/flows/src/main/resources/js/page.js +++ /dev/null @@ -1,1733 +0,0 @@ -/* - * Copyright (c) 2013-2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -//PAGE flows -one.f = {}; - -// specify dashlets and layouts -one.f.dashlet = { - flows : { - id : 'flows', - name : 'Flow Entries' - }, - nodes : { - id : 'nodes', - name : 'Nodes' - }, - detail : { - id : 'detail', - name : 'Flow Detail' - } -}; - -one.f.menu = { - left : { - top : [ - one.f.dashlet.flows - ], - bottom : [ - one.f.dashlet.nodes - ] - }, - right : { - top : [], - bottom : [ - one.f.dashlet.detail - ] - } -}; - -one.f.address = { - root : "/controller/web/flows", - flows : { - main : "/main", - flows : "/node-flows", - nodes : "/node-ports", - flow : "/flow", - modifyFlow : "/modifyFlow", - deleteFlows:"/flow/deleteFlows" - } -} - -/** NODES **/ -one.f.nodes = { - id : { - dashlet: { - datagrid: "one_f_nodes_id_dashlet_datagrid" - } - }, - registry : {}, - dashlet : function($dashlet) { - var $h4 = one.lib.dashlet.header("Nodes"); - $dashlet.append($h4); - - one.f.nodes.ajax.dashlet(function(data) { - var $gridHTML = one.lib.dashlet.datagrid.init(one.f.nodes.id.dashlet.datagrid, { - searchable: true, - filterable: false, - pagination: true, - flexibleRowsPerPage: true - }, "table-striped table-condensed"); - $dashlet.append($gridHTML); - var dataSource = one.f.nodes.data.nodesDataGrid(data); - $("#" + one.f.nodes.id.dashlet.datagrid).datagrid({dataSource: dataSource}); - }); - }, - ajax : { - dashlet : function(callback) { - $.getJSON(one.f.address.root+one.f.address.flows.flows, function(data) { - callback(data); - }); - } - }, - data : { - nodesDataGrid: function(data) { - var gridData = []; - $.each(data, function(nodeName, flow) { - var nodeFlowObject = {}; - nodeFlowObject["nodeName"] = nodeName; - nodeFlowObject["flows"] = flow; - nodeFlowObject["rowData"] = nodeName + flow + "-foobar"; - gridData.push(nodeFlowObject); - }); - - var source = new StaticDataSource({ - columns: [ - { - property: 'nodeName', - label: 'Node', - sortable: true - }, - { - property: 'flows', - label: 'Flows', - sortable: true - } - ], - data: gridData, - delay: 0 - }); - return source; - } - }, - body : { - dashlet : function(body, callback) { - var attributes = ['table-striped', 'table-bordered', 'table-hover', 'table-condensed']; - var $table = one.lib.dashlet.table.table(attributes); - - var headers = ['Node', 'Flows']; - var $thead = one.lib.dashlet.table.header(headers); - $table.append($thead); - - var $tbody = one.lib.dashlet.table.body(body); - $table.append($tbody); - - return $table; - } - } -} - -/** FLOW DETAIL **/ -one.f.detail = { - id : {}, - registry : {}, - dashlet : function($dashlet, details) { - var $h4 = one.lib.dashlet.header("Flow Details"); - $dashlet.append($h4); - - // details - if (details == undefined) { - var $none = $(document.createElement('div')); - $none.addClass('none'); - var $p = $(document.createElement('p')); - $p.text('Please select a flow'); - $p.addClass('text-center').addClass('text-info'); - - $dashlet.append($none) - .append($p); - } - }, - data : { - dashlet : function(data) { - var body = []; - var tr = {}; - var entry = []; - - entry.push(data['name']); - entry.push(data['node']); - entry.push(data['flow']['priority']); - entry.push(data['flow']['hardTimeout']); - entry.push(data['flow']['idleTimeout']); - - tr.entry = entry; - body.push(tr); - return body; - }, - description : function(data) { - var body = []; - var tr = {}; - var entry = []; - entry.push(data['flow']['ingressPort']); - entry.push(data['flow']['etherType']); - entry.push(data['flow']['vlanId']); - entry.push(data['flow']['vlanPriority']); - entry.push(data['flow']['srcMac']); - entry.push(data['flow']['dstMac']); - entry.push(data['flow']['srcIp']); - entry.push(data['flow']['dstIp']); - entry.push(data['flow']['tosBits']); - entry.push(data['flow']['srcPort']); - entry.push(data['flow']['dstPort']); - entry.push(data['flow']['protocol']); - entry.push(data['flow']['cookie']); - - tr.entry = entry; - body.push(tr); - return body; - }, - actions : function(data) { - var body = []; - var tr = {}; - var entry = []; - var actions = ''; - - $(data['flow']['actions']).each(function(index, value) { - var locEqualTo = value.indexOf("="); - if ( locEqualTo == -1 ) { - actions += value + ', '; - } else { - var action = value.substr(0,locEqualTo); - if( action == "OUTPUT") { - var portIds = value.substr(locEqualTo+1).split(","); - actions += action + "="; - var allPorts = one.f.flows.registry.nodeports[one.f.flows.registry.selectedNode]['ports']; - for(var i =0; i < portIds.length ; i++) { - var portName = allPorts[portIds[i]]; - actions += portName + ", "; - } - } else { - actions += value + ', '; - } - } - }); - actions = actions.slice(0,-2); - entry.push(actions); - - tr.entry = entry; - body.push(tr); - return body; - } - }, - body : { - dashlet : function(body) { - // create table - var header = ['Flow Name', 'Node', 'Priority', 'Hard Timeout', 'Idle Timeout']; - var $thead = one.lib.dashlet.table.header(header); - var attributes = ['table-striped', 'table-bordered', 'table-condensed']; - var $table = one.lib.dashlet.table.table(attributes); - $table.append($thead); - - var $tbody = one.lib.dashlet.table.body(body); - $table.append($tbody); - - return $table; - }, - description : function(body) { - var header = ['Input Port', 'Ethernet Type', 'VLAN ID', 'VLAN Priority', 'Source MAC', 'Dest MAC', 'Source IP', 'Dest IP', 'ToS', 'Source Port', 'Dest Port', 'Protocol', 'Cookie']; - var $thead = one.lib.dashlet.table.header(header); - var attributes = ['table-striped', 'table-bordered', 'table-condensed']; - var $table = one.lib.dashlet.table.table(attributes); - $table.append($thead); - - var $tbody = one.lib.dashlet.table.body(body); - $table.append($tbody); - - return $table; - }, - actions : function(body) { - var header = ['Actions']; - var $thead = one.lib.dashlet.table.header(header); - var attributes = ['table-striped', 'table-bordered', 'table-condensed']; - var $table = one.lib.dashlet.table.table(attributes); - $table.append($thead); - - var $tbody = one.lib.dashlet.table.body(body); - $table.append($tbody); - - return $table; - } - } -} - -/** FLOW ENTRIES **/ -one.f.flows = { - id : { - dashlet : { - add : "one_f_flows_id_dashlet_add", - removeMultiple : "one_f_flows_id_dashlet_removeMultiple", - remove : "one_f_flows_id_dashlet_remove", - toggle : "one_f_flows_id_dashlet_toggle", - edit : "one_f_flows_id_dashlet_edit", - datagrid : "one_f_flows_id_dashlet_datagrid", - selectAllFlows : "one_f_flows_id_dashlet_selectAllFlows" - }, - modal : { - install : "one_f_flows_id_modal_install", - edit : "one_f_flows_id_modal_edit", - add : "one_f_flows_id_modal_add", - close : "one_f_flows_id_modal_close", - modal : "one_f_flows_id_modal_modal", - dialog : { - modal : "one_f_flows_id_modal_dialog_modal", - remove : "one_f_flows_id_modal_dialog_remove", - close : "one_f_flows_id_modal_dialog_close" - }, - action : { - button : "one_f_flows_id_modal_action_button", - modal : "one_f_flows_id_modal_action_modal", - add : "one_f_flows_id_modal_action_add", - close : "one_f_flows_id_modal_action_close", - table : "one_f_flows_id_modal_action_table", - addOutputPorts : "one_f_flows_id_modal_action_addOutputPorts", - setVlanId : "one_f_flows_id_modal_action_setVlanId", - setVlanPriority : "one_f_flows_id_modal_action_setVlanPriority", - modifyDatalayerSourceAddress : "one_f_flows_id_modal_action_modifyDatalayerSourceAddress", - modifyDatalayerDestinationAddress : "one_f_flows_id_modal_action_modifyDatalayerDestinationAddress", - modifyNetworkSourceAddress : "one_f_flows_modal_action_modifyNetworkSourceAddress", - modifyNetworkDestinationAddress : "one_f_flows_modal_action_modifyNetworkDestinationAddress", - modifyTosBits : "one_f_flows_modal_action_modifyTosBits", - modifyTransportSourcePort : "one_f_flows_modal_action_modifyTransportSourcePort", - modifyTransportDestinationPort : "one_f_flows_modal_action_modifyTransportDestinationPort", - enqueue : 'one-f-flows-modal-action-enqueue', - queue : 'one-f-flows-modal-action-queue', - setEthertype : 'one-f-flows-modal-action-setEthertype', - pushVlan : 'one-f-flows-modal-action-pushVlan', - setVlanCfi : 'one-f-flows-modal-action-setVlanCfi', - modal : { - modal : "one_f_flows_modal_action_modal_modal", - remove : "one_f_flows_modal_action_modal_remove", - cancel : "one_f_flows_modal_action_modal_cancel" - } - }, - form : { - name : "one_f_flows_id_modal_form_name", - nodes : "one_f_flows_id_modal_form_nodes", - port : "one_f_flows_id_modal_form_port", - priority : "one_f_flows_id_modal_form_priority", - hardTimeout : "one_f_flows_id_modal_form_hardTimeout", - idleTimeout : "one_f_flows_id_modal_form_idleTimeout", - cookie : "one_f_flows_id_modal_form_cookie", - etherType : "one_f_flows_id_modal_form_etherType", - vlanId : "one_f_flows_id_modal_form_vlanId", - vlanPriority : "one_f_flows_id_modal_form_vlanPriority", - srcMac : "one_f_flows_id_modal_form_srcMac", - dstMac : "one_f_flows_id_modal_form_dstMac", - srcIp : "one_f_flows_id_modal_form_srcIp", - dstIp : "one_f_flows_id_modal_form_dstIp", - tosBits : "one_f_flows_id_modal_form_tosBits", - srcPort : "one_f_flows_id_modal_form_srcPort", - dstPort : "one_f_flows_id_modal_form_dstPort", - protocol : "one_f_flows_id_modal_form_protocol", - action : 'one-f-flows-id-modal-form-action' - } - } - }, - registry : {}, - dashlet : function($dashlet, callback) { - // load body - one.f.flows.ajax.dashlet(function(data) { - var $h4 = one.lib.dashlet.header("Flow Entries"); - $dashlet.append($h4); - if (one.f.flows.registry.privilege === 'WRITE') { - var button = one.lib.dashlet.button.single("Add Flow Entry", one.f.flows.id.dashlet.add, "btn-primary", "btn-mini"); - var $button = one.lib.dashlet.button.button(button); - - $button.click(function() { - var $modal = one.f.flows.modal.initialize(); - $modal.modal(); - }); - $dashlet.append($button); - var button = one.lib.dashlet.button.single("Remove Flow Entry", one.f.flows.id.dashlet.removeMultiple, "btn-danger", "btn-mini"); - var $button = one.lib.dashlet.button.button(button); - - $button.click(function() { - var checkedCheckBoxes = $('.flowEntry[type=checkbox]:checked'); - if (checkedCheckBoxes.size() === 0) { - return false; - } - - var requestData = []; - - checkedCheckBoxes.each(function(index, value) { - var flowEntry = {}; - flowEntry['name'] = checkedCheckBoxes[index].name; - flowEntry['node'] = checkedCheckBoxes[index].getAttribute("node"); - requestData.push(flowEntry); - }); - one.f.flows.modal.removeMultiple.dialog(requestData); - }); - $dashlet.append($button); - - } - var $gridHTML = one.lib.dashlet.datagrid.init(one.f.flows.id.dashlet.datagrid, { - searchable: true, - filterable: false, - pagination: true, - flexibleRowsPerPage: true - }, "table-striped table-condensed"); - $dashlet.append($gridHTML); - var dataSource = one.f.flows.data.flowsDataGrid(data); - $("#" + one.f.flows.id.dashlet.datagrid).datagrid({dataSource: dataSource}).on("loaded", function() { - $("#"+one.f.flows.id.dashlet.datagrid.selectAllFlows).click(function() { - $("#" + one.f.flows.id.dashlet.datagrid).find(':checkbox').prop('checked', - $("#"+one.f.flows.id.dashlet.datagrid.selectAllFlows).is(':checked')); - }); - - $("#" + one.f.flows.id.dashlet.datagrid).find("tbody tr").each(function(index, tr) { - $tr = $(tr); - $span = $("td span", $tr); - var flowstatus = $span.data("flowstatus"); - if($span.data("installinhw") != null) { - var installInHw = $span.data("installinhw").toString(); - if(installInHw == "true" && flowstatus == "Success") { - $tr.addClass("success"); - } else { - $tr.addClass("warning"); - } - } - // attach mouseover to show pointer cursor - $tr.mouseover(function() { - $(this).css("cursor", "pointer"); - }); - // attach click event - $tr.click(function() { - var $td = $($(this).find("td")[1]); - var id = $td.text(); - var node = $td.find("span").data("nodeid"); - one.f.flows.detail(id, node); - }); - $(".flowEntry").click(function(e){ - if (!$('.flowEntry[type=checkbox]:not(:checked)').length) { - $("#"+one.f.flows.id.dashlet.datagrid.selectAllFlows) - .prop("checked", - true); - } else { - $("#"+one.f.flows.id.dashlet.datagrid.selectAllFlows) - .prop("checked", - false); - } - e.stopPropagation(); - }); - }); - }); - - // details callback - if(callback != undefined) callback(); - }); - }, - detail : function(id, node) { - // clear flow details - var $detailDashlet = one.main.dashlet.right.bottom; - $detailDashlet.empty(); - var $h4 = one.lib.dashlet.header("Flow Overview"); - $detailDashlet.append($h4); - - // details - var flows = one.f.flows.registry.flows; - one.f.flows.registry['selectedId'] = id; - one.f.flows.registry['selectedNode'] = node; - var flow; - $(flows).each(function(index, value) { - if (value.name == id && value.nodeId == node) { - flow = value; - } - }); - if (one.f.flows.registry.privilege === 'WRITE') { - // remove button - var button = one.lib.dashlet.button.single("Remove Flow", one.f.flows.id.dashlet.remove, "btn-danger", "btn-mini"); - var $button = one.lib.dashlet.button.button(button); - $button.click(function() { - var $modal = one.f.flows.modal.dialog.initialize(id, node); - $modal.modal(); - }); - // edit button - var editButton = one.lib.dashlet.button.single("Edit Flow", one.f.flows.id.dashlet.edit, "btn-primary", "btn-mini"); - var $editButton = one.lib.dashlet.button.button(editButton); - $editButton.click(function() { - var install = flow['flow']['installInHw']; - var $modal = one.f.flows.modal.initialize(true,install); - $modal.modal().on('shown',function(){ - var $port = $('#'+one.f.flows.id.modal.form.port); - $('#'+one.f.flows.id.modal.form.nodes).trigger("change"); - }); - }); - // toggle button - var toggle; - if (flow['flow']['installInHw'] == 'true' && flow['flow']['status'] == 'Success') { - toggle = one.lib.dashlet.button.single("Uninstall Flow", one.f.flows.id.dashlet.toggle, "btn-warning", "btn-mini"); - } else { - toggle = one.lib.dashlet.button.single("Install Flow", one.f.flows.id.dashlet.toggle, "btn-success", "btn-mini"); - } - var $toggle = one.lib.dashlet.button.button(toggle); - $toggle.click(function() { - one.f.flows.modal.ajax.toggleflow(id, node, function(data) { - if(data == "Success") { - one.main.dashlet.right.bottom.empty(); - one.f.detail.dashlet(one.main.dashlet.right.bottom); - one.main.dashlet.left.top.empty(); - one.f.flows.dashlet(one.main.dashlet.left.top, function() { - // checks are backwards due to stale registry - if(flow['flow']['installInHw'] == 'true') { - one.lib.alert('Uninstalled Flow'); - } else { - one.lib.alert('Installed Flow'); - } - one.f.flows.detail(id, node) - }); - } else { - one.lib.alert('Cannot toggle flow: '+data); - } - }); - }); - - $detailDashlet.append($button).append($editButton).append($toggle); - } - // append details - var body = one.f.detail.data.dashlet(flow); - var $body = one.f.detail.body.dashlet(body); - $detailDashlet.append($body); - var body = one.f.detail.data.description(flow); - var $body = one.f.detail.body.description(body); - $detailDashlet.append($body); - var body = one.f.detail.data.actions(flow); - var $body = one.f.detail.body.actions(body); - $detailDashlet.append($body); - }, - modal : { - dialog : { - initialize : function(id, node) { - var h3 = "Remove Flow"; - var $p = one.f.flows.modal.dialog.body(id); - var footer = one.f.flows.modal.dialog.footer(); - var $modal = one.lib.modal.spawn(one.f.flows.id.modal.dialog.modal, h3, $p, footer); - $('#'+one.f.flows.id.modal.dialog.close, $modal).click(function() { - $modal.modal('hide'); - }); - $('#'+one.f.flows.id.modal.dialog.remove, $modal).click(function() { - one.f.flows.modal.ajax.removeflow(id, node, function(data) { - if (data == "Success") { - $modal.modal('hide'); - one.main.dashlet.right.bottom.empty(); - one.f.detail.dashlet(one.main.dashlet.right.bottom); - one.main.dashlet.left.top.empty(); - one.f.flows.dashlet(one.main.dashlet.left.top); - one.lib.alert('Flow removed'); - } else { - one.lib.alert('Cannot remove flow: '+data); - } - }); - }); - return $modal; - }, - footer : function() { - var footer = []; - - var removeButton = one.lib.dashlet.button.single("Remove Flow", one.f.flows.id.modal.dialog.remove, "btn-danger", ""); - var $removeButton = one.lib.dashlet.button.button(removeButton); - footer.push($removeButton); - - var closeButton = one.lib.dashlet.button.single("Cancel", one.f.flows.id.modal.dialog.close, "", ""); - var $closeButton = one.lib.dashlet.button.button(closeButton); - footer.push($closeButton); - - return footer; - }, - body : function(id) { - var $p = $(document.createElement('p')); - $p.append('Remove flow '+id+'?'); - return $p; - } - }, - initialize : function(edit,install) { - var h3; - if(edit) { - h3 = "Edit Flow Entry"; - var footer = one.f.flows.modal.footerEdit(); - - } else { - h3 = "Add Flow Entry"; - var footer = one.f.flows.modal.footer(); - } - - var $modal = one.lib.modal.spawn(one.f.flows.id.modal.modal, h3, "", footer); - - // bind close button - $('#'+one.f.flows.id.modal.close, $modal).click(function() { - $modal.modal('hide'); - }); - - if (edit) { - // bind edit flow button - $('#'+one.f.flows.id.modal.edit, $modal).click(function() { - one.f.flows.modal.save($modal, install, true); - }); - } else { - // bind add flow button - $('#'+one.f.flows.id.modal.add, $modal).click(function() { - one.f.flows.modal.save($modal, 'false'); - }); - - // bind install flow button - $('#'+one.f.flows.id.modal.install, $modal).click(function() { - one.f.flows.modal.save($modal, 'true'); - }); - } - - var nodes = one.f.flows.registry.nodes; - var nodeports = one.f.flows.registry.nodeports; - var $body = one.f.flows.modal.body(nodes, nodeports, edit); - one.lib.modal.inject.body($modal, $body,edit); - - return $modal; - }, - save : function($modal, install, edit) { - var result = {}; - - result['name'] = $('#'+one.f.flows.id.modal.form.name, $modal).val(); - result['ingressPort'] = $('#'+one.f.flows.id.modal.form.port, $modal).val(); - result['priority'] = $('#'+one.f.flows.id.modal.form.priority, $modal).val(); - result['hardTimeout'] = $('#'+one.f.flows.id.modal.form.hardTimeout, $modal).val(); - result['idleTimeout'] = $('#'+one.f.flows.id.modal.form.idleTimeout, $modal).val(); - result['cookie'] = $('#'+one.f.flows.id.modal.form.cookie, $modal).val(); - result['etherType'] = $('#'+one.f.flows.id.modal.form.etherType, $modal).val(); - result['vlanId'] = $('#'+one.f.flows.id.modal.form.vlanId, $modal).val(); - result['vlanPriority'] = $('#'+one.f.flows.id.modal.form.vlanPriority, $modal).val(); - result['dlSrc'] = $('#'+one.f.flows.id.modal.form.srcMac, $modal).val(); - result['dlDst'] = $('#'+one.f.flows.id.modal.form.dstMac, $modal).val(); - result['nwSrc'] = $('#'+one.f.flows.id.modal.form.srcIp, $modal).val(); - result['nwDst'] = $('#'+one.f.flows.id.modal.form.dstIp, $modal).val(); - result['tosBits'] = $('#'+one.f.flows.id.modal.form.tosBits, $modal).val(); - result['tpSrc'] = $('#'+one.f.flows.id.modal.form.srcPort, $modal).val(); - result['tpDst'] = $('#'+one.f.flows.id.modal.form.dstPort, $modal).val(); - result['protocol'] = $('#'+one.f.flows.id.modal.form.protocol, $modal).val(); - result['installInHw'] = install; - - var nodeId = $('#'+one.f.flows.id.modal.form.nodes, $modal).val(); - - $.each(result, function(key, value) { - if (value == "") delete result[key]; - }); - - var action = []; - var $table = $('#'+one.f.flows.id.modal.action.table, $modal); - $($table.find('tbody').find('tr')).each(function(index, value) { - if (!$(this).find('td').hasClass('empty')) { - action.push($(value).data('action')); - } - }); - result['actions'] = action; - - // frontend validation - if (result['name'] == undefined) { - alert('Need flow name'); - return; - } - if (nodeId == '') { - alert('Select node'); - return; - } - if (action.length == 0) { - alert('Please specify an action'); - return; - } - - // package for ajax call - var resource = {}; - resource['body'] = JSON.stringify(result); - if(edit){ - resource['action'] = 'edit'; - } else { - resource['action'] = 'add'; - } - - resource['nodeId'] = nodeId; - - if (edit) { - one.f.flows.modal.ajax.saveflow(resource, function(data) { - if (data == "Success") { - $modal.modal('hide').on('hidden', function () { - one.f.flows.detail(result['name'], nodeId); - }); - one.lib.alert('Flow Entry edited'); - one.main.dashlet.left.top.empty(); - one.f.flows.dashlet(one.main.dashlet.left.top); - } else { - alert('Could not edit flow: '+data); - } - }); - } else { - one.f.flows.modal.ajax.saveflow(resource, function(data) { - if (data == "Success") { - $modal.modal('hide'); - one.lib.alert('Flow Entry added'); - one.main.dashlet.left.top.empty(); - one.f.flows.dashlet(one.main.dashlet.left.top); - } else { - alert('Could not add flow: '+data); - } - }); - } - }, - ajax : { - nodes : function(successCallback) { - $.getJSON(one.f.address.root+one.f.address.flows.nodes, function(data) { - var nodes = one.f.flows.modal.data.nodes(data); - var nodeports = data; - one.f.flows.registry['nodes'] = nodes; - one.f.flows.registry['nodeports'] = nodeports; - - successCallback(nodes, nodeports); - }); - }, - saveflow : function(resource, callback) { - $.post(one.f.address.root+one.f.address.flows.flow, resource, function(data) { - callback(data); - }); - }, - removeflow : function(id, node, callback) { - resource = {}; - resource['action'] = 'remove'; - $.post(one.f.address.root+one.f.address.flows.flow+'/'+node+'/'+id, resource, function(data) { - callback(data); - }); - }, - toggleflow : function(id, node, callback) { - resource = {}; - resource['action'] = 'toggle'; - $.post(one.f.address.root+one.f.address.flows.flow+'/'+node+'/'+id, resource, function(data) { - callback(data); - }); - } - }, - data : { - nodes : function(data) { - result = {}; - $.each(data, function(key, value) { - result[key] = value['name']; - }); - return result; - } - }, - body : function(nodes, nodeports, edit) { - var $form = $(document.createElement('form')); - var $fieldset = $(document.createElement('fieldset')); - var existingFlow; - // flow description - var $legend = one.lib.form.legend(""); - $legend.css('visibility', 'hidden'); - $fieldset.append($legend); - // name - var $label = one.lib.form.label("Name"); - var $input = one.lib.form.input("Flow Name"); - $input.attr('id', one.f.flows.id.modal.form.name); - if(edit) { - $input.attr('disabled', 'disabled'); - var flows = one.f.flows.registry.flows; - $(flows).each(function(index, value) { - if (value.name == one.f.flows.registry.selectedId && value.nodeId == one.f.flows.registry.selectedNode) { - existingFlow = value.flow; - } - }); - $input.val(existingFlow.name); - } - - $fieldset.append($label).append($input); - // node - var $label = one.lib.form.label("Node"); - var $select = one.lib.form.select.create(nodes); - one.lib.form.select.prepend($select, { '' : 'Please Select a Node' }); - $select.val($select.find("option:first").val()); - $select.attr('id', one.f.flows.id.modal.form.nodes); - if(edit) { - $select.attr('disabled', 'disabled'); - $select.val(existingFlow.node.type + "|"+ existingFlow.node.nodeIDString); - } - - // bind onchange - $select.change(function() { - // retrieve port value - var node = $(this).find('option:selected').attr('value'); - var $ports = $('#'+one.f.flows.id.modal.form.port); - if (node == '') { - one.lib.form.select.inject($ports, {}); - return; - } - one.f.flows.registry['currentNode'] = node; - var ports = nodeports[node]['ports']; - one.lib.form.select.inject($ports, ports); - one.lib.form.select.prepend($ports, { '' : 'Please Select a Port' }); - $ports.val($ports.find("option:first").val()); - if(edit) { - $ports.val( existingFlow.ingressPort ); - } - $.getJSON(one.f.address.root+'/valid-flows/'+node, function(response) { - var $select = $('#'+one.f.flows.id.modal.form.action, $fieldset); - one.lib.form.select.inject($select, response); - one.lib.form.select.prepend($select, {'' : 'Please Select an Action'}); - // when selecting an action - $select.change(function() { - var action = $(this).find('option:selected'); - one.f.flows.modal.action.parse(action.attr('value')); - $select[0].selectedIndex = 0; - }); - }); - }); - - $fieldset.append($label).append($select); - // input port - var $label = one.lib.form.label("Input Port"); - var $select = one.lib.form.select.create(); - - $select.attr('id', one.f.flows.id.modal.form.port); - $fieldset.append($label).append($select); - // priority - var $label = one.lib.form.label("Priority"); - var $input = one.lib.form.input("Priority"); - $input.attr('id', one.f.flows.id.modal.form.priority); - $input.val('500'); - $fieldset.append($label).append($input); - if(edit) { - $input.val(existingFlow.priority); - } - // hardTimeout - var $label = one.lib.form.label("Hard Timeout"); - var $input = one.lib.form.input("Hard Timeout"); - $input.attr('id', one.f.flows.id.modal.form.hardTimeout); - if(edit) { - $input.val(existingFlow.hardTimeout); - } - $fieldset.append($label).append($input); - - // idleTimeout - var $label = one.lib.form.label("Idle Timeout"); - var $input = one.lib.form.input("Idle Timeout"); - $input.attr('id', one.f.flows.id.modal.form.idleTimeout); - $fieldset.append($label).append($input); - if(edit) { - $input.val(existingFlow.idleTimeout); - } - // cookie - var $label = one.lib.form.label("Cookie"); - var $input = one.lib.form.input("Cookie"); - $input.attr('id', one.f.flows.id.modal.form.cookie); - $fieldset.append($label).append($input); - if(edit) { - $input.val(existingFlow.cookie); - } - - // layer 2 - var $legend = one.lib.form.legend("Layer 2"); - $fieldset.append($legend); - // etherType - var $label = one.lib.form.label("Ethernet Type"); - var $input = one.lib.form.input("Ethernet Type"); - $input.attr('id', one.f.flows.id.modal.form.etherType); - $input.val('0x800'); - $fieldset.append($label).append($input); - if(edit) { - $input.val(existingFlow.etherType); - } - // vlanId - var $label = one.lib.form.label("VLAN Identification Number"); - var $input = one.lib.form.input("VLAN Identification Number"); - $input.attr('id', one.f.flows.id.modal.form.vlanId); - var $help = one.lib.form.help("Range: 0 - 4095"); - $fieldset.append($label).append($input).append($help); - if(edit) { - $input.val(existingFlow.vlanId); - } - - // vlanPriority - var $label = one.lib.form.label("VLAN Priority"); - var $input = one.lib.form.input("VLAN Priority"); - $input.attr('id', one.f.flows.id.modal.form.vlanPriority); - var $help = one.lib.form.help("Range: 0 - 7"); - $fieldset.append($label).append($input).append($help); - if(edit) { - $input.val(existingFlow.vlanPriority); - } - - // srcMac - var $label = one.lib.form.label("Source MAC Address"); - var $input = one.lib.form.input("3c:97:0e:75:c3:f7"); - $input.attr('id', one.f.flows.id.modal.form.srcMac); - $fieldset.append($label).append($input); - if(edit) { - $input.val(existingFlow.srcMac); - } - // dstMac - var $label = one.lib.form.label("Destination MAC Address"); - var $input = one.lib.form.input("7c:d1:c3:e8:e6:99"); - $input.attr('id', one.f.flows.id.modal.form.dstMac); - $fieldset.append($label).append($input); - if(edit) { - $input.val(existingFlow.dstMac); - } - // layer 3 - var $legend = one.lib.form.legend("Layer 3"); - $fieldset.append($legend); - - // srcIp - var $label = one.lib.form.label("Source IP Address"); - var $input = one.lib.form.input("192.168.3.128"); - $input.attr('id', one.f.flows.id.modal.form.srcIp); - $fieldset.append($label).append($input); - if(edit) { - $input.val(existingFlow.srcIp); - } - // dstIp - var $label = one.lib.form.label("Destination IP Address"); - var $input = one.lib.form.input("2001:2334::0/32"); - $input.attr('id', one.f.flows.id.modal.form.dstIp); - $fieldset.append($label).append($input); - if(edit) { - $input.val(existingFlow.dstIp); - } - // tosBits - var $label = one.lib.form.label("ToS Bits"); - var $input = one.lib.form.input("ToS Bits"); - $input.attr('id', one.f.flows.id.modal.form.tosBits); - var $help = one.lib.form.help("Range: 0 - 63"); - $fieldset.append($label).append($input).append($help); - if(edit) { - $input.val(existingFlow.tosBits); - } - - // layer 4 - var $legend = one.lib.form.legend("Layer 4"); - $fieldset.append($legend); - // srcPort - var $label = one.lib.form.label("Source Port"); - var $input = one.lib.form.input("Source Port"); - $input.attr('id', one.f.flows.id.modal.form.srcPort); - var $help = one.lib.form.help("Range: 0 - 65535"); - $fieldset.append($label).append($input).append($help); - if(edit) { - $input.val(existingFlow.srcPort); - } - // dstPort - var $label = one.lib.form.label("Destination Port"); - var $input = one.lib.form.input("Destination Port"); - $input.attr('id', one.f.flows.id.modal.form.dstPort); - var $help = one.lib.form.help("Range: 0 - 65535"); - $fieldset.append($label).append($input).append($help); - if(edit) { - $input.val(existingFlow.dstPort); - } - // protocol - var $label = one.lib.form.label("Protocol"); - var $input = one.lib.form.input("Protocol"); - $input.attr('id', one.f.flows.id.modal.form.protocol); - $fieldset.append($label).append($input); - if(edit) { - $input.val(existingFlow.protocol); - } - // actions - var $legend = one.lib.form.label("Actions"); - $fieldset.append($legend); - // actions table - var tableAttributes = ["table-striped", "table-bordered", "table-condensed", "table-hover", "table-cursor"]; - var $table = one.lib.dashlet.table.table(tableAttributes); - $table.attr('id', one.f.flows.id.modal.action.table); - var tableHeaders = ["Action", "Data"]; - var $thead = one.lib.dashlet.table.header(tableHeaders); - var $tbody = one.lib.dashlet.table.body("", tableHeaders); - $table.append($thead).append($tbody); - // actions - var actions = { - "" : "Please Select an Action", - "DROP" : "Drop", - "LOOPBACK" : "Loopback", - "FLOOD" : "Flood", - "FLOOD_ALL" : "Flood All", - "CONTROLLER" : "Controller", - "SW_PATH" : "Software Path", - "HW_PATH" : "Hardware Path", - "OUTPUT" : "Add Output Ports", - "ENQUEUE" : "Enqueue", - "SET_VLAN_ID" : "Set VLAN ID", - "SET_VLAN_PCP" : "Set VLAN Priority", - "SET_VLAN_CFI" : "Set VLAN CFI", - "POP_VLAN" : "Strip VLAN Header", - "PUSH_VLAN" : "Push VLAN", - "SET_DL_SRC" : "Modify Datalayer Source Address", - "SET_DL_DST" : "Modify Datalayer Destination Address", - "SET_DL_TYPE" : "Set Ethertype", - "SET_NW_SRC" : "Modify Network Source Address", - "SET_NW_DST" :"Modify Network Destination Address", - "SET_NW_TOS" : "Modify ToS Bits", - "SET_TP_SRC" : "Modify Transport Source Port", - "SET_TP_DST" : "Modify Transport Destination Port" - }; - var $select = one.lib.form.select.create(actions); - $select.attr('id', one.f.flows.id.modal.form.action); - // when selecting an action - $select.change(function() { - var action = $(this).find('option:selected'); - one.f.flows.modal.action.parse(action.attr('value')); - $select[0].selectedIndex = 0; - }); - - if(edit) { - $(existingFlow.actions).each(function(index, value){ - setTimeout(function(){ - var locEqualTo = value.indexOf("="); - if ( locEqualTo == -1 ) { - one.f.flows.modal.action.add.add(actions[value], value); - } else { - var action = value.substr(0,locEqualTo); - if( action == "OUTPUT") { - var portIds = value.substr(locEqualTo+1).split(","); - var ports = []; - var allPorts = one.f.flows.registry.nodeports[one.f.flows.registry.currentNode]['ports']; - for(var i =0; i < portIds.length ; i++) { - var portName = allPorts[portIds[i]]; - ports.push(portName); - } - one.f.flows.modal.action.add.addPortsToTable(ports.join(", "), portIds.join(",")); - } else { - var val = value.substr(locEqualTo+1); - one.f.flows.modal.action.add.addDataToTable(actions[action], val, action) - } - } - }, 1000) - }); - } - $fieldset.append($select).append($table); - - // return - $form.append($fieldset); - return $form; - }, - action : { - parse : function(option) { - switch (option) { - case "OUTPUT" : - var h3 = "Add Output Port"; - var $modal = one.f.flows.modal.action.initialize(h3, one.f.flows.modal.action.body.addOutputPorts, one.f.flows.modal.action.add.addOutputPorts); - $modal.modal(); - break; - case "SET_VLAN_ID" : - var h3 = "Set VLAN ID"; - var placeholder = "VLAN Identification Number"; - var id = one.f.flows.id.modal.action.setVlanId; - var help = "Range: 0 - 4095"; - var action = 'SET_VLAN_ID'; - var name = "VLAN ID"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "SET_VLAN_PCP" : - var h3 = "Set VLAN Priority"; - var placeholder = "VLAN Priority"; - var id = one.f.flows.id.modal.action.setVlanPriority; - var help = "Range: 0 - 7"; - var action = 'SET_VLAN_PCP'; - var name = "VLAN Priority"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "SET_VLAN_CFI" : - var h3 = "Set VLAN CFI"; - var placeholder = "VLAN CFI"; - var id = one.f.flows.id.modal.action.setVlanCfi; - var help = "Range: 0 - 1"; - var action = 'SET_VLAN_CFI'; - var name = "VLAN CFI"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "POP_VLAN" : - var name = "Strip VLAN Header"; - var action = 'POP_VLAN'; - one.f.flows.modal.action.add.add(name, action); - break; - case "PUSH_VLAN" : - var h3 = "Push VLAN"; - var placeholder = "VLAN"; - var id = one.f.flows.id.modal.action.pushVlan; - var help = "Range: 0 - 4095"; - var action = 'PUSH_VLAN'; - var name = "VLAN"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "SET_DL_SRC" : - var h3 = "Set Source MAC Address"; - var placeholder = "Source MAC Address"; - var id = one.f.flows.id.modal.action.modifyDatalayerSourceAddress; - var help = "Example: 00:11:22:aa:bb:cc"; - var action = 'SET_DL_SRC'; - var name = "Source MAC"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "SET_DL_DST" : - var h3 = "Set Destination MAC Address"; - var placeholder = "Destination MAC Address"; - var id = one.f.flows.id.modal.action.modifyDatalayerDestinationAddress; - var help = "Example: 00:11:22:aa:bb:cc"; - var action = 'SET_DL_DST'; - var name = "Destination MAC"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "SET_DL_TYPE" : - var h3 = "Set Ethertype"; - var placeholder = "Ethertype"; - var id = one.f.flows.id.modal.action.setEthertype; - var help = "Range: 0 - 65535"; - var action = 'SET_DL_TYPE'; - var name = "Ethertype"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "SET_NW_SRC" : - var h3 = "Set IP Source Address"; - var placeholder = "Source IP Address"; - var id = one.f.flows.id.modal.action.modifyNetworkSourceAddress; - var help = "Example: 127.0.0.1"; - var action = 'SET_NW_SRC'; - var name = "Source IP"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "SET_NW_DST" : - var h3 = "Set IP Destination Address"; - var placeholder = "Destination IP Address"; - var id = one.f.flows.id.modal.action.modifyNetworkDestinationAddress; - var help = "Example: 127.0.0.1"; - var action = 'SET_NW_DST'; - var name = "Destination IP"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "SET_NW_TOS" : - var h3 = "Set IPv4 ToS"; - var placeholder = "IPv4 ToS"; - var id = one.f.flows.id.modal.action.modifyTosBits; - var help = "Range: 0 - 63"; - var action = 'SET_NW_TOS'; - var name = "ToS Bits"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "SET_TP_SRC" : - var h3 = "Set Transport Source Port"; - var placeholder = "Transport Source Port"; - var id = one.f.flows.id.modal.action.modifyTransportSourcePort; - var help = "Range: 0 - 65535"; - var action = 'SET_TP_SRC'; - var name = "Source Port"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "SET_TP_DST" : - var h3 = "Set Transport Destination Port"; - var placeholder = "Transport Destination Port"; - var id = one.f.flows.id.modal.action.modifyTransportDestinationPort; - var help = "Range: 0 - 65535"; - var action = 'SET_TP_DST'; - var name = "Destination Port"; - var body = function() { - return one.f.flows.modal.action.body.set(h3, placeholder, id, help); - }; - var add = function($modal) { - one.f.flows.modal.action.add.set(name, id, action, $modal); - }; - var $modal = one.f.flows.modal.action.initialize(h3, body, add); - $modal.modal(); - break; - case "ENQUEUE" : - var h3 = "Enqueue"; - var placeholder = "Enqueue"; - var id = one.f.flows.id.modal.action.enqueue; - var $modal = one.f.flows.modal.action.initialize(h3, one.f.flows.modal.action.body.addEnqueue, one.f.flows.modal.action.add.addEnqueue); - $modal.modal(); - break; - case "DROP" : - var name = "Drop"; - var action = 'DROP'; - one.f.flows.modal.action.add.add(name, action); - break; - case "LOOPBACK" : - var name = "Loopback"; - var action = 'LOOPBACK'; - one.f.flows.modal.action.add.add(name, action); - break; - case "FLOOD" : - var name = "Flood"; - var action = 'FLOOD'; - one.f.flows.modal.action.add.add(name, action); - break; - case "FLOOD_ALL" : - var name = "Flood All"; - var action = 'FLOOD_ALL'; - one.f.flows.modal.action.add.add(name, action); - break; - case "SW_PATH" : - var name = "Software Path"; - var action = 'SW_PATH'; - one.f.flows.modal.action.add.add(name, action); - break; - case "HW_PATH" : - var name = "Hardware Path"; - var action = 'HW_PATH'; - one.f.flows.modal.action.add.add(name, action); - break; - case "CONTROLLER" : - var name = "Controller"; - var action = 'CONTROLLER'; - one.f.flows.modal.action.add.add(name, action); - break; - } - }, - initialize : function(h3, bodyCallback, addCallback) { - var footer = one.f.flows.modal.action.footer(); - var $body = bodyCallback(); - var $modal = one.lib.modal.spawn(one.f.flows.id.modal.action.modal, h3, $body, footer); - // bind close button - $('#'+one.f.flows.id.modal.action.close, $modal).click(function() { - $modal.modal('hide'); - }); - // bind add flow button - $('#'+one.f.flows.id.modal.action.add, $modal).click(function() { - addCallback($modal); - }); - return $modal; - }, - add : { - addOutputPorts : function($modal) { - var $options = $('#'+one.f.flows.id.modal.action.addOutputPorts).find('option:selected'); - var ports = ''; - var pid = ''; - $options.each(function(index, value) { - ports = ports+$(value).text()+", "; - pid = pid+$(value).attr('value')+","; - }); - ports = ports.slice(0,-2); - pid = pid.slice(0,-1); - one.f.flows.modal.action.add.addPortsToTable(ports, pid); - $modal.modal('hide'); - }, - addEnqueue : function($modal) { - var $options = $('#'+one.f.flows.id.modal.action.addOutputPorts).find('option:selected'); - var ports = ''; - var pid = ''; - $options.each(function(index, value) { - ports = ports+$(value).text()+", "; - pid = pid+$(value).attr('value')+","; - }); - var $input = $('#'+one.f.flows.id.modal.action.queue); - var queue = $input.val(); - ports = ports.slice(0,-2); - pid = pid.slice(0,-1); - one.f.flows.modal.action.add.addEnqueueToTable(ports, pid, queue); - $modal.modal('hide'); - }, - addEnqueueToTable : function(ports, pid, queue) { - if (queue !== '' && queue >= 0) { - ports += ':'+queue; - } - var $tr = one.f.flows.modal.action.table.add("Enqueue", ports); - $tr.attr('id', 'ENQUEUE'); - if (queue !== '' && queue >= 0) { - $tr.data('action', 'ENQUEUE='+pid+':'+queue); - } else { - $tr.data('action', 'ENQUEUE='+pid+':0'); // default queue to 0 - } - $tr.click(function() { - one.f.flows.modal.action.add.modal.initialize(this); - }); - one.f.flows.modal.action.table.append($tr); - }, - addPortsToTable : function(ports, pid){ - var $tr = one.f.flows.modal.action.table.add("Add Output Ports", ports); - $tr.attr('id', 'OUTPUT'); - $tr.data('action', 'OUTPUT='+pid); - $tr.click(function() { - one.f.flows.modal.action.add.modal.initialize(this); - }); - one.f.flows.modal.action.table.append($tr); - }, - add : function(name, action) { - var $tr = one.f.flows.modal.action.table.add(name); - $tr.attr('id', action); - $tr.data('action', action); - $tr.click(function() { - one.f.flows.modal.action.add.modal.initialize(this); - }); - one.f.flows.modal.action.table.append($tr); - }, - set : function(name, id, action, $modal) { - var $input = $('#'+id); - var value = $input.val(); - one.f.flows.modal.action.add.addDataToTable(name,value,action) - $modal.modal('hide'); - }, - addDataToTable : function(name,value,action) { - var $tr = one.f.flows.modal.action.table.add(name, value); - $tr.attr('id', action); - $tr.data('action', action+'='+value); - $tr.click(function() { - one.f.flows.modal.action.add.modal.initialize(this); - }); - one.f.flows.modal.action.table.append($tr); - }, - remove : function(that) { - $(that).remove(); - var $table = $('#'+one.f.flows.id.modal.action.table); - if ($table.find('tbody').find('tr').size() == 0) { - var $tr = $(document.createElement('tr')); - var $td = $(document.createElement('td')); - $td.attr('colspan', '3'); - $tr.addClass('empty'); - $td.text('No data available'); - $tr.append($td); - $table.find('tbody').append($tr); - } - }, - modal : { - initialize : function(that) { - var h3 = "Remove Action"; - var footer = one.f.flows.modal.action.add.modal.footer(); - var $body = one.f.flows.modal.action.add.modal.body(); - var $modal = one.lib.modal.spawn(one.f.flows.id.modal.action.modal.modal, h3, $body, footer); - - // bind cancel button - $('#'+one.f.flows.id.modal.action.modal.cancel, $modal).click(function() { - $modal.modal('hide'); - }); - - // bind remove button - $('#'+one.f.flows.id.modal.action.modal.remove, $modal).click(function() { - one.f.flows.modal.action.add.remove(that); - $modal.modal('hide'); - }); - - $modal.modal(); - }, - body : function() { - var $p = $(document.createElement('p')); - $p.append("Remove this action?"); - return $p; - }, - footer : function() { - var footer = []; - - var removeButton = one.lib.dashlet.button.single("Remove Action", one.f.flows.id.modal.action.modal.remove, "btn-danger", ""); - var $removeButton = one.lib.dashlet.button.button(removeButton); - footer.push($removeButton); - - var cancelButton = one.lib.dashlet.button.single("Cancel", one.f.flows.id.modal.action.modal.cancel, "", ""); - var $cancelButton = one.lib.dashlet.button.button(cancelButton); - footer.push($cancelButton); - - return footer; - } - } - }, - table : { - add : function(action, data) { - var $tr = $(document.createElement('tr')); - var $td = $(document.createElement('td')); - $td.append(action); - $tr.append($td); - var $td = $(document.createElement('td')); - if (data != undefined) $td.append(data); - $tr.append($td); - return $tr; - }, - append : function($tr) { - var $table = $('#'+one.f.flows.id.modal.action.table); - var $empty = $table.find('.empty').parent(); - if ($empty.size() > 0) $empty.remove(); - $table.append($tr); - } - }, - body : { - common : function() { - var $form = $(document.createElement('form')); - var $fieldset = $(document.createElement('fieldset')); - return [$form, $fieldset]; - }, - addOutputPorts : function() { - var common = one.f.flows.modal.action.body.common(); - var $form = common[0]; - var $fieldset = common[1]; - // output port - $label = one.lib.form.label("Select Output Ports"); - if (one.f.flows.registry.currentNode == undefined){ - return; //Selecting Output ports without selecting node throws an exception - } - var ports = one.f.flows.registry.nodeports[one.f.flows.registry.currentNode]['ports']; - $select = one.lib.form.select.create(ports, true); - $select.attr('id', one.f.flows.id.modal.action.addOutputPorts); - $fieldset.append($label).append($select); - $form.append($fieldset); - return $form; - }, - addEnqueue : function() { - var common = one.f.flows.modal.action.body.common(); - var $form = common[0]; - var $fieldset = common[1]; - // output port - $label = one.lib.form.label("Select Output Ports"); - if (one.f.flows.registry.currentNode == undefined){ - return; //Selecting Output ports without selecting node throws an exception - } - var ports = one.f.flows.registry.nodeports[one.f.flows.registry.currentNode]['ports']; - $select = one.lib.form.select.create(ports); - $select.attr('id', one.f.flows.id.modal.action.addOutputPorts); - $fieldset.append($label).append($select); - $label = one.lib.form.label('Queue (Optional)'); - $input = one.lib.form.input('Queue') - .attr('id', one.f.flows.id.modal.action.queue); - $help = one.lib.form.help('Range: 1 - 2147483647'); - $fieldset.append($label).append($input).append($help); - $form.append($fieldset); - return $form; - }, - set : function(label, placeholder, id, help) { - var common = one.f.flows.modal.action.body.common(); - var $form = common[0]; - var $fieldset = common[1]; - // input - $label = one.lib.form.label(label); - $input = one.lib.form.input(placeholder); - $input.attr('id', id); - $help = one.lib.form.help(help); - // append - $fieldset.append($label).append($input).append($help); - $form.append($fieldset); - return $form; - } - }, - footer : function() { - var footer = []; - var addButton = one.lib.dashlet.button.single("Add Action", one.f.flows.id.modal.action.add, "btn-primary", ""); - var $addButton = one.lib.dashlet.button.button(addButton); - footer.push($addButton); - - var closeButton = one.lib.dashlet.button.single("Close", one.f.flows.id.modal.action.close, "", ""); - var $closeButton = one.lib.dashlet.button.button(closeButton); - footer.push($closeButton); - - return footer; - } - }, - footer : function() { - var footer = []; - - var installButton = one.lib.dashlet.button.single("Install Flow", one.f.flows.id.modal.install, "btn-success", ""); - var $installButton = one.lib.dashlet.button.button(installButton); - footer.push($installButton); - - var addButton = one.lib.dashlet.button.single("Save Flow", one.f.flows.id.modal.add, "btn-primary", ""); - var $addButton = one.lib.dashlet.button.button(addButton); - footer.push($addButton); - - var closeButton = one.lib.dashlet.button.single("Close", one.f.flows.id.modal.close, "", ""); - var $closeButton = one.lib.dashlet.button.button(closeButton); - footer.push($closeButton); - - return footer; - }, - footerEdit : function() { - var footer = []; - - var editButton = one.lib.dashlet.button.single("Save Flow", one.f.flows.id.modal.edit, "btn-success", ""); - var $editButton = one.lib.dashlet.button.button(editButton); - footer.push($editButton); - - var closeButton = one.lib.dashlet.button.single("Close", one.f.flows.id.modal.close, "", ""); - var $closeButton = one.lib.dashlet.button.button(closeButton); - footer.push($closeButton); - - return footer; - }, - removeMultiple: { - dialog: function(flows) { - var h3 = 'Remove Flow Entry'; - var flowList = []; - for (var i = 0; i < flows.length; i++) { - flowList.push(flows[i]["name"]); - } - var footer = one.f.flows.modal.removeMultiple.footer(); - var $body = one.f.flows.modal.removeMultiple.body(flowList); - var $modal = one.lib.modal.spawn(one.f.flows.id.modal.dialog.modal, h3, $body, footer); - - // bind close button - $('#'+one.f.flows.id.modal.dialog.close, $modal).click(function() { - $modal.modal('hide'); - }); - - // bind remove rule button - $('#'+one.f.flows.id.modal.dialog.remove, $modal).click(this, function(e) { - var resource = {}; - resource['body'] = JSON.stringify(flows); - - $.post(one.f.address.root+one.f.address.flows.deleteFlows, resource, function(response) { - $modal.modal('hide'); - if(response == "Success") { - one.lib.alert("Flow Entry(s) successfully removed"); - } else { - one.lib.alert(response); - } - one.main.dashlet.right.bottom.empty(); - one.f.detail.dashlet(one.main.dashlet.right.bottom); - one.main.dashlet.left.top.empty(); - one.f.flows.dashlet(one.main.dashlet.left.top); - }); - }); - $modal.modal(); - }, - footer : function() { - var footer = []; - var remove = one.lib.dashlet.button.single('Remove Flow Entry',one.f.flows.id.modal.dialog.remove, 'btn-danger', ''); - var $remove = one.lib.dashlet.button.button(remove); - footer.push($remove); - - var cancel = one.lib.dashlet.button.single('Cancel', one.f.flows.id.modal.dialog.close, '', ''); - var $cancel = one.lib.dashlet.button.button(cancel); - footer.push($cancel); - - return footer; - }, - body : function (flows) { - var $p = $(document.createElement('p')); - var p = 'Remove the following Flow Entry(s)?'; - //creata a BS label for each rule and append to list - $(flows).each(function(){ - var $span = $(document.createElement('span')); - $span.append(this); - p += '
' + $span[0].outerHTML; - }); - $p.append(p); - return $p; - } - } - }, - ajax : { - dashlet : function(callback) { - $.getJSON(one.f.address.root+one.f.address.flows.main, function(data) { - one.f.flows.registry['flows'] = data.flows; - one.f.flows.registry['privilege'] = data.privilege; - one.f.flows.modal.ajax.nodes(function(){/*Empty function. Do nothing. */}) - - callback(data); - }); - } - }, - data : { - flowsDataGrid: function(data) { - var source = new StaticDataSource({ - columns: [ - { - property: 'selector', - label: "", - sortable: false - }, - { - property: 'name', - label: 'Flow Name', - sortable: true - }, - { - property: 'node', - label: 'Node', - sortable: true - } - ], - data: data.flows, - formatter: function(items) { - $.each(items, function(index, item) { - var $checkbox = document.createElement("input"); - $checkbox.setAttribute("type", "checkbox"); - $checkbox.setAttribute("name", item.name); - $checkbox.setAttribute("node", item.nodeId); - $checkbox.setAttribute('class','flowEntry') - item.selector = $checkbox.outerHTML; - item["name"] = '' + item["name"] + ''; - }); - - }, - delay: 0 - }); - return source; - }, - dashlet : function(data) { - var body = []; - $(data).each(function(index, value) { - var tr = {}; - var entry = []; - - - entry.push(value['name']); - entry.push(value['node']); - if (value['flow']['installInHw'] == 'true' && value['flow']['status'] == 'Success') - tr['type'] = ['success']; - else if (value['flow']['installInHw'] == 'false' && value['flow']['status'] == 'Success') - tr['type'] = ['warning']; - else - tr['type'] = ['warning']; - tr['entry'] = entry; - tr['id'] = value['nodeId']; - - body.push(tr); - }); - return body; - } - }, - body : { - dashlet : function(body, callback) { - var attributes = ['table-striped', 'table-bordered', 'table-hover', 'table-condensed', 'table-cursor']; - var $table = one.lib.dashlet.table.table(attributes); - - var headers = ['Flow Name', 'Node']; - - var $thead = one.lib.dashlet.table.header(headers); - $table.append($thead); - - var $tbody = one.lib.dashlet.table.body(body); - $table.append($tbody); - return $table; - } - } -} - -/** INIT **/ -// populate nav tabs -$(one.f.menu.left.top).each(function(index, value) { - var $nav = $(".nav", "#left-top"); - one.main.page.dashlet($nav, value); -}); - -$(one.f.menu.left.bottom).each(function(index, value) { - var $nav = $(".nav", "#left-bottom"); - one.main.page.dashlet($nav, value); -}); - -$(one.f.menu.right.bottom).each(function(index, value) { - var $nav = $(".nav", "#right-bottom"); - one.main.page.dashlet($nav, value); -}); - -one.f.populate = function($dashlet, header) { - var $h4 = one.lib.dashlet.header(header); - $dashlet.append($h4); -}; - -// bind dashlet nav -$('.dash .nav a', '#main').click(function() { - // de/activation - var $li = $(this).parent(); - var $ul = $li.parent(); - one.lib.nav.unfocus($ul); - $li.addClass('active'); - // clear respective dashlet - var $dashlet = $ul.parent().find('.dashlet'); - one.lib.dashlet.empty($dashlet); - // callback based on menu - var id = $(this).attr('id'); - var menu = one.f.dashlet; - switch (id) { - case menu.flows.id: - one.f.flows.dashlet($dashlet); - break; - case menu.nodes.id: - one.f.nodes.dashlet($dashlet); - break; - case menu.detail.id: - one.f.detail.dashlet($dashlet); - break; - }; -}); - -// activate first tab on each dashlet -$('.dash .nav').each(function(index, value) { - $($(value).find('li')[0]).find('a').click(); -}); diff --git a/opendaylight/adsal/web/osgi-brandfragment/pom.xml b/opendaylight/adsal/web/osgi-brandfragment/pom.xml deleted file mode 100644 index 31e1bf805e..0000000000 --- a/opendaylight/adsal/web/osgi-brandfragment/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - osgi-brandfragment.web - 0.2.0-SNAPSHOT - bundle - OSGi management web application brand fragment - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.apache.felix.webconsole - - - - - - - diff --git a/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/META-INF/webconsole.properties b/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/META-INF/webconsole.properties deleted file mode 100644 index 2cc8e912c1..0000000000 --- a/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/META-INF/webconsole.properties +++ /dev/null @@ -1,11 +0,0 @@ -webconsole.brand.name = OpenDaylight -webconsole.product.name = OpenDaylight Controller -webconsole.product.url = http://www.opendaylight.org/ -webconsole.product.image = /res/imgs/odl/logo.png -webconsole.favicon = /res/imgs/odl/favicon.ico -#To disable web console authentication clear default username -webconsole.username = -# webconsole.vendor.name = Linux Foundation -# webconsole.vendor.url = http://www.linuxfoundation.org/ -# webconsole.vendor.image = /res/imgs/vendor.png -# webconsole.stylesheet = /res/css/my.css diff --git a/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/res/imgs/odl/favicon.ico b/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/res/imgs/odl/favicon.ico deleted file mode 100644 index 59f0ec6c35..0000000000 Binary files a/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/res/imgs/odl/favicon.ico and /dev/null differ diff --git a/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/res/imgs/odl/logo.png b/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/res/imgs/odl/logo.png deleted file mode 100644 index 103520b1b6..0000000000 Binary files a/opendaylight/adsal/web/osgi-brandfragment/src/main/resources/res/imgs/odl/logo.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/pom.xml b/opendaylight/adsal/web/root/pom.xml deleted file mode 100644 index 992f9b3dc5..0000000000 --- a/opendaylight/adsal/web/root/pom.xml +++ /dev/null @@ -1,142 +0,0 @@ - - - 4.0.0 - - org.opendaylight.controller - commons.opendaylight - 1.6.0-SNAPSHOT - ../../../commons/opendaylight - - - web - 0.6.0-SNAPSHOT - bundle - - - com.google.code.gson - gson - - - equinoxSDK381 - javax.servlet - - - junit - junit - - - commons-io - commons-io - - - org.opendaylight.controller - clustering.services - - - org.opendaylight.controller - configuration - - - org.opendaylight.controller - connectionmanager - - - org.opendaylight.controller - containermanager - - - org.opendaylight.controller - sal - - - org.opendaylight.controller - switchmanager - - - org.opendaylight.controller - usermanager - - - org.springframework - org.springframework.web - - - - - - - org.apache.felix - maven-bundle-plugin - true - - - org.opendaylight.controller.configuration, - org.opendaylight.controller.sal.authorization, - org.opendaylight.controller.sal.core, - org.opendaylight.controller.sal.utils, - org.opendaylight.controller.usermanager, - org.opendaylight.controller.containermanager, - org.opendaylight.controller.clustering.services, - org.opendaylight.controller.connectionmanager, - org.opendaylight.controller.switchmanager, - com.google.gson, - javax.annotation, - javax.naming, - javax.servlet, - javax.servlet.annotation, - javax.servlet.http, - javax.servlet.jsp, - javax.servlet.jsp.el, - javax.servlet.jsp.jstl.core, - javax.servlet.jsp.jstl.fmt, - javax.servlet.jsp.jstl.tlv, - javax.servlet.jsp.tagext, - javax.servlet.resources, - javax.xml.parsers, - javax.xml.transform, - org.apache.commons.io, - org.apache.commons.logging, - org.apache.taglibs.standard.functions, - org.apache.taglibs.standard.resources, - org.apache.taglibs.standard.tag.common.core, - org.apache.taglibs.standard.tag.common.fmt, - org.apache.taglibs.standard.tag.rt.core, - org.apache.taglibs.standard.tag.rt.fmt, - org.apache.taglibs.standard.tei, - org.apache.taglibs.standard.tlv, - com.fasterxml.jackson.core, - com.fasterxml.jackson.databind, - com.fasterxml.jackson.annotation, - org.osgi.framework, - org.slf4j, - org.springframework.beans, - org.springframework.beans.factory.xml, - org.springframework.context.config, - org.springframework.core, - org.springframework.stereotype, - org.springframework.ui, - org.springframework.web, - org.springframework.web.bind.annotation, - org.springframework.web.servlet, - org.springframework.web.servlet.config, - org.springframework.web.servlet.view, - org.springframework.web.servlet.view.json, - org.springframework.web.filter, - org.springframework.web.context, - org.springframework.util, - org.apache.catalina.filters - org.opendaylight.controller.web - / - - ${project.basedir}/src/main/resources/META-INF - - - - - - scm:git:ssh://git.opendaylight.org:29418/controller.git - scm:git:ssh://git.opendaylight.org:29418/controller.git - HEAD - https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main - - diff --git a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/ClusterNodeBean.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/ClusterNodeBean.java deleted file mode 100644 index 974fdee1f6..0000000000 --- a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/ClusterNodeBean.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.web; - -import java.net.InetAddress; - -/** - * Information about a clustered controller to send to the UI frontend - * @author andrekim - */ -public class ClusterNodeBean { - private final byte[] address; - private final String name; - private final Boolean me; - private final Boolean coordinator; - private final Integer numConnectedNodes; - - public static class Builder { - // required params - private final byte[] address; - private final String name; - - // optional params - private Boolean me = null; - private Boolean coordinator = null; - private Integer numConnectedNodes = null; - - public Builder(InetAddress address) { - this.address = address.getAddress(); - this.name = address.getHostAddress(); - } - - public Builder highlightMe() { - this.me = true; - return this; - } - - public Builder iAmCoordinator() { - this.coordinator = true; - return this; - } - - public Builder nodesConnected(int numNodes) { - this.numConnectedNodes = numNodes; - return this; - } - - public ClusterNodeBean build() { - return new ClusterNodeBean(this); - } - } - - private ClusterNodeBean(Builder builder) { - this.address = builder.address; - this.name = builder.name; - this.me = builder.me; - this.coordinator = builder.coordinator; - this.numConnectedNodes = builder.numConnectedNodes; - } -} diff --git a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/ControllerUISessionManager.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/ControllerUISessionManager.java deleted file mode 100644 index 72b9d6bd26..0000000000 --- a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/ControllerUISessionManager.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.web; - -import javax.servlet.http.HttpSessionEvent; -import javax.servlet.http.HttpSessionListener; - -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.usermanager.IUserManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ControllerUISessionManager implements HttpSessionListener { - - private static final Logger logger = LoggerFactory.getLogger(ControllerUISessionManager.class); - - @Override - public void sessionCreated(HttpSessionEvent se) { - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - if (userManager != null) { - ((HttpSessionListener) userManager.getSessionManager()).sessionCreated(se); - } else { - logger.warn("User Manager is currently unavailable. Unable to register UI session."); - } - } - - @Override - public void sessionDestroyed(HttpSessionEvent se) { - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - if (userManager != null) { - ((HttpSessionListener) userManager.getSessionManager()).sessionDestroyed(se); - } else { - logger.warn("User Manager is currently unavailable. Unable to destroy UI session."); - } - } - -} diff --git a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWeb.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWeb.java deleted file mode 100644 index 090efec31e..0000000000 --- a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWeb.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) 2013, 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.web; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.io.IOUtils; -import org.opendaylight.controller.configuration.IConfigurationContainerService; -import org.opendaylight.controller.configuration.IConfigurationService; -import org.opendaylight.controller.containermanager.IContainerAuthorization; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.authorization.Resource; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.usermanager.IUserManager; -import org.springframework.stereotype.Controller; -import org.springframework.ui.Model; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -@Controller -@RequestMapping("/") -public class DaylightWeb { - @RequestMapping(value = "") - public String index(Model model, HttpServletRequest request) { - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return "User Manager is not available"; - } - - String username = request.getUserPrincipal().getName(); - - model.addAttribute("username", username); - model.addAttribute("role", userManager.getUserLevel(username) - .toNumber()); - - return "main"; - } - - /** - * Read the version.properties file for the property - * - * @param request - * @return String value configured in the version.properties file - */ - @RequestMapping(value="/versionProperty/{property}", method = RequestMethod.GET) - @ResponseBody - public String getVersion(HttpServletRequest request, @PathVariable("property") String property) { - Properties prop = new Properties(); - FileInputStream propertiesFile = null; - try { - propertiesFile = new FileInputStream("version.properties"); - prop.load(propertiesFile); - return prop.getProperty(property+".version"); - } catch (IOException e) { - // TODO: We should be logging the exception here - // "Failed to open version.properties." - return null; - } finally { - IOUtils.closeQuietly(propertiesFile); - } - } - @RequestMapping(value = "web.json") - @ResponseBody - public Map> bundles(HttpServletRequest request) { - Object[] instances = ServiceHelper.getGlobalInstances( - IDaylightWeb.class, this, null); - Map> bundles = new HashMap>(); - Map entry; - IDaylightWeb bundle; - String username = request.getUserPrincipal().getName(); - IUserManager userManger = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - for (Object instance : instances) { - bundle = (IDaylightWeb) instance; - if (userManger != null - && bundle.isAuthorized(userManger.getUserLevel(username))) { - entry = new HashMap(); - entry.put("name", bundle.getWebName()); - entry.put("order", bundle.getWebOrder()); - bundles.put(bundle.getWebId(), entry); - } - } - return bundles; - } - - @RequestMapping(value = "save", method = RequestMethod.POST) - @ResponseBody - public String save(HttpServletRequest request) { - String username = request.getUserPrincipal().getName(); - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return "User Manager is not available"; - } - UserLevel level = userManager.getUserLevel(username); - Status status; - switch (level) { - case SYSTEMADMIN: - case NETWORKADMIN: - IConfigurationService configService = (IConfigurationService) ServiceHelper.getGlobalInstance( - IConfigurationService.class, this); - if (configService != null) { - status = configService.saveConfigurations(); - } else { - status = new Status(StatusCode.NOSERVICE, "Configuration Service is not available"); - } - break; - case NETWORKOPERATOR: - case CONTAINERUSER: - IContainerAuthorization containerAuth = (IContainerAuthorization) ServiceHelper.getGlobalInstance( - IContainerAuthorization.class, this); - if (containerAuth != null) { - boolean oneSaved = false; - Set authorizedContainers = containerAuth.getAllResourcesforUser(username); - if (authorizedContainers.isEmpty()) { - status = new Status(StatusCode.UNAUTHORIZED, "User is not authorized for any container"); - } else { - for (Resource container : authorizedContainers) { - if (container.getPrivilege() == Privilege.WRITE) { - String containerName = (String)container.getResource(); - IConfigurationContainerService containerConfigService = (IConfigurationContainerService) ServiceHelper - .getInstance(IConfigurationContainerService.class, containerName, this); - if (containerConfigService != null) { - status = containerConfigService.saveConfigurations(); - if (status.isSuccess()) { - oneSaved = true; - } - } - } - } - if (oneSaved) { - status = new Status(StatusCode.SUCCESS); - } else { - status = new Status(StatusCode.UNAUTHORIZED, "Operation not allowed for current user"); - } - } - } else { - status = new Status(StatusCode.NOSERVICE, "Container Authorization Service is not available"); - } - break; - case APPUSER: - case NOUSER: - default: - status = new Status(StatusCode.UNAUTHORIZED, "Operation not allowed for current user"); - break; - } - // This function will eventually return a Status - return status.getDescription(); - } - - @RequestMapping(value = "logout") - public String logout(Map model, final HttpServletRequest request) { - - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return "User Manager is not available"; - } - String username = request.getUserPrincipal().getName(); - HttpSession session = request.getSession(false); - if (session != null) { - if (username != null) { - userManager.userLogout(username); - } - session.invalidate(); - - } - return "redirect:" + "/"; - } - - @RequestMapping(value = "login") - public String login(Model model, final HttpServletRequest request, - final HttpServletResponse response) { - // response.setHeader("X-Page-Location", "/login"); - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return "User Manager is not available"; - } - - String username = request.getUserPrincipal().getName(); - - model.addAttribute("username", username); - model.addAttribute("role", userManager.getUserLevel(username) - .toNumber()); - return "forward:" + "/"; - } - -} diff --git a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebAdmin.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebAdmin.java deleted file mode 100644 index b6a4d0dd54..0000000000 --- a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebAdmin.java +++ /dev/null @@ -1,348 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.web; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.opendaylight.controller.clustering.services.IClusterGlobalServices; -import org.opendaylight.controller.connectionmanager.IConnectionManager; -import org.opendaylight.controller.sal.authorization.UserLevel; -import org.opendaylight.controller.sal.core.Description; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.sal.utils.Status; -import org.opendaylight.controller.sal.utils.StatusCode; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.usermanager.IUserManager; -import org.opendaylight.controller.usermanager.UserConfig; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.google.gson.Gson; - -@Controller -@RequestMapping("/admin") -public class DaylightWebAdmin { - Gson gson = new Gson(); - - /** - * Returns list of clustered controllers. Highlights "this" controller and - * if controller is coordinator - * - * @return List - */ - @RequestMapping("/cluster") - @ResponseBody - public String getClusteredControllers() { - IClusterGlobalServices clusterServices = (IClusterGlobalServices) ServiceHelper.getGlobalInstance( - IClusterGlobalServices.class, this); - if (clusterServices == null) { - return null; - } - IConnectionManager connectionManager = (IConnectionManager) ServiceHelper.getGlobalInstance( - IConnectionManager.class, this); - if (connectionManager == null) { - return null; - } - - List clusterNodes = new ArrayList(); - - List controllers = clusterServices.getClusteredControllers(); - for (InetAddress controller : controllers) { - ClusterNodeBean.Builder clusterBeanBuilder = new ClusterNodeBean.Builder(controller); - - // get number of connected nodes - Set connectedNodes = connectionManager.getNodes(controller); - int numNodes = connectedNodes == null ? 0 : connectedNodes.size(); - clusterBeanBuilder.nodesConnected(numNodes); - - // determine if this is the executing controller - if (controller.equals(clusterServices.getMyAddress())) { - clusterBeanBuilder.highlightMe(); - } - - // determine whether this is coordinator - if (clusterServices.getCoordinatorAddress().equals(controller)) { - clusterBeanBuilder.iAmCoordinator(); - } - clusterNodes.add(clusterBeanBuilder.build()); - } - - return gson.toJson(clusterNodes); - } - - /** - * Return nodes connected to controller {controller} - * - * @param controller - * - byte[] of the address of the controller - * @return List - */ - @RequestMapping("/cluster/controller/{controller}") - @ResponseBody - public String getNodesConnectedToController(@PathVariable("controller") String controller) { - IClusterGlobalServices clusterServices = (IClusterGlobalServices) ServiceHelper.getGlobalInstance( - IClusterGlobalServices.class, this); - if (clusterServices == null) { - return null; - } - IConnectionManager connectionManager = (IConnectionManager) ServiceHelper.getGlobalInstance( - IConnectionManager.class, this); - if (connectionManager == null) { - return null; - } - ISwitchManager switchManager = (ISwitchManager) ServiceHelper.getInstance(ISwitchManager.class, - GlobalConstants.DEFAULT.toString(), this); - if (switchManager == null) { - return null; - } - - byte[] address = gson.fromJson(controller, byte[].class); - InetAddress controllerAddress = null; - try { - controllerAddress = InetAddress.getByAddress(address); - } catch (UnknownHostException e) { - return null; - } - - List result = new ArrayList(); - - Set nodes = connectionManager.getNodes(controllerAddress); - if (nodes == null) { - return gson.toJson(result); - } - for (Node node : nodes) { - Description description = (Description) switchManager.getNodeProp(node, Description.propertyName); - NodeBean nodeBean; - if (description == null || description.getValue().equals("None")) { - nodeBean = new NodeBean(node); - } else { - nodeBean = new NodeBean(node, description.getValue()); - } - result.add(nodeBean); - } - - return gson.toJson(result); - } - - @RequestMapping(value = "/users", method = RequestMethod.GET) - @ResponseBody - public List getUsers() { - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return null; - } - - List result = new ArrayList(); - List configs = userManager.getLocalUserList(); - for (UserConfig config : configs) { - UserBean bean = new UserBean(config); - result.add(bean); - } - - return result; - } - - /* - * Password in clear text, moving to HTTP/SSL soon - */ - @RequestMapping(value = "/users", method = RequestMethod.POST) - @ResponseBody - public Status saveLocalUserConfig(@RequestParam(required = true) String json, - @RequestParam(required = true) String action, HttpServletRequest request) { - - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return new Status(StatusCode.NOSERVICE, "User Manager unavailable"); - } - - if (!authorize(userManager, UserLevel.NETWORKADMIN, request)) { - return new Status(StatusCode.UNAUTHORIZED, "Operation not permitted"); - } - - Gson gson = new Gson(); - UserConfig plainConfig = gson.fromJson(json, UserConfig.class); - // Recreate using the proper constructor which will hash the password - UserConfig config = new UserConfig(plainConfig.getUser(), plainConfig.getPassword(), plainConfig.getRoles()); - - Status result = (action.equals("add")) ? userManager.addLocalUser(config) : userManager.removeLocalUser(config); - if (result.isSuccess()) { - if (action.equals("add")) { - DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), "added", config.getUser() - + " as " + config.getRoles().toString()); - } else { - DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), "removed", config.getUser()); - } - } - return result; - } - - @RequestMapping(value = "/user/modify", method = RequestMethod.POST) - @ResponseBody - public Status modifyUser(@RequestParam(required = true) String json, - @RequestParam(required = true) String action, HttpServletRequest request) { - - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return new Status(StatusCode.NOSERVICE, "User Manager unavailable"); - } - - if (!authorize(userManager, UserLevel.NETWORKADMIN, request)) { - return new Status(StatusCode.UNAUTHORIZED, "Operation not permitted"); - } - - UserConfig newConfig = gson.fromJson(json, UserConfig.class); - List currentUserConfig = userManager.getLocalUserList(); - String password = null; - byte[] salt = null; - String user = newConfig.getUser(); - for (UserConfig userConfig : currentUserConfig) { - if(userConfig.getUser().equals(user)){ - password = userConfig.getPassword(); - salt = userConfig.getSalt(); - break; - } - } - if (password == null) { - String msg = String.format("User %s not found in configuration database", user); - return new Status(StatusCode.NOTFOUND, msg); - } - - //While modifying a user role, the password is not provided from GUI for any user. - //The password is stored in hash mode, hence it cannot be retrieved and added to UserConfig object - //The hashed password is injected below to the json string containing username and new roles before - //converting to UserConfig object. - Gson gson = new Gson(); - json = json.replace("\"roles\"", "\"salt\":" + gson.toJson(salt, salt.getClass()) + ",\"password\":\""+ password + "\",\"roles\""); - - newConfig = gson.fromJson(json, UserConfig.class); - - Status result = userManager.modifyLocalUser(newConfig); - if (result.isSuccess()) { - DaylightWebUtil.auditlog("Roles of", request.getUserPrincipal().getName(), "updated", newConfig.getUser() - + " to " + newConfig.getRoles().toString()); - } - return result; - } - - - @RequestMapping(value = "/users/{username}", method = RequestMethod.POST) - @ResponseBody - public Status removeLocalUser(@PathVariable("username") String userName, HttpServletRequest request) { - - String loggedInUser = request.getUserPrincipal().getName(); - if (loggedInUser.equals(userName)) { - String msg = "Invalid Request: User cannot delete itself"; - return new Status(StatusCode.NOTALLOWED, msg); - } - - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return new Status(StatusCode.NOSERVICE, "User Manager unavailable"); - } - - if (!authorize(userManager, UserLevel.NETWORKADMIN, request)) { - return new Status(StatusCode.UNAUTHORIZED, "Operation not permitted"); - } - - Status status = userManager.removeLocalUser(userName); - if (status.isSuccess()) { - DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), "removed", userName); - return status; - } - return status; - } - - @RequestMapping(value = "/users/password/{username}", method = RequestMethod.POST) - @ResponseBody - public Status changePassword( - @PathVariable("username") String username, HttpServletRequest request, - @RequestParam(value = "currentPassword", required=false) String currentPassword, - @RequestParam("newPassword") String newPassword) { - IUserManager userManager = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, this); - if (userManager == null) { - return new Status(StatusCode.NOSERVICE, "User Manager unavailable"); - } - - Status status; - String requestingUser = request.getUserPrincipal().getName(); - - //changing own password - if (requestingUser.equals(username) ) { - status = userManager.changeLocalUserPassword(username, currentPassword, newPassword); - //enforce the user to re-login with new password - if (status.isSuccess() && !newPassword.equals(currentPassword)) { - userManager.userLogout(username); - HttpSession session = request.getSession(false); - if ( session != null) { - session.invalidate(); - } - } - - //admin level user resetting other's password - } else if (authorize(userManager, UserLevel.NETWORKADMIN, request)) { - - //Since User Manager doesn't have an unprotected password change API, - //we re-create the user with the new password (and current roles). - List roles = userManager.getUserRoles(username); - UserConfig newConfig = new UserConfig(username, newPassword, roles); - - //validate before removing existing config, so we don't remove but fail to add - status = newConfig.validate(); - if (!status.isSuccess()) { - return status; - } - - userManager.userLogout(username); - status = userManager.removeLocalUser(username); - if (!status.isSuccess()) { - return status; - } - if (userManager.addLocalUser(newConfig).isSuccess()) { - status = new Status(StatusCode.SUCCESS, "Password for user " + username + " reset successfully."); - } else { - //unexpected - status = new Status(StatusCode.INTERNALERROR, "Failed resetting password for user " + username + ". User is now removed."); - } - - //unauthorized - } else { - status = new Status(StatusCode.UNAUTHORIZED, "Operation not permitted"); - } - - if (status.isSuccess()) { - DaylightWebUtil.auditlog("User", request.getUserPrincipal().getName(), "changed password for", - username); - } - return status; - } - - /** - * Is the operation permitted for the given level - * - * @param level - */ - private boolean authorize(IUserManager userManager, UserLevel level, HttpServletRequest request) { - String username = request.getUserPrincipal().getName(); - UserLevel userLevel = userManager.getUserLevel(username); - return userLevel.toNumber() <= level.toNumber(); - } -} diff --git a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebUtil.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebUtil.java deleted file mode 100644 index e889836301..0000000000 --- a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/DaylightWebUtil.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.web; - -import org.opendaylight.controller.containermanager.IContainerAuthorization; -import org.opendaylight.controller.sal.authorization.Privilege; -import org.opendaylight.controller.sal.core.Description; -import org.opendaylight.controller.sal.core.Name; -import org.opendaylight.controller.sal.core.Node; -import org.opendaylight.controller.sal.core.NodeConnector; -import org.opendaylight.controller.sal.utils.GlobalConstants; -import org.opendaylight.controller.sal.utils.ServiceHelper; -import org.opendaylight.controller.switchmanager.ISwitchManager; -import org.opendaylight.controller.usermanager.IUserManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DaylightWebUtil { - - private static final String AUDIT = "audit"; - private static final Logger logger = LoggerFactory.getLogger(AUDIT); - - /** - * Returns the access privilege the user has on the specified container - * - * @param userName - * The user name - * @param container - * The container name. If null, the default container will be assumed - * @param bundle - * The bundle originating the request - * @return The access privilege the user is granted on the container - */ - public static Privilege getContainerPrivilege(String userName, - String container, Object bundle) { - // Derive the target resource - String resource = (container == null) ? GlobalConstants.DEFAULT.toString() : container; - - // Retrieve the Container Authorization service - IContainerAuthorization auth = (IContainerAuthorization) ServiceHelper - .getGlobalInstance(IContainerAuthorization.class, bundle); - if (auth != null) { - return auth.getResourcePrivilege(userName, resource); - } - - /* - * Container Authorization service not available. We can only derive the - * access privilege to the default container based on user level - */ - if (resource.equals(GlobalConstants.DEFAULT.toString())) { - IUserManager userManager = (IUserManager) ServiceHelper - .getGlobalInstance(IUserManager.class, bundle); - if (userManager != null) { - switch (userManager.getUserLevel(userName)) { - case NETWORKADMIN: - return Privilege.WRITE; - case NETWORKOPERATOR: - return Privilege.READ; - default: - return Privilege.NONE; - } - } - } - - return Privilege.NONE; - } - - public static void auditlog(String moduleName, String user, String action, String resource, - String containerName) { - String auditMsg = ""; - String mode = "UI"; - if (containerName != null) { - auditMsg = "Mode: " + mode + " User " + user + " " + action + " " + moduleName + " " + resource + " in container " - + containerName; - } else { - auditMsg = "Mode: " + mode + " User " + user + " " + action + " " + moduleName + " " + resource; - } - logger.trace(auditMsg); - } - - public static void auditlog(String moduleName, String user, String action, String resource) { - auditlog(moduleName, user, action, resource, null); - } - - public static String getNodeDesc(Node node, ISwitchManager switchManager) { - Description desc = (Description) switchManager.getNodeProp(node, - Description.propertyName); - String description = (desc == null) ? "" : desc.getValue(); - return (description.isEmpty() || description.equalsIgnoreCase("none")) ? node - .toString() : description; - } - - public static String getNodeDesc(Node node, String containerName, - Object bundle) { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, containerName, bundle); - if (switchManager == null) { - return null; - } - - return getNodeDesc(node, switchManager); - } - - public static String getNodeDesc(Node node, Object bundle) { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, - GlobalConstants.DEFAULT.toString(), bundle); - if (switchManager == null) { - return null; - } - - return getNodeDesc(node, switchManager); - } - - public static String getPortName(NodeConnector nodeConnector, - String container, Object bundle) { - ISwitchManager switchManager = (ISwitchManager) ServiceHelper - .getInstance(ISwitchManager.class, container, bundle); - return getPortName(nodeConnector, switchManager); - } - - public static String getPortName(NodeConnector nodeConnector, Object bundle) { - return getPortName(nodeConnector, GlobalConstants.DEFAULT.toString(), bundle); - } - - public static String getPortName(NodeConnector nodeConnector, - ISwitchManager switchManager) { - Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector, - Name.NamePropName)); - String nodeConnectorName = (ncName != null) ? ncName.getValue() : nodeConnector.getNodeConnectorIdAsString(); - nodeConnectorName = nodeConnectorName + "@" - + getNodeDesc(nodeConnector.getNode(), switchManager); - return nodeConnectorName.substring(0, nodeConnectorName.length()); - } -} diff --git a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/IDaylightWeb.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/IDaylightWeb.java deleted file mode 100644 index 7421759d98..0000000000 --- a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/IDaylightWeb.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.controller.web; - -import org.opendaylight.controller.sal.authorization.UserLevel; - -public interface IDaylightWeb { - /** - * Returns the name of the bundle. In the GUI, this name will be displayed - * on the tab. - * - * @return Name assigned to the bundle. - */ - public String getWebName(); - - /** - * Returns the Id assigned to the web bundle. - * - * @return Id assigned to the web bundle. - */ - public String getWebId(); - - /** - * Returns the position where the bundle tab will be placed in the GUI. - * - * @return Position number for the bundle tab. - */ - public short getWebOrder(); - - /** - * This method checks if the user is authorized to access the bundle. - * - * @param userLevel - * user role level in the controller space. - * - * @return true, if user is authorized to access the bundle, else false. - */ - public boolean isAuthorized(UserLevel userLevel); -} diff --git a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/NodeBean.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/NodeBean.java deleted file mode 100644 index 6ef1efc407..0000000000 --- a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/NodeBean.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.web; - -import org.opendaylight.controller.sal.core.Node; - -/** - * Information about a node connected to a controller to send to the UI frontend - * @author andrekim - */ -public class NodeBean { - private final String node; - private final String description; - - public NodeBean(Node node) { - this(node, node.toString()); - } - - public NodeBean(Node node, String description) { - this.node = node.toString(); - this.description = description; - } -} diff --git a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/UserBean.java b/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/UserBean.java deleted file mode 100644 index b4e4cd694f..0000000000 --- a/opendaylight/adsal/web/root/src/main/java/org/opendaylight/controller/web/UserBean.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.controller.web; - -import java.util.List; - -import org.opendaylight.controller.usermanager.UserConfig; - -public class UserBean { - private String user; - private List roles; - - public UserBean(String user, List roles) { - this.user = user; - this.roles = roles; - } - - public UserBean(UserConfig config) { - this(config.getUser(), config.getRoles()); - } - - public String getUser() { - return user; - } - - public List getRoles() { - return roles; - } -} diff --git a/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.factories b/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 93db02ec92..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1 +0,0 @@ -org.springframework.beans.BeanInfoFactory=org.springframework.beans.ExtendedBeanInfoFactory diff --git a/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.handlers b/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index 957af910d8..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1,10 +0,0 @@ -http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler -http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler -http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler -http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler -http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler -http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler -http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler -http\://www.springframework.org/schema/util=org.springframework.beans.factory.xml.UtilNamespaceHandler -http\://www.springframework.org/schema/mvc=org.springframework.web.servlet.config.MvcNamespaceHandler -http\://www.springframework.org/schema/security=org.springframework.security.config.SecurityNamespaceHandler diff --git a/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.schemas b/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index d865edcfd2..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,49 +0,0 @@ -http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd -http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd -http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd -http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd -http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd -http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd -http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd -http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd -http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd -http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd -http\://www.springframework.org/schema/security/spring-security-3.1.xsd=org/springframework/security/config/spring-security-3.1.xsd -http\://www.springframework.org/schema/security/spring-security-3.2.xsd=org/springframework/security/config/spring-security-3.2.xsd - diff --git a/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.tooling b/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.tooling deleted file mode 100644 index 057d834289..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/META-INF/spring.tooling +++ /dev/null @@ -1,39 +0,0 @@ -# Tooling related information for the beans namespace -http\://www.springframework.org/schema/beans@name=beans Namespace -http\://www.springframework.org/schema/beans@prefix=beans -http\://www.springframework.org/schema/beans@icon=org/springframework/beans/factory/xml/spring-beans.gif - -# Tooling related information for the util namespace -http\://www.springframework.org/schema/util@name=util Namespace -http\://www.springframework.org/schema/util@prefix=util -http\://www.springframework.org/schema/util@icon=org/springframework/beans/factory/xml/spring-util.gif - -# Tooling related information for the context namespace -http\://www.springframework.org/schema/context@name=context Namespace -http\://www.springframework.org/schema/context@prefix=context -http\://www.springframework.org/schema/context@icon=org/springframework/context/config/spring-context.gif - -# Tooling related information for the jee namespace -http\://www.springframework.org/schema/jee@name=jee Namespace -http\://www.springframework.org/schema/jee@prefix=jee -http\://www.springframework.org/schema/jee@icon=org/springframework/ejb/config/spring-jee.gif - -# Tooling related information for the scheduling namespace -http\://www.springframework.org/schema/task@name=task Namespace -http\://www.springframework.org/schema/task@prefix=task -http\://www.springframework.org/schema/task@icon=org/springframework/scheduling/config/spring-task.gif - -# Tooling related information for the lang namespace -http\://www.springframework.org/schema/lang@name=lang Namespace -http\://www.springframework.org/schema/lang@prefix=lang -http\://www.springframework.org/schema/lang@icon=org/springframework/scripting/config/spring-lang.gif - -# Tooling related information for the cache namespace -http\://www.springframework.org/schema/cache@name=cache Namespace -http\://www.springframework.org/schema/cache@prefix=cache -http\://www.springframework.org/schema/cache@icon=org/springframework/cache/config/spring-cache.gif - -# Tooling related information for the mvc namespace -http\://www.springframework.org/schema/mvc@name=mvc Namespace -http\://www.springframework.org/schema/mvc@prefix=mvc -http\://www.springframework.org/schema/mvc@icon=org/springframework/web/servlet/config/spring-mvc.gif diff --git a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/RootGUI-servlet.xml b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/RootGUI-servlet.xml deleted file mode 100644 index a8cb864367..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/RootGUI-servlet.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/autherror.jsp b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/autherror.jsp deleted file mode 100644 index a2fa4287a5..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/autherror.jsp +++ /dev/null @@ -1,55 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@ page import="java.net.URL" %> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - - - - - - - - - - - - -<% - String filePath = "/WEB-INF/jsp/customerror.jsp"; - URL fileURL = pageContext.getServletContext().getResource(filePath); - if(fileURL!=null) { -%> - -<% } %> - ${title} - - - - - - - - -
- -
-
- -
-
-
- <% if (session != null) session.invalidate(); %> - - diff --git a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/error.jsp b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/error.jsp deleted file mode 100644 index d288969c0a..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/error.jsp +++ /dev/null @@ -1,54 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@ page import="java.net.URL" %> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - - - - - - - - - - - - -<% - String filePath = "/WEB-INF/jsp/customerror.jsp"; - URL fileURL = pageContext.getServletContext().getResource(filePath); - if(fileURL!=null) { -%> - -<% } %> - ${title} - - - - - - - - -
- -
-
- -
-
-
- - diff --git a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/login.jsp b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/login.jsp deleted file mode 100644 index e2d1dd37e0..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/login.jsp +++ /dev/null @@ -1,57 +0,0 @@ -<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> -<%@ page import="java.net.URL" %> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> - - - - - - - - - - - - - -<% - String filePath = "/WEB-INF/jsp/customlogin.jsp"; - URL fileURL = pageContext.getServletContext().getResource(filePath); - if(fileURL!=null) { -%> - -<% } %> - ${title} - - - - - - - - -
- -
-
- -
-
-
- - diff --git a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/main.jsp b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/main.jsp deleted file mode 100644 index 5dfbc46a2c..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/jsp/main.jsp +++ /dev/null @@ -1,198 +0,0 @@ -<%-- - - Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - - - - This program and the accompanying materials are made available under the - - terms of the Eclipse Public License v1.0 which accompanies this distribution, - - and is available at http://www.eclipse.org/legal/epl-v10.html ---%> -<%@ page import="java.net.URL"%> -<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> - - - - - - - - - - - - - - - - - - -<% - String filePath = "/WEB-INF/jsp/custommain.jsp"; - URL fileURL = pageContext.getServletContext().getResource(filePath); - if (fileURL != null) { -%> - -<% - } -%> - -${name} - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - -
- - -
- -
- -
-
- -
- - - -
- -
- -
-
- -
- - -
- - - - - - -
- - - - - - - - - <% - String jsPath = "/WEB-INF/jsp/customjs.jsp"; - URL jsURL = pageContext.getServletContext().getResource(jsPath); - if (jsURL != null) { - %> - - <% - } else { - %> - - - - - - <% - } - %> - - - - diff --git a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/spring/servlet/security.xml b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/spring/servlet/security.xml deleted file mode 100644 index a649b082e4..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/spring/servlet/security.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/web.xml b/opendaylight/adsal/web/root/src/main/resources/WEB-INF/web.xml deleted file mode 100644 index 062766d1ab..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/WEB-INF/web.xml +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - CorsFilter - org.apache.catalina.filters.CorsFilter - - cors.allowed.origins - * - - - cors.allowed.methods - GET,POST,HEAD,OPTIONS,PUT,DELETE - - - cors.allowed.headers - Content-Type,X-Requested-With,accept,authorization, origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers - - - cors.exposed.headers - Access-Control-Allow-Origin,Access-Control-Allow-Credentials - - - cors.support.credentials - true - - - cors.preflight.maxage - 10 - - - - CorsFilter - /* - - - - - free access - /js/* - /img/* - /css/* - /favicon.ico - /versionProperty/* - - - - - RootApp - - RootGUI - /* - POST - GET - PUT - DELETE - HEAD - - - System-Admin - Network-Admin - Network-Operator - Container-User - - - - - System-Admin - - - Network-Admin - - - Network-Operator - - - Container-User - - - - - FORM - - /WEB-INF/jsp/login.jsp - /WEB-INF/jsp/error.jsp - - - - - 403 - /WEB-INF/jsp/autherror.jsp - - - - RootGUI - org.springframework.web.servlet.DispatcherServlet - 1 - - - - RootGUI - / - - - OpenDaylight Controller - OpenDaylight Controller - - - org.opendaylight.controller.web.ControllerUISessionManager - - - - - / - - - - diff --git a/opendaylight/adsal/web/root/src/main/resources/css/bootstrap.min.css b/opendaylight/adsal/web/root/src/main/resources/css/bootstrap.min.css deleted file mode 100644 index fd5ed73407..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/css/bootstrap.min.css +++ /dev/null @@ -1,9 +0,0 @@ -/*! - * Bootstrap v2.3.0 - * - * Copyright 2012 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world @twitter by @mdo and @fat. - */.clearfix{*zoom:1}.clearfix:before,.clearfix:after{display:table;line-height:0;content:""}.clearfix:after{clear:both}.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio,canvas,video{display:inline-block;*display:inline;*zoom:1}audio:not([controls]){display:none}html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}a:hover,a:active{outline:0}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-0.5em}sub{bottom:-0.25em}img{width:auto\9;height:auto;max-width:100%;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic}#map_canvas img,.google-maps img{max-width:none}button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle}button,input{*overflow:visible;line-height:normal}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}button,html input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button}label,select,button,input[type="button"],input[type="reset"],input[type="submit"],input[type="radio"],input[type="checkbox"]{cursor:pointer}input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}textarea{overflow:auto;vertical-align:top}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}@page{margin:.5cm}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}}body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;color:#333;background-color:#fff}a{color:#08c;text-decoration:none}a:hover,a:focus{color:#005580;text-decoration:underline}.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.1);box-shadow:0 1px 3px rgba(0,0,0,0.1)}.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px}.row{margin-left:-20px;*zoom:1}.row:before,.row:after{display:table;line-height:0;content:""}.row:after{clear:both}[class*="span"]{float:left;min-height:1px;margin-left:20px}.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.span12{width:940px}.span11{width:860px}.span10{width:780px}.span9{width:700px}.span8{width:620px}.span7{width:540px}.span6{width:460px}.span5{width:380px}.span4{width:300px}.span3{width:220px}.span2{width:140px}.span1{width:60px}.offset12{margin-left:980px}.offset11{margin-left:900px}.offset10{margin-left:820px}.offset9{margin-left:740px}.offset8{margin-left:660px}.offset7{margin-left:580px}.offset6{margin-left:500px}.offset5{margin-left:420px}.offset4{margin-left:340px}.offset3{margin-left:260px}.offset2{margin-left:180px}.offset1{margin-left:100px}.row-fluid{width:100%;*zoom:1}.row-fluid:before,.row-fluid:after{display:table;line-height:0;content:""}.row-fluid:after{clear:both}.row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.row-fluid [class*="span"]:first-child{margin-left:0}.row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.127659574468085%}.row-fluid .span12{width:100%;*width:99.94680851063829%}.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%}.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%}.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%}.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%}.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%}.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%}.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%}.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%}.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%}.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%}.row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%}.row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%}.row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%}.row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%}.row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%}.row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%}.row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%}.row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%}.row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%}.row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%}.row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%}.row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%}.row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%}.row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%}.row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%}.row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%}.row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%}.row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%}.row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%}.row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%}.row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%}.row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%}.row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%}.row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%}.row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%}[class*="span"].hide,.row-fluid [class*="span"].hide{display:none}[class*="span"].pull-right,.row-fluid [class*="span"].pull-right{float:right}.container{margin-right:auto;margin-left:auto;*zoom:1}.container:before,.container:after{display:table;line-height:0;content:""}.container:after{clear:both}.container-fluid{padding-right:20px;padding-left:20px;*zoom:1}.container-fluid:before,.container-fluid:after{display:table;line-height:0;content:""}.container-fluid:after{clear:both}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px}small{font-size:85%}strong{font-weight:bold}em{font-style:italic}cite{font-style:normal}.muted{color:#999}a.muted:hover,a.muted:focus{color:#808080}.text-warning{color:#c09853}a.text-warning:hover,a.text-warning:focus{color:#a47e3c}.text-error{color:#b94a48}a.text-error:hover,a.text-error:focus{color:#953b39}.text-info{color:#3a87ad}a.text-info:hover,a.text-info:focus{color:#2d6987}.text-success{color:#468847}a.text-success:hover,a.text-success:focus{color:#356635}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}h1,h2,h3,h4,h5,h6{margin:10px 0;font-family:inherit;font-weight:bold;line-height:20px;color:inherit;text-rendering:optimizelegibility}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-weight:normal;line-height:1;color:#999}h1,h2,h3{line-height:40px}h1{font-size:38.5px}h2{font-size:31.5px}h3{font-size:24.5px}h4{font-size:17.5px}h5{font-size:14px}h6{font-size:11.9px}h1 small{font-size:24.5px}h2 small{font-size:17.5px}h3 small{font-size:14px}h4 small{font-size:14px}.page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eee}ul,ol{padding:0;margin:0 0 10px 25px}ul ul,ul ol,ol ol,ol ul{margin-bottom:0}li{line-height:20px}ul.unstyled,ol.unstyled{margin-left:0;list-style:none}ul.inline,ol.inline{margin-left:0;list-style:none}ul.inline>li,ol.inline>li{display:inline-block;*display:inline;padding-right:5px;padding-left:5px;*zoom:1}dl{margin-bottom:20px}dt,dd{line-height:20px}dt{font-weight:bold}dd{margin-left:10px}.dl-horizontal{*zoom:1}.dl-horizontal:before,.dl-horizontal:after{display:table;line-height:0;content:""}.dl-horizontal:after{clear:both}.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}hr{margin:20px 0;border:0;border-top:1px solid #eee;border-bottom:1px solid #fff}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}abbr.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:0 0 0 15px;margin:0 0 20px;border-left:5px solid #eee}blockquote p{margin-bottom:0;font-size:17.5px;font-weight:300;line-height:1.25}blockquote small{display:block;line-height:20px;color:#999}blockquote small:before{content:'\2014 \00A0'}blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}blockquote.pull-right p,blockquote.pull-right small{text-align:right}blockquote.pull-right small:before{content:''}blockquote.pull-right small:after{content:'\00A0 \2014'}q:before,q:after,blockquote:before,blockquote:after{content:""}address{display:block;margin-bottom:20px;font-style:normal;line-height:20px}code,pre{padding:0 3px 2px;font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;color:#333;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}code{padding:2px 4px;color:#d14;white-space:nowrap;background-color:#f7f7f9;border:1px solid #e1e1e8}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}pre.prettyprint{margin-bottom:20px}pre code{padding:0;color:inherit;white-space:pre;white-space:pre-wrap;background-color:transparent;border:0}.pre-scrollable{max-height:340px;overflow-y:scroll}form{margin:0 0 20px}fieldset{padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5}legend small{font-size:15px;color:#999}label,input,button,select,textarea{font-size:14px;font-weight:normal;line-height:20px}input,button,select,textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif}label{display:block;margin-bottom:5px}select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:10px;font-size:14px;line-height:20px;color:#555;vertical-align:middle;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}input,textarea,.uneditable-input{width:206px}textarea{height:auto}textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#fff;border:1px solid #ccc;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border linear .2s,box-shadow linear .2s;-moz-transition:border linear .2s,box-shadow linear .2s;-o-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82,168,236,0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}input[type="radio"],input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;*margin-top:0;line-height:normal}input[type="file"],input[type="image"],input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto}select,input[type="file"]{height:30px;*margin-top:4px;line-height:30px}select{width:220px;background-color:#fff;border:1px solid #ccc}select[multiple],select[size]{height:auto}select:focus,input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.uneditable-input,.uneditable-textarea{color:#999;cursor:not-allowed;background-color:#fcfcfc;border-color:#ccc;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);box-shadow:inset 0 1px 2px rgba(0,0,0,0.025)}.uneditable-input{overflow:hidden;white-space:nowrap}.uneditable-textarea{width:auto;height:auto}input:-moz-placeholder,textarea:-moz-placeholder{color:#999}input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#999}input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#999}.radio,.checkbox{min-height:20px;padding-left:20px}.radio input[type="radio"],.checkbox input[type="checkbox"]{float:left;margin-left:-20px}.controls>.radio:first-child,.controls>.checkbox:first-child{padding-top:5px}.radio.inline,.checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle}.radio.inline+.radio.inline,.checkbox.inline+.checkbox.inline{margin-left:10px}.input-mini{width:60px}.input-small{width:90px}.input-medium{width:150px}.input-large{width:210px}.input-xlarge{width:270px}.input-xxlarge{width:530px}input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0}.input-append input[class*="span"],.input-append .uneditable-input[class*="span"],.input-prepend input[class*="span"],.input-prepend .uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"],.row-fluid .input-prepend [class*="span"],.row-fluid .input-append [class*="span"]{display:inline-block}input,textarea,.uneditable-input{margin-left:0}.controls-row [class*="span"]+[class*="span"]{margin-left:20px}input.span12,textarea.span12,.uneditable-input.span12{width:926px}input.span11,textarea.span11,.uneditable-input.span11{width:846px}input.span10,textarea.span10,.uneditable-input.span10{width:766px}input.span9,textarea.span9,.uneditable-input.span9{width:686px}input.span8,textarea.span8,.uneditable-input.span8{width:606px}input.span7,textarea.span7,.uneditable-input.span7{width:526px}input.span6,textarea.span6,.uneditable-input.span6{width:446px}input.span5,textarea.span5,.uneditable-input.span5{width:366px}input.span4,textarea.span4,.uneditable-input.span4{width:286px}input.span3,textarea.span3,.uneditable-input.span3{width:206px}input.span2,textarea.span2,.uneditable-input.span2{width:126px}input.span1,textarea.span1,.uneditable-input.span1{width:46px}.controls-row{*zoom:1}.controls-row:before,.controls-row:after{display:table;line-height:0;content:""}.controls-row:after{clear:both}.controls-row [class*="span"],.row-fluid .controls-row [class*="span"]{float:left}.controls-row .checkbox[class*="span"],.controls-row .radio[class*="span"]{padding-top:5px}input[disabled],select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#eee}input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"][readonly],input[type="checkbox"][readonly]{background-color:transparent}.control-group.warning .control-label,.control-group.warning .help-block,.control-group.warning .help-inline{color:#c09853}.control-group.warning .checkbox,.control-group.warning .radio,.control-group.warning input,.control-group.warning select,.control-group.warning textarea{color:#c09853}.control-group.warning input,.control-group.warning select,.control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.warning input:focus,.control-group.warning select:focus,.control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.control-group.warning .input-prepend .add-on,.control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.control-group.error .control-label,.control-group.error .help-block,.control-group.error .help-inline{color:#b94a48}.control-group.error .checkbox,.control-group.error .radio,.control-group.error input,.control-group.error select,.control-group.error textarea{color:#b94a48}.control-group.error input,.control-group.error select,.control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.error input:focus,.control-group.error select:focus,.control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.control-group.error .input-prepend .add-on,.control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.control-group.success .control-label,.control-group.success .help-block,.control-group.success .help-inline{color:#468847}.control-group.success .checkbox,.control-group.success .radio,.control-group.success input,.control-group.success select,.control-group.success textarea{color:#468847}.control-group.success input,.control-group.success select,.control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.success input:focus,.control-group.success select:focus,.control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.control-group.success .input-prepend .add-on,.control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847}.control-group.info .control-label,.control-group.info .help-block,.control-group.info .help-inline{color:#3a87ad}.control-group.info .checkbox,.control-group.info .radio,.control-group.info input,.control-group.info select,.control-group.info textarea{color:#3a87ad}.control-group.info input,.control-group.info select,.control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.control-group.info input:focus,.control-group.info select:focus,.control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3}.control-group.info .input-prepend .add-on,.control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad}input:focus:invalid,textarea:focus:invalid,select:focus:invalid{color:#b94a48;border-color:#ee5f5b}input:focus:invalid:focus,textarea:focus:invalid:focus,select:focus:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7}.form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#f5f5f5;border-top:1px solid #e5e5e5;*zoom:1}.form-actions:before,.form-actions:after{display:table;line-height:0;content:""}.form-actions:after{clear:both}.help-block,.help-inline{color:#595959}.help-block{display:block;margin-bottom:10px}.help-inline{display:inline-block;*display:inline;padding-left:5px;vertical-align:middle;*zoom:1}.input-append,.input-prepend{display:inline-block;margin-bottom:10px;font-size:0;white-space:nowrap;vertical-align:middle}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input,.input-append .dropdown-menu,.input-prepend .dropdown-menu,.input-append .popover,.input-prepend .popover{font-size:14px}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;vertical-align:top;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append input:focus,.input-prepend input:focus,.input-append select:focus,.input-prepend select:focus,.input-append .uneditable-input:focus,.input-prepend .uneditable-input:focus{z-index:2}.input-append .add-on,.input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:14px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #fff;background-color:#eee;border:1px solid #ccc}.input-append .add-on,.input-prepend .add-on,.input-append .btn,.input-prepend .btn,.input-append .btn-group>.dropdown-toggle,.input-prepend .btn-group>.dropdown-toggle{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-append .active,.input-prepend .active{background-color:#a9dba9;border-color:#46a546}.input-prepend .add-on,.input-prepend .btn{margin-right:-1px}.input-prepend .add-on:first-child,.input-prepend .btn:first-child{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input,.input-append select,.input-append .uneditable-input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-append input+.btn-group .btn:last-child,.input-append select+.btn-group .btn:last-child,.input-append .uneditable-input+.btn-group .btn:last-child{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-append .add-on,.input-append .btn,.input-append .btn-group{margin-left:-1px}.input-append .add-on:last-child,.input-append .btn:last-child,.input-append .btn-group:last-child>.dropdown-toggle{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append input,.input-prepend.input-append select,.input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.input-prepend.input-append input+.btn-group .btn,.input-prepend.input-append select+.btn-group .btn,.input-prepend.input-append .uneditable-input+.btn-group .btn{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .add-on:first-child,.input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.input-prepend.input-append .add-on:last-child,.input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.input-prepend.input-append .btn-group:first-child{margin-left:0}input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.form-search .input-append .search-query,.form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.form-search input,.form-inline input,.form-horizontal input,.form-search textarea,.form-inline textarea,.form-horizontal textarea,.form-search select,.form-inline select,.form-horizontal select,.form-search .help-inline,.form-inline .help-inline,.form-horizontal .help-inline,.form-search .uneditable-input,.form-inline .uneditable-input,.form-horizontal .uneditable-input,.form-search .input-prepend,.form-inline .input-prepend,.form-horizontal .input-prepend,.form-search .input-append,.form-inline .input-append,.form-horizontal .input-append{display:inline-block;*display:inline;margin-bottom:0;vertical-align:middle;*zoom:1}.form-search .hide,.form-inline .hide,.form-horizontal .hide{display:none}.form-search label,.form-inline label,.form-search .btn-group,.form-inline .btn-group{display:inline-block}.form-search .input-append,.form-inline .input-append,.form-search .input-prepend,.form-inline .input-prepend{margin-bottom:0}.form-search .radio,.form-search .checkbox,.form-inline .radio,.form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle}.form-search .radio input[type="radio"],.form-search .checkbox input[type="checkbox"],.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0}.control-group{margin-bottom:10px}legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate}.form-horizontal .control-group{margin-bottom:20px;*zoom:1}.form-horizontal .control-group:before,.form-horizontal .control-group:after{display:table;line-height:0;content:""}.form-horizontal .control-group:after{clear:both}.form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right}.form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0}.form-horizontal .controls:first-child{*padding-left:180px}.form-horizontal .help-block{margin-bottom:0}.form-horizontal input+.help-block,.form-horizontal select+.help-block,.form-horizontal textarea+.help-block,.form-horizontal .uneditable-input+.help-block,.form-horizontal .input-prepend+.help-block,.form-horizontal .input-append+.help-block{margin-top:10px}.form-horizontal .form-actions{padding-left:180px}table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0}.table{width:100%;margin-bottom:20px}.table th,.table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #ddd}.table th{font-weight:bold}.table thead th{vertical-align:bottom}.table caption+thead tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child th,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child th,.table thead:first-child tr:first-child td{border-top:0}.table tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed th,.table-condensed td{padding:4px 5px}.table-bordered{border:1px solid #ddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.table-bordered th,.table-bordered td{border-left:1px solid #ddd}.table-bordered caption+thead tr:first-child th,.table-bordered caption+tbody tr:first-child th,.table-bordered caption+tbody tr:first-child td,.table-bordered colgroup+thead tr:first-child th,.table-bordered colgroup+tbody tr:first-child th,.table-bordered colgroup+tbody tr:first-child td,.table-bordered thead:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child td{border-top:0}.table-bordered thead:first-child tr:first-child>th:first-child,.table-bordered tbody:first-child tr:first-child>td:first-child,.table-bordered tbody:first-child tr:first-child>th:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered thead:first-child tr:first-child>th:last-child,.table-bordered tbody:first-child tr:first-child>td:last-child,.table-bordered tbody:first-child tr:first-child>th:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-bordered thead:last-child tr:last-child>th:first-child,.table-bordered tbody:last-child tr:last-child>td:first-child,.table-bordered tbody:last-child tr:last-child>th:first-child,.table-bordered tfoot:last-child tr:last-child>td:first-child,.table-bordered tfoot:last-child tr:last-child>th:first-child{-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px}.table-bordered thead:last-child tr:last-child>th:last-child,.table-bordered tbody:last-child tr:last-child>td:last-child,.table-bordered tbody:last-child tr:last-child>th:last-child,.table-bordered tfoot:last-child tr:last-child>td:last-child,.table-bordered tfoot:last-child tr:last-child>th:last-child{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px}.table-bordered tfoot+tbody:last-child tr:last-child td:first-child{-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-moz-border-radius-bottomleft:0}.table-bordered tfoot+tbody:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;-moz-border-radius-bottomright:0}.table-bordered caption+thead tr:first-child th:first-child,.table-bordered caption+tbody tr:first-child td:first-child,.table-bordered colgroup+thead tr:first-child th:first-child,.table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.table-bordered caption+thead tr:first-child th:last-child,.table-bordered caption+tbody tr:first-child td:last-child,.table-bordered colgroup+thead tr:first-child th:last-child,.table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.table-striped tbody>tr:nth-child(odd)>td,.table-striped tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover tbody tr:hover>td,.table-hover tbody tr:hover>th{background-color:#f5f5f5}table td[class*="span"],table th[class*="span"],.row-fluid table td[class*="span"],.row-fluid table th[class*="span"]{display:table-cell;float:none;margin-left:0}.table td.span1,.table th.span1{float:none;width:44px;margin-left:0}.table td.span2,.table th.span2{float:none;width:124px;margin-left:0}.table td.span3,.table th.span3{float:none;width:204px;margin-left:0}.table td.span4,.table th.span4{float:none;width:284px;margin-left:0}.table td.span5,.table th.span5{float:none;width:364px;margin-left:0}.table td.span6,.table th.span6{float:none;width:444px;margin-left:0}.table td.span7,.table th.span7{float:none;width:524px;margin-left:0}.table td.span8,.table th.span8{float:none;width:604px;margin-left:0}.table td.span9,.table th.span9{float:none;width:684px;margin-left:0}.table td.span10,.table th.span10{float:none;width:764px;margin-left:0}.table td.span11,.table th.span11{float:none;width:844px;margin-left:0}.table td.span12,.table th.span12{float:none;width:924px;margin-left:0}.table tbody tr.success>td{background-color:#dff0d8}.table tbody tr.error>td{background-color:#f2dede}.table tbody tr.warning>td{background-color:#fcf8e3}.table tbody tr.info>td{background-color:#d9edf7}.table-hover tbody tr.success:hover>td{background-color:#d0e9c6}.table-hover tbody tr.error:hover>td{background-color:#ebcccc}.table-hover tbody tr.warning:hover>td{background-color:#faf2cc}.table-hover tbody tr.info:hover>td{background-color:#c4e3f3}[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;margin-top:1px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat}.icon-white,.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:focus>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>li>a:focus>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"],.dropdown-submenu:hover>a>[class^="icon-"],.dropdown-submenu:focus>a>[class^="icon-"],.dropdown-submenu:hover>a>[class*=" icon-"],.dropdown-submenu:focus>a>[class*=" icon-"]{background-image:url("../img/glyphicons-halflings-white.png")}.icon-glass{background-position:0 0}.icon-music{background-position:-24px 0}.icon-search{background-position:-48px 0}.icon-envelope{background-position:-72px 0}.icon-heart{background-position:-96px 0}.icon-star{background-position:-120px 0}.icon-star-empty{background-position:-144px 0}.icon-user{background-position:-168px 0}.icon-film{background-position:-192px 0}.icon-th-large{background-position:-216px 0}.icon-th{background-position:-240px 0}.icon-th-list{background-position:-264px 0}.icon-ok{background-position:-288px 0}.icon-remove{background-position:-312px 0}.icon-zoom-in{background-position:-336px 0}.icon-zoom-out{background-position:-360px 0}.icon-off{background-position:-384px 0}.icon-signal{background-position:-408px 0}.icon-cog{background-position:-432px 0}.icon-trash{background-position:-456px 0}.icon-home{background-position:0 -24px}.icon-file{background-position:-24px -24px}.icon-time{background-position:-48px -24px}.icon-road{background-position:-72px -24px}.icon-download-alt{background-position:-96px -24px}.icon-download{background-position:-120px -24px}.icon-upload{background-position:-144px -24px}.icon-inbox{background-position:-168px -24px}.icon-play-circle{background-position:-192px -24px}.icon-repeat{background-position:-216px -24px}.icon-refresh{background-position:-240px -24px}.icon-list-alt{background-position:-264px -24px}.icon-lock{background-position:-287px -24px}.icon-flag{background-position:-312px -24px}.icon-headphones{background-position:-336px -24px}.icon-volume-off{background-position:-360px -24px}.icon-volume-down{background-position:-384px -24px}.icon-volume-up{background-position:-408px -24px}.icon-qrcode{background-position:-432px -24px}.icon-barcode{background-position:-456px -24px}.icon-tag{background-position:0 -48px}.icon-tags{background-position:-25px -48px}.icon-book{background-position:-48px -48px}.icon-bookmark{background-position:-72px -48px}.icon-print{background-position:-96px -48px}.icon-camera{background-position:-120px -48px}.icon-font{background-position:-144px -48px}.icon-bold{background-position:-167px -48px}.icon-italic{background-position:-192px -48px}.icon-text-height{background-position:-216px -48px}.icon-text-width{background-position:-240px -48px}.icon-align-left{background-position:-264px -48px}.icon-align-center{background-position:-288px -48px}.icon-align-right{background-position:-312px -48px}.icon-align-justify{background-position:-336px -48px}.icon-list{background-position:-360px -48px}.icon-indent-left{background-position:-384px -48px}.icon-indent-right{background-position:-408px -48px}.icon-facetime-video{background-position:-432px -48px}.icon-picture{background-position:-456px -48px}.icon-pencil{background-position:0 -72px}.icon-map-marker{background-position:-24px -72px}.icon-adjust{background-position:-48px -72px}.icon-tint{background-position:-72px -72px}.icon-edit{background-position:-96px -72px}.icon-share{background-position:-120px -72px}.icon-check{background-position:-144px -72px}.icon-move{background-position:-168px -72px}.icon-step-backward{background-position:-192px -72px}.icon-fast-backward{background-position:-216px -72px}.icon-backward{background-position:-240px -72px}.icon-play{background-position:-264px -72px}.icon-pause{background-position:-288px -72px}.icon-stop{background-position:-312px -72px}.icon-forward{background-position:-336px -72px}.icon-fast-forward{background-position:-360px -72px}.icon-step-forward{background-position:-384px -72px}.icon-eject{background-position:-408px -72px}.icon-chevron-left{background-position:-432px -72px}.icon-chevron-right{background-position:-456px -72px}.icon-plus-sign{background-position:0 -96px}.icon-minus-sign{background-position:-24px -96px}.icon-remove-sign{background-position:-48px -96px}.icon-ok-sign{background-position:-72px -96px}.icon-question-sign{background-position:-96px -96px}.icon-info-sign{background-position:-120px -96px}.icon-screenshot{background-position:-144px -96px}.icon-remove-circle{background-position:-168px -96px}.icon-ok-circle{background-position:-192px -96px}.icon-ban-circle{background-position:-216px -96px}.icon-arrow-left{background-position:-240px -96px}.icon-arrow-right{background-position:-264px -96px}.icon-arrow-up{background-position:-289px -96px}.icon-arrow-down{background-position:-312px -96px}.icon-share-alt{background-position:-336px -96px}.icon-resize-full{background-position:-360px -96px}.icon-resize-small{background-position:-384px -96px}.icon-plus{background-position:-408px -96px}.icon-minus{background-position:-433px -96px}.icon-asterisk{background-position:-456px -96px}.icon-exclamation-sign{background-position:0 -120px}.icon-gift{background-position:-24px -120px}.icon-leaf{background-position:-48px -120px}.icon-fire{background-position:-72px -120px}.icon-eye-open{background-position:-96px -120px}.icon-eye-close{background-position:-120px -120px}.icon-warning-sign{background-position:-144px -120px}.icon-plane{background-position:-168px -120px}.icon-calendar{background-position:-192px -120px}.icon-random{width:16px;background-position:-216px -120px}.icon-comment{background-position:-240px -120px}.icon-magnet{background-position:-264px -120px}.icon-chevron-up{background-position:-288px -120px}.icon-chevron-down{background-position:-313px -119px}.icon-retweet{background-position:-336px -120px}.icon-shopping-cart{background-position:-360px -120px}.icon-folder-close{width:16px;background-position:-384px -120px}.icon-folder-open{width:16px;background-position:-408px -120px}.icon-resize-vertical{background-position:-432px -119px}.icon-resize-horizontal{background-position:-456px -118px}.icon-hdd{background-position:0 -144px}.icon-bullhorn{background-position:-24px -144px}.icon-bell{background-position:-48px -144px}.icon-certificate{background-position:-72px -144px}.icon-thumbs-up{background-position:-96px -144px}.icon-thumbs-down{background-position:-120px -144px}.icon-hand-right{background-position:-144px -144px}.icon-hand-left{background-position:-168px -144px}.icon-hand-up{background-position:-192px -144px}.icon-hand-down{background-position:-216px -144px}.icon-circle-arrow-right{background-position:-240px -144px}.icon-circle-arrow-left{background-position:-264px -144px}.icon-circle-arrow-up{background-position:-288px -144px}.icon-circle-arrow-down{background-position:-312px -144px}.icon-globe{background-position:-336px -144px}.icon-wrench{background-position:-360px -144px}.icon-tasks{background-position:-384px -144px}.icon-filter{background-position:-408px -144px}.icon-briefcase{background-position:-432px -144px}.icon-fullscreen{background-position:-456px -144px}.dropup,.dropdown{position:relative}.dropdown-toggle{*margin-bottom:-3px}.dropdown-toggle:active,.open .dropdown-toggle{outline:0}.caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.dropdown .caret{margin-top:8px;margin-left:2px}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus,.dropdown-submenu:hover>a,.dropdown-submenu:focus>a{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;outline:0;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#999}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open{*z-index:1000}.open>.dropdown-menu{display:block}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.dropdown-submenu{position:relative}.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px}.dropdown-submenu:hover>.dropdown-menu{display:block}.dropup .dropdown-submenu>.dropdown-menu{top:auto;bottom:0;margin-top:0;margin-bottom:-2px;-webkit-border-radius:5px 5px 5px 0;-moz-border-radius:5px 5px 5px 0;border-radius:5px 5px 5px 0}.dropdown-submenu>a:after{display:block;float:right;width:0;height:0;margin-top:5px;margin-right:-10px;border-color:transparent;border-left-color:#ccc;border-style:solid;border-width:5px 0 5px 5px;content:" "}.dropdown-submenu:hover>a:after{border-left-color:#fff}.dropdown-submenu.pull-left{float:none}.dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.dropdown .dropdown-menu .nav-header{padding-right:20px;padding-left:20px}.typeahead{z-index:1051;margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fade{opacity:0;-webkit-transition:opacity .15s linear;-moz-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;-moz-transition:height .35s ease;-o-transition:height .35s ease;transition:height .35s ease}.collapse.in{height:auto}.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.4;filter:alpha(opacity=40)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.btn{display:inline-block;*display:inline;padding:4px 12px;margin-bottom:0;*margin-left:.3em;font-size:14px;line-height:20px;color:#333;text-align:center;text-shadow:0 1px 1px rgba(255,255,255,0.75);vertical-align:middle;cursor:pointer;background-color:#f5f5f5;*background-color:#e6e6e6;background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-repeat:repeat-x;border:1px solid #ccc;*border:0;border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);*zoom:1;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn:hover,.btn:focus,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.btn:active,.btn.active{background-color:#ccc \9}.btn:first-child{*margin-left:0}.btn:hover,.btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.active,.btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn.disabled,.btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.btn-large [class^="icon-"],.btn-large [class*=" icon-"]{margin-top:4px}.btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-small [class^="icon-"],.btn-small [class*=" icon-"]{margin-top:0}.btn-mini [class^="icon-"],.btn-mini [class*=" icon-"]{margin-top:-1px}.btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.btn-block{display:block;width:100%;padding-right:0;padding-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.btn-block+.btn-block{margin-top:5px}input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%}.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255,255,255,0.75)}.btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;*background-color:#04c;background-image:-moz-linear-gradient(top,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.btn-primary:active,.btn-primary.active{background-color:#039 \9}.btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;*background-color:#f89406;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.btn-warning:active,.btn-warning.active{background-color:#c67605 \9}.btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;*background-color:#bd362f;background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-repeat:repeat-x;border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.btn-danger:active,.btn-danger.active{background-color:#942a25 \9}.btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;*background-color:#51a351;background-image:-moz-linear-gradient(top,#62c462,#51a351);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-repeat:repeat-x;border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.btn-success:active,.btn-success.active{background-color:#408140 \9}.btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;*background-color:#2f96b4;background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-repeat:repeat-x;border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.btn-info:active,.btn-info.active{background-color:#24748c \9}.btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;*background-color:#222;background-image:-moz-linear-gradient(top,#444,#222);background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-repeat:repeat-x;border-color:#222 #222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.btn-inverse:hover,.btn-inverse:focus,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9}button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.btn-link{color:#08c;cursor:pointer;border-color:transparent;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-link:hover,.btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,.btn-link[disabled]:focus{color:#333;text-decoration:none}.btn-group{position:relative;display:inline-block;*display:inline;*margin-left:.3em;font-size:0;white-space:nowrap;vertical-align:middle;*zoom:1}.btn-group:first-child{*margin-left:0}.btn-group+.btn-group{margin-left:5px}.btn-toolbar{margin-top:10px;margin-bottom:10px;font-size:0}.btn-toolbar>.btn+.btn,.btn-toolbar>.btn-group+.btn,.btn-toolbar>.btn+.btn-group{margin-left:5px}.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group>.btn+.btn{margin-left:-1px}.btn-group>.btn,.btn-group>.dropdown-menu,.btn-group>.popover{font-size:14px}.btn-group>.btn-mini{font-size:10.5px}.btn-group>.btn-small{font-size:11.9px}.btn-group>.btn-large{font-size:17.5px}.btn-group>.btn:first-child{margin-left:0;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{*padding-top:5px;padding-right:8px;*padding-bottom:5px;padding-left:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.btn-group>.btn-mini+.dropdown-toggle{*padding-top:2px;padding-right:5px;*padding-bottom:2px;padding-left:5px}.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px}.btn-group>.btn-large+.dropdown-toggle{*padding-top:7px;padding-right:12px;*padding-bottom:7px;padding-left:12px}.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6}.btn-group.open .btn-primary.dropdown-toggle{background-color:#04c}.btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406}.btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f}.btn-group.open .btn-success.dropdown-toggle{background-color:#51a351}.btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4}.btn-group.open .btn-inverse.dropdown-toggle{background-color:#222}.btn .caret{margin-top:8px;margin-left:0}.btn-large .caret{margin-top:6px}.btn-large .caret{border-top-width:5px;border-right-width:5px;border-left-width:5px}.btn-mini .caret,.btn-small .caret{margin-top:8px}.dropup .btn-large .caret{border-bottom-width:5px}.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#fff;border-bottom-color:#fff}.btn-group-vertical{display:inline-block;*display:inline;*zoom:1}.btn-group-vertical>.btn{display:block;float:none;max-width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.btn-group-vertical>.btn+.btn{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.btn-group-vertical>.btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.btn-group-vertical>.btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0}.btn-group-vertical>.btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255,255,255,0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.alert,.alert h4{color:#c09853}.alert h4{margin:0}.alert .close{position:relative;top:-2px;right:-21px;line-height:20px}.alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.alert-success h4{color:#468847}.alert-danger,.alert-error{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.alert-danger h4,.alert-error h4{color:#b94a48}.alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.alert-info h4{color:#3a87ad}.alert-block{padding-top:14px;padding-bottom:14px}.alert-block>p,.alert-block>ul{margin-bottom:0}.alert-block p+p{margin-top:5px}.nav{margin-bottom:20px;margin-left:0;list-style:none}.nav>li>a{display:block}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li>a>img{max-width:none}.nav>.pull-right{float:right}.nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#999;text-shadow:0 1px 0 rgba(255,255,255,0.5);text-transform:uppercase}.nav li+.nav-header{margin-top:9px}.nav-list{padding-right:15px;padding-left:15px;margin-bottom:0}.nav-list>li>a,.nav-list .nav-header{margin-right:-15px;margin-left:-15px;text-shadow:0 1px 0 rgba(255,255,255,0.5)}.nav-list>li>a{padding:3px 15px}.nav-list>.active>a,.nav-list>.active>a:hover,.nav-list>.active>a:focus{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.2);background-color:#08c}.nav-list [class^="icon-"],.nav-list [class*=" icon-"]{margin-right:2px}.nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.nav-tabs,.nav-pills{*zoom:1}.nav-tabs:before,.nav-pills:before,.nav-tabs:after,.nav-pills:after{display:table;line-height:0;content:""}.nav-tabs:after,.nav-pills:after{clear:both}.nav-tabs>li,.nav-pills>li{float:left}.nav-tabs>li>a,.nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{margin-bottom:-1px}.nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover,.nav-tabs>li>a:focus{border-color:#eee #eee #ddd}.nav-tabs>.active>a,.nav-tabs>.active>a:hover,.nav-tabs>.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.nav-pills>.active>a,.nav-pills>.active>a:hover,.nav-pills>.active>a:focus{color:#fff;background-color:#08c}.nav-stacked>li{float:none}.nav-stacked>li>a{margin-right:0}.nav-tabs.nav-stacked{border-bottom:0}.nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-topleft:4px}.nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomright:4px;-moz-border-radius-bottomleft:4px}.nav-tabs.nav-stacked>li>a:hover,.nav-tabs.nav-stacked>li>a:focus{z-index:2;border-color:#ddd}.nav-pills.nav-stacked>li>a{margin-bottom:3px}.nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px}.nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.nav .dropdown-toggle .caret{margin-top:6px;border-top-color:#08c;border-bottom-color:#08c}.nav .dropdown-toggle:hover .caret,.nav .dropdown-toggle:focus .caret{border-top-color:#005580;border-bottom-color:#005580}.nav-tabs .dropdown-toggle .caret{margin-top:8px}.nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.nav-tabs .active .dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.nav>.dropdown.active>a:hover,.nav>.dropdown.active>a:focus{cursor:pointer}.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover,.nav>li.dropdown.open.active>a:focus{color:#fff;background-color:#999;border-color:#999}.nav li.dropdown.open .caret,.nav li.dropdown.open.active .caret,.nav li.dropdown.open a:hover .caret,.nav li.dropdown.open a:focus .caret{border-top-color:#fff;border-bottom-color:#fff;opacity:1;filter:alpha(opacity=100)}.tabs-stacked .open>a:hover,.tabs-stacked .open>a:focus{border-color:#999}.tabbable{*zoom:1}.tabbable:before,.tabbable:after{display:table;line-height:0;content:""}.tabbable:after{clear:both}.tab-content{overflow:auto}.tabs-below>.nav-tabs,.tabs-right>.nav-tabs,.tabs-left>.nav-tabs{border-bottom:0}.tab-content>.tab-pane,.pill-content>.pill-pane{display:none}.tab-content>.active,.pill-content>.active{display:block}.tabs-below>.nav-tabs{border-top:1px solid #ddd}.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0}.tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.tabs-below>.nav-tabs>li>a:hover,.tabs-below>.nav-tabs>li>a:focus{border-top-color:#ddd;border-bottom-color:transparent}.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:hover,.tabs-below>.nav-tabs>.active>a:focus{border-color:transparent #ddd #ddd #ddd}.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none}.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px}.tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd}.tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.tabs-left>.nav-tabs>li>a:hover,.tabs-left>.nav-tabs>li>a:focus{border-color:#eee #ddd #eee #eee}.tabs-left>.nav-tabs .active>a,.tabs-left>.nav-tabs .active>a:hover,.tabs-left>.nav-tabs .active>a:focus{border-color:#ddd transparent #ddd #ddd;*border-right-color:#fff}.tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd}.tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.tabs-right>.nav-tabs>li>a:hover,.tabs-right>.nav-tabs>li>a:focus{border-color:#eee #eee #eee #ddd}.tabs-right>.nav-tabs .active>a,.tabs-right>.nav-tabs .active>a:hover,.tabs-right>.nav-tabs .active>a:focus{border-color:#ddd #ddd #ddd transparent;*border-left-color:#fff}.nav>.disabled>a{color:#999}.nav>.disabled>a:hover,.nav>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent}.navbar{*position:relative;*z-index:2;margin-bottom:20px;overflow:visible}.navbar-inner{min-height:40px;padding-right:20px;padding-left:20px;background-color:#fafafa;background-image:-moz-linear-gradient(top,#fff,#f2f2f2);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#f2f2f2));background-image:-webkit-linear-gradient(top,#fff,#f2f2f2);background-image:-o-linear-gradient(top,#fff,#f2f2f2);background-image:linear-gradient(to bottom,#fff,#f2f2f2);background-repeat:repeat-x;border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff',endColorstr='#fff2f2f2',GradientType=0);*zoom:1;-webkit-box-shadow:0 1px 4px rgba(0,0,0,0.065);-moz-box-shadow:0 1px 4px rgba(0,0,0,0.065);box-shadow:0 1px 4px rgba(0,0,0,0.065)}.navbar-inner:before,.navbar-inner:after{display:table;line-height:0;content:""}.navbar-inner:after{clear:both}.navbar .container{width:auto}.nav-collapse.collapse{height:auto;overflow:visible}.navbar .brand{display:block;float:left;padding:10px 20px 10px;margin-left:-20px;font-size:20px;font-weight:200;color:#777;text-shadow:0 1px 0 #fff}.navbar .brand:hover,.navbar .brand:focus{text-decoration:none}.navbar-text{margin-bottom:0;line-height:40px;color:#777}.navbar-link{color:#777}.navbar-link:hover,.navbar-link:focus{color:#333}.navbar .divider-vertical{height:40px;margin:0 9px;border-right:1px solid #fff;border-left:1px solid #f2f2f2}.navbar .btn,.navbar .btn-group{margin-top:5px}.navbar .btn-group .btn,.navbar .input-prepend .btn,.navbar .input-append .btn,.navbar .input-prepend .btn-group,.navbar .input-append .btn-group{margin-top:0}.navbar-form{margin-bottom:0;*zoom:1}.navbar-form:before,.navbar-form:after{display:table;line-height:0;content:""}.navbar-form:after{clear:both}.navbar-form input,.navbar-form select,.navbar-form .radio,.navbar-form .checkbox{margin-top:5px}.navbar-form input,.navbar-form select,.navbar-form .btn{display:inline-block;margin-bottom:0}.navbar-form input[type="image"],.navbar-form input[type="checkbox"],.navbar-form input[type="radio"]{margin-top:3px}.navbar-form .input-append,.navbar-form .input-prepend{margin-top:5px;white-space:nowrap}.navbar-form .input-append input,.navbar-form .input-prepend input{margin-top:0}.navbar-search{position:relative;float:left;margin-top:5px;margin-bottom:0}.navbar-search .search-query{padding:4px 14px;margin-bottom:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.navbar-static-top{position:static;margin-bottom:0}.navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{border-width:0 0 1px}.navbar-fixed-bottom .navbar-inner{border-width:1px 0 0}.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding-right:0;padding-left:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px}.navbar-fixed-top{top:0}.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{-webkit-box-shadow:0 1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 10px rgba(0,0,0,0.1);box-shadow:0 1px 10px rgba(0,0,0,0.1)}.navbar-fixed-bottom{bottom:0}.navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:0 -1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 -1px 10px rgba(0,0,0,0.1);box-shadow:0 -1px 10px rgba(0,0,0,0.1)}.navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0}.navbar .nav.pull-right{float:right;margin-right:0}.navbar .nav>li{float:left}.navbar .nav>li>a{float:none;padding:10px 15px 10px;color:#777;text-decoration:none;text-shadow:0 1px 0 #fff}.navbar .nav .dropdown-toggle .caret{margin-top:8px}.navbar .nav>li>a:focus,.navbar .nav>li>a:hover{color:#333;text-decoration:none;background-color:transparent}.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{color:#555;text-decoration:none;background-color:#e5e5e5;-webkit-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);-moz-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);box-shadow:inset 0 3px 8px rgba(0,0,0,0.125)}.navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-right:5px;margin-left:5px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#ededed;*background-color:#e5e5e5;background-image:-moz-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#e5e5e5));background-image:-webkit-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-o-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:linear-gradient(to bottom,#f2f2f2,#e5e5e5);background-repeat:repeat-x;border-color:#e5e5e5 #e5e5e5 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffe5e5e5',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075)}.navbar .btn-navbar:hover,.navbar .btn-navbar:focus,.navbar .btn-navbar:active,.navbar .btn-navbar.active,.navbar .btn-navbar.disabled,.navbar .btn-navbar[disabled]{color:#fff;background-color:#e5e5e5;*background-color:#d9d9d9}.navbar .btn-navbar:active,.navbar .btn-navbar.active{background-color:#ccc \9}.navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.25);-moz-box-shadow:0 1px 0 rgba(0,0,0,0.25);box-shadow:0 1px 0 rgba(0,0,0,0.25)}.btn-navbar .icon-bar+.icon-bar{margin-top:3px}.navbar .nav>li>.dropdown-menu:before{position:absolute;top:-7px;left:9px;display:inline-block;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-left:7px solid transparent;border-bottom-color:rgba(0,0,0,0.2);content:''}.navbar .nav>li>.dropdown-menu:after{position:absolute;top:-6px;left:10px;display:inline-block;border-right:6px solid transparent;border-bottom:6px solid #fff;border-left:6px solid transparent;content:''}.navbar-fixed-bottom .nav>li>.dropdown-menu:before{top:auto;bottom:-7px;border-top:7px solid #ccc;border-bottom:0;border-top-color:rgba(0,0,0,0.2)}.navbar-fixed-bottom .nav>li>.dropdown-menu:after{top:auto;bottom:-6px;border-top:6px solid #fff;border-bottom:0}.navbar .nav li.dropdown>a:hover .caret,.navbar .nav li.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle{color:#555;background-color:#e5e5e5}.navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#777;border-bottom-color:#777}.navbar .nav li.dropdown.open>.dropdown-toggle .caret,.navbar .nav li.dropdown.active>.dropdown-toggle .caret,.navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.navbar .pull-right>li>.dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right{right:0;left:auto}.navbar .pull-right>li>.dropdown-menu:before,.navbar .nav>li>.dropdown-menu.pull-right:before{right:12px;left:auto}.navbar .pull-right>li>.dropdown-menu:after,.navbar .nav>li>.dropdown-menu.pull-right:after{right:13px;left:auto}.navbar .pull-right>li>.dropdown-menu .dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{right:100%;left:auto;margin-right:-1px;margin-left:0;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top,#222,#111);background-image:-webkit-gradient(linear,0 0,0 100%,from(#222),to(#111));background-image:-webkit-linear-gradient(top,#222,#111);background-image:-o-linear-gradient(top,#222,#111);background-image:linear-gradient(to bottom,#222,#111);background-repeat:repeat-x;border-color:#252525;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222',endColorstr='#ff111111',GradientType=0)}.navbar-inverse .brand,.navbar-inverse .nav>li>a{color:#999;text-shadow:0 -1px 0 rgba(0,0,0,0.25)}.navbar-inverse .brand:hover,.navbar-inverse .nav>li>a:hover,.navbar-inverse .brand:focus,.navbar-inverse .nav>li>a:focus{color:#fff}.navbar-inverse .brand{color:#999}.navbar-inverse .navbar-text{color:#999}.navbar-inverse .nav>li>a:focus,.navbar-inverse .nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .nav .active>a,.navbar-inverse .nav .active>a:hover,.navbar-inverse .nav .active>a:focus{color:#fff;background-color:#111}.navbar-inverse .navbar-link{color:#999}.navbar-inverse .navbar-link:hover,.navbar-inverse .navbar-link:focus{color:#fff}.navbar-inverse .divider-vertical{border-right-color:#222;border-left-color:#111}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{color:#fff;background-color:#111}.navbar-inverse .nav li.dropdown>a:hover .caret,.navbar-inverse .nav li.dropdown>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#999;border-bottom-color:#999}.navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.navbar-inverse .navbar-search .search-query{color:#fff;background-color:#515151;border-color:#111;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none}.navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#ccc}.navbar-inverse .navbar-search .search-query:focus,.navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#333;text-shadow:0 1px 0 #fff;background-color:#fff;border:0;outline:0;-webkit-box-shadow:0 0 3px rgba(0,0,0,0.15);-moz-box-shadow:0 0 3px rgba(0,0,0,0.15);box-shadow:0 0 3px rgba(0,0,0,0.15)}.navbar-inverse .btn-navbar{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e0e0e;*background-color:#040404;background-image:-moz-linear-gradient(top,#151515,#040404);background-image:-webkit-gradient(linear,0 0,0 100%,from(#151515),to(#040404));background-image:-webkit-linear-gradient(top,#151515,#040404);background-image:-o-linear-gradient(top,#151515,#040404);background-image:linear-gradient(to bottom,#151515,#040404);background-repeat:repeat-x;border-color:#040404 #040404 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515',endColorstr='#ff040404',GradientType=0);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.navbar-inverse .btn-navbar:hover,.navbar-inverse .btn-navbar:focus,.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active,.navbar-inverse .btn-navbar.disabled,.navbar-inverse .btn-navbar[disabled]{color:#fff;background-color:#040404;*background-color:#000}.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active{background-color:#000 \9}.breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.breadcrumb>li{display:inline-block;*display:inline;text-shadow:0 1px 0 #fff;*zoom:1}.breadcrumb>li>.divider{padding:0 5px;color:#ccc}.breadcrumb>.active{color:#999}.pagination{margin:20px 0}.pagination ul{display:inline-block;*display:inline;margin-bottom:0;margin-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*zoom:1;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.pagination ul>li{display:inline}.pagination ul>li>a,.pagination ul>li>span{float:left;padding:4px 12px;line-height:20px;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.pagination ul>li>a:hover,.pagination ul>li>a:focus,.pagination ul>.active>a,.pagination ul>.active>span{background-color:#f5f5f5}.pagination ul>.active>a,.pagination ul>.active>span{color:#999;cursor:default}.pagination ul>.disabled>span,.pagination ul>.disabled>a,.pagination ul>.disabled>a:hover,.pagination ul>.disabled>a:focus{color:#999;cursor:default;background-color:transparent}.pagination ul>li:first-child>a,.pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.pagination ul>li:last-child>a,.pagination ul>li:last-child>span{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.pagination-centered{text-align:center}.pagination-right{text-align:right}.pagination-large ul>li>a,.pagination-large ul>li>span{padding:11px 19px;font-size:17.5px}.pagination-large ul>li:first-child>a,.pagination-large ul>li:first-child>span{-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.pagination-large ul>li:last-child>a,.pagination-large ul>li:last-child>span{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.pagination-mini ul>li:first-child>a,.pagination-small ul>li:first-child>a,.pagination-mini ul>li:first-child>span,.pagination-small ul>li:first-child>span{-webkit-border-bottom-left-radius:3px;border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-top-left-radius:3px;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px}.pagination-mini ul>li:last-child>a,.pagination-small ul>li:last-child>a,.pagination-mini ul>li:last-child>span,.pagination-small ul>li:last-child>span{-webkit-border-top-right-radius:3px;border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-bottom-right-radius:3px;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px}.pagination-small ul>li>a,.pagination-small ul>li>span{padding:2px 10px;font-size:11.9px}.pagination-mini ul>li>a,.pagination-mini ul>li>span{padding:0 6px;font-size:10.5px}.pager{margin:20px 0;text-align:center;list-style:none;*zoom:1}.pager:before,.pager:after{display:table;line-height:0;content:""}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#999;cursor:default;background-color:#fff}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0}.modal-backdrop,.modal-backdrop.fade.in{opacity:.8;filter:alpha(opacity=80)}.modal{position:fixed;top:10%;left:50%;z-index:1050;width:560px;margin-left:-280px;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;outline:0;-webkit-box-shadow:0 3px 7px rgba(0,0,0,0.3);-moz-box-shadow:0 3px 7px rgba(0,0,0,0.3);box-shadow:0 3px 7px rgba(0,0,0,0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box}.modal.fade{top:-25%;-webkit-transition:opacity .3s linear,top .3s ease-out;-moz-transition:opacity .3s linear,top .3s ease-out;-o-transition:opacity .3s linear,top .3s ease-out;transition:opacity .3s linear,top .3s ease-out}.modal.fade.in{top:10%}.modal-header{padding:9px 15px;border-bottom:1px solid #eee}.modal-header .close{margin-top:2px}.modal-header h3{margin:0;line-height:30px}.modal-body{position:relative;max-height:400px;padding:15px;overflow-y:auto}.modal-form{margin-bottom:0}.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;*zoom:1;-webkit-box-shadow:inset 0 1px 0 #fff;-moz-box-shadow:inset 0 1px 0 #fff;box-shadow:inset 0 1px 0 #fff}.modal-footer:before,.modal-footer:after{display:table;line-height:0;content:""}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.tooltip{position:absolute;z-index:1030;display:block;font-size:11px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.tooltip.in{opacity:.8;filter:alpha(opacity=80)}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:#000;border-width:5px 5px 0}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:#000;border-width:5px 5px 5px 0}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:#000;border-width:5px 0 5px 5px}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:#000;border-width:0 5px 5px}.popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0}.popover-title:empty{display:none}.popover-content{padding:9px 14px}.popover .arrow,.popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover .arrow{border-width:11px}.popover .arrow:after{border-width:10px;content:""}.popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0}.popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0}.popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0}.popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0}.thumbnails{margin-left:-20px;list-style:none;*zoom:1}.thumbnails:before,.thumbnails:after{display:table;line-height:0;content:""}.thumbnails:after{clear:both}.row-fluid .thumbnails{margin-left:0}.thumbnails>li{float:left;margin-bottom:20px;margin-left:20px}.thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.055);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.055);box-shadow:0 1px 3px rgba(0,0,0,0.055);-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}a.thumbnail:hover,a.thumbnail:focus{border-color:#08c;-webkit-box-shadow:0 1px 4px rgba(0,105,214,0.25);-moz-box-shadow:0 1px 4px rgba(0,105,214,0.25);box-shadow:0 1px 4px rgba(0,105,214,0.25)}.thumbnail>img{display:block;max-width:100%;margin-right:auto;margin-left:auto}.thumbnail .caption{padding:9px;color:#555}.media,.media-body{overflow:hidden;*overflow:visible;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{margin-left:0;list-style:none}.label,.badge{display:inline-block;padding:2px 4px;font-size:11.844px;font-weight:bold;line-height:14px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);white-space:nowrap;vertical-align:baseline;background-color:#999}.label{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.badge{padding-right:9px;padding-left:9px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px}.label:empty,.badge:empty{display:none}a.label:hover,a.label:focus,a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.label-important,.badge-important{background-color:#b94a48}.label-important[href],.badge-important[href]{background-color:#953b39}.label-warning,.badge-warning{background-color:#f89406}.label-warning[href],.badge-warning[href]{background-color:#c67605}.label-success,.badge-success{background-color:#468847}.label-success[href],.badge-success[href]{background-color:#356635}.label-info,.badge-info{background-color:#3a87ad}.label-info[href],.badge-info[href]{background-color:#2d6987}.label-inverse,.badge-inverse{background-color:#333}.label-inverse[href],.badge-inverse[href]{background-color:#1a1a1a}.btn .label,.btn .badge{position:relative;top:-1px}.btn-mini .label,.btn-mini .badge{top:0}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f7f7f7;background-image:-moz-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f5f5f5),to(#f9f9f9));background-image:-webkit-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-o-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);background-repeat:repeat-x;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5',endColorstr='#fff9f9f9',GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.progress .bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top,#149bdf,#0480be);background-image:-webkit-gradient(linear,0 0,0 100%,from(#149bdf),to(#0480be));background-image:-webkit-linear-gradient(top,#149bdf,#0480be);background-image:-o-linear-gradient(top,#149bdf,#0480be);background-image:linear-gradient(to bottom,#149bdf,#0480be);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf',endColorstr='#ff0480be',GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width .6s ease;-moz-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15)}.progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px}.progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-danger .bar,.progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top,#ee5f5b,#c43c35);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#c43c35));background-image:-webkit-linear-gradient(top,#ee5f5b,#c43c35);background-image:-o-linear-gradient(top,#ee5f5b,#c43c35);background-image:linear-gradient(to bottom,#ee5f5b,#c43c35);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffc43c35',GradientType=0)}.progress-danger.progress-striped .bar,.progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-success .bar,.progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top,#62c462,#57a957);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#57a957));background-image:-webkit-linear-gradient(top,#62c462,#57a957);background-image:-o-linear-gradient(top,#62c462,#57a957);background-image:linear-gradient(to bottom,#62c462,#57a957);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff57a957',GradientType=0)}.progress-success.progress-striped .bar,.progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-info .bar,.progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top,#5bc0de,#339bb9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#339bb9));background-image:-webkit-linear-gradient(top,#5bc0de,#339bb9);background-image:-o-linear-gradient(top,#5bc0de,#339bb9);background-image:linear-gradient(to bottom,#5bc0de,#339bb9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff339bb9',GradientType=0)}.progress-info.progress-striped .bar,.progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.progress-warning .bar,.progress .bar-warning{background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0)}.progress-warning.progress-striped .bar,.progress-striped .bar-warning{background-color:#fbb450;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.accordion{margin-bottom:20px}.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.accordion-heading{border-bottom:0}.accordion-heading .accordion-toggle{display:block;padding:8px 15px}.accordion-toggle{cursor:pointer}.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.carousel{position:relative;margin-bottom:20px;line-height:1}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-moz-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#fff;text-align:center;background:#222;border:3px solid #fff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:.5;filter:alpha(opacity=50)}.carousel-control.right{right:15px;left:auto}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-indicators{position:absolute;top:15px;right:15px;z-index:5;margin:0;list-style:none}.carousel-indicators li{display:block;float:left;width:10px;height:10px;margin-left:5px;text-indent:-999px;background-color:#ccc;background-color:rgba(255,255,255,0.25);border-radius:5px}.carousel-indicators .active{background-color:#fff}.carousel-caption{position:absolute;right:0;bottom:0;left:0;padding:15px;background:#333;background:rgba(0,0,0,0.75)}.carousel-caption h4,.carousel-caption p{line-height:20px;color:#fff}.carousel-caption h4{margin:0 0 5px}.carousel-caption p{margin-bottom:0}.hero-unit{padding:60px;margin-bottom:30px;font-size:18px;font-weight:200;line-height:30px;color:inherit;background-color:#eee;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;letter-spacing:-1px;color:inherit}.hero-unit li{line-height:30px}.pull-right{float:right}.pull-left{float:left}.hide{display:none}.show{display:block}.invisible{visibility:hidden}.affix{position:fixed} diff --git a/opendaylight/adsal/web/root/src/main/resources/css/fuelux-responsive.min.css b/opendaylight/adsal/web/root/src/main/resources/css/fuelux-responsive.min.css deleted file mode 100755 index 1dbe3232c8..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/css/fuelux-responsive.min.css +++ /dev/null @@ -1,9 +0,0 @@ -/*! - * Bootstrap Responsive v2.3.2 - * - * Copyright 2012 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world @twitter by @mdo and @fat. - */.fuelux .clearfix{*zoom:1}.fuelux .clearfix:before,.fuelux .clearfix:after{display:table;line-height:0;content:""}.fuelux .clearfix:after{clear:both}.fuelux .hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.fuelux .input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}@-ms-viewport{width:device-width}.fuelux .hidden{display:none;visibility:hidden}.fuelux .visible-phone{display:none!important}.fuelux .visible-tablet{display:none!important}.fuelux .hidden-desktop{display:none!important}.fuelux .visible-desktop{display:inherit!important}@media(min-width:768px) and (max-width:979px){.fuelux .hidden-desktop{display:inherit!important}.fuelux .visible-desktop{display:none!important}.fuelux .visible-tablet{display:inherit!important}.fuelux .hidden-tablet{display:none!important}}@media(max-width:767px){.fuelux .hidden-desktop{display:inherit!important}.fuelux .visible-desktop{display:none!important}.fuelux .visible-phone{display:inherit!important}.fuelux .hidden-phone{display:none!important}}.fuelux .visible-print{display:none!important}@media print{.fuelux .visible-print{display:inherit!important}.fuelux .hidden-print{display:none!important}}@media(min-width:1200px){.fuelux .row{margin-left:-30px;*zoom:1}.fuelux .row:before,.fuelux .row:after{display:table;line-height:0;content:""}.fuelux .row:after{clear:both}.fuelux [class*="span"]{float:left;min-height:1px;margin-left:30px}.fuelux .container,.fuelux .navbar-static-top .container,.fuelux .navbar-fixed-top .container,.fuelux .navbar-fixed-bottom .container{width:1170px}.fuelux .span12{width:1170px}.fuelux .span11{width:1070px}.fuelux .span10{width:970px}.fuelux .span9{width:870px}.fuelux .span8{width:770px}.fuelux .span7{width:670px}.fuelux .span6{width:570px}.fuelux .span5{width:470px}.fuelux .span4{width:370px}.fuelux .span3{width:270px}.fuelux .span2{width:170px}.fuelux .span1{width:70px}.fuelux .offset12{margin-left:1230px}.fuelux .offset11{margin-left:1130px}.fuelux .offset10{margin-left:1030px}.fuelux .offset9{margin-left:930px}.fuelux .offset8{margin-left:830px}.fuelux .offset7{margin-left:730px}.fuelux .offset6{margin-left:630px}.fuelux .offset5{margin-left:530px}.fuelux .offset4{margin-left:430px}.fuelux .offset3{margin-left:330px}.fuelux .offset2{margin-left:230px}.fuelux .offset1{margin-left:130px}.fuelux .row-fluid{width:100%;*zoom:1}.fuelux .row-fluid:before,.fuelux .row-fluid:after{display:table;line-height:0;content:""}.fuelux .row-fluid:after{clear:both}.fuelux .row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.564102564102564%;*margin-left:2.5109110747408616%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.fuelux .row-fluid [class*="span"]:first-child{margin-left:0}.fuelux .row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.564102564102564%}.fuelux .row-fluid .span12{width:100%;*width:99.94680851063829%}.fuelux .row-fluid .span11{width:91.45299145299145%;*width:91.39979996362975%}.fuelux .row-fluid .span10{width:82.90598290598291%;*width:82.8527914166212%}.fuelux .row-fluid .span9{width:74.35897435897436%;*width:74.30578286961266%}.fuelux .row-fluid .span8{width:65.81196581196582%;*width:65.75877432260411%}.fuelux .row-fluid .span7{width:57.26495726495726%;*width:57.21176577559556%}.fuelux .row-fluid .span6{width:48.717948717948715%;*width:48.664757228587014%}.fuelux .row-fluid .span5{width:40.17094017094017%;*width:40.11774868157847%}.fuelux .row-fluid .span4{width:31.623931623931625%;*width:31.570740134569924%}.fuelux .row-fluid .span3{width:23.076923076923077%;*width:23.023731587561375%}.fuelux .row-fluid .span2{width:14.52991452991453%;*width:14.476723040552828%}.fuelux .row-fluid .span1{width:5.982905982905983%;*width:5.929714493544281%}.fuelux .row-fluid .offset12{margin-left:105.12820512820512%;*margin-left:105.02182214948171%}.fuelux .row-fluid .offset12:first-child{margin-left:102.56410256410257%;*margin-left:102.45771958537915%}.fuelux .row-fluid .offset11{margin-left:96.58119658119658%;*margin-left:96.47481360247316%}.fuelux .row-fluid .offset11:first-child{margin-left:94.01709401709402%;*margin-left:93.91071103837061%}.fuelux .row-fluid .offset10{margin-left:88.03418803418803%;*margin-left:87.92780505546462%}.fuelux .row-fluid .offset10:first-child{margin-left:85.47008547008548%;*margin-left:85.36370249136206%}.fuelux .row-fluid .offset9{margin-left:79.48717948717949%;*margin-left:79.38079650845607%}.fuelux .row-fluid .offset9:first-child{margin-left:76.92307692307693%;*margin-left:76.81669394435352%}.fuelux .row-fluid .offset8{margin-left:70.94017094017094%;*margin-left:70.83378796144753%}.fuelux .row-fluid .offset8:first-child{margin-left:68.37606837606839%;*margin-left:68.26968539734497%}.fuelux .row-fluid .offset7{margin-left:62.393162393162385%;*margin-left:62.28677941443899%}.fuelux .row-fluid .offset7:first-child{margin-left:59.82905982905982%;*margin-left:59.72267685033642%}.fuelux .row-fluid .offset6{margin-left:53.84615384615384%;*margin-left:53.739770867430444%}.fuelux .row-fluid .offset6:first-child{margin-left:51.28205128205128%;*margin-left:51.175668303327875%}.fuelux .row-fluid .offset5{margin-left:45.299145299145295%;*margin-left:45.1927623204219%}.fuelux .row-fluid .offset5:first-child{margin-left:42.73504273504273%;*margin-left:42.62865975631933%}.fuelux .row-fluid .offset4{margin-left:36.75213675213675%;*margin-left:36.645753773413354%}.fuelux .row-fluid .offset4:first-child{margin-left:34.18803418803419%;*margin-left:34.081651209310785%}.fuelux .row-fluid .offset3{margin-left:28.205128205128204%;*margin-left:28.0987452264048%}.fuelux .row-fluid .offset3:first-child{margin-left:25.641025641025642%;*margin-left:25.53464266230224%}.fuelux .row-fluid .offset2{margin-left:19.65811965811966%;*margin-left:19.551736679396257%}.fuelux .row-fluid .offset2:first-child{margin-left:17.094017094017094%;*margin-left:16.98763411529369%}.fuelux .row-fluid .offset1{margin-left:11.11111111111111%;*margin-left:11.004728132387708%}.fuelux .row-fluid .offset1:first-child{margin-left:8.547008547008547%;*margin-left:8.440625568285142%}.fuelux input,.fuelux textarea,.fuelux .uneditable-input{margin-left:0}.fuelux .controls-row [class*="span"]+[class*="span"]{margin-left:30px}.fuelux input.span12,textarea.span12,.uneditable-input.span12{width:1156px}.fuelux input.span11,textarea.span11,.uneditable-input.span11{width:1056px}.fuelux input.span10,textarea.span10,.uneditable-input.span10{width:956px}.fuelux input.span9,textarea.span9,.uneditable-input.span9{width:856px}.fuelux input.span8,textarea.span8,.uneditable-input.span8{width:756px}.fuelux input.span7,textarea.span7,.uneditable-input.span7{width:656px}.fuelux input.span6,textarea.span6,.uneditable-input.span6{width:556px}.fuelux input.span5,textarea.span5,.uneditable-input.span5{width:456px}.fuelux input.span4,textarea.span4,.uneditable-input.span4{width:356px}.fuelux input.span3,textarea.span3,.uneditable-input.span3{width:256px}.fuelux input.span2,textarea.span2,.uneditable-input.span2{width:156px}.fuelux input.span1,textarea.span1,.uneditable-input.span1{width:56px}.fuelux .thumbnails{margin-left:-30px}.fuelux .thumbnails>li{margin-left:30px}.fuelux .row-fluid .thumbnails{margin-left:0}}@media(min-width:768px) and (max-width:979px){.fuelux .row{margin-left:-20px;*zoom:1}.fuelux .row:before,.fuelux .row:after{display:table;line-height:0;content:""}.fuelux .row:after{clear:both}.fuelux [class*="span"]{float:left;min-height:1px;margin-left:20px}.fuelux .container,.fuelux .navbar-static-top .container,.fuelux .navbar-fixed-top .container,.fuelux .navbar-fixed-bottom .container{width:724px}.fuelux .span12{width:724px}.fuelux .span11{width:662px}.fuelux .span10{width:600px}.fuelux .span9{width:538px}.fuelux .span8{width:476px}.fuelux .span7{width:414px}.fuelux .span6{width:352px}.fuelux .span5{width:290px}.fuelux .span4{width:228px}.fuelux .span3{width:166px}.fuelux .span2{width:104px}.fuelux .span1{width:42px}.fuelux .offset12{margin-left:764px}.fuelux .offset11{margin-left:702px}.fuelux .offset10{margin-left:640px}.fuelux .offset9{margin-left:578px}.fuelux .offset8{margin-left:516px}.fuelux .offset7{margin-left:454px}.fuelux .offset6{margin-left:392px}.fuelux .offset5{margin-left:330px}.fuelux .offset4{margin-left:268px}.fuelux .offset3{margin-left:206px}.fuelux .offset2{margin-left:144px}.fuelux .offset1{margin-left:82px}.fuelux .row-fluid{width:100%;*zoom:1}.fuelux .row-fluid:before,.fuelux .row-fluid:after{display:table;line-height:0;content:""}.fuelux .row-fluid:after{clear:both}.fuelux .row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.7624309392265194%;*margin-left:2.709239449864817%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.fuelux .row-fluid [class*="span"]:first-child{margin-left:0}.fuelux .row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.7624309392265194%}.fuelux .row-fluid .span12{width:100%;*width:99.94680851063829%}.fuelux .row-fluid .span11{width:91.43646408839778%;*width:91.38327259903608%}.fuelux .row-fluid .span10{width:82.87292817679558%;*width:82.81973668743387%}.fuelux .row-fluid .span9{width:74.30939226519337%;*width:74.25620077583166%}.fuelux .row-fluid .span8{width:65.74585635359117%;*width:65.69266486422946%}.fuelux .row-fluid .span7{width:57.18232044198895%;*width:57.12912895262725%}.fuelux .row-fluid .span6{width:48.61878453038674%;*width:48.56559304102504%}.fuelux .row-fluid .span5{width:40.05524861878453%;*width:40.00205712942283%}.fuelux .row-fluid .span4{width:31.491712707182323%;*width:31.43852121782062%}.fuelux .row-fluid .span3{width:22.92817679558011%;*width:22.87498530621841%}.fuelux .row-fluid .span2{width:14.3646408839779%;*width:14.311449394616199%}.fuelux .row-fluid .span1{width:5.801104972375691%;*width:5.747913483013988%}.fuelux .row-fluid .offset12{margin-left:105.52486187845304%;*margin-left:105.41847889972962%}.fuelux .row-fluid .offset12:first-child{margin-left:102.76243093922652%;*margin-left:102.6560479605031%}.fuelux .row-fluid .offset11{margin-left:96.96132596685082%;*margin-left:96.8549429881274%}.fuelux .row-fluid .offset11:first-child{margin-left:94.1988950276243%;*margin-left:94.09251204890089%}.fuelux .row-fluid .offset10{margin-left:88.39779005524862%;*margin-left:88.2914070765252%}.fuelux .row-fluid .offset10:first-child{margin-left:85.6353591160221%;*margin-left:85.52897613729868%}.fuelux .row-fluid .offset9{margin-left:79.8342541436464%;*margin-left:79.72787116492299%}.fuelux .row-fluid .offset9:first-child{margin-left:77.07182320441989%;*margin-left:76.96544022569647%}.fuelux .row-fluid .offset8{margin-left:71.2707182320442%;*margin-left:71.16433525332079%}.fuelux .row-fluid .offset8:first-child{margin-left:68.50828729281768%;*margin-left:68.40190431409427%}.fuelux .row-fluid .offset7{margin-left:62.70718232044199%;*margin-left:62.600799341718584%}.fuelux .row-fluid .offset7:first-child{margin-left:59.94475138121547%;*margin-left:59.838368402492065%}.fuelux .row-fluid .offset6{margin-left:54.14364640883978%;*margin-left:54.037263430116376%}.fuelux .row-fluid .offset6:first-child{margin-left:51.38121546961326%;*margin-left:51.27483249088986%}.fuelux .row-fluid .offset5{margin-left:45.58011049723757%;*margin-left:45.47372751851417%}.fuelux .row-fluid .offset5:first-child{margin-left:42.81767955801105%;*margin-left:42.71129657928765%}.fuelux .row-fluid .offset4{margin-left:37.01657458563536%;*margin-left:36.91019160691196%}.fuelux .row-fluid .offset4:first-child{margin-left:34.25414364640884%;*margin-left:34.14776066768544%}.fuelux .row-fluid .offset3{margin-left:28.45303867403315%;*margin-left:28.346655695309746%}.fuelux .row-fluid .offset3:first-child{margin-left:25.69060773480663%;*margin-left:25.584224756083227%}.fuelux .row-fluid .offset2{margin-left:19.88950276243094%;*margin-left:19.783119783707537%}.fuelux .row-fluid .offset2:first-child{margin-left:17.12707182320442%;*margin-left:17.02068884448102%}.fuelux .row-fluid .offset1{margin-left:11.32596685082873%;*margin-left:11.219583872105325%}.fuelux .row-fluid .offset1:first-child{margin-left:8.56353591160221%;*margin-left:8.457152932878806%}.fuelux input,.fuelux textarea,.fuelux .uneditable-input{margin-left:0}.fuelux .controls-row [class*="span"]+[class*="span"]{margin-left:20px}.fuelux input.span12,textarea.span12,.uneditable-input.span12{width:710px}.fuelux input.span11,textarea.span11,.uneditable-input.span11{width:648px}.fuelux input.span10,textarea.span10,.uneditable-input.span10{width:586px}.fuelux input.span9,textarea.span9,.uneditable-input.span9{width:524px}.fuelux input.span8,textarea.span8,.uneditable-input.span8{width:462px}.fuelux input.span7,textarea.span7,.uneditable-input.span7{width:400px}.fuelux input.span6,textarea.span6,.uneditable-input.span6{width:338px}.fuelux input.span5,textarea.span5,.uneditable-input.span5{width:276px}.fuelux input.span4,textarea.span4,.uneditable-input.span4{width:214px}.fuelux input.span3,textarea.span3,.uneditable-input.span3{width:152px}.fuelux input.span2,textarea.span2,.uneditable-input.span2{width:90px}.fuelux input.span1,textarea.span1,.uneditable-input.span1{width:28px}}@media(max-width:767px){.fuelux body{padding-right:20px;padding-left:20px}.fuelux .navbar-fixed-top,.fuelux .navbar-fixed-bottom,.fuelux .navbar-static-top{margin-right:-20px;margin-left:-20px}.fuelux .container-fluid{padding:0}.fuelux .dl-horizontal dt{float:none;width:auto;clear:none;text-align:left}.fuelux .dl-horizontal dd{margin-left:0}.fuelux .container{width:auto}.fuelux .row-fluid{width:100%}.fuelux .row,.fuelux .thumbnails{margin-left:0}.fuelux .thumbnails>li{float:none;margin-left:0}.fuelux [class*="span"],.fuelux .uneditable-input[class*="span"],.fuelux .row-fluid [class*="span"]{display:block;float:none;width:100%;margin-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.fuelux .span12,.fuelux .row-fluid .span12{width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.fuelux .row-fluid [class*="offset"]:first-child{margin-left:0}.fuelux .input-large,.fuelux .input-xlarge,.fuelux .input-xxlarge,.fuelux input[class*="span"],.fuelux select[class*="span"],.fuelux textarea[class*="span"],.fuelux .uneditable-input{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.fuelux .input-prepend input,.fuelux .input-append input,.fuelux .input-prepend input[class*="span"],.fuelux .input-append input[class*="span"]{display:inline-block;width:auto}.fuelux .controls-row [class*="span"]+[class*="span"]{margin-left:0}.fuelux .modal{position:fixed;top:20px;right:20px;left:20px;width:auto;margin:0}.fuelux .modal.fade{top:-100px}.fuelux .modal.fade.in{top:20px}}@media(max-width:480px){.fuelux .nav-collapse{-webkit-transform:translate3d(0,0,0)}.fuelux .page-header h1 small{display:block;line-height:20px}.fuelux input[type="checkbox"],.fuelux input[type="radio"]{border:1px solid #ccc}.fuelux .form-horizontal .control-label{float:none;width:auto;padding-top:0;text-align:left}.fuelux .form-horizontal .controls{margin-left:0}.fuelux .form-horizontal .control-list{padding-top:0}.fuelux .form-horizontal .form-actions{padding-right:10px;padding-left:10px}.fuelux .media .pull-left,.fuelux .media .pull-right{display:block;float:none;margin-bottom:10px}.fuelux .media-object{margin-right:0;margin-left:0}.fuelux .modal{top:10px;right:10px;left:10px}.fuelux .modal-header .close{padding:10px;margin:-10px}.fuelux .carousel-caption{position:static}}@media(max-width:979px){.fuelux body{padding-top:0}.fuelux .navbar-fixed-top,.fuelux .navbar-fixed-bottom{position:static}.fuelux .navbar-fixed-top{margin-bottom:20px}.fuelux .navbar-fixed-bottom{margin-top:20px}.fuelux .navbar-fixed-top .navbar-inner,.fuelux .navbar-fixed-bottom .navbar-inner{padding:5px}.fuelux .navbar .container{width:auto;padding:0}.fuelux .navbar .brand{padding-right:10px;padding-left:10px;margin:0 0 0 -5px}.fuelux .nav-collapse{clear:both}.fuelux .nav-collapse .nav{float:none;margin:0 0 10px}.fuelux .nav-collapse .nav>li{float:none}.fuelux .nav-collapse .nav>li>a{margin-bottom:2px}.fuelux .nav-collapse .nav>.divider-vertical{display:none}.fuelux .nav-collapse .nav .nav-header{color:#777;text-shadow:none}.fuelux .nav-collapse .nav>li>a,.fuelux .nav-collapse .dropdown-menu a{padding:9px 15px;font-weight:bold;color:#777;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fuelux .nav-collapse .btn{padding:4px 10px 4px;font-weight:normal;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.fuelux .nav-collapse .dropdown-menu li+li a{margin-bottom:2px}.fuelux .nav-collapse .nav>li>a:hover,.fuelux .nav-collapse .nav>li>a:focus,.fuelux .nav-collapse .dropdown-menu a:hover,.fuelux .nav-collapse .dropdown-menu a:focus{background-color:#f2f2f2}.fuelux .navbar-inverse .nav-collapse .nav>li>a,.fuelux .navbar-inverse .nav-collapse .dropdown-menu a{color:#999}.fuelux .navbar-inverse .nav-collapse .nav>li>a:hover,.fuelux .navbar-inverse .nav-collapse .nav>li>a:focus,.fuelux .navbar-inverse .nav-collapse .dropdown-menu a:hover,.fuelux .navbar-inverse .nav-collapse .dropdown-menu a:focus{background-color:#111}.fuelux .nav-collapse.in .btn-group{padding:0;margin-top:5px}.fuelux .nav-collapse .dropdown-menu{position:static;top:auto;left:auto;display:none;float:none;max-width:none;padding:0;margin:0 15px;background-color:transparent;border:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.fuelux .nav-collapse .open>.dropdown-menu{display:block}.fuelux .nav-collapse .dropdown-menu:before,.fuelux .nav-collapse .dropdown-menu:after{display:none}.fuelux .nav-collapse .dropdown-menu .divider{display:none}.fuelux .nav-collapse .nav>li>.dropdown-menu:before,.fuelux .nav-collapse .nav>li>.dropdown-menu:after{display:none}.fuelux .nav-collapse .navbar-form,.fuelux .nav-collapse .navbar-search{float:none;padding:10px 15px;margin:10px 0;border-top:1px solid #f2f2f2;border-bottom:1px solid #f2f2f2;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.1)}.fuelux .navbar-inverse .nav-collapse .navbar-form,.fuelux .navbar-inverse .nav-collapse .navbar-search{border-top-color:#111;border-bottom-color:#111}.fuelux .navbar .nav-collapse .nav.pull-right{float:none;margin-left:0}.fuelux .nav-collapse,.fuelux .nav-collapse.collapse{height:0;overflow:hidden}.fuelux .navbar .btn-navbar{display:block}.fuelux .navbar-static .navbar-inner{padding-right:10px;padding-left:10px}}@media(min-width:980px){.fuelux .nav-collapse.collapse{height:auto!important;overflow:visible!important}} \ No newline at end of file diff --git a/opendaylight/adsal/web/root/src/main/resources/css/fuelux.min.css b/opendaylight/adsal/web/root/src/main/resources/css/fuelux.min.css deleted file mode 100755 index 314f3dc3e8..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/css/fuelux.min.css +++ /dev/null @@ -1,9 +0,0 @@ -/*! - * Bootstrap v2.3.2 - * - * Copyright 2012 Twitter, Inc - * Licensed under the Apache License v2.0 - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Designed and built with all the love in the world @twitter by @mdo and @fat. - */.fuelux .clearfix{*zoom:1}.fuelux .clearfix:before,.fuelux .clearfix:after{display:table;line-height:0;content:""}.fuelux .clearfix:after{clear:both}.fuelux .hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.fuelux .input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.fuelux article,.fuelux aside,.fuelux details,.fuelux figcaption,.fuelux figure,.fuelux footer,.fuelux header,.fuelux hgroup,.fuelux nav,.fuelux section{display:block}.fuelux audio,.fuelux canvas,.fuelux video{display:inline-block;*display:inline;*zoom:1}.fuelux audio:not([controls]){display:none}.fuelux html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}.fuelux a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.fuelux a:hover,.fuelux a:active{outline:0}.fuelux sub,.fuelux sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}.fuelux sup{top:-0.5em}.fuelux sub{bottom:-0.25em}.fuelux img{width:auto\9;height:auto;max-width:100%;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic}.fuelux #map_canvas img,.fuelux .google-maps img{max-width:none}.fuelux button,.fuelux input,.fuelux select,.fuelux textarea{margin:0;font-size:100%;vertical-align:middle}.fuelux button,.fuelux input{*overflow:visible;line-height:normal}.fuelux button::-moz-focus-inner,.fuelux input::-moz-focus-inner{padding:0;border:0}.fuelux button,.fuelux html input[type="button"],.fuelux input[type="reset"],.fuelux input[type="submit"]{cursor:pointer;-webkit-appearance:button}.fuelux label,.fuelux select,.fuelux button,.fuelux input[type="button"],.fuelux input[type="reset"],.fuelux input[type="submit"],.fuelux input[type="radio"],.fuelux input[type="checkbox"]{cursor:pointer}.fuelux input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}.fuelux input[type="search"]::-webkit-search-decoration,.fuelux input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none}.fuelux textarea{overflow:auto;vertical-align:top}@media print{.fuelux *{color:#000!important;text-shadow:none!important;background:transparent!important;box-shadow:none!important}.fuelux a,.fuelux a:visited{text-decoration:underline}.fuelux a[href]:after{content:" (" attr(href) ")"}.fuelux abbr[title]:after{content:" (" attr(title) ")"}.fuelux .ir a:after,.fuelux a[href^="javascript:"]:after,.fuelux a[href^="#"]:after{content:""}.fuelux pre,.fuelux blockquote{border:1px solid #999;page-break-inside:avoid}.fuelux thead{display:table-header-group}.fuelux tr,.fuelux img{page-break-inside:avoid}.fuelux img{max-width:100%!important}@page{margin:.5cm}.fuelux p,.fuelux h2,.fuelux h3{widows:3;orphans:3}.fuelux h2,.fuelux h3{page-break-after:avoid}}.fuelux body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;color:#333;background-color:#fff}.fuelux a{color:#08c;text-decoration:none}.fuelux a:hover,.fuelux a:focus{color:#005580;text-decoration:underline}.fuelux .img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.fuelux .img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.1);box-shadow:0 1px 3px rgba(0,0,0,0.1)}.fuelux .img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px}.fuelux .row{margin-left:-20px;*zoom:1}.fuelux .row:before,.fuelux .row:after{display:table;line-height:0;content:""}.fuelux .row:after{clear:both}.fuelux [class*="span"]{float:left;min-height:1px;margin-left:20px}.fuelux .container,.fuelux .navbar-static-top .container,.fuelux .navbar-fixed-top .container,.fuelux .navbar-fixed-bottom .container{width:940px}.fuelux .span12{width:940px}.fuelux .span11{width:860px}.fuelux .span10{width:780px}.fuelux .span9{width:700px}.fuelux .span8{width:620px}.fuelux .span7{width:540px}.fuelux .span6{width:460px}.fuelux .span5{width:380px}.fuelux .span4{width:300px}.fuelux .span3{width:220px}.fuelux .span2{width:140px}.fuelux .span1{width:60px}.fuelux .offset12{margin-left:980px}.fuelux .offset11{margin-left:900px}.fuelux .offset10{margin-left:820px}.fuelux .offset9{margin-left:740px}.fuelux .offset8{margin-left:660px}.fuelux .offset7{margin-left:580px}.fuelux .offset6{margin-left:500px}.fuelux .offset5{margin-left:420px}.fuelux .offset4{margin-left:340px}.fuelux .offset3{margin-left:260px}.fuelux .offset2{margin-left:180px}.fuelux .offset1{margin-left:100px}.fuelux .row-fluid{width:100%;*zoom:1}.fuelux .row-fluid:before,.fuelux .row-fluid:after{display:table;line-height:0;content:""}.fuelux .row-fluid:after{clear:both}.fuelux .row-fluid [class*="span"]{display:block;float:left;width:100%;min-height:30px;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.fuelux .row-fluid [class*="span"]:first-child{margin-left:0}.fuelux .row-fluid .controls-row [class*="span"]+[class*="span"]{margin-left:2.127659574468085%}.fuelux .row-fluid .span12{width:100%;*width:99.94680851063829%}.fuelux .row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%}.fuelux .row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%}.fuelux .row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%}.fuelux .row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%}.fuelux .row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%}.fuelux .row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%}.fuelux .row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%}.fuelux .row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%}.fuelux .row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%}.fuelux .row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%}.fuelux .row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%}.fuelux .row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%}.fuelux .row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%}.fuelux .row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%}.fuelux .row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%}.fuelux .row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%}.fuelux .row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%}.fuelux .row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%}.fuelux .row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%}.fuelux .row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%}.fuelux .row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%}.fuelux .row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%}.fuelux .row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%}.fuelux .row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%}.fuelux .row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%}.fuelux .row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%}.fuelux .row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%}.fuelux .row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%}.fuelux .row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%}.fuelux .row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%}.fuelux .row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%}.fuelux .row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%}.fuelux .row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%}.fuelux .row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%}.fuelux .row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%}.fuelux [class*="span"].hide,.fuelux .row-fluid [class*="span"].hide{display:none}.fuelux [class*="span"].pull-right,.fuelux .row-fluid [class*="span"].pull-right{float:right}.fuelux .container{margin-right:auto;margin-left:auto;*zoom:1}.fuelux .container:before,.fuelux .container:after{display:table;line-height:0;content:""}.fuelux .container:after{clear:both}.fuelux .container-fluid{padding-right:20px;padding-left:20px;*zoom:1}.fuelux .container-fluid:before,.fuelux .container-fluid:after{display:table;line-height:0;content:""}.fuelux .container-fluid:after{clear:both}.fuelux p{margin:0 0 10px}.fuelux .lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px}.fuelux small{font-size:85%}.fuelux strong{font-weight:bold}.fuelux em{font-style:italic}.fuelux cite{font-style:normal}.fuelux .muted{color:#999}.fuelux a.muted:hover,.fuelux a.muted:focus{color:#808080}.fuelux .text-warning{color:#c09853}.fuelux a.text-warning:hover,.fuelux a.text-warning:focus{color:#a47e3c}.fuelux .text-error{color:#b94a48}.fuelux a.text-error:hover,.fuelux a.text-error:focus{color:#953b39}.fuelux .text-info{color:#3a87ad}.fuelux a.text-info:hover,.fuelux a.text-info:focus{color:#2d6987}.fuelux .text-success{color:#468847}.fuelux a.text-success:hover,.fuelux a.text-success:focus{color:#356635}.fuelux .text-left{text-align:left}.fuelux .text-right{text-align:right}.fuelux .text-center{text-align:center}.fuelux h1,.fuelux h2,.fuelux h3,.fuelux h4,.fuelux h5,.fuelux h6{margin:10px 0;font-family:inherit;font-weight:bold;line-height:20px;color:inherit;text-rendering:optimizelegibility}.fuelux h1 small,.fuelux h2 small,.fuelux h3 small,.fuelux h4 small,.fuelux h5 small,.fuelux h6 small{font-weight:normal;line-height:1;color:#999}.fuelux h1,.fuelux h2,.fuelux h3{line-height:40px}.fuelux h1{font-size:38.5px}.fuelux h2{font-size:31.5px}.fuelux h3{font-size:24.5px}.fuelux h4{font-size:17.5px}.fuelux h5{font-size:14px}.fuelux h6{font-size:11.9px}.fuelux h1 small{font-size:24.5px}.fuelux h2 small{font-size:17.5px}.fuelux h3 small{font-size:14px}.fuelux h4 small{font-size:14px}.fuelux .page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eee}.fuelux ul,.fuelux ol{padding:0;margin:0 0 10px 25px}.fuelux ul ul,.fuelux ul ol,.fuelux ol ol,.fuelux ol ul{margin-bottom:0}.fuelux li{line-height:20px}.fuelux ul.unstyled,.fuelux ol.unstyled{margin-left:0;list-style:none}.fuelux ul.inline,.fuelux ol.inline{margin-left:0;list-style:none}.fuelux ul.inline>li,.fuelux ol.inline>li{display:inline-block;*display:inline;padding-right:5px;padding-left:5px;*zoom:1}.fuelux dl{margin-bottom:20px}.fuelux dt,.fuelux dd{line-height:20px}.fuelux dt{font-weight:bold}.fuelux dd{margin-left:10px}.fuelux .dl-horizontal{*zoom:1}.fuelux .dl-horizontal:before,.fuelux .dl-horizontal:after{display:table;line-height:0;content:""}.fuelux .dl-horizontal:after{clear:both}.fuelux .dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.fuelux .dl-horizontal dd{margin-left:180px}.fuelux hr{margin:20px 0;border:0;border-top:1px solid #eee;border-bottom:1px solid #fff}.fuelux abbr[title],.fuelux abbr[data-original-title]{cursor:help;border-bottom:1px dotted #999}.fuelux abbr.initialism{font-size:90%;text-transform:uppercase}.fuelux blockquote{padding:0 0 0 15px;margin:0 0 20px;border-left:5px solid #eee}.fuelux blockquote p{margin-bottom:0;font-size:17.5px;font-weight:300;line-height:1.25}.fuelux blockquote small{display:block;line-height:20px;color:#999}.fuelux blockquote small:before{content:'\2014 \00A0'}.fuelux blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0}.fuelux blockquote.pull-right p,.fuelux blockquote.pull-right small{text-align:right}.fuelux blockquote.pull-right small:before{content:''}.fuelux blockquote.pull-right small:after{content:'\00A0 \2014'}.fuelux q:before,.fuelux q:after,.fuelux blockquote:before,.fuelux blockquote:after{content:""}.fuelux address{display:block;margin-bottom:20px;font-style:normal;line-height:20px}.fuelux code,.fuelux pre{padding:0 3px 2px;font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;color:#333;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fuelux code{padding:2px 4px;color:#d14;white-space:nowrap;background-color:#f7f7f9;border:1px solid #e1e1e8}.fuelux pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.fuelux pre.prettyprint{margin-bottom:20px}.fuelux pre code{padding:0;color:inherit;white-space:pre;white-space:pre-wrap;background-color:transparent;border:0}.fuelux .pre-scrollable{max-height:340px;overflow-y:scroll}.fuelux form{margin:0 0 20px}.fuelux fieldset{padding:0;margin:0;border:0}.fuelux legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333;border:0;border-bottom:1px solid #e5e5e5}.fuelux legend small{font-size:15px;color:#999}.fuelux label,.fuelux input,.fuelux button,.fuelux select,.fuelux textarea{font-size:14px;font-weight:normal;line-height:20px}.fuelux input,.fuelux button,.fuelux select,.fuelux textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif}.fuelux label{display:block;margin-bottom:5px}.fuelux select,.fuelux textarea,.fuelux input[type="text"],.fuelux input[type="password"],.fuelux input[type="datetime"],.fuelux input[type="datetime-local"],.fuelux input[type="date"],.fuelux input[type="month"],.fuelux input[type="time"],.fuelux input[type="week"],.fuelux input[type="number"],.fuelux input[type="email"],.fuelux input[type="url"],.fuelux input[type="search"],.fuelux input[type="tel"],.fuelux input[type="color"],.fuelux .uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:10px;font-size:14px;line-height:20px;color:#555;vertical-align:middle;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.fuelux input,.fuelux textarea,.fuelux .uneditable-input{width:206px}.fuelux textarea{height:auto}.fuelux textarea,.fuelux input[type="text"],.fuelux input[type="password"],.fuelux input[type="datetime"],.fuelux input[type="datetime-local"],.fuelux input[type="date"],.fuelux input[type="month"],.fuelux input[type="time"],.fuelux input[type="week"],.fuelux input[type="number"],.fuelux input[type="email"],.fuelux input[type="url"],.fuelux input[type="search"],.fuelux input[type="tel"],.fuelux input[type="color"],.fuelux .uneditable-input{background-color:#fff;border:1px solid #ccc;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border linear .2s,box-shadow linear .2s;-moz-transition:border linear .2s,box-shadow linear .2s;-o-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s}.fuelux textarea:focus,.fuelux input[type="text"]:focus,.fuelux input[type="password"]:focus,.fuelux input[type="datetime"]:focus,.fuelux input[type="datetime-local"]:focus,.fuelux input[type="date"]:focus,.fuelux input[type="month"]:focus,.fuelux input[type="time"]:focus,.fuelux input[type="week"]:focus,.fuelux input[type="number"]:focus,.fuelux input[type="email"]:focus,.fuelux input[type="url"]:focus,.fuelux input[type="search"]:focus,.fuelux input[type="tel"]:focus,.fuelux input[type="color"]:focus,.fuelux .uneditable-input:focus{border-color:rgba(82,168,236,0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}.fuelux input[type="radio"],.fuelux input[type="checkbox"]{margin:4px 0 0;margin-top:1px \9;*margin-top:0;line-height:normal}.fuelux input[type="file"],.fuelux input[type="image"],.fuelux input[type="submit"],.fuelux input[type="reset"],.fuelux input[type="button"],.fuelux input[type="radio"],.fuelux input[type="checkbox"]{width:auto}.fuelux select,.fuelux input[type="file"]{height:30px;*margin-top:4px;line-height:30px}.fuelux select{width:220px;background-color:#fff;border:1px solid #ccc}.fuelux select[multiple],.fuelux select[size]{height:auto}.fuelux select:focus,.fuelux input[type="file"]:focus,.fuelux input[type="radio"]:focus,.fuelux input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.fuelux .uneditable-input,.fuelux .uneditable-textarea{color:#999;cursor:not-allowed;background-color:#fcfcfc;border-color:#ccc;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.025);box-shadow:inset 0 1px 2px rgba(0,0,0,0.025)}.fuelux .uneditable-input{overflow:hidden;white-space:nowrap}.fuelux .uneditable-textarea{width:auto;height:auto}.fuelux input:-moz-placeholder,.fuelux textarea:-moz-placeholder{color:#999}.fuelux input:-ms-input-placeholder,.fuelux textarea:-ms-input-placeholder{color:#999}.fuelux input::-webkit-input-placeholder,.fuelux textarea::-webkit-input-placeholder{color:#999}.fuelux .radio,.fuelux .checkbox{min-height:20px;padding-left:20px}.fuelux .radio input[type="radio"],.fuelux .checkbox input[type="checkbox"]{float:left;margin-left:-20px}.fuelux .controls>.radio:first-child,.fuelux .controls>.checkbox:first-child{padding-top:5px}.fuelux .radio.inline,.fuelux .checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle}.fuelux .radio.inline+.radio.inline,.fuelux .checkbox.inline+.checkbox.inline{margin-left:10px}.fuelux .input-mini{width:60px}.fuelux .input-small{width:90px}.fuelux .input-medium{width:150px}.fuelux .input-large{width:210px}.fuelux .input-xlarge{width:270px}.fuelux .input-xxlarge{width:530px}.fuelux input[class*="span"],.fuelux select[class*="span"],.fuelux textarea[class*="span"],.fuelux .uneditable-input[class*="span"],.fuelux .row-fluid input[class*="span"],.fuelux .row-fluid select[class*="span"],.fuelux .row-fluid textarea[class*="span"],.fuelux .row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0}.fuelux .input-append input[class*="span"],.fuelux .input-append .uneditable-input[class*="span"],.fuelux .input-prepend input[class*="span"],.fuelux .input-prepend .uneditable-input[class*="span"],.fuelux .row-fluid input[class*="span"],.fuelux .row-fluid select[class*="span"],.fuelux .row-fluid textarea[class*="span"],.fuelux .row-fluid .uneditable-input[class*="span"],.fuelux .row-fluid .input-prepend [class*="span"],.fuelux .row-fluid .input-append [class*="span"]{display:inline-block}.fuelux input,.fuelux textarea,.fuelux .uneditable-input{margin-left:0}.fuelux .controls-row [class*="span"]+[class*="span"]{margin-left:20px}.fuelux input.span12,textarea.span12,.uneditable-input.span12{width:926px}.fuelux input.span11,textarea.span11,.uneditable-input.span11{width:846px}.fuelux input.span10,textarea.span10,.uneditable-input.span10{width:766px}.fuelux input.span9,textarea.span9,.uneditable-input.span9{width:686px}.fuelux input.span8,textarea.span8,.uneditable-input.span8{width:606px}.fuelux input.span7,textarea.span7,.uneditable-input.span7{width:526px}.fuelux input.span6,textarea.span6,.uneditable-input.span6{width:446px}.fuelux input.span5,textarea.span5,.uneditable-input.span5{width:366px}.fuelux input.span4,textarea.span4,.uneditable-input.span4{width:286px}.fuelux input.span3,textarea.span3,.uneditable-input.span3{width:206px}.fuelux input.span2,textarea.span2,.uneditable-input.span2{width:126px}.fuelux input.span1,textarea.span1,.uneditable-input.span1{width:46px}.fuelux .controls-row{*zoom:1}.fuelux .controls-row:before,.fuelux .controls-row:after{display:table;line-height:0;content:""}.fuelux .controls-row:after{clear:both}.fuelux .controls-row [class*="span"],.fuelux .row-fluid .controls-row [class*="span"]{float:left}.fuelux .controls-row .checkbox[class*="span"],.fuelux .controls-row .radio[class*="span"]{padding-top:5px}.fuelux input[disabled],.fuelux select[disabled],.fuelux textarea[disabled],.fuelux input[readonly],.fuelux select[readonly],.fuelux textarea[readonly]{cursor:not-allowed;background-color:#eee}.fuelux input[type="radio"][disabled],.fuelux input[type="checkbox"][disabled],.fuelux input[type="radio"][readonly],.fuelux input[type="checkbox"][readonly]{background-color:transparent}.fuelux .control-group.warning .control-label,.fuelux .control-group.warning .help-block,.fuelux .control-group.warning .help-inline{color:#c09853}.fuelux .control-group.warning .checkbox,.fuelux .control-group.warning .radio,.fuelux .control-group.warning input,.fuelux .control-group.warning select,.fuelux .control-group.warning textarea{color:#c09853}.fuelux .control-group.warning input,.fuelux .control-group.warning select,.fuelux .control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.fuelux .control-group.warning input:focus,.fuelux .control-group.warning select:focus,.fuelux .control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #dbc59e}.fuelux .control-group.warning .input-prepend .add-on,.fuelux .control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853}.fuelux .control-group.error .control-label,.fuelux .control-group.error .help-block,.fuelux .control-group.error .help-inline{color:#b94a48}.fuelux .control-group.error .checkbox,.fuelux .control-group.error .radio,.fuelux .control-group.error input,.fuelux .control-group.error select,.fuelux .control-group.error textarea{color:#b94a48}.fuelux .control-group.error input,.fuelux .control-group.error select,.fuelux .control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.fuelux .control-group.error input:focus,.fuelux .control-group.error select:focus,.fuelux .control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #d59392}.fuelux .control-group.error .input-prepend .add-on,.fuelux .control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48}.fuelux .control-group.success .control-label,.fuelux .control-group.success .help-block,.fuelux .control-group.success .help-inline{color:#468847}.fuelux .control-group.success .checkbox,.fuelux .control-group.success .radio,.fuelux .control-group.success input,.fuelux .control-group.success select,.fuelux .control-group.success textarea{color:#468847}.fuelux .control-group.success input,.fuelux .control-group.success select,.fuelux .control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.fuelux .control-group.success input:focus,.fuelux .control-group.success select:focus,.fuelux .control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7aba7b}.fuelux .control-group.success .input-prepend .add-on,.fuelux .control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847}.fuelux .control-group.info .control-label,.fuelux .control-group.info .help-block,.fuelux .control-group.info .help-inline{color:#3a87ad}.fuelux .control-group.info .checkbox,.fuelux .control-group.info .radio,.fuelux .control-group.info input,.fuelux .control-group.info select,.fuelux .control-group.info textarea{color:#3a87ad}.fuelux .control-group.info input,.fuelux .control-group.info select,.fuelux .control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075)}.fuelux .control-group.info input:focus,.fuelux .control-group.info select:focus,.fuelux .control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 6px #7ab5d3}.fuelux .control-group.info .input-prepend .add-on,.fuelux .control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad}.fuelux input:focus:invalid,.fuelux textarea:focus:invalid,.fuelux select:focus:invalid{color:#b94a48;border-color:#ee5f5b}.fuelux input:focus:invalid:focus,.fuelux textarea:focus:invalid:focus,.fuelux select:focus:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7}.fuelux .form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#f5f5f5;border-top:1px solid #e5e5e5;*zoom:1}.fuelux .form-actions:before,.fuelux .form-actions:after{display:table;line-height:0;content:""}.fuelux .form-actions:after{clear:both}.fuelux .help-block,.fuelux .help-inline{color:#595959}.fuelux .help-block{display:block;margin-bottom:10px}.fuelux .help-inline{display:inline-block;*display:inline;padding-left:5px;vertical-align:middle;*zoom:1}.fuelux .input-append,.fuelux .input-prepend{display:inline-block;margin-bottom:10px;font-size:0;white-space:nowrap;vertical-align:middle}.fuelux .input-append input,.fuelux .input-prepend input,.fuelux .input-append select,.fuelux .input-prepend select,.fuelux .input-append .uneditable-input,.fuelux .input-prepend .uneditable-input,.fuelux .input-append .dropdown-menu,.fuelux .input-prepend .dropdown-menu,.fuelux .input-append .popover,.fuelux .input-prepend .popover{font-size:14px}.fuelux .input-append input,.fuelux .input-prepend input,.fuelux .input-append select,.fuelux .input-prepend select,.fuelux .input-append .uneditable-input,.fuelux .input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;vertical-align:top;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.fuelux .input-append input:focus,.fuelux .input-prepend input:focus,.fuelux .input-append select:focus,.fuelux .input-prepend select:focus,.fuelux .input-append .uneditable-input:focus,.fuelux .input-prepend .uneditable-input:focus{z-index:2}.fuelux .input-append .add-on,.fuelux .input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:14px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #fff;background-color:#eee;border:1px solid #ccc}.fuelux .input-append .add-on,.fuelux .input-prepend .add-on,.fuelux .input-append .btn,.fuelux .input-prepend .btn,.fuelux .input-append .btn-group>.dropdown-toggle,.fuelux .input-prepend .btn-group>.dropdown-toggle{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .input-append .active,.fuelux .input-prepend .active{background-color:#a9dba9;border-color:#46a546}.fuelux .input-prepend .add-on,.fuelux .input-prepend .btn{margin-right:-1px}.fuelux .input-prepend .add-on:first-child,.fuelux .input-prepend .btn:first-child{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.fuelux .input-append input,.fuelux .input-append select,.fuelux .input-append .uneditable-input{-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.fuelux .input-append input+.btn-group .btn:last-child,.fuelux .input-append select+.btn-group .btn:last-child,.fuelux .input-append .uneditable-input+.btn-group .btn:last-child{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.fuelux .input-append .add-on,.fuelux .input-append .btn,.fuelux .input-append .btn-group{margin-left:-1px}.fuelux .input-append .add-on:last-child,.fuelux .input-append .btn:last-child,.fuelux .input-append .btn-group:last-child>.dropdown-toggle{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.fuelux .input-prepend.input-append input,.fuelux .input-prepend.input-append select,.fuelux .input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .input-prepend.input-append input+.btn-group .btn,.fuelux .input-prepend.input-append select+.btn-group .btn,.fuelux .input-prepend.input-append .uneditable-input+.btn-group .btn{-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.fuelux .input-prepend.input-append .add-on:first-child,.fuelux .input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.fuelux .input-prepend.input-append .add-on:last-child,.fuelux .input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.fuelux .input-prepend.input-append .btn-group:first-child{margin-left:0}.fuelux input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.fuelux .form-search .input-append .search-query,.fuelux .form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.fuelux .form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.fuelux .form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0}.fuelux .form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px}.fuelux .form-search input,.fuelux .form-inline input,.fuelux .form-horizontal input,.fuelux .form-search textarea,.fuelux .form-inline textarea,.fuelux .form-horizontal textarea,.fuelux .form-search select,.fuelux .form-inline select,.fuelux .form-horizontal select,.fuelux .form-search .help-inline,.fuelux .form-inline .help-inline,.fuelux .form-horizontal .help-inline,.fuelux .form-search .uneditable-input,.fuelux .form-inline .uneditable-input,.fuelux .form-horizontal .uneditable-input,.fuelux .form-search .input-prepend,.fuelux .form-inline .input-prepend,.fuelux .form-horizontal .input-prepend,.fuelux .form-search .input-append,.fuelux .form-inline .input-append,.fuelux .form-horizontal .input-append{display:inline-block;*display:inline;margin-bottom:0;vertical-align:middle;*zoom:1}.fuelux .form-search .hide,.fuelux .form-inline .hide,.fuelux .form-horizontal .hide{display:none}.fuelux .form-search label,.fuelux .form-inline label,.fuelux .form-search .btn-group,.fuelux .form-inline .btn-group{display:inline-block}.fuelux .form-search .input-append,.fuelux .form-inline .input-append,.fuelux .form-search .input-prepend,.fuelux .form-inline .input-prepend{margin-bottom:0}.fuelux .form-search .radio,.fuelux .form-search .checkbox,.fuelux .form-inline .radio,.fuelux .form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle}.fuelux .form-search .radio input[type="radio"],.fuelux .form-search .checkbox input[type="checkbox"],.fuelux .form-inline .radio input[type="radio"],.fuelux .form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0}.fuelux .control-group{margin-bottom:10px}.fuelux legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate}.fuelux .form-horizontal .control-group{margin-bottom:20px;*zoom:1}.fuelux .form-horizontal .control-group:before,.fuelux .form-horizontal .control-group:after{display:table;line-height:0;content:""}.fuelux .form-horizontal .control-group:after{clear:both}.fuelux .form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right}.fuelux .form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0}.fuelux .form-horizontal .controls:first-child{*padding-left:180px}.fuelux .form-horizontal .help-block{margin-bottom:0}.fuelux .form-horizontal input+.help-block,.fuelux .form-horizontal select+.help-block,.fuelux .form-horizontal textarea+.help-block,.fuelux .form-horizontal .uneditable-input+.help-block,.fuelux .form-horizontal .input-prepend+.help-block,.fuelux .form-horizontal .input-append+.help-block{margin-top:10px}.fuelux .form-horizontal .form-actions{padding-left:180px}.fuelux table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0}.fuelux .table{width:100%;margin-bottom:20px}.fuelux .table th,.fuelux .table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #ddd}.fuelux .table th{font-weight:bold}.fuelux .table thead th{vertical-align:bottom}.fuelux .table caption+thead tr:first-child th,.fuelux .table caption+thead tr:first-child td,.fuelux .table colgroup+thead tr:first-child th,.fuelux .table colgroup+thead tr:first-child td,.fuelux .table thead:first-child tr:first-child th,.fuelux .table thead:first-child tr:first-child td{border-top:0}.fuelux .table tbody+tbody{border-top:2px solid #ddd}.fuelux .table .table{background-color:#fff}.fuelux .table-condensed th,.fuelux .table-condensed td{padding:4px 5px}.fuelux .table-bordered{border:1px solid #ddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.fuelux .table-bordered th,.fuelux .table-bordered td{border-left:1px solid #ddd}.fuelux .table-bordered caption+thead tr:first-child th,.fuelux .table-bordered caption+tbody tr:first-child th,.fuelux .table-bordered caption+tbody tr:first-child td,.fuelux .table-bordered colgroup+thead tr:first-child th,.fuelux .table-bordered colgroup+tbody tr:first-child th,.fuelux .table-bordered colgroup+tbody tr:first-child td,.fuelux .table-bordered thead:first-child tr:first-child th,.fuelux .table-bordered tbody:first-child tr:first-child th,.fuelux .table-bordered tbody:first-child tr:first-child td{border-top:0}.fuelux .table-bordered thead:first-child tr:first-child>th:first-child,.fuelux .table-bordered tbody:first-child tr:first-child>td:first-child,.fuelux .table-bordered tbody:first-child tr:first-child>th:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.fuelux .table-bordered thead:first-child tr:first-child>th:last-child,.fuelux .table-bordered tbody:first-child tr:first-child>td:last-child,.fuelux .table-bordered tbody:first-child tr:first-child>th:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.fuelux .table-bordered thead:last-child tr:last-child>th:first-child,.fuelux .table-bordered tbody:last-child tr:last-child>td:first-child,.fuelux .table-bordered tbody:last-child tr:last-child>th:first-child,.fuelux .table-bordered tfoot:last-child tr:last-child>td:first-child,.fuelux .table-bordered tfoot:last-child tr:last-child>th:first-child{-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px}.fuelux .table-bordered thead:last-child tr:last-child>th:last-child,.fuelux .table-bordered tbody:last-child tr:last-child>td:last-child,.fuelux .table-bordered tbody:last-child tr:last-child>th:last-child,.fuelux .table-bordered tfoot:last-child tr:last-child>td:last-child,.fuelux .table-bordered tfoot:last-child tr:last-child>th:last-child{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px}.fuelux .table-bordered tfoot+tbody:last-child tr:last-child td:first-child{-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-moz-border-radius-bottomleft:0}.fuelux .table-bordered tfoot+tbody:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;-moz-border-radius-bottomright:0}.fuelux .table-bordered caption+thead tr:first-child th:first-child,.fuelux .table-bordered caption+tbody tr:first-child td:first-child,.fuelux .table-bordered colgroup+thead tr:first-child th:first-child,.fuelux .table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px}.fuelux .table-bordered caption+thead tr:first-child th:last-child,.fuelux .table-bordered caption+tbody tr:first-child td:last-child,.fuelux .table-bordered colgroup+thead tr:first-child th:last-child,.fuelux .table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px}.fuelux .table-striped tbody>tr:nth-child(odd)>td,.fuelux .table-striped tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.fuelux .table-hover tbody tr:hover>td,.fuelux .table-hover tbody tr:hover>th{background-color:#f5f5f5}.fuelux table td[class*="span"],.fuelux table th[class*="span"],.fuelux .row-fluid table td[class*="span"],.fuelux .row-fluid table th[class*="span"]{display:table-cell;float:none;margin-left:0}.fuelux .table td.span1,.fuelux .table th.span1{float:none;width:44px;margin-left:0}.fuelux .table td.span2,.fuelux .table th.span2{float:none;width:124px;margin-left:0}.fuelux .table td.span3,.fuelux .table th.span3{float:none;width:204px;margin-left:0}.fuelux .table td.span4,.fuelux .table th.span4{float:none;width:284px;margin-left:0}.fuelux .table td.span5,.fuelux .table th.span5{float:none;width:364px;margin-left:0}.fuelux .table td.span6,.fuelux .table th.span6{float:none;width:444px;margin-left:0}.fuelux .table td.span7,.fuelux .table th.span7{float:none;width:524px;margin-left:0}.fuelux .table td.span8,.fuelux .table th.span8{float:none;width:604px;margin-left:0}.fuelux .table td.span9,.fuelux .table th.span9{float:none;width:684px;margin-left:0}.fuelux .table td.span10,.fuelux .table th.span10{float:none;width:764px;margin-left:0}.fuelux .table td.span11,.fuelux .table th.span11{float:none;width:844px;margin-left:0}.fuelux .table td.span12,.fuelux .table th.span12{float:none;width:924px;margin-left:0}.fuelux .table tbody tr.success>td{background-color:#dff0d8}.fuelux .table tbody tr.error>td{background-color:#f2dede}.fuelux .table tbody tr.warning>td{background-color:#fcf8e3}.fuelux .table tbody tr.info>td{background-color:#d9edf7}.fuelux .table-hover tbody tr.success:hover>td{background-color:#d0e9c6}.fuelux .table-hover tbody tr.error:hover>td{background-color:#ebcccc}.fuelux .table-hover tbody tr.warning:hover>td{background-color:#faf2cc}.fuelux .table-hover tbody tr.info:hover>td{background-color:#c4e3f3}.fuelux [class^="icon-"],.fuelux [class*=" icon-"]{display:inline-block;width:14px;height:14px;margin-top:1px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat}.fuelux .icon-white,.fuelux .nav-pills>.active>a>[class^="icon-"],.fuelux .nav-pills>.active>a>[class*=" icon-"],.fuelux .nav-list>.active>a>[class^="icon-"],.fuelux .nav-list>.active>a>[class*=" icon-"],.fuelux .navbar-inverse .nav>.active>a>[class^="icon-"],.fuelux .navbar-inverse .nav>.active>a>[class*=" icon-"],.fuelux .dropdown-menu>li>a:hover>[class^="icon-"],.fuelux .dropdown-menu>li>a:focus>[class^="icon-"],.fuelux .dropdown-menu>li>a:hover>[class*=" icon-"],.fuelux .dropdown-menu>li>a:focus>[class*=" icon-"],.fuelux .dropdown-menu>.active>a>[class^="icon-"],.fuelux .dropdown-menu>.active>a>[class*=" icon-"],.fuelux .dropdown-submenu:hover>a>[class^="icon-"],.fuelux .dropdown-submenu:focus>a>[class^="icon-"],.fuelux .dropdown-submenu:hover>a>[class*=" icon-"],.fuelux .dropdown-submenu:focus>a>[class*=" icon-"]{background-image:url("../img/glyphicons-halflings-white.png")}.fuelux .icon-glass{background-position:0 0}.fuelux .icon-music{background-position:-24px 0}.fuelux .icon-search{background-position:-48px 0}.fuelux .icon-envelope{background-position:-72px 0}.fuelux .icon-heart{background-position:-96px 0}.fuelux .icon-star{background-position:-120px 0}.fuelux .icon-star-empty{background-position:-144px 0}.fuelux .icon-user{background-position:-168px 0}.fuelux .icon-film{background-position:-192px 0}.fuelux .icon-th-large{background-position:-216px 0}.fuelux .icon-th{background-position:-240px 0}.fuelux .icon-th-list{background-position:-264px 0}.fuelux .icon-ok{background-position:-288px 0}.fuelux .icon-remove{background-position:-312px 0}.fuelux .icon-zoom-in{background-position:-336px 0}.fuelux .icon-zoom-out{background-position:-360px 0}.fuelux .icon-off{background-position:-384px 0}.fuelux .icon-signal{background-position:-408px 0}.fuelux .icon-cog{background-position:-432px 0}.fuelux .icon-trash{background-position:-456px 0}.fuelux .icon-home{background-position:0 -24px}.fuelux .icon-file{background-position:-24px -24px}.fuelux .icon-time{background-position:-48px -24px}.fuelux .icon-road{background-position:-72px -24px}.fuelux .icon-download-alt{background-position:-96px -24px}.fuelux .icon-download{background-position:-120px -24px}.fuelux .icon-upload{background-position:-144px -24px}.fuelux .icon-inbox{background-position:-168px -24px}.fuelux .icon-play-circle{background-position:-192px -24px}.fuelux .icon-repeat{background-position:-216px -24px}.fuelux .icon-refresh{background-position:-240px -24px}.fuelux .icon-list-alt{background-position:-264px -24px}.fuelux .icon-lock{background-position:-287px -24px}.fuelux .icon-flag{background-position:-312px -24px}.fuelux .icon-headphones{background-position:-336px -24px}.fuelux .icon-volume-off{background-position:-360px -24px}.fuelux .icon-volume-down{background-position:-384px -24px}.fuelux .icon-volume-up{background-position:-408px -24px}.fuelux .icon-qrcode{background-position:-432px -24px}.fuelux .icon-barcode{background-position:-456px -24px}.fuelux .icon-tag{background-position:0 -48px}.fuelux .icon-tags{background-position:-25px -48px}.fuelux .icon-book{background-position:-48px -48px}.fuelux .icon-bookmark{background-position:-72px -48px}.fuelux .icon-print{background-position:-96px -48px}.fuelux .icon-camera{background-position:-120px -48px}.fuelux .icon-font{background-position:-144px -48px}.fuelux .icon-bold{background-position:-167px -48px}.fuelux .icon-italic{background-position:-192px -48px}.fuelux .icon-text-height{background-position:-216px -48px}.fuelux .icon-text-width{background-position:-240px -48px}.fuelux .icon-align-left{background-position:-264px -48px}.fuelux .icon-align-center{background-position:-288px -48px}.fuelux .icon-align-right{background-position:-312px -48px}.fuelux .icon-align-justify{background-position:-336px -48px}.fuelux .icon-list{background-position:-360px -48px}.fuelux .icon-indent-left{background-position:-384px -48px}.fuelux .icon-indent-right{background-position:-408px -48px}.fuelux .icon-facetime-video{background-position:-432px -48px}.fuelux .icon-picture{background-position:-456px -48px}.fuelux .icon-pencil{background-position:0 -72px}.fuelux .icon-map-marker{background-position:-24px -72px}.fuelux .icon-adjust{background-position:-48px -72px}.fuelux .icon-tint{background-position:-72px -72px}.fuelux .icon-edit{background-position:-96px -72px}.fuelux .icon-share{background-position:-120px -72px}.fuelux .icon-check{background-position:-144px -72px}.fuelux .icon-move{background-position:-168px -72px}.fuelux .icon-step-backward{background-position:-192px -72px}.fuelux .icon-fast-backward{background-position:-216px -72px}.fuelux .icon-backward{background-position:-240px -72px}.fuelux .icon-play{background-position:-264px -72px}.fuelux .icon-pause{background-position:-288px -72px}.fuelux .icon-stop{background-position:-312px -72px}.fuelux .icon-forward{background-position:-336px -72px}.fuelux .icon-fast-forward{background-position:-360px -72px}.fuelux .icon-step-forward{background-position:-384px -72px}.fuelux .icon-eject{background-position:-408px -72px}.fuelux .icon-chevron-left{background-position:-432px -72px}.fuelux .icon-chevron-right{background-position:-456px -72px}.fuelux .icon-plus-sign{background-position:0 -96px}.fuelux .icon-minus-sign{background-position:-24px -96px}.fuelux .icon-remove-sign{background-position:-48px -96px}.fuelux .icon-ok-sign{background-position:-72px -96px}.fuelux .icon-question-sign{background-position:-96px -96px}.fuelux .icon-info-sign{background-position:-120px -96px}.fuelux .icon-screenshot{background-position:-144px -96px}.fuelux .icon-remove-circle{background-position:-168px -96px}.fuelux .icon-ok-circle{background-position:-192px -96px}.fuelux .icon-ban-circle{background-position:-216px -96px}.fuelux .icon-arrow-left{background-position:-240px -96px}.fuelux .icon-arrow-right{background-position:-264px -96px}.fuelux .icon-arrow-up{background-position:-289px -96px}.fuelux .icon-arrow-down{background-position:-312px -96px}.fuelux .icon-share-alt{background-position:-336px -96px}.fuelux .icon-resize-full{background-position:-360px -96px}.fuelux .icon-resize-small{background-position:-384px -96px}.fuelux .icon-plus{background-position:-408px -96px}.fuelux .icon-minus{background-position:-433px -96px}.fuelux .icon-asterisk{background-position:-456px -96px}.fuelux .icon-exclamation-sign{background-position:0 -120px}.fuelux .icon-gift{background-position:-24px -120px}.fuelux .icon-leaf{background-position:-48px -120px}.fuelux .icon-fire{background-position:-72px -120px}.fuelux .icon-eye-open{background-position:-96px -120px}.fuelux .icon-eye-close{background-position:-120px -120px}.fuelux .icon-warning-sign{background-position:-144px -120px}.fuelux .icon-plane{background-position:-168px -120px}.fuelux .icon-calendar{background-position:-192px -120px}.fuelux .icon-random{width:16px;background-position:-216px -120px}.fuelux .icon-comment{background-position:-240px -120px}.fuelux .icon-magnet{background-position:-264px -120px}.fuelux .icon-chevron-up{background-position:-288px -120px}.fuelux .icon-chevron-down{background-position:-313px -119px}.fuelux .icon-retweet{background-position:-336px -120px}.fuelux .icon-shopping-cart{background-position:-360px -120px}.fuelux .icon-folder-close{width:16px;background-position:-384px -120px}.fuelux .icon-folder-open{width:16px;background-position:-408px -120px}.fuelux .icon-resize-vertical{background-position:-432px -119px}.fuelux .icon-resize-horizontal{background-position:-456px -118px}.fuelux .icon-hdd{background-position:0 -144px}.fuelux .icon-bullhorn{background-position:-24px -144px}.fuelux .icon-bell{background-position:-48px -144px}.fuelux .icon-certificate{background-position:-72px -144px}.fuelux .icon-thumbs-up{background-position:-96px -144px}.fuelux .icon-thumbs-down{background-position:-120px -144px}.fuelux .icon-hand-right{background-position:-144px -144px}.fuelux .icon-hand-left{background-position:-168px -144px}.fuelux .icon-hand-up{background-position:-192px -144px}.fuelux .icon-hand-down{background-position:-216px -144px}.fuelux .icon-circle-arrow-right{background-position:-240px -144px}.fuelux .icon-circle-arrow-left{background-position:-264px -144px}.fuelux .icon-circle-arrow-up{background-position:-288px -144px}.fuelux .icon-circle-arrow-down{background-position:-312px -144px}.fuelux .icon-globe{background-position:-336px -144px}.fuelux .icon-wrench{background-position:-360px -144px}.fuelux .icon-tasks{background-position:-384px -144px}.fuelux .icon-filter{background-position:-408px -144px}.fuelux .icon-briefcase{background-position:-432px -144px}.fuelux .icon-fullscreen{background-position:-456px -144px}.fuelux .dropup,.fuelux .dropdown{position:relative}.fuelux .dropdown-toggle{*margin-bottom:-3px}.fuelux .dropdown-toggle:active,.fuelux .open .dropdown-toggle{outline:0}.fuelux .caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000;border-right:4px solid transparent;border-left:4px solid transparent;content:""}.fuelux .dropdown .caret{margin-top:8px;margin-left:2px}.fuelux .dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.fuelux .dropdown-menu.pull-right{right:0;left:auto}.fuelux .dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.fuelux .dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#333;white-space:nowrap}.fuelux .dropdown-menu>li>a:hover,.fuelux .dropdown-menu>li>a:focus,.fuelux .dropdown-submenu:hover>a,.fuelux .dropdown-submenu:focus>a{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-repeat:repeat-x;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.fuelux .dropdown-menu>.active>a,.fuelux .dropdown-menu>.active>a:hover,.fuelux .dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#0081c2;background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#0077b3));background-image:-moz-linear-gradient(top,#08c,#0077b3);background-image:linear-gradient(to bottom,#08c,#0077b3);background-image:-webkit-linear-gradient(top,#08c,#0077b3);background-image:-o-linear-gradient(top,#08c,#0077b3);background-repeat:repeat-x;outline:0;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0077b3',GradientType=0)}.fuelux .dropdown-menu>.disabled>a,.fuelux .dropdown-menu>.disabled>a:hover,.fuelux .dropdown-menu>.disabled>a:focus{color:#999}.fuelux .dropdown-menu>.disabled>a:hover,.fuelux .dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent;background-image:none;filter:progid:dximagetransform.microsoft.gradient(enabled=false)}.fuelux .open{*z-index:1000}.fuelux .open>.dropdown-menu{display:block}.fuelux .dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.fuelux .pull-right>.dropdown-menu{right:0;left:auto}.fuelux .dropup .caret,.fuelux .navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000;content:""}.fuelux .dropup .dropdown-menu,.fuelux .navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}.fuelux .dropdown-submenu{position:relative}.fuelux .dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px}.fuelux .dropdown-submenu:hover>.dropdown-menu{display:block}.fuelux .dropup .dropdown-submenu>.dropdown-menu{top:auto;bottom:0;margin-top:0;margin-bottom:-2px;-webkit-border-radius:5px 5px 5px 0;-moz-border-radius:5px 5px 5px 0;border-radius:5px 5px 5px 0}.fuelux .dropdown-submenu>a:after{display:block;float:right;width:0;height:0;margin-top:5px;margin-right:-10px;border-color:transparent;border-left-color:#ccc;border-style:solid;border-width:5px 0 5px 5px;content:" "}.fuelux .dropdown-submenu:hover>a:after{border-left-color:#fff}.fuelux .dropdown-submenu.pull-left{float:none}.fuelux .dropdown-submenu.pull-left>.dropdown-menu{left:-100%;margin-left:10px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.fuelux .dropdown .dropdown-menu .nav-header{padding-right:20px;padding-left:20px}.fuelux .typeahead{z-index:1051;margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.fuelux .well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.05);box-shadow:inset 0 1px 1px rgba(0,0,0,0.05)}.fuelux .well blockquote{border-color:#ddd;border-color:rgba(0,0,0,0.15)}.fuelux .well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.fuelux .well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fuelux .fade{opacity:0;-webkit-transition:opacity .15s linear;-moz-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fuelux .fade.in{opacity:1}.fuelux .collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;-moz-transition:height .35s ease;-o-transition:height .35s ease;transition:height .35s ease}.fuelux .collapse.in{height:auto}.fuelux .close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.fuelux .close:hover,.fuelux .close:focus{color:#000;text-decoration:none;cursor:pointer;opacity:.4;filter:alpha(opacity=40)}.fuelux button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.fuelux .btn{display:inline-block;*display:inline;padding:4px 12px;margin-bottom:0;*margin-left:.3em;font-size:14px;line-height:20px;color:#333;text-align:center;text-shadow:0 1px 1px rgba(255,255,255,0.75);vertical-align:middle;cursor:pointer;background-color:#f5f5f5;*background-color:#e6e6e6;background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));background-image:-webkit-linear-gradient(top,#fff,#e6e6e6);background-image:-o-linear-gradient(top,#fff,#e6e6e6);background-image:linear-gradient(to bottom,#fff,#e6e6e6);background-image:-moz-linear-gradient(top,#fff,#e6e6e6);background-repeat:repeat-x;border:1px solid #ccc;*border:0;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-bottom-color:#b3b3b3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ffffffff',endColorstr='#ffe6e6e6',GradientType=0);filter:progid:dximagetransform.microsoft.gradient(enabled=false);*zoom:1;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.fuelux .btn:hover,.fuelux .btn:focus,.fuelux .btn:active,.fuelux .btn.active,.fuelux .btn.disabled,.fuelux .btn[disabled]{color:#333;background-color:#e6e6e6;*background-color:#d9d9d9}.fuelux .btn:active,.fuelux .btn.active{background-color:#ccc \9}.fuelux .btn:first-child{*margin-left:0}.fuelux .btn:hover,.fuelux .btn:focus{color:#333;text-decoration:none;background-position:0 -15px;-webkit-transition:background-position .1s linear;-moz-transition:background-position .1s linear;-o-transition:background-position .1s linear;transition:background-position .1s linear}.fuelux .btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.fuelux .btn.active,.fuelux .btn:active{background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.fuelux .btn.disabled,.fuelux .btn[disabled]{cursor:default;background-image:none;opacity:.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.fuelux .btn-large{padding:11px 19px;font-size:17.5px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.fuelux .btn-large [class^="icon-"],.fuelux .btn-large [class*=" icon-"]{margin-top:4px}.fuelux .btn-small{padding:2px 10px;font-size:11.9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fuelux .btn-small [class^="icon-"],.fuelux .btn-small [class*=" icon-"]{margin-top:0}.fuelux .btn-mini [class^="icon-"],.fuelux .btn-mini [class*=" icon-"]{margin-top:-1px}.fuelux .btn-mini{padding:0 6px;font-size:10.5px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fuelux .btn-block{display:block;width:100%;padding-right:0;padding-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.fuelux .btn-block+.btn-block{margin-top:5px}.fuelux input[type="submit"].btn-block,.fuelux input[type="reset"].btn-block,.fuelux input[type="button"].btn-block{width:100%}.fuelux .btn-primary.active,.fuelux .btn-warning.active,.fuelux .btn-danger.active,.fuelux .btn-success.active,.fuelux .btn-info.active,.fuelux .btn-inverse.active{color:rgba(255,255,255,0.75)}.fuelux .btn-primary{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#006dcc;*background-color:#04c;background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(top,#08c,#04c);background-image:-o-linear-gradient(top,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-image:-moz-linear-gradient(top,#08c,#04c);background-repeat:repeat-x;border-color:#04c #04c #002a80;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff0088cc',endColorstr='#ff0044cc',GradientType=0);filter:progid:dximagetransform.microsoft.gradient(enabled=false)}.fuelux .btn-primary:hover,.fuelux .btn-primary:focus,.fuelux .btn-primary:active,.fuelux .btn-primary.active,.fuelux .btn-primary.disabled,.fuelux .btn-primary[disabled]{color:#fff;background-color:#04c;*background-color:#003bb3}.fuelux .btn-primary:active,.fuelux .btn-primary.active{background-color:#039 \9}.fuelux .btn-warning{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#faa732;*background-color:#f89406;background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-repeat:repeat-x;border-color:#f89406 #f89406 #ad6704;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:dximagetransform.microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0);filter:progid:dximagetransform.microsoft.gradient(enabled=false)}.fuelux .btn-warning:hover,.fuelux .btn-warning:focus,.fuelux .btn-warning:active,.fuelux .btn-warning.active,.fuelux .btn-warning.disabled,.fuelux .btn-warning[disabled]{color:#fff;background-color:#f89406;*background-color:#df8505}.fuelux .btn-warning:active,.fuelux .btn-warning.active{background-color:#c67605 \9}.fuelux .btn-danger{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#da4f49;*background-color:#bd362f;background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#bd362f));background-image:-webkit-linear-gradient(top,#ee5f5b,#bd362f);background-image:-o-linear-gradient(top,#ee5f5b,#bd362f);background-image:linear-gradient(to bottom,#ee5f5b,#bd362f);background-image:-moz-linear-gradient(top,#ee5f5b,#bd362f);background-repeat:repeat-x;border-color:#bd362f #bd362f #802420;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffbd362f',GradientType=0);filter:progid:dximagetransform.microsoft.gradient(enabled=false)}.fuelux .btn-danger:hover,.fuelux .btn-danger:focus,.fuelux .btn-danger:active,.fuelux .btn-danger.active,.fuelux .btn-danger.disabled,.fuelux .btn-danger[disabled]{color:#fff;background-color:#bd362f;*background-color:#a9302a}.fuelux .btn-danger:active,.fuelux .btn-danger.active{background-color:#942a25 \9}.fuelux .btn-success{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#5bb75b;*background-color:#51a351;background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#51a351));background-image:-webkit-linear-gradient(top,#62c462,#51a351);background-image:-o-linear-gradient(top,#62c462,#51a351);background-image:linear-gradient(to bottom,#62c462,#51a351);background-image:-moz-linear-gradient(top,#62c462,#51a351);background-repeat:repeat-x;border-color:#51a351 #51a351 #387038;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff51a351',GradientType=0);filter:progid:dximagetransform.microsoft.gradient(enabled=false)}.fuelux .btn-success:hover,.fuelux .btn-success:focus,.fuelux .btn-success:active,.fuelux .btn-success.active,.fuelux .btn-success.disabled,.fuelux .btn-success[disabled]{color:#fff;background-color:#51a351;*background-color:#499249}.fuelux .btn-success:active,.fuelux .btn-success.active{background-color:#408140 \9}.fuelux .btn-info{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#49afcd;*background-color:#2f96b4;background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#2f96b4));background-image:-webkit-linear-gradient(top,#5bc0de,#2f96b4);background-image:-o-linear-gradient(top,#5bc0de,#2f96b4);background-image:linear-gradient(to bottom,#5bc0de,#2f96b4);background-image:-moz-linear-gradient(top,#5bc0de,#2f96b4);background-repeat:repeat-x;border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff2f96b4',GradientType=0);filter:progid:dximagetransform.microsoft.gradient(enabled=false)}.fuelux .btn-info:hover,.fuelux .btn-info:focus,.fuelux .btn-info:active,.fuelux .btn-info.active,.fuelux .btn-info.disabled,.fuelux .btn-info[disabled]{color:#fff;background-color:#2f96b4;*background-color:#2a85a0}.fuelux .btn-info:active,.fuelux .btn-info.active{background-color:#24748c \9}.fuelux .btn-inverse{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#363636;*background-color:#222;background-image:-webkit-gradient(linear,0 0,0 100%,from(#444),to(#222));background-image:-webkit-linear-gradient(top,#444,#222);background-image:-o-linear-gradient(top,#444,#222);background-image:linear-gradient(to bottom,#444,#222);background-image:-moz-linear-gradient(top,#444,#222);background-repeat:repeat-x;border-color:#222 #222 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff444444',endColorstr='#ff222222',GradientType=0);filter:progid:dximagetransform.microsoft.gradient(enabled=false)}.fuelux .btn-inverse:hover,.fuelux .btn-inverse:focus,.fuelux .btn-inverse:active,.fuelux .btn-inverse.active,.fuelux .btn-inverse.disabled,.fuelux .btn-inverse[disabled]{color:#fff;background-color:#222;*background-color:#151515}.fuelux .btn-inverse:active,.fuelux .btn-inverse.active{background-color:#080808 \9}.fuelux button.btn,.fuelux input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px}.fuelux button.btn::-moz-focus-inner,.fuelux input[type="submit"].btn::-moz-focus-inner{padding:0;border:0}.fuelux button.btn.btn-large,.fuelux input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px}.fuelux button.btn.btn-small,.fuelux input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px}.fuelux button.btn.btn-mini,.fuelux input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px}.fuelux .btn-link,.fuelux .btn-link:active,.fuelux .btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none}.fuelux .btn-link{color:#08c;cursor:pointer;border-color:transparent;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .btn-link:hover,.fuelux .btn-link:focus{color:#005580;text-decoration:underline;background-color:transparent}.fuelux .btn-link[disabled]:hover,.fuelux .btn-link[disabled]:focus{color:#333;text-decoration:none}.fuelux .btn-group{position:relative;display:inline-block;*display:inline;*margin-left:.3em;font-size:0;white-space:nowrap;vertical-align:middle;*zoom:1}.fuelux .btn-group:first-child{*margin-left:0}.fuelux .btn-group+.btn-group{margin-left:5px}.fuelux .btn-toolbar{margin-top:10px;margin-bottom:10px;font-size:0}.fuelux .btn-toolbar>.btn+.btn,.fuelux .btn-toolbar>.btn-group+.btn,.fuelux .btn-toolbar>.btn+.btn-group{margin-left:5px}.fuelux .btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .btn-group>.btn+.btn{margin-left:-1px}.fuelux .btn-group>.btn,.fuelux .btn-group>.dropdown-menu,.fuelux .btn-group>.popover{font-size:14px}.fuelux .btn-group>.btn-mini{font-size:10.5px}.fuelux .btn-group>.btn-small{font-size:11.9px}.fuelux .btn-group>.btn-large{font-size:17.5px}.fuelux .btn-group>.btn:first-child{margin-left:0;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.fuelux .btn-group>.btn:last-child,.fuelux .btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.fuelux .btn-group>.btn.large:first-child{margin-left:0;-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.fuelux .btn-group>.btn.large:last-child,.fuelux .btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.fuelux .btn-group>.btn:hover,.fuelux .btn-group>.btn:focus,.fuelux .btn-group>.btn:active,.fuelux .btn-group>.btn.active{z-index:2}.fuelux .btn-group .dropdown-toggle:active,.fuelux .btn-group.open .dropdown-toggle{outline:0}.fuelux .btn-group>.btn+.dropdown-toggle{*padding-top:5px;padding-right:8px;*padding-bottom:5px;padding-left:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 1px 0 0 rgba(255,255,255,0.125),inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05)}.fuelux .btn-group>.btn-mini+.dropdown-toggle{*padding-top:2px;padding-right:5px;*padding-bottom:2px;padding-left:5px}.fuelux .btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px}.fuelux .btn-group>.btn-large+.dropdown-toggle{*padding-top:7px;padding-right:12px;*padding-bottom:7px;padding-left:12px}.fuelux .btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05);box-shadow:inset 0 2px 4px rgba(0,0,0,0.15),0 1px 2px rgba(0,0,0,0.05)}.fuelux .btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6}.fuelux .btn-group.open .btn-primary.dropdown-toggle{background-color:#04c}.fuelux .btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406}.fuelux .btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f}.fuelux .btn-group.open .btn-success.dropdown-toggle{background-color:#51a351}.fuelux .btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4}.fuelux .btn-group.open .btn-inverse.dropdown-toggle{background-color:#222}.fuelux .btn .caret{margin-top:8px;margin-left:0}.fuelux .btn-large .caret{margin-top:6px}.fuelux .btn-large .caret{border-top-width:5px;border-right-width:5px;border-left-width:5px}.fuelux .btn-mini .caret,.fuelux .btn-small .caret{margin-top:8px}.fuelux .dropup .btn-large .caret{border-bottom-width:5px}.fuelux .btn-primary .caret,.fuelux .btn-warning .caret,.fuelux .btn-danger .caret,.fuelux .btn-info .caret,.fuelux .btn-success .caret,.fuelux .btn-inverse .caret{border-top-color:#fff;border-bottom-color:#fff}.fuelux .btn-group-vertical{display:inline-block;*display:inline;*zoom:1}.fuelux .btn-group-vertical>.btn{display:block;float:none;max-width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .btn-group-vertical>.btn+.btn{margin-top:-1px;margin-left:0}.fuelux .btn-group-vertical>.btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.fuelux .btn-group-vertical>.btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.fuelux .btn-group-vertical>.btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0}.fuelux .btn-group-vertical>.btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.fuelux .alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255,255,255,0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.fuelux .alert,.fuelux .alert h4{color:#c09853}.fuelux .alert h4{margin:0}.fuelux .alert .close{position:relative;top:-2px;right:-21px;line-height:20px}.fuelux .alert-success{color:#468847;background-color:#dff0d8;border-color:#d6e9c6}.fuelux .alert-success h4{color:#468847}.fuelux .alert-danger,.fuelux .alert-error{color:#b94a48;background-color:#f2dede;border-color:#eed3d7}.fuelux .alert-danger h4,.fuelux .alert-error h4{color:#b94a48}.fuelux .alert-info{color:#3a87ad;background-color:#d9edf7;border-color:#bce8f1}.fuelux .alert-info h4{color:#3a87ad}.fuelux .alert-block{padding-top:14px;padding-bottom:14px}.fuelux .alert-block>p,.fuelux .alert-block>ul{margin-bottom:0}.fuelux .alert-block p+p{margin-top:5px}.fuelux .nav{margin-bottom:20px;margin-left:0;list-style:none}.fuelux .nav>li>a{display:block}.fuelux .nav>li>a:hover,.fuelux .nav>li>a:focus{text-decoration:none;background-color:#eee}.fuelux .nav>li>a>img{max-width:none}.fuelux .nav>.pull-right{float:right}.fuelux .nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#999;text-shadow:0 1px 0 rgba(255,255,255,0.5);text-transform:uppercase}.fuelux .nav li+.nav-header{margin-top:9px}.fuelux .nav-list{padding-right:15px;padding-left:15px;margin-bottom:0}.fuelux .nav-list>li>a,.fuelux .nav-list .nav-header{margin-right:-15px;margin-left:-15px;text-shadow:0 1px 0 rgba(255,255,255,0.5)}.fuelux .nav-list>li>a{padding:3px 15px}.fuelux .nav-list>.active>a,.fuelux .nav-list>.active>a:hover,.fuelux .nav-list>.active>a:focus{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.2);background-color:#08c}.fuelux .nav-list [class^="icon-"],.fuelux .nav-list [class*=" icon-"]{margin-right:2px}.fuelux .nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #fff}.fuelux .nav-tabs,.fuelux .nav-pills{*zoom:1}.fuelux .nav-tabs:before,.fuelux .nav-pills:before,.fuelux .nav-tabs:after,.fuelux .nav-pills:after{display:table;line-height:0;content:""}.fuelux .nav-tabs:after,.fuelux .nav-pills:after{clear:both}.fuelux .nav-tabs>li,.fuelux .nav-pills>li{float:left}.fuelux .nav-tabs>li>a,.fuelux .nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px}.fuelux .nav-tabs{border-bottom:1px solid #ddd}.fuelux .nav-tabs>li{margin-bottom:-1px}.fuelux .nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0}.fuelux .nav-tabs>li>a:hover,.fuelux .nav-tabs>li>a:focus{border-color:#eee #eee #ddd}.fuelux .nav-tabs>.active>a,.fuelux .nav-tabs>.active>a:hover,.fuelux .nav-tabs>.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.fuelux .nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px}.fuelux .nav-pills>.active>a,.fuelux .nav-pills>.active>a:hover,.fuelux .nav-pills>.active>a:focus{color:#fff;background-color:#08c}.fuelux .nav-stacked>li{float:none}.fuelux .nav-stacked>li>a{margin-right:0}.fuelux .nav-tabs.nav-stacked{border-bottom:0}.fuelux .nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-topleft:4px}.fuelux .nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomright:4px;-moz-border-radius-bottomleft:4px}.fuelux .nav-tabs.nav-stacked>li>a:hover,.fuelux .nav-tabs.nav-stacked>li>a:focus{z-index:2;border-color:#ddd}.fuelux .nav-pills.nav-stacked>li>a{margin-bottom:3px}.fuelux .nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px}.fuelux .nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px}.fuelux .nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.fuelux .nav .dropdown-toggle .caret{margin-top:6px;border-top-color:#08c;border-bottom-color:#08c}.fuelux .nav .dropdown-toggle:hover .caret,.fuelux .nav .dropdown-toggle:focus .caret{border-top-color:#005580;border-bottom-color:#005580}.fuelux .nav-tabs .dropdown-toggle .caret{margin-top:8px}.fuelux .nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.fuelux .nav-tabs .active .dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.fuelux .nav>.dropdown.active>a:hover,.fuelux .nav>.dropdown.active>a:focus{cursor:pointer}.fuelux .nav-tabs .open .dropdown-toggle,.fuelux .nav-pills .open .dropdown-toggle,.fuelux .nav>li.dropdown.open.active>a:hover,.fuelux .nav>li.dropdown.open.active>a:focus{color:#fff;background-color:#999;border-color:#999}.fuelux .nav li.dropdown.open .caret,.fuelux .nav li.dropdown.open.active .caret,.fuelux .nav li.dropdown.open a:hover .caret,.fuelux .nav li.dropdown.open a:focus .caret{border-top-color:#fff;border-bottom-color:#fff;opacity:1;filter:alpha(opacity=100)}.fuelux .tabs-stacked .open>a:hover,.fuelux .tabs-stacked .open>a:focus{border-color:#999}.fuelux .tabbable{*zoom:1}.fuelux .tabbable:before,.fuelux .tabbable:after{display:table;line-height:0;content:""}.fuelux .tabbable:after{clear:both}.fuelux .tab-content{overflow:auto}.fuelux .tabs-below>.nav-tabs,.fuelux .tabs-right>.nav-tabs,.fuelux .tabs-left>.nav-tabs{border-bottom:0}.fuelux .tab-content>.tab-pane,.fuelux .pill-content>.pill-pane{display:none}.fuelux .tab-content>.active,.fuelux .pill-content>.active{display:block}.fuelux .tabs-below>.nav-tabs{border-top:1px solid #ddd}.fuelux .tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0}.fuelux .tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px}.fuelux .tabs-below>.nav-tabs>li>a:hover,.fuelux .tabs-below>.nav-tabs>li>a:focus{border-top-color:#ddd;border-bottom-color:transparent}.fuelux .tabs-below>.nav-tabs>.active>a,.fuelux .tabs-below>.nav-tabs>.active>a:hover,.fuelux .tabs-below>.nav-tabs>.active>a:focus{border-color:transparent #ddd #ddd #ddd}.fuelux .tabs-left>.nav-tabs>li,.fuelux .tabs-right>.nav-tabs>li{float:none}.fuelux .tabs-left>.nav-tabs>li>a,.fuelux .tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px}.fuelux .tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd}.fuelux .tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.fuelux .tabs-left>.nav-tabs>li>a:hover,.fuelux .tabs-left>.nav-tabs>li>a:focus{border-color:#eee #ddd #eee #eee}.fuelux .tabs-left>.nav-tabs .active>a,.fuelux .tabs-left>.nav-tabs .active>a:hover,.fuelux .tabs-left>.nav-tabs .active>a:focus{border-color:#ddd transparent #ddd #ddd;*border-right-color:#fff}.fuelux .tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd}.fuelux .tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.fuelux .tabs-right>.nav-tabs>li>a:hover,.fuelux .tabs-right>.nav-tabs>li>a:focus{border-color:#eee #eee #eee #ddd}.fuelux .tabs-right>.nav-tabs .active>a,.fuelux .tabs-right>.nav-tabs .active>a:hover,.fuelux .tabs-right>.nav-tabs .active>a:focus{border-color:#ddd #ddd #ddd transparent;*border-left-color:#fff}.fuelux .nav>.disabled>a{color:#999}.fuelux .nav>.disabled>a:hover,.fuelux .nav>.disabled>a:focus{text-decoration:none;cursor:default;background-color:transparent}.fuelux .navbar{*position:relative;*z-index:2;margin-bottom:20px;overflow:visible}.fuelux .navbar-inner{min-height:40px;padding-right:20px;padding-left:20px;background-color:#fafafa;background-image:-moz-linear-gradient(top,#fff,#f2f2f2);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fff),to(#f2f2f2));background-image:-webkit-linear-gradient(top,#fff,#f2f2f2);background-image:-o-linear-gradient(top,#fff,#f2f2f2);background-image:linear-gradient(to bottom,#fff,#f2f2f2);background-repeat:repeat-x;border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ffffffff',endColorstr='#fff2f2f2',GradientType=0);*zoom:1;-webkit-box-shadow:0 1px 4px rgba(0,0,0,0.065);-moz-box-shadow:0 1px 4px rgba(0,0,0,0.065);box-shadow:0 1px 4px rgba(0,0,0,0.065)}.fuelux .navbar-inner:before,.fuelux .navbar-inner:after{display:table;line-height:0;content:""}.fuelux .navbar-inner:after{clear:both}.fuelux .navbar .container{width:auto}.fuelux .nav-collapse.collapse{height:auto;overflow:visible}.fuelux .navbar .brand{display:block;float:left;padding:10px 20px 10px;margin-left:-20px;font-size:20px;font-weight:200;color:#777;text-shadow:0 1px 0 #fff}.fuelux .navbar .brand:hover,.fuelux .navbar .brand:focus{text-decoration:none}.fuelux .navbar-text{margin-bottom:0;line-height:40px;color:#777}.fuelux .navbar-link{color:#777}.fuelux .navbar-link:hover,.fuelux .navbar-link:focus{color:#333}.fuelux .navbar .divider-vertical{height:40px;margin:0 9px;border-right:1px solid #fff;border-left:1px solid #f2f2f2}.fuelux .navbar .btn,.fuelux .navbar .btn-group{margin-top:5px}.fuelux .navbar .btn-group .btn,.fuelux .navbar .input-prepend .btn,.fuelux .navbar .input-append .btn,.fuelux .navbar .input-prepend .btn-group,.fuelux .navbar .input-append .btn-group{margin-top:0}.fuelux .navbar-form{margin-bottom:0;*zoom:1}.fuelux .navbar-form:before,.fuelux .navbar-form:after{display:table;line-height:0;content:""}.fuelux .navbar-form:after{clear:both}.fuelux .navbar-form input,.fuelux .navbar-form select,.fuelux .navbar-form .radio,.fuelux .navbar-form .checkbox{margin-top:5px}.fuelux .navbar-form input,.fuelux .navbar-form select,.fuelux .navbar-form .btn{display:inline-block;margin-bottom:0}.fuelux .navbar-form input[type="image"],.fuelux .navbar-form input[type="checkbox"],.fuelux .navbar-form input[type="radio"]{margin-top:3px}.fuelux .navbar-form .input-append,.fuelux .navbar-form .input-prepend{margin-top:5px;white-space:nowrap}.fuelux .navbar-form .input-append input,.fuelux .navbar-form .input-prepend input{margin-top:0}.fuelux .navbar-search{position:relative;float:left;margin-top:5px;margin-bottom:0}.fuelux .navbar-search .search-query{padding:4px 14px;margin-bottom:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.fuelux .navbar-static-top{position:static;margin-bottom:0}.fuelux .navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .navbar-fixed-top,.fuelux .navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0}.fuelux .navbar-fixed-top .navbar-inner,.fuelux .navbar-static-top .navbar-inner{border-width:0 0 1px}.fuelux .navbar-fixed-bottom .navbar-inner{border-width:1px 0 0}.fuelux .navbar-fixed-top .navbar-inner,.fuelux .navbar-fixed-bottom .navbar-inner{padding-right:0;padding-left:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .navbar-static-top .container,.fuelux .navbar-fixed-top .container,.fuelux .navbar-fixed-bottom .container{width:940px}.fuelux .navbar-fixed-top{top:0}.fuelux .navbar-fixed-top .navbar-inner,.fuelux .navbar-static-top .navbar-inner{-webkit-box-shadow:0 1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 1px 10px rgba(0,0,0,0.1);box-shadow:0 1px 10px rgba(0,0,0,0.1)}.fuelux .navbar-fixed-bottom{bottom:0}.fuelux .navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:0 -1px 10px rgba(0,0,0,0.1);-moz-box-shadow:0 -1px 10px rgba(0,0,0,0.1);box-shadow:0 -1px 10px rgba(0,0,0,0.1)}.fuelux .navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0}.fuelux .navbar .nav.pull-right{float:right;margin-right:0}.fuelux .navbar .nav>li{float:left}.fuelux .navbar .nav>li>a{float:none;padding:10px 15px 10px;color:#777;text-decoration:none;text-shadow:0 1px 0 #fff}.fuelux .navbar .nav .dropdown-toggle .caret{margin-top:8px}.fuelux .navbar .nav>li>a:focus,.fuelux .navbar .nav>li>a:hover{color:#333;text-decoration:none;background-color:transparent}.fuelux .navbar .nav>.active>a,.fuelux .navbar .nav>.active>a:hover,.fuelux .navbar .nav>.active>a:focus{color:#555;text-decoration:none;background-color:#e5e5e5;-webkit-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);-moz-box-shadow:inset 0 3px 8px rgba(0,0,0,0.125);box-shadow:inset 0 3px 8px rgba(0,0,0,0.125)}.fuelux .navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-right:5px;margin-left:5px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#ededed;*background-color:#e5e5e5;background-image:-webkit-gradient(linear,0 0,0 100%,from(#f2f2f2),to(#e5e5e5));background-image:-webkit-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:-o-linear-gradient(top,#f2f2f2,#e5e5e5);background-image:linear-gradient(to bottom,#f2f2f2,#e5e5e5);background-image:-moz-linear-gradient(top,#f2f2f2,#e5e5e5);background-repeat:repeat-x;border-color:#e5e5e5 #e5e5e5 #bfbfbf;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:dximagetransform.microsoft.gradient(startColorstr='#fff2f2f2',endColorstr='#ffe5e5e5',GradientType=0);filter:progid:dximagetransform.microsoft.gradient(enabled=false);-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.1),0 1px 0 rgba(255,255,255,0.075)}.fuelux .navbar .btn-navbar:hover,.fuelux .navbar .btn-navbar:focus,.fuelux .navbar .btn-navbar:active,.fuelux .navbar .btn-navbar.active,.fuelux .navbar .btn-navbar.disabled,.fuelux .navbar .btn-navbar[disabled]{color:#fff;background-color:#e5e5e5;*background-color:#d9d9d9}.fuelux .navbar .btn-navbar:active,.fuelux .navbar .btn-navbar.active{background-color:#ccc \9}.fuelux .navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.25);-moz-box-shadow:0 1px 0 rgba(0,0,0,0.25);box-shadow:0 1px 0 rgba(0,0,0,0.25)}.fuelux .btn-navbar .icon-bar+.icon-bar{margin-top:3px}.fuelux .navbar .nav>li>.dropdown-menu:before{position:absolute;top:-7px;left:9px;display:inline-block;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-left:7px solid transparent;border-bottom-color:rgba(0,0,0,0.2);content:''}.fuelux .navbar .nav>li>.dropdown-menu:after{position:absolute;top:-6px;left:10px;display:inline-block;border-right:6px solid transparent;border-bottom:6px solid #fff;border-left:6px solid transparent;content:''}.fuelux .navbar-fixed-bottom .nav>li>.dropdown-menu:before{top:auto;bottom:-7px;border-top:7px solid #ccc;border-bottom:0;border-top-color:rgba(0,0,0,0.2)}.fuelux .navbar-fixed-bottom .nav>li>.dropdown-menu:after{top:auto;bottom:-6px;border-top:6px solid #fff;border-bottom:0}.fuelux .navbar .nav li.dropdown>a:hover .caret,.fuelux .navbar .nav li.dropdown>a:focus .caret{border-top-color:#333;border-bottom-color:#333}.fuelux .navbar .nav li.dropdown.open>.dropdown-toggle,.fuelux .navbar .nav li.dropdown.active>.dropdown-toggle,.fuelux .navbar .nav li.dropdown.open.active>.dropdown-toggle{color:#555;background-color:#e5e5e5}.fuelux .navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#777;border-bottom-color:#777}.fuelux .navbar .nav li.dropdown.open>.dropdown-toggle .caret,.fuelux .navbar .nav li.dropdown.active>.dropdown-toggle .caret,.fuelux .navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#555;border-bottom-color:#555}.fuelux .navbar .pull-right>li>.dropdown-menu,.fuelux .navbar .nav>li>.dropdown-menu.pull-right{right:0;left:auto}.fuelux .navbar .pull-right>li>.dropdown-menu:before,.fuelux .navbar .nav>li>.dropdown-menu.pull-right:before{right:12px;left:auto}.fuelux .navbar .pull-right>li>.dropdown-menu:after,.fuelux .navbar .nav>li>.dropdown-menu.pull-right:after{right:13px;left:auto}.fuelux .navbar .pull-right>li>.dropdown-menu .dropdown-menu,.fuelux .navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{right:100%;left:auto;margin-right:-1px;margin-left:0;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px}.fuelux .navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top,#222,#111);background-image:-webkit-gradient(linear,0 0,0 100%,from(#222),to(#111));background-image:-webkit-linear-gradient(top,#222,#111);background-image:-o-linear-gradient(top,#222,#111);background-image:linear-gradient(to bottom,#222,#111);background-repeat:repeat-x;border-color:#252525;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff222222',endColorstr='#ff111111',GradientType=0)}.fuelux .navbar-inverse .brand,.fuelux .navbar-inverse .nav>li>a{color:#999;text-shadow:0 -1px 0 rgba(0,0,0,0.25)}.fuelux .navbar-inverse .brand:hover,.fuelux .navbar-inverse .nav>li>a:hover,.fuelux .navbar-inverse .brand:focus,.fuelux .navbar-inverse .nav>li>a:focus{color:#fff}.fuelux .navbar-inverse .brand{color:#999}.fuelux .navbar-inverse .navbar-text{color:#999}.fuelux .navbar-inverse .nav>li>a:focus,.fuelux .navbar-inverse .nav>li>a:hover{color:#fff;background-color:transparent}.fuelux .navbar-inverse .nav .active>a,.fuelux .navbar-inverse .nav .active>a:hover,.fuelux .navbar-inverse .nav .active>a:focus{color:#fff;background-color:#111}.fuelux .navbar-inverse .navbar-link{color:#999}.fuelux .navbar-inverse .navbar-link:hover,.fuelux .navbar-inverse .navbar-link:focus{color:#fff}.fuelux .navbar-inverse .divider-vertical{border-right-color:#222;border-left-color:#111}.fuelux .navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.fuelux .navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.fuelux .navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{color:#fff;background-color:#111}.fuelux .navbar-inverse .nav li.dropdown>a:hover .caret,.fuelux .navbar-inverse .nav li.dropdown>a:focus .caret{border-top-color:#fff;border-bottom-color:#fff}.fuelux .navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#999;border-bottom-color:#999}.fuelux .navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.fuelux .navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.fuelux .navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff}.fuelux .navbar-inverse .navbar-search .search-query{color:#fff;background-color:#515151;border-color:#111;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1),0 1px 0 rgba(255,255,255,0.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none}.fuelux .navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#ccc}.fuelux .navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#ccc}.fuelux .navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#ccc}.fuelux .navbar-inverse .navbar-search .search-query:focus,.fuelux .navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#333;text-shadow:0 1px 0 #fff;background-color:#fff;border:0;outline:0;-webkit-box-shadow:0 0 3px rgba(0,0,0,0.15);-moz-box-shadow:0 0 3px rgba(0,0,0,0.15);box-shadow:0 0 3px rgba(0,0,0,0.15)}.fuelux .navbar-inverse .btn-navbar{color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e0e0e;*background-color:#040404;background-image:-webkit-gradient(linear,0 0,0 100%,from(#151515),to(#040404));background-image:-webkit-linear-gradient(top,#151515,#040404);background-image:-o-linear-gradient(top,#151515,#040404);background-image:linear-gradient(to bottom,#151515,#040404);background-image:-moz-linear-gradient(top,#151515,#040404);background-repeat:repeat-x;border-color:#040404 #040404 #000;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff151515',endColorstr='#ff040404',GradientType=0);filter:progid:dximagetransform.microsoft.gradient(enabled=false)}.fuelux .navbar-inverse .btn-navbar:hover,.fuelux .navbar-inverse .btn-navbar:focus,.fuelux .navbar-inverse .btn-navbar:active,.fuelux .navbar-inverse .btn-navbar.active,.fuelux .navbar-inverse .btn-navbar.disabled,.fuelux .navbar-inverse .btn-navbar[disabled]{color:#fff;background-color:#040404;*background-color:#000}.fuelux .navbar-inverse .btn-navbar:active,.fuelux .navbar-inverse .btn-navbar.active{background-color:#000 \9}.fuelux .breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.fuelux .breadcrumb>li{display:inline-block;*display:inline;text-shadow:0 1px 0 #fff;*zoom:1}.fuelux .breadcrumb>li>.divider{padding:0 5px;color:#ccc}.fuelux .breadcrumb>.active{color:#999}.fuelux .pagination{margin:20px 0}.fuelux .pagination ul{display:inline-block;*display:inline;margin-bottom:0;margin-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*zoom:1;-webkit-box-shadow:0 1px 2px rgba(0,0,0,0.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,0.05);box-shadow:0 1px 2px rgba(0,0,0,0.05)}.fuelux .pagination ul>li{display:inline}.fuelux .pagination ul>li>a,.fuelux .pagination ul>li>span{float:left;padding:4px 12px;line-height:20px;text-decoration:none;background-color:#fff;border:1px solid #ddd;border-left-width:0}.fuelux .pagination ul>li>a:hover,.fuelux .pagination ul>li>a:focus,.fuelux .pagination ul>.active>a,.fuelux .pagination ul>.active>span{background-color:#f5f5f5}.fuelux .pagination ul>.active>a,.fuelux .pagination ul>.active>span{color:#999;cursor:default}.fuelux .pagination ul>.disabled>span,.fuelux .pagination ul>.disabled>a,.fuelux .pagination ul>.disabled>a:hover,.fuelux .pagination ul>.disabled>a:focus{color:#999;cursor:default;background-color:transparent}.fuelux .pagination ul>li:first-child>a,.fuelux .pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-bottomleft:4px;-moz-border-radius-topleft:4px}.fuelux .pagination ul>li:last-child>a,.fuelux .pagination ul>li:last-child>span{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-topright:4px;-moz-border-radius-bottomright:4px}.fuelux .pagination-centered{text-align:center}.fuelux .pagination-right{text-align:right}.fuelux .pagination-large ul>li>a,.fuelux .pagination-large ul>li>span{padding:11px 19px;font-size:17.5px}.fuelux .pagination-large ul>li:first-child>a,.fuelux .pagination-large ul>li:first-child>span{-webkit-border-bottom-left-radius:6px;border-bottom-left-radius:6px;-webkit-border-top-left-radius:6px;border-top-left-radius:6px;-moz-border-radius-bottomleft:6px;-moz-border-radius-topleft:6px}.fuelux .pagination-large ul>li:last-child>a,.fuelux .pagination-large ul>li:last-child>span{-webkit-border-top-right-radius:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;border-bottom-right-radius:6px;-moz-border-radius-topright:6px;-moz-border-radius-bottomright:6px}.fuelux .pagination-mini ul>li:first-child>a,.fuelux .pagination-small ul>li:first-child>a,.fuelux .pagination-mini ul>li:first-child>span,.fuelux .pagination-small ul>li:first-child>span{-webkit-border-bottom-left-radius:3px;border-bottom-left-radius:3px;-webkit-border-top-left-radius:3px;border-top-left-radius:3px;-moz-border-radius-bottomleft:3px;-moz-border-radius-topleft:3px}.fuelux .pagination-mini ul>li:last-child>a,.fuelux .pagination-small ul>li:last-child>a,.fuelux .pagination-mini ul>li:last-child>span,.fuelux .pagination-small ul>li:last-child>span{-webkit-border-top-right-radius:3px;border-top-right-radius:3px;-webkit-border-bottom-right-radius:3px;border-bottom-right-radius:3px;-moz-border-radius-topright:3px;-moz-border-radius-bottomright:3px}.fuelux .pagination-small ul>li>a,.fuelux .pagination-small ul>li>span{padding:2px 10px;font-size:11.9px}.fuelux .pagination-mini ul>li>a,.fuelux .pagination-mini ul>li>span{padding:0 6px;font-size:10.5px}.fuelux .pager{margin:20px 0;text-align:center;list-style:none;*zoom:1}.fuelux .pager:before,.fuelux .pager:after{display:table;line-height:0;content:""}.fuelux .pager:after{clear:both}.fuelux .pager li{display:inline}.fuelux .pager li>a,.fuelux .pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px}.fuelux .pager li>a:hover,.fuelux .pager li>a:focus{text-decoration:none;background-color:#f5f5f5}.fuelux .pager .next>a,.fuelux .pager .next>span{float:right}.fuelux .pager .previous>a,.fuelux .pager .previous>span{float:left}.fuelux .pager .disabled>a,.fuelux .pager .disabled>a:hover,.fuelux .pager .disabled>a:focus,.fuelux .pager .disabled>span{color:#999;cursor:default;background-color:#fff}.fuelux .modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.fuelux .modal-backdrop.fade{opacity:0}.fuelux .modal-backdrop,.fuelux .modal-backdrop.fade.in{opacity:.8;filter:alpha(opacity=80)}.fuelux .modal{position:fixed;top:10%;left:50%;z-index:1050;width:560px;margin-left:-280px;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;outline:0;-webkit-box-shadow:0 3px 7px rgba(0,0,0,0.3);-moz-box-shadow:0 3px 7px rgba(0,0,0,0.3);box-shadow:0 3px 7px rgba(0,0,0,0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box}.fuelux .modal.fade{top:-25%;-webkit-transition:opacity .3s linear,top .3s ease-out;-moz-transition:opacity .3s linear,top .3s ease-out;-o-transition:opacity .3s linear,top .3s ease-out;transition:opacity .3s linear,top .3s ease-out}.fuelux .modal.fade.in{top:10%}.fuelux .modal-header{padding:9px 15px;border-bottom:1px solid #eee}.fuelux .modal-header .close{margin-top:2px}.fuelux .modal-header h3{margin:0;line-height:30px}.fuelux .modal-body{position:relative;max-height:400px;padding:15px;overflow-y:auto}.fuelux .modal-form{margin-bottom:0}.fuelux .modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;*zoom:1;-webkit-box-shadow:inset 0 1px 0 #fff;-moz-box-shadow:inset 0 1px 0 #fff;box-shadow:inset 0 1px 0 #fff}.fuelux .modal-footer:before,.fuelux .modal-footer:after{display:table;line-height:0;content:""}.fuelux .modal-footer:after{clear:both}.fuelux .modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.fuelux .modal-footer .btn-group .btn+.btn{margin-left:-1px}.fuelux .modal-footer .btn-block+.btn-block{margin-left:0}.fuelux .tooltip{position:absolute;z-index:1030;display:block;font-size:11px;line-height:1.4;opacity:0;filter:alpha(opacity=0);visibility:visible}.fuelux .tooltip.in{opacity:.8;filter:alpha(opacity=80)}.fuelux .tooltip.top{padding:5px 0;margin-top:-3px}.fuelux .tooltip.right{padding:0 5px;margin-left:3px}.fuelux .tooltip.bottom{padding:5px 0;margin-top:3px}.fuelux .tooltip.left{padding:0 5px;margin-left:-3px}.fuelux .tooltip-inner{max-width:200px;padding:8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.fuelux .tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.fuelux .tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-top-color:#000;border-width:5px 5px 0}.fuelux .tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-right-color:#000;border-width:5px 5px 5px 0}.fuelux .tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-left-color:#000;border-width:5px 0 5px 5px}.fuelux .tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-bottom-color:#000;border-width:0 5px 5px}.fuelux .popover{position:absolute;top:0;left:0;z-index:1010;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,0.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,0.2);box-shadow:0 5px 10px rgba(0,0,0,0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box}.fuelux .popover.top{margin-top:-10px}.fuelux .popover.right{margin-left:10px}.fuelux .popover.bottom{margin-top:10px}.fuelux .popover.left{margin-left:-10px}.fuelux .popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0}.fuelux .popover-title:empty{display:none}.fuelux .popover-content{padding:9px 14px}.fuelux .popover .arrow,.fuelux .popover .arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.fuelux .popover .arrow{border-width:11px}.fuelux .popover .arrow:after{border-width:10px;content:""}.fuelux .popover.top .arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,0.25);border-bottom-width:0}.fuelux .popover.top .arrow:after{bottom:1px;margin-left:-10px;border-top-color:#fff;border-bottom-width:0}.fuelux .popover.right .arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,0.25);border-left-width:0}.fuelux .popover.right .arrow:after{bottom:-10px;left:1px;border-right-color:#fff;border-left-width:0}.fuelux .popover.bottom .arrow{top:-11px;left:50%;margin-left:-11px;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,0.25);border-top-width:0}.fuelux .popover.bottom .arrow:after{top:1px;margin-left:-10px;border-bottom-color:#fff;border-top-width:0}.fuelux .popover.left .arrow{top:50%;right:-11px;margin-top:-11px;border-left-color:#999;border-left-color:rgba(0,0,0,0.25);border-right-width:0}.fuelux .popover.left .arrow:after{right:1px;bottom:-10px;border-left-color:#fff;border-right-width:0}.fuelux .thumbnails{margin-left:-20px;list-style:none;*zoom:1}.fuelux .thumbnails:before,.fuelux .thumbnails:after{display:table;line-height:0;content:""}.fuelux .thumbnails:after{clear:both}.fuelux .row-fluid .thumbnails{margin-left:0}.fuelux .thumbnails>li{float:left;margin-bottom:20px;margin-left:20px}.fuelux .thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0,0,0,0.055);-moz-box-shadow:0 1px 3px rgba(0,0,0,0.055);box-shadow:0 1px 3px rgba(0,0,0,0.055);-webkit-transition:all .2s ease-in-out;-moz-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.fuelux a.thumbnail:hover,.fuelux a.thumbnail:focus{border-color:#08c;-webkit-box-shadow:0 1px 4px rgba(0,105,214,0.25);-moz-box-shadow:0 1px 4px rgba(0,105,214,0.25);box-shadow:0 1px 4px rgba(0,105,214,0.25)}.fuelux .thumbnail>img{display:block;max-width:100%;margin-right:auto;margin-left:auto}.fuelux .thumbnail .caption{padding:9px;color:#555}.fuelux .media,.fuelux .media-body{overflow:hidden;*overflow:visible;zoom:1}.fuelux .media,.fuelux .media .media{margin-top:15px}.fuelux .media:first-child{margin-top:0}.fuelux .media-object{display:block}.fuelux .media-heading{margin:0 0 5px}.fuelux .media>.pull-left{margin-right:10px}.fuelux .media>.pull-right{margin-left:10px}.fuelux .media-list{margin-left:0;list-style:none}.fuelux .label,.fuelux .badge{display:inline-block;padding:2px 4px;font-size:11.844px;font-weight:bold;line-height:14px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);white-space:nowrap;vertical-align:baseline;background-color:#999}.fuelux .label{-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fuelux .badge{padding-right:9px;padding-left:9px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px}.fuelux .label:empty,.fuelux .badge:empty{display:none}.fuelux a.label:hover,.fuelux a.label:focus,.fuelux a.badge:hover,.fuelux a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}.fuelux .label-important,.fuelux .badge-important{background-color:#b94a48}.fuelux .label-important[href],.fuelux .badge-important[href]{background-color:#953b39}.fuelux .label-warning,.fuelux .badge-warning{background-color:#f89406}.fuelux .label-warning[href],.fuelux .badge-warning[href]{background-color:#c67605}.fuelux .label-success,.fuelux .badge-success{background-color:#468847}.fuelux .label-success[href],.fuelux .badge-success[href]{background-color:#356635}.fuelux .label-info,.fuelux .badge-info{background-color:#3a87ad}.fuelux .label-info[href],.fuelux .badge-info[href]{background-color:#2d6987}.fuelux .label-inverse,.fuelux .badge-inverse{background-color:#333}.fuelux .label-inverse[href],.fuelux .badge-inverse[href]{background-color:#1a1a1a}.fuelux .btn .label,.fuelux .btn .badge{position:relative;top:-1px}.fuelux .btn-mini .label,.fuelux .btn-mini .badge{top:0}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:0 0}to{background-position:40px 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.fuelux .progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f7f7f7;background-image:-moz-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f5f5f5),to(#f9f9f9));background-image:-webkit-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:-o-linear-gradient(top,#f5f5f5,#f9f9f9);background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);background-repeat:repeat-x;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#fff5f5f5',endColorstr='#fff9f9f9',GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);-moz-box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);box-shadow:inset 0 1px 2px rgba(0,0,0,0.1)}.fuelux .progress .bar{float:left;width:0;height:100%;font-size:12px;color:#fff;text-align:center;text-shadow:0 -1px 0 rgba(0,0,0,0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top,#149bdf,#0480be);background-image:-webkit-gradient(linear,0 0,0 100%,from(#149bdf),to(#0480be));background-image:-webkit-linear-gradient(top,#149bdf,#0480be);background-image:-o-linear-gradient(top,#149bdf,#0480be);background-image:linear-gradient(to bottom,#149bdf,#0480be);background-repeat:repeat-x;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff149bdf',endColorstr='#ff0480be',GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width .6s ease;-moz-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.fuelux .progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);-moz-box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15);box-shadow:inset 1px 0 0 rgba(0,0,0,0.15),inset 0 -1px 0 rgba(0,0,0,0.15)}.fuelux .progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px}.fuelux .progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.fuelux .progress-danger .bar,.fuelux .progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top,#ee5f5b,#c43c35);background-image:-webkit-gradient(linear,0 0,0 100%,from(#ee5f5b),to(#c43c35));background-image:-webkit-linear-gradient(top,#ee5f5b,#c43c35);background-image:-o-linear-gradient(top,#ee5f5b,#c43c35);background-image:linear-gradient(to bottom,#ee5f5b,#c43c35);background-repeat:repeat-x;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ffee5f5b',endColorstr='#ffc43c35',GradientType=0)}.fuelux .progress-danger.progress-striped .bar,.fuelux .progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.fuelux .progress-success .bar,.fuelux .progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top,#62c462,#57a957);background-image:-webkit-gradient(linear,0 0,0 100%,from(#62c462),to(#57a957));background-image:-webkit-linear-gradient(top,#62c462,#57a957);background-image:-o-linear-gradient(top,#62c462,#57a957);background-image:linear-gradient(to bottom,#62c462,#57a957);background-repeat:repeat-x;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff62c462',endColorstr='#ff57a957',GradientType=0)}.fuelux .progress-success.progress-striped .bar,.fuelux .progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.fuelux .progress-info .bar,.fuelux .progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top,#5bc0de,#339bb9);background-image:-webkit-gradient(linear,0 0,0 100%,from(#5bc0de),to(#339bb9));background-image:-webkit-linear-gradient(top,#5bc0de,#339bb9);background-image:-o-linear-gradient(top,#5bc0de,#339bb9);background-image:linear-gradient(to bottom,#5bc0de,#339bb9);background-repeat:repeat-x;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#ff5bc0de',endColorstr='#ff339bb9',GradientType=0)}.fuelux .progress-info.progress-striped .bar,.fuelux .progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.fuelux .progress-warning .bar,.fuelux .progress .bar-warning{background-color:#faa732;background-image:-moz-linear-gradient(top,#fbb450,#f89406);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fbb450),to(#f89406));background-image:-webkit-linear-gradient(top,#fbb450,#f89406);background-image:-o-linear-gradient(top,#fbb450,#f89406);background-image:linear-gradient(to bottom,#fbb450,#f89406);background-repeat:repeat-x;filter:progid:dximagetransform.microsoft.gradient(startColorstr='#fffbb450',endColorstr='#fff89406',GradientType=0)}.fuelux .progress-warning.progress-striped .bar,.fuelux .progress-striped .bar-warning{background-color:#fbb450;background-image:-webkit-gradient(linear,0 100%,100% 0,color-stop(0.25,rgba(255,255,255,0.15)),color-stop(0.25,transparent),color-stop(0.5,transparent),color-stop(0.5,rgba(255,255,255,0.15)),color-stop(0.75,rgba(255,255,255,0.15)),color-stop(0.75,transparent),to(transparent));background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-moz-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent)}.fuelux .accordion{margin-bottom:20px}.fuelux .accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.fuelux .accordion-heading{border-bottom:0}.fuelux .accordion-heading .accordion-toggle{display:block;padding:8px 15px}.fuelux .accordion-toggle{cursor:pointer}.fuelux .accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5}.fuelux .carousel{position:relative;margin-bottom:20px;line-height:1}.fuelux .carousel-inner{position:relative;width:100%;overflow:hidden}.fuelux .carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-moz-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.fuelux .carousel-inner>.item>img,.fuelux .carousel-inner>.item>a>img{display:block;line-height:1}.fuelux .carousel-inner>.active,.fuelux .carousel-inner>.next,.fuelux .carousel-inner>.prev{display:block}.fuelux .carousel-inner>.active{left:0}.fuelux .carousel-inner>.next,.fuelux .carousel-inner>.prev{position:absolute;top:0;width:100%}.fuelux .carousel-inner>.next{left:100%}.fuelux .carousel-inner>.prev{left:-100%}.fuelux .carousel-inner>.next.left,.fuelux .carousel-inner>.prev.right{left:0}.fuelux .carousel-inner>.active.left{left:-100%}.fuelux .carousel-inner>.active.right{left:100%}.fuelux .carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#fff;text-align:center;background:#222;border:3px solid #fff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:.5;filter:alpha(opacity=50)}.fuelux .carousel-control.right{right:15px;left:auto}.fuelux .carousel-control:hover,.fuelux .carousel-control:focus{color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.fuelux .carousel-indicators{position:absolute;top:15px;right:15px;z-index:5;margin:0;list-style:none}.fuelux .carousel-indicators li{display:block;float:left;width:10px;height:10px;margin-left:5px;text-indent:-999px;background-color:#ccc;background-color:rgba(255,255,255,0.25);border-radius:5px}.fuelux .carousel-indicators .active{background-color:#fff}.fuelux .carousel-caption{position:absolute;right:0;bottom:0;left:0;padding:15px;background:#333;background:rgba(0,0,0,0.75)}.fuelux .carousel-caption h4,.fuelux .carousel-caption p{line-height:20px;color:#fff}.fuelux .carousel-caption h4{margin:0 0 5px}.fuelux .carousel-caption p{margin-bottom:0}.fuelux .hero-unit{padding:60px;margin-bottom:30px;font-size:18px;font-weight:200;line-height:30px;color:inherit;background-color:#eee;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.fuelux .hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;letter-spacing:-1px;color:inherit}.fuelux .hero-unit li{line-height:30px}.fuelux .pull-right{float:right}.fuelux .pull-left{float:left}.fuelux .hide{display:none}.fuelux .show{display:block}.fuelux .invisible{visibility:hidden}.fuelux .affix{position:fixed}.fuelux .form-inline .checkbox-custom{padding-left:20px}.fuelux .form-inline .checkbox-custom .checkbox{padding-left:16px}.fuelux .checkbox-custom input[type=checkbox]{position:relative;top:-99999px}.fuelux .checkbox-custom i{width:16px;height:16px;padding-left:16px;margin-right:4px;margin-left:-20px;background-image:url(../img/form.png);background-position:0 1px;background-repeat:no-repeat}.fuelux .checkbox-custom i.checked{background-position:-48px 1px}.fuelux .checkbox-custom i.disabled{background-position:-64px 1px}.fuelux .checkbox-custom i.disabled.checked{background-position:-80px 1px}.fuelux .checkbox-custom:hover i{background-position:-16px 1px}.fuelux .checkbox-custom:hover i.checked{background-position:-32px 1px}.fuelux .checkbox-custom:hover i.disabled{background-position:-64px 1px}.fuelux .checkbox-custom:hover i.disabled.checked{background-position:-80px 1px}.fuelux .combobox{display:inline-block}.fuelux .combobox a{font-size:14px}.fuelux .combobox button.btn{border-radius:0 4px 4px 0}.fuelux .datagrid thead{background-color:#f9f9f9}.fuelux .datagrid thead .datagrid-header-title{float:left;margin-right:10px;font-size:14px;font-weight:normal;line-height:28px}.fuelux .datagrid thead .datagrid-header-left{float:left}.fuelux .datagrid thead .datagrid-header-right{float:right}.fuelux .datagrid thead .datagrid-header-right .search,.fuelux .datagrid thead .datagrid-header-left .search,.fuelux .datagrid thead .datagrid-header-right .filter,.fuelux .datagrid thead .datagrid-header-left .filter{margin-bottom:0;margin-left:8px}.fuelux .datagrid thead .datagrid-header-right .search .dropdown-menu,.fuelux .datagrid thead .datagrid-header-left .search .dropdown-menu,.fuelux .datagrid thead .datagrid-header-right .filter .dropdown-menu,.fuelux .datagrid thead .datagrid-header-left .filter .dropdown-menu{top:auto;left:auto}.fuelux .datagrid thead .sorted{padding-right:30px;color:#333;text-shadow:'none';background-color:#f1f1f1;background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9f9f9),to(#e5e5e5));background-image:-webkit-linear-gradient(top,#f9f9f9,#e5e5e5);background-image:-o-linear-gradient(top,#f9f9f9,#e5e5e5);background-image:-moz-linear-gradient(top,#f9f9f9,#e5e5e5);background-image:linear-gradient(to bottom,#f9f9f9,#e5e5e5);background-repeat:repeat-x;border-color:#e5e5e5 #e5e5e5 #bebebe;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:dximagetransform.microsoft.gradient(startColorstr='#fff9f9f9',endColorstr='#ffe5e5e5',GradientType=0)}.fuelux .datagrid thead .sorted i{float:right;margin-top:2px;margin-right:-22px}.fuelux .datagrid thead .sortable{cursor:pointer}.fuelux .datagrid thead .sortable:hover{color:#333;text-shadow:'none';background-color:#f1f1f1;background-image:-moz-linear-gradient(top,#f9f9f9,#e5e5e5);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f9f9f9),to(#e5e5e5));background-image:-webkit-linear-gradient(top,#f9f9f9,#e5e5e5);background-image:-o-linear-gradient(top,#f9f9f9,#e5e5e5);background-image:linear-gradient(to bottom,#f9f9f9,#e5e5e5);background-repeat:repeat-x;border-color:#e5e5e5 #e5e5e5 #bebebe;border-color:rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);filter:progid:dximagetransform.microsoft.gradient(startColorstr='#fff9f9f9',endColorstr='#ffe5e5e5',GradientType=0)}.fuelux .datagrid tfoot{background-color:#f9f9f9}.fuelux .datagrid tfoot .datagrid-footer-left{float:left}.fuelux .datagrid tfoot .datagrid-footer-left .grid-controls{margin-top:7px}.fuelux .datagrid tfoot .datagrid-footer-left .grid-controls select{width:60px;margin:0 5px 1px}.fuelux .datagrid tfoot .datagrid-footer-left .grid-controls .grid-pagesize{display:inline-block;margin-bottom:5px;vertical-align:middle}.fuelux .datagrid tfoot .datagrid-footer-left .grid-controls .grid-pagesize .dropdown-menu{top:auto;left:auto}.fuelux .datagrid tfoot .datagrid-footer-left .grid-controls span{font-weight:normal}.fuelux .datagrid tfoot .datagrid-footer-right{float:right}.fuelux .datagrid tfoot .datagrid-footer-right .grid-pager>span{position:relative;top:8px;font-weight:normal}.fuelux .datagrid tfoot .datagrid-footer-right .grid-pager .dropdown-menu{min-width:50px}.fuelux .datagrid tfoot .datagrid-footer-right .grid-pager .combobox{position:relative;top:-2px;display:inline-block;margin-bottom:4px;vertical-align:baseline}.fuelux .datagrid tfoot .datagrid-footer-right .grid-pager>button{position:relative;top:7px}.fuelux .datagrid-stretch-header{margin-bottom:0;border-bottom:0;-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-moz-border-radius-bottomright:0;-moz-border-radius-bottomleft:0}.fuelux .datagrid-stretch-header thead:last-child tr:last-child>th:first-child,.fuelux .datagrid-stretch-header thead:last-child tr:last-child>th:last-child{-webkit-border-bottom-right-radius:0;border-bottom-right-radius:0;-webkit-border-bottom-left-radius:0;border-bottom-left-radius:0;-moz-border-radius-bottomright:0;-moz-border-radius-bottomleft:0}.fuelux .datagrid-stretch-wrapper{overflow:auto;border:1px solid #ddd}.fuelux .datagrid-stretch-wrapper .datagrid{margin-bottom:0;border:0;border-collapse:collapse;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .datagrid-stretch-wrapper .datagrid td,.fuelux .datagrid-stretch-wrapper .datagrid th{border-bottom:1px solid #ddd}.fuelux .datagrid-stretch-wrapper .datagrid td:first-child,.fuelux .datagrid-stretch-wrapper .datagrid th:first-child{border-left:none;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.fuelux .datagrid-stretch-footer{border-top:0;-webkit-border-top-right-radius:0;border-top-right-radius:0;-webkit-border-top-left-radius:0;border-top-left-radius:0;-moz-border-radius-topright:0;-moz-border-radius-topleft:0}.fuelux .datagrid-stretch-footer th{border-top:0}.fuelux .pillbox{padding:3px}.fuelux .pillbox ul{display:inline-block;margin:0}.fuelux .pillbox li{display:inline-block;float:left;padding:1px 4px 2px;margin:2px;font-size:11.844px;font-weight:bold;line-height:21px;color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,0.25);vertical-align:baseline;cursor:pointer;background-color:#999;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px}.fuelux .pillbox li:after{position:relative;top:-2px;float:right;padding-left:4px;font-size:20px;font-weight:bold;line-height:20px;color:#000;text-shadow:0 1px 0 #fff;content:" \00D7";opacity:.2;filter:alpha(opacity=20)}.fuelux .pillbox li:hover:after{opacity:.4;filter:alpha(opacity=40)}.fuelux .pillbox li.status-important{background-color:#b94a48}.fuelux .pillbox li.status-warning{background-color:#f89406}.fuelux .pillbox li.status-success{background-color:#468847}.fuelux .pillbox li.status-info{background-color:#3a87ad}.fuelux .radio-custom input[type=radio]{display:none}.fuelux .radio-custom i{width:16px;height:16px;padding-left:16px;margin-right:4px;margin-left:-20px;background-image:url(../img/form.png);background-position:0 -15px;background-repeat:no-repeat}.fuelux .radio-custom i.checked{background-position:-48px -15px}.fuelux .radio-custom i.disabled{background-position:-64px -15px}.fuelux .radio-custom i.disabled.checked{background-position:-80px -15px}.fuelux .radio-custom:hover i{background-position:-16px -15px}.fuelux .radio-custom:hover i.checked{background-position:-32px -15px}.fuelux .radio-custom:hover i.disabled{background-position:-64px -15px}.fuelux .radio-custom:hover i.disabled.checked{background-position:-80px -15px}.fuelux .spinner input{float:left;width:43px}.fuelux .spinner .btn{position:relative;width:20px;height:14px;padding-top:0;padding-right:9px;padding-left:9px}.fuelux .spinner .btn.disabled{cursor:not-allowed}.fuelux .spinner .spinner-buttons{position:relative;left:-22px;float:left;width:20px;height:28px}.fuelux .spinner .spinner-up{top:2px;padding:0 0 4px 1px}.fuelux .spinner .spinner-up i{position:relative;top:-4px}.fuelux .spinner .spinner-down{top:2px;height:13px;padding:0 0 4px 1px}.fuelux .spinner .spinner-down i{position:relative;top:-5px}.fuelux .search{display:inline-block}.fuelux .select .dropdown-label{display:inline-block;padding:0 10px 0 0;margin:0;font-weight:normal;color:#333;text-align:left}.fuelux #selectTextSize{position:absolute;top:0;display:inline-block;visibility:hidden}.fuelux .tree{position:relative;padding:10px 15px 0 15px;overflow-x:hidden;overflow-y:auto;border:1px solid #bbb;border-radius:4px 4px 4px 4px}.fuelux .tree .tree-folder{width:100%;min-height:20px;margin-top:1px;cursor:pointer}.fuelux .tree .tree-folder .tree-folder-header{position:relative;height:20px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.fuelux .tree .tree-folder .tree-folder-header:hover{background-color:#dfeef5}.fuelux .tree .tree-folder .tree-folder-header i{position:absolute;top:1px;left:5px;float:left}.fuelux .tree .tree-folder .tree-folder-header .tree-folder-name{padding-left:29px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.fuelux .tree .tree-folder .tree-folder-content{margin-left:23px}.fuelux .tree .tree-item{position:relative;width:100%;height:20px;margin-top:1px;cursor:pointer;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.fuelux .tree .tree-item:hover{background-color:#dfeef5}.fuelux .tree .tree-item .tree-item-name{position:absolute;left:29px}.fuelux .tree .tree-item .tree-dot{position:absolute;top:8px;left:10px;display:block;width:4px;height:4px;background-color:#333;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px}.fuelux .tree .tree-item .icon-ok{position:absolute;top:1px;left:5px}.fuelux .tree .tree-selected{background-color:#b9dff1}.fuelux .tree .tree-selected:hover{background-color:#b9dff1}.fuelux .wizard{background-color:#f9f9f9;border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*zoom:1;-webkit-box-shadow:0 1px 4px rgba(0,0,0,0.065);-moz-box-shadow:0 1px 4px rgba(0,0,0,0.065);box-shadow:0 1px 4px rgba(0,0,0,0.065)}.fuelux .wizard:before,.fuelux .wizard:after{display:table;line-height:0;content:""}.fuelux .wizard:after{clear:both}.fuelux .wizard ul{padding:0;margin:0;list-style:none outside none}.fuelux .wizard ul li{position:relative;float:left;height:46px;padding:0 20px 0 30px;margin:0;font-size:16px;line-height:46px;color:#999;cursor:default;background:#ededed}.fuelux .wizard ul li .chevron{position:absolute;top:0;right:-14px;display:block;border:24px solid transparent;border-right:0;border-left:14px solid #d4d4d4}.fuelux .wizard ul li .chevron:before{position:absolute;top:-24px;right:1px;display:block;border:24px solid transparent;border-right:0;border-left:14px solid #ededed;content:""}.fuelux .wizard ul li.complete{color:#468847;background:#f3f4f5}.fuelux .wizard ul li.complete:hover{cursor:pointer;background:#e7eff8}.fuelux .wizard ul li.complete:hover .chevron:before{border-left:14px solid #e7eff8}.fuelux .wizard ul li.complete .chevron:before{border-left:14px solid #f3f4f5}.fuelux .wizard ul li.active{color:#3a87ad;background:#f1f6fc}.fuelux .wizard ul li.active .chevron:before{border-left:14px solid #f1f6fc}.fuelux .wizard ul li .badge{margin-right:8px}.fuelux .wizard ul li:nth-child(1){z-index:10;padding-left:20px;border-radius:4px 0 0 4px}.fuelux .wizard ul li:nth-child(2){z-index:9}.fuelux .wizard ul li:nth-child(3){z-index:8}.fuelux .wizard ul li:nth-child(4){z-index:7}.fuelux .wizard ul li:nth-child(5){z-index:6}.fuelux .wizard ul li:nth-child(6){z-index:5}.fuelux .wizard ul li:nth-child(7){z-index:4}.fuelux .wizard ul li:nth-child(8){z-index:3}.fuelux .wizard ul li:nth-child(9){z-index:2}.fuelux .wizard ul li:nth-child(10){z-index:1}.fuelux .wizard .actions{float:right;padding-right:15px;line-height:44px;vertical-align:middle}.fuelux .wizard .actions a{margin-right:8px;font-size:12px;line-height:45px}.fuelux .wizard .actions .btn-prev i{margin-right:5px}.fuelux .wizard .actions .btn-next i{margin-left:5px}.fuelux .step-content .step-pane{display:none}.fuelux .step-content .active{display:block}.fuelux .step-content .active .btn-group .active{display:inline-block} \ No newline at end of file diff --git a/opendaylight/adsal/web/root/src/main/resources/css/login.less b/opendaylight/adsal/web/root/src/main/resources/css/login.less deleted file mode 100644 index cdaba2385f..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/css/login.less +++ /dev/null @@ -1,53 +0,0 @@ -.reset { - padding: 0; - margin: 0; -} - -html , body { - .reset; - height: 100%; - width: 100%; - background-color: #eee; -} - -html { - display: table; -} - -body { - display: table-cell; - vertical-align: middle; - padding-bottom: 10%; -} - -.container { - width: 650px; - .content { - padding: 25px; - background-color: #fff; - -webkit-border-radius: 10px; - -moz-border-radius: 10px; - border-radius: 10px; - -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .15); - -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, .15); - box-shadow: 0 1px 2px rgba(0, 0, 0, .15); - text-align: center; - .login-form { - #logo { - background-repeat: no-repeat; - background-position: center; - background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAADQCAMAAADGQmMsAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoTWFjaW50b3NoKSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDpBQ0I5NEY2RjhBM0QxMUUyOUMzMUNFMzQ4NjM5NUNFRiIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDpBQ0I5NEY3MDhBM0QxMUUyOUMzMUNFMzQ4NjM5NUNFRiI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkFDQjk0RjZEOEEzRDExRTI5QzMxQ0UzNDg2Mzk1Q0VGIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkFDQjk0RjZFOEEzRDExRTI5QzMxQ0UzNDg2Mzk1Q0VGIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+EBgRdAAAAwBQTFRFrKus/sxW8VIj////Y2Nk/s9gysrL+qMY/tl//uWp+6wW9ogeW1pco6Ok8E4jzc3N/b8p/chJ//jp/tZ2/tyJ/cZC+Pj48vLy//Xd8lwi7Ozs820hbGts/bscxcXF4eDh//LV/tFke3t8U1JU//DN/b0l6enp9fX1/s5d/+3E3t3etrW2u7q7/uzA/cAt/t2P/uq5/LIV/tRx//bi/uOh/bUU/cExTEtN5ubm/clM9oQfwcHC//fl/ui09Hkh/tmA/cI0/cQ8/bgU/+/K2tra/td61dXW/tNs8Vgj//vzmpqb/uy//uGd8mUi/cM5+qUX9YUg/bkWdXR2/tqE0tLS8Ewj//z2/uSk/uiy/tJo9HEh/r8S8mAi9Hgh//789HYi/t6T9X4g//34hYSF/bwh//bg/uCY+6wa//HQcXBx/bwi/Pz88mIi//vw//z0vb29//Ta/r8R/stS9YIf/boa9HkilpaX//PX/sER/bcT/+7HkZGS/s1Y/cdF+vr6//rviYmKnZ2e9vb2/cU99YIg2NjY+JQbgYCCjYyN/um28Eoj/uSm//76V1ZYsbGx9Xsf/t6Q/uu88WAi/t+V/tuI+Zwa/uas/boT/tBi/bgT/cQ694sdRkVH9HMh/uCW/bwV9oIg828h+Zgb/tl59Xsh/rgT9YAgQkFD/r0S/t2N9X0h/ueu/uevj46Q/bwfx8fI//PY/rwS/boZ+Z4Z9Hwhb25wi4uMxMPE/tyM//LT//ns/chH//rt//jn///+//HS/bkT/b0SR0ZI9YEg/bkYQ0JE/uau/v7+/s5b/b4RSUhKh4aIRENFv7/AdHN0/s1anJuc/b4S9H0hd3Z3/LAV7+/wUE9R/stU/tRv09PUeHd59Hwg8WIiXl1f/uewqKeos7O0/bkSt7e3/r0R4+Pjc3J029vc8mMiYWBhmJeZiIeIl5eY/rsS+Z0ZhIOFTk1P9Xwg9X0goJ+g9oEgZ2Zo/b0R0M/Q/r0UcG9x/tuGvLu89X4h/rwTlJOUg4OE9H8hK2JASQAAFM5JREFUeNrsnXtAVVW+x8WlJop6BEFASRRQaRQNFIRB0oMIiiDkIx+ASmioaIoPEjVrtGt1oxS91kq9k43DYsZHaZniA80081VZaJMzjl6vDU5Ttxmv13vNW87a57kfa629z0F8nPP7/gV7r/04+7N/6/Fbv9/aTRDI69QEHgFABwF0EEAHAXQQQAcBdBBABwF0EEAHAXQQQAcBdBBABwF0EEAHAXQQQAfoIIAOAugggA4C6CCADgLoIIAOAugggA4C6CCADgLoIIAOAugggA4C6AAdBNBBAB0E0EEAHQTQQQAdBNBBAB0E0EEAHQTQQQAdBNBBAB10D6DPWffxFpbWTYXn7rHQ1+Ry9AQ8d4+F3gdz1A+eu8dCn8yDDpYO0EEA3ZhCb1x88fHOu3Z1nv5BkxahrBIzv27XQq3RZ1WFzrbTFrJpiKNQ9478+5g5ul0PgH5XoO9+MoHIdOLn09oyHX8gWiV0u3RMXug04crPUejVZs9y7yToBBnqzdC3FrsHPXWgq8inUyadF19ud6V79wHtei3uTP+9rsHew4+sXLxNrsUrO58i5Oo7skIPk4htykJ2PddEVugkH7ofGeLF0H2xaY470IuL8DhXrjNgJSHn2jwi3/RCkwhCzg9QQa8g2mp/wKULhAyXQ39c/4rvENIEoLOZYxwf5zr0sii6xQVbH1JBDn9+VlOXX0wgFe3U0B9hHN/jmpz6w2S6IeikHUBnM6fU57gKvdgkbck1TH3oOdLsL6wdXT4lh28YgI7Qj4S8esw16IdJxIBagM5krrR1I9DDo2zbDFLvkkC6cXrLx06SDaONQEdtSEKoa9BfHE6uBwF0NnOFrRuAftBk32bM1n91lfwfvyf9LYk4awQ6uk7+5hr0hagZWQnQOcwp9anGoTvsXNKfDVzoA+InGDNTmN0MQd9NEjq6BP05dCWBtAHoHOYYDwo2Cj08Rr419yXdC71AyA3R/isnyC+NQEcXyNMuQe8mlSSnATqHObX1YGPQa6JU27fqXWk6+VZc4CK5MNMI9IXkJ5eg75IeFTncBaBzmDtsXQe60s6N2PoQcrS7uMSzEU5TF0HvZR+euwAdnSQXOgJ0SbVa5tgcE6wPvWYG48Atwmu9SLbp3c41Z39LBP0GaeY69JmdyZcAnW3nFlufqge9LIa1J7ev4FJBEfrPd8CGw6EGoH/tDnTUPULuzPNa6LVs5tTW54ihHyxi78oV2PoN4jdT94522btod97SERpNyCWAvo7HFQ+KE0Fn27lFfFtvoteNszpefjIA/bQ7bTrVJXLqL94O/QnMV4w/943oHVfEP878Me9qJ8mr+rc0mnQ2AH24G713ixaTilDvhr4OixQY+7/sHTt+s1x4IMfWaT/qhv49XSERM3WhH/MjvdyDjr4knWd6M/QnhOjw6yNbnWFtn9hq5OvCAzm2Th/vI/o3dfaE3a8ugN6CJPSwQ3/cNej0LrZ5MfSBYua4+u0Vjx7Xbp5bd/v7ap1De7Ou1yPiVEf9u6IQXtCFfv3oQmSHXjH8+eEM/XU3Gzp6YYOilfEy6GWDdaC/Nynp0bkaO697a9JDOtADg1nXCyUJMw1BH6oH/Zp8lo2jo9040NFuQlp4b/Uel60D/fcLctTU59bN27xZB3rgXublOp7bYMTSL+ha+mXitNWHyYVeT/di6BdDedDR5yQi1Hs7cvsDdaBXpaioH6+bl1KlA739MK4NG3i8HX843F0IfebzhHyOnNBdbNMl/SybXPe+IZvQ1iXoKuqSnVfpQOfYOaV1nRuzJHfJkYggex/gqLZmuHLpqpy56713C+ir5Gcvds7sDdSBXpWS9OhEZ7+d2rkOdJ6dUz1JDNzt10ev2zt+fuT8k0p1a0Zb6wvKaFg3oKMB5xyT697oe0/O1oEu2fpxuZ2LoXPtHEnzpk8a+EHkOTv0q4z+2blPf6EIe3IPOmpx1D657pUTLnxbt0GXbP2M1c7fSqnSgb5vluBSRnzvx7rZ3S6Spbe5rFCvFkPVFb6b0Om7dcI6uR5U4Y3z6QeydaBL1I9Ldr5ic5UO9KX7hX20c+RrXd9MgmPKnbbp+glH7kJH35Jmlirj2WZeGUThH6gDndbwdRMddi6ALrRzS6N+Uu9mLjp74yLfe8OhH5tuu1I37wyX8n9TB/pHKUmH+r9ls3M+9KXLdC7Ujhy9olPkqqN2b2ToKDTiqGUUcN5LAyMPBIqhV31U9dprVVU60Pct073QN3pduUukIuguQafjBMsL5q3Q0d7BYug5+RkZKTli6Hp1u6ShRJwiejbCmbvS6NBRL8vdeC10dGC5CHpOfkheZWV+kgi6uA9n138RP1Hn7Lx83rPRoaOFpOIs+tJ705r2LudDp8xL6rPyHNRZ0NvPNnQZasqf8vf+lWyQBSk3PnTaiTt/7GcvTmAcW3poh1JzH7q9QlJOfl5JFlVlZUqOZcOtkc+oih7yqTV4maGHyXNBXObkMrqr0Hv4kZ9Wegf0sj1rO2g0ImDk2/+m0HutO0na1KlphlVNM+g/klq/97284PdvP5U2TXvGtR1YrfzDp8g3zNVGfrWNKBOP7gJ0NOQwObzBK6CzI2C/q8uZ9L5ctzrlUWWFtH25rU0vt62sl7Z1uqUoOKn1o98xT8lcZLDFCVLxI2NzM/XKAXcDujQff9groG85wkT0P/1bL6iSacWmvHralLcd09ahMW3zsurr8yaskJdbsH7RDrazJo5tXdMJ+eaXCn9q0I1uhPip5uAMQv+yQdDRNXLKO6DvZDM60791igq6krkkSl0JPWX9ojOcWLk4zg20+YGQiL/92MXSke/R5fQ1aWploXp1CoPQr+5+eDdTTw8xAt1beu886Pi4gjqFrmUu2boCesp6zPPEc6Gj0IsXLFNmV69fbxYh/VXxeRdNV7AjMYDjaf7qUs5xwmnZSlMaBe16x6uhK219xaZ6DXOLrdc7od/m27kIutSGD+/mZ2VT8fhPLVizb0HPLw7V/S2PLF78AUcvXnYWEj2mAQO8G7pk6452fcWEEBbzMW0rNzqg5/PtXAe6RLV7lytXugwIQqB7Cl2ydTv1nE4s5hL1TTaP7O0FAjvXhw66T6Dj44ts1HPyM5jM6cgtIyXJ1m/Homg5gP6gQJdsPV9iPikvoy1HGZWW2Rdq5x9igO4J0K19+JxJIVk86GNCSiQ/fP76Q+L4d4D+4EDH1f1b384PKRFAz8qrTLm1fpFOogtAf4Cg4+PVUzLy6kXQs/Iy5s2tXgTQPQf63P5TQiqzxNBD5i06jgG6x0Cf2Gre7b9X5omgV/5pyq2kuokA3VOgW3IaklIq80K40Cv/9H6SLTIaoHsCdFusc85r9U25Q7b6fyRZ4uHrzgB0T4A+t+4ja6xz0h8zXuY4Z0KmJMmyIAD6gw59rjOngeuGbTohx5kFAW7YBx76RLudWyZcKpuyJlya5jkmXD4S2vqDD70wOTg8OjI4ucCToctylyxTqyVa6mOa1pfI5tOljCeD0Av7BCj1O99iI09zTUDATWW5ZfTgVcIDYh0B2b4BAeIVa/sFBGQydxRPTg+Mmk9/R5hp3x9GaLNxD6QFtPTnnXVEQMBq619lAUKtKb7H0CfWOXOXrEEUGuqUuSKIQmTrKuhjtYvPhcV3HThM527LpILKdSgLS0WLFEoLKC0Za//PB+N04fnbY9xSu3VZv31hils1NY9WvxR0aw3npLWBjrNuEY9rY/rdW+jUzjerw6VU1CXm6nAprq2robNXn3tzTaHwbgMsqRTKbWMHUQqcTPhZJvokHcxROpOpTM0x7qM1/0HWm9u+vLTUJ9D2tn5SrigTHoa3v8s76xKMf2f96yUx9OXr7g70j3M5dj5vszYwUkF9TNMSRmCkLX9dLzBSgj5+Wh+7Jo9qHmj9GEi26Hf7z8e59H5VZlaOuQYsvSSyCt0d6ME+0m0V+UwLj5tdW4vGJkdOK5Xs/sjaAteh+48b6FTfdTH0Iax2bvhzdPLdgc4Ogf7/VlMm/V6u25YQ6PpKeQh0iTUE+rai4KT/brXDQAi0BF21wFyy73jLC5jGb9sfwzh2FLUy1eY/8Fary6Q7YlGDoGdK72LRKOVH6sLTJOyJyS5DV2kwxtPuRUcuedzHWzWKbNnqvZEKtVq/aePGjRMmTQjJCLEoI4T+Szd1+pdWypIPPdWhXHvGLVvHaqBrv+5Tlm6mD7M5717HUsuIPEBLhCu376XbBzHahYJsWrnPahB0S32crh15BNNT4ai4hkEfls17GxoZOvtNGPx6tVLP2NOa/lhfaUlryppiTWv6YuQzqqKvG0lfZENHKFpqP3u+wulbYxyIUE+MA1Q7+tKDHtOWH6Ws3N2AHi31ePox07QGRuHsAx4EvXg7P4Ex6bXKvKysvJJ/rOAnMMbMcRs62luqqpJlhrscm2n3Nhqbw9Sjo670oEh1+VRabXRFDYHuL9XtvE5Gefp+5DnQi02iVOWklMrKypK/C1OV44Pdho6G0WET+3ut1J5Nw6wjoLXqHl6RpRJQviO0XNH+BkHvKWCO3Om937fQI8PEixIkfZERMmWFcFECs6nMbehobzw2x7AWskjEeJStlo9RJ0NvpVfdo9y0R0vMRejSIH8U8gboB006y4/cvtU65wu95Uf0bF0AHfWl1fJNxstIh0mW/nJhjFn71fZPMN6pGCC8ewTjN1BDoBcsN+PsAm+AzrRzBfT89dXfObMgeAsNmcLdho7eoB1jrbcl3dHWd6B1uRrGgRkYf6WqF4oONAh6X+H3SDwIOtvOZdClnIYPZVkQ3CXF4qe6DX0OHa9rHJJTd2Kz7UU6QF/M1RoHN73mCNW/tQ2C3lXbT/BI6Bw7l0FfsP4/KOX/tGdBCBYPFNq6ELr07BMZzrVEmTemVOPhpt3+MIe7JG4+xp+xKgvj0JeZGK+eB0KvMektE2rPabBlQQiXCY2Pcxf6OIxzVR7JYVGyA4rpfs2EVHCYzK/zGX0D4hoGvZz2EpI9H3rqdr0FgfMtdi6J2nqK3oLApho3oSdv13S8p2E8WNFtG8/y3WBfp3N5BGoY9FW0aqn1eOh8O7dDz5flNFRb23Xh0t98WxdDl6Y4lWOlgkEKin2ZhryUvmcWb+9eE6N9cBW6VNjTodemFukt8q/MXbKuWiBe5J9r6zrQx6s98L6KKVJUMBibtX7Xsp02FxxllxvcUOiJFv+fZ0PXfAtbAz1flbtksXWdz3nExLkFfa26p0aNOE3VV48aqzmsj3W6TZol6YMaCn2QUW+cDXrRMMEQ9P6EXl6k8+Ge9/PX/7ZandO6foHeh3s4tq4DnY7E28uq1tpojOcrTHesiTkrSc8ajxCncncZ+hHVxP3Urs2V2iOHnvtVc45M9yn06DDdT3QxcpE/7N96o94nuqIOumfpCl/YG5qO2yiMBxWwvHZ4z01u6JKL0MNUzuRUTaSLHLpQ9yX03rnim97xduvfVrPy13P0PsYXFukG9D1KWw3WTqJJDpotzLdF0lrUcOjxmm+BF8sfkjTz7/NgQ0eZ4rs+9FR/JtwP61odEh5YlOpO9Z5mVkAPwHifpq9nZtXhBZbl6gML7gD0NzVt+uzyaKeK96igh/lGRrOUmrrvvu3ICTvvuOfNX7N3fLdqibBJn+NWR+4zbJbNhPuHMSZbI82aYDlbO2UO40USuwR9iU4sU28V9CKuJ6fn/TtO7z1f8K0t9K+8XasLBJ9VnpHq1pBNOqWs+72K2X4nsgOrfATxVi5BjzVzgjlsGqiC/mA6Z1Jn8NglDkOTefHs/dDepa7auR708Fz5jIoUGsewOTowMzPO35XlrHMHej9+M+FB0FE0x9YTZyMudGlmez/H1qMi3XTDUtOOcgY00komG7FtOo3JresdgV5Df0GZ50OvTWU6aBKl5y+CzrF1kyBUTgi9YJC8Sa+lRbMfS9OoZXv6avg3HvTCbHHcjIdAt0V/qplbPF9C6GjZcrMrdq4D3VcRxbpa1FHs0HjQUUuMYwq9ADoq19h6e2s9K4bO+J6bOExOBL0wHuP4QnktLnDzjm086O/mcry5ngZdY+uJtqevAx3NCnTBzsXQWyrmRaXUwNg1exia3BIzHDR3DrrkB5wR5w3QVbbe3h6WqgddZes6IXIi6OuUOYrjFRPpmgFwYCNCD56PzYncsi95EHRUvlNr5wagK2w9Si/Rmg9dCmY2O1+Z4O0CH4mUq7a68aBboqi5Y/VoT4KOymdo7NwIdOTvGLmZDiJ3oT8h+bdl89iPYbOJ+2U/Ke/BpxGh1/LTbdCwN+S+4Qc/ral8vtrODUFHw2y2HlWD3ISeHCsd/+/ODbNMZlYMvGwInxveeNCtX6grZcX1li9X5M95QAKjdXK9vTwnyAh0lGyxdZOBRTQodLMmpjx4j6U/MVlmav0w3imIr3wlRmOJOtBHuQQdJUsJlVFr1J65uJZShSR7gTwAOkqdr7Rzg9Attm6qQYagyxNKC5cl10wutSCfIe+P18YLnKo23912/wZbegEXOprV07JUQtpBZxuzrDxdiibcKQ+m8gToKDp3sDKdzBh0lBwfFokMQg9s7mPTkqWD7DO76Qo33jjaqSsXnUeagLvpCvT4z3y0Kk17hQcdoT7WW8uOXeO7enWm7+R062ok7VORp0FHkSoHp0HoKLkGGYXOcNYHqFqGRF7gk0MBtGqZ5QJ0tuxLGjDXnAmO1c46Z6tiJj0DulpGoRvUbE24dVRiej+1J13KJhsoPlGZOiwlkZH9Ytcn3FjtQsfBrEY/eG3pEXlObldfdYli7foYTi1lLplAm44ozg4PhV6QmqlQ74Os7low3aNbJWVmKqqH8MxM7tMvy+QossBxMCcF792X1sYuSSxN/Cp2VSZjwbjZvTOjud+SPsg5q/QQpnoRdNCdEkAH6HdUfXjQ+8Fz91jo04o48oXn7rHQQQAdBNBBAB0E0EEAHQTQQQAdBNBBAB0E0EEAHaCDADoIoIMAOgiggwA6CKCDADoIoIMAOgiggwA6CKCDADoIoIMAOgigA3QQQAcBdBBABwF0EEAHAXQQQAcBdBBABwF0EEAHAXQQQAcBdBBABwF0gA4C6CCADgLoIIAOAuig+13/FGAApyIqjoQlf2EAAAAASUVORK5CYII='); - width: 400px; - height: 175px; - margin: 0 auto 20px; - } - .icon-login { - width: 20px; - height: 16px; - background-position: left center; - background-repeat: no-repeat; - background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAc5JREFUeNpi3NLKAAKMQBwNxP5AbM0AAUeBeCMQLwXi/95V/xmwARao5nphGeN6KTUPBlF5S7DE64fHQ57d2hHy9slZFSC3EWQILgOiQZqVjRMY3r+4zHBqYx5YQlLVhQEkBjIcaMgdIL0EmwFMIGeDbAZpvn1yVtGXd/cEQRjEBomB5KBeY8BlgDXI2c9v7wHx53vnnf0AwiA2SAzqJWt8BlAEQAYcBQYY2M9AkLh1krEACIPYIDGQHDRGcBqwERjaDIISugyq5ml9PEJK70EYxAaJgeTYWTRDcBnACEwHuKIRrPnLi28MipZBDF+f7WJQcpoAUsvAI2qFYgDOhASy+cXDzwx6dpIgzQz39hWADQHRIKAXfoqB8f///zgD6NJKMxD1/9Kh5yiGQC0EG0AwFm6f/sAI0gwyBOoCBuRUSVQ0ggyRkOfFaggLIc2qpgIM7558/K/jW8Lw7PwMsCEMDAUMYloxDIcm6U7FGwYwcKBX/b+0liqDoHIQw4UNPQyggJVTF2Cwy7vMyOgizMj4W4iDkZGZhYmdmZGBi/E/Cws7IzMDCwvLPyZGlvdf/nK+//qHuy9L6gbIsNTex/oT8xWKvCuug3Ldd4AAAwBj/b+B1P2YnAAAAABJRU5ErkJggg=='); - } - } - } -} \ No newline at end of file diff --git a/opendaylight/adsal/web/root/src/main/resources/css/one.less b/opendaylight/adsal/web/root/src/main/resources/css/one.less deleted file mode 100644 index e19733fcd1..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/css/one.less +++ /dev/null @@ -1,292 +0,0 @@ -// properties -@mainTop: 43px; -@mainBottom: 41px; - -@minWidth: 640px; -@minHeight: 480px; - -@topologyOffset: -4px; // ensure calibration - -@interface-admin-up: #46A040; -@interface-admin-down: #C41230; -@interface-edge-down: #F58025; - -// mixins -.dash-size (@width, @height) { - width: @width; - height: @height; -} -.position (@type, @top, @right, @bottom, @left) { - position: @type; - top: @top; - right: @right; - bottom: @bottom; - left: @left; -} -.dash-position (@top, @right, @bottom, @left) { - .position(absolute, @top, @right, @bottom, @left); -} -.icon { - width: 22px; - height: 16px; - background-position: left center; - background-repeat: no-repeat; -} -.dashlet-elements { - width: 98%; - margin: 5px auto; -} - -// header -#menu { - .navbar-inner { - .brand { - font-size: 1.4em; - font-variant: small-caps; - margin: 0 12px; - padding: 10px 0 10px 45px; - background-image: url('../img/logo.png'); - background-position: left center; - background-repeat: no-repeat; - } - ul { - margin-top: 10px; - border-bottom: transparent; - li { - a { - padding: 5px 15px; - &:hover { - border-color: transparent; - } - } - } - .active { - a { - border-radius: 1px; - background: #f6f6f6; - &:hover { - border-top: 1px solid #ddd; - border-right: 1px solid #ddd; - border-left: 1px solid #ddd; - } - } - } - } - #toolbar { - position: absolute; - right: 10px; - .dropdown-menu { - right: 0; - left: auto; - min-width: 120px; - } - .icon-user { - .icon; - background-image: url('../img/user_0020_16.png'); - } - .icon-users { - .icon; - background-image: url('../img/user_group_0107_16.png'); - } - .icon-cluster { - .icon; - background-image: url('../img/topology_view_1033_16.png'); - } - .icon-default { - .icon; - background-image: url('../img/logo_16.png'); - } - .icon-save { - .icon; - background-image: url('../img/save_as_0106_16.png'); - } - .icon-logout { - .icon; - background-image: url('../img/open_1054_16.png'); - } - } - } -} - -// footer -#footer { - #alert { - margin: 0; - p { - padding: 0; - margin: 0; - } - } -} - -// main -#main { - position: fixed; - top: @mainTop; - right: 0; - bottom: @mainBottom; - left: 0; - min-width: @minWidth; - min-height: @minHeight; - - // topology - #topology { - position: absolute; - top: @topologyOffset; - right: 0; - bottom: @topologyOffset; - left: 0; - background: #ddd; - } - - // left - #left { - .dash-size(30%, 100%); - float: left; - - #left-top { - .dash-size(100%, 60%); - - .dash { - .dash-position(5px, 5px, 5px, 5px); - } - } - - #left-bottom { - .dash-size(100%, 40%); - - .dash { - .dash-position(0, 5px, 5px, 5px); - } - } - } - - // right - #right { - .dash-size(70%, 100%); - float: right; - - #right-top { - .dash-size(100%, 60%); - - .dash { - .dash-position(5px, 5px, 5px, 0); - } - } - - #right-bottom { - .dash-size(100%, 40%); - - .dash { - .dash-position(0, 5px, 5px, 0); - } - } - } - - #left-top, #left-bottom, - #right-top, #right-bottom { - position: relative; - } - - // dashentries - .dash { - border-radius: 1px; - background: #fff; - border: 1px solid #ddd; - - .nav { - padding: 2px; - padding-bottom: 0; - margin: 0; - } - - .nav-tabs { - background: #eee; - li { - a { - background: #ddd; - padding: 4px 8px; - margin-right: 3px; - border-radius: 1px; - &:hover { - border-color: transparent; - } - } - } - .active { - a { - background: #fff; - border-radius: 1px; - &:hover { - border-top: 1px solid #ddd; - border-left: 1px solid #ddd; - border-right: 1px solid #ddd; - } - } - } - } - - .dashlet { - overflow: auto; - .dash-position(45px,0,0,0); - - h4 { - .dashlet-elements; - } - - p { - .dashlet-elements; - } - - table { - .dashlet-elements; - } - - .btn-group { - margin: 5px; - } - - .none { - margin: 0 auto; - padding-top: 128px; - background-position: center; - background-repeat: no-repeat; - background-image: url('../img/alert_unreachable_2008_128.png'); - text-align: center; - p { - cursor: default; - } - } - } - } - - // defaults for visual topology - #right-top .dash { - background: #ddd; - overflow: hidden; - } -} - -.table-cursor tr:hover { - cursor: pointer; -} - -// interfaces -table { - .admin-up { - color: @interface-admin-up; - } - .admin-down { - color: @interface-admin-down; - } - .edge-down { - color: @interface-edge-down; - } -} - -// hide -.modal { - .help { - display: none; - } -} diff --git a/opendaylight/adsal/web/root/src/main/resources/css/opendaylight.css b/opendaylight/adsal/web/root/src/main/resources/css/opendaylight.css deleted file mode 100644 index 296bdf771d..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/css/opendaylight.css +++ /dev/null @@ -1,93 +0,0 @@ -.fuelux [class^="icon-"], -.fuelux [class*=" icon-"] { - display: inline-block; - width: 14px; - height: 14px; - margin-top: 1px; - *margin-right: .3em; - line-height: 14px; - vertical-align: text-top; - background-position: 14px 14px; - background-repeat: no-repeat; -} - -.fuelux .icon-white, -.fuelux .nav-pills > .active > a > [class^="icon-"], -.fuelux .nav-pills > .active > a > [class*=" icon-"], -.fuelux .nav-list > .active > a > [class^="icon-"], -.fuelux .nav-list > .active > a > [class*=" icon-"], -.fuelux .navbar-inverse .nav > .active > a > [class^="icon-"], -.fuelux .navbar-inverse .nav > .active > a > [class*=" icon-"], -.fuelux .dropdown-menu > li > a:hover > [class^="icon-"], -.fuelux .dropdown-menu > li > a:focus > [class^="icon-"], -.fuelux .dropdown-menu > li > a:hover > [class*=" icon-"], -.fuelux .dropdown-menu > li > a:focus > [class*=" icon-"], -.fuelux .dropdown-menu > .active > a > [class^="icon-"], -.fuelux .dropdown-menu > .active > a > [class*=" icon-"], -.fuelux .dropdown-submenu:hover > a > [class^="icon-"], -.fuelux .dropdown-submenu:focus > a > [class^="icon-"], -.fuelux .dropdown-submenu:hover > a > [class*=" icon-"], -.fuelux .dropdown-submenu:focus > a > [class*=" icon-"] { -} - -.fuelux .icon-search { - background:url('../img/search.png') 0 0 no-repeat; - height: 16px; - line-height: 16px; - width: 16px; -} -.fuelux .icon-remove { - background:url('../img/searchremove.png') 0 0 no-repeat; - height: 16px; - line-height: 16px; - width: 16px; -} - -.fuelux .icon-chevron-up { - background:url('../img/sort_up.png') 0 0 no-repeat; - height: 16px; - line-height: 16px; - width: 16px; -} - -.fuelux .icon-chevron-down { - background:url('../img/sort_down.png') 0 0 no-repeat; - height: 16px; - line-height: 16px; - width: 16px; -} - -.fuelux .icon-chevron-left { - background:url('../img/nextpageleft.png') 0 0 no-repeat; - height: 16px; - line-height: 16px; - width: 16px; -} - -.fuelux .icon-chevron-right { - background:url('../img/nextpageright.png') 0 0 no-repeat; - height: 16px; - line-height: 16px; - width: 16px; -} - -.fuelux .icon-chevron-right { - background:url('../img/nextpageright.png') 0 0 no-repeat; - height: 16px; - line-height: 16px; - width: 16px; -} - -.tip { - background-color: white; - border: 1px solid #CCCCCC; - box-shadow: 2px 2px 8px #555555; - color: #111111; - font-family: Verdana,Geneva,Arial,Helvetica,sans-serif; - font-size: 14px; - opacity: 0.9; - padding: 7px; - width: 260px; - border-radius: 8px; -} - diff --git a/opendaylight/adsal/web/root/src/main/resources/img/Device_pc_3045_default_64.png b/opendaylight/adsal/web/root/src/main/resources/img/Device_pc_3045_default_64.png deleted file mode 100644 index cd4fff6712..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/Device_pc_3045_default_64.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/Device_switch_3062_unknown_64.png b/opendaylight/adsal/web/root/src/main/resources/img/Device_switch_3062_unknown_64.png deleted file mode 100644 index c55127d961..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/Device_switch_3062_unknown_64.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/Expand16T.png b/opendaylight/adsal/web/root/src/main/resources/img/Expand16T.png deleted file mode 100644 index 489a4d6644..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/Expand16T.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/Key_0024_16.png b/opendaylight/adsal/web/root/src/main/resources/img/Key_0024_16.png deleted file mode 100644 index 1faeb825c9..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/Key_0024_16.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/alert_unreachable_2008_128.png b/opendaylight/adsal/web/root/src/main/resources/img/alert_unreachable_2008_128.png deleted file mode 100644 index cb0e44620e..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/alert_unreachable_2008_128.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/form.png b/opendaylight/adsal/web/root/src/main/resources/img/form.png deleted file mode 100755 index ce846da940..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/form.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/logo.png b/opendaylight/adsal/web/root/src/main/resources/img/logo.png deleted file mode 100644 index 46c02e2aeb..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/logo.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/logo_16.png b/opendaylight/adsal/web/root/src/main/resources/img/logo_16.png deleted file mode 100644 index e9833ac8ff..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/logo_16.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/nextpageleft.png b/opendaylight/adsal/web/root/src/main/resources/img/nextpageleft.png deleted file mode 100644 index 62126b1b2e..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/nextpageleft.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/nextpageright.png b/opendaylight/adsal/web/root/src/main/resources/img/nextpageright.png deleted file mode 100644 index 2a71a1495e..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/nextpageright.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/open_1054_16.png b/opendaylight/adsal/web/root/src/main/resources/img/open_1054_16.png deleted file mode 100644 index 62ee475e18..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/open_1054_16.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/open_1054_24.png b/opendaylight/adsal/web/root/src/main/resources/img/open_1054_24.png deleted file mode 100644 index 055cc3c2cf..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/open_1054_24.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/save_as_0106_16.png b/opendaylight/adsal/web/root/src/main/resources/img/save_as_0106_16.png deleted file mode 100644 index 931662272d..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/save_as_0106_16.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/save_as_0106_24.png b/opendaylight/adsal/web/root/src/main/resources/img/save_as_0106_24.png deleted file mode 100644 index 1afce220b8..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/save_as_0106_24.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/search.png b/opendaylight/adsal/web/root/src/main/resources/img/search.png deleted file mode 100644 index b8742d2edd..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/search.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/searchremove.png b/opendaylight/adsal/web/root/src/main/resources/img/searchremove.png deleted file mode 100644 index 3809f51a79..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/searchremove.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/sort_down.png b/opendaylight/adsal/web/root/src/main/resources/img/sort_down.png deleted file mode 100644 index 708e44e79a..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/sort_down.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/sort_up.png b/opendaylight/adsal/web/root/src/main/resources/img/sort_up.png deleted file mode 100644 index 0b5c041d3e..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/sort_up.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/topology_view_1033_128.png b/opendaylight/adsal/web/root/src/main/resources/img/topology_view_1033_128.png deleted file mode 100644 index de0d6415ca..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/topology_view_1033_128.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/topology_view_1033_16.png b/opendaylight/adsal/web/root/src/main/resources/img/topology_view_1033_16.png deleted file mode 100644 index 1a132542c9..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/topology_view_1033_16.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/user_0020_16.png b/opendaylight/adsal/web/root/src/main/resources/img/user_0020_16.png deleted file mode 100644 index 1ed7a09b9d..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/user_0020_16.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/user_0020_24.png b/opendaylight/adsal/web/root/src/main/resources/img/user_0020_24.png deleted file mode 100644 index b8c371532e..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/user_0020_24.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/user_group_0107_16.png b/opendaylight/adsal/web/root/src/main/resources/img/user_group_0107_16.png deleted file mode 100644 index a0e017b8c9..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/user_group_0107_16.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/img/user_group_0107_24.png b/opendaylight/adsal/web/root/src/main/resources/img/user_group_0107_24.png deleted file mode 100644 index 427a871d33..0000000000 Binary files a/opendaylight/adsal/web/root/src/main/resources/img/user_group_0107_24.png and /dev/null differ diff --git a/opendaylight/adsal/web/root/src/main/resources/js/bootstrap.min.js b/opendaylight/adsal/web/root/src/main/resources/js/bootstrap.min.js deleted file mode 100644 index 95c5ac5ee6..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/js/bootstrap.min.js +++ /dev/null @@ -1,6 +0,0 @@ -/*! -* Bootstrap.js by @fat & @mdo -* Copyright 2012 Twitter, Inc. -* http://www.apache.org/licenses/LICENSE-2.0.txt -*/ -!function(e){"use strict";e(function(){e.support.transition=function(){var e=function(){var e=document.createElement("bootstrap"),t={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},n;for(n in t)if(e.style[n]!==undefined)return t[n]}();return e&&{end:e}}()})}(window.jQuery),!function(e){"use strict";var t='[data-dismiss="alert"]',n=function(n){e(n).on("click",t,this.close)};n.prototype.close=function(t){function s(){i.trigger("closed").remove()}var n=e(this),r=n.attr("data-target"),i;r||(r=n.attr("href"),r=r&&r.replace(/.*(?=#[^\s]*$)/,"")),i=e(r),t&&t.preventDefault(),i.length||(i=n.hasClass("alert")?n:n.parent()),i.trigger(t=e.Event("close"));if(t.isDefaultPrevented())return;i.removeClass("in"),e.support.transition&&i.hasClass("fade")?i.on(e.support.transition.end,s):s()};var r=e.fn.alert;e.fn.alert=function(t){return this.each(function(){var r=e(this),i=r.data("alert");i||r.data("alert",i=new n(this)),typeof t=="string"&&i[t].call(r)})},e.fn.alert.Constructor=n,e.fn.alert.noConflict=function(){return e.fn.alert=r,this},e(document).on("click.alert.data-api",t,n.prototype.close)}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.button.defaults,n)};t.prototype.setState=function(e){var t="disabled",n=this.$element,r=n.data(),i=n.is("input")?"val":"html";e+="Text",r.resetText||n.data("resetText",n[i]()),n[i](r[e]||this.options[e]),setTimeout(function(){e=="loadingText"?n.addClass(t).attr(t,t):n.removeClass(t).removeAttr(t)},0)},t.prototype.toggle=function(){var e=this.$element.closest('[data-toggle="buttons-radio"]');e&&e.find(".active").removeClass("active"),this.$element.toggleClass("active")};var n=e.fn.button;e.fn.button=function(n){return this.each(function(){var r=e(this),i=r.data("button"),s=typeof n=="object"&&n;i||r.data("button",i=new t(this,s)),n=="toggle"?i.toggle():n&&i.setState(n)})},e.fn.button.defaults={loadingText:"loading..."},e.fn.button.Constructor=t,e.fn.button.noConflict=function(){return e.fn.button=n,this},e(document).on("click.button.data-api","[data-toggle^=button]",function(t){var n=e(t.target);n.hasClass("btn")||(n=n.closest(".btn")),n.button("toggle")})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.$indicators=this.$element.find(".carousel-indicators"),this.options=n,this.options.pause=="hover"&&this.$element.on("mouseenter",e.proxy(this.pause,this)).on("mouseleave",e.proxy(this.cycle,this))};t.prototype={cycle:function(t){return t||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(e.proxy(this.next,this),this.options.interval)),this},getActiveIndex:function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},to:function(t){var n=this.getActiveIndex(),r=this;if(t>this.$items.length-1||t<0)return;return this.sliding?this.$element.one("slid",function(){r.to(t)}):n==t?this.pause().cycle():this.slide(t>n?"next":"prev",e(this.$items[t]))},pause:function(t){return t||(this.paused=!0),this.$element.find(".next, .prev").length&&e.support.transition.end&&(this.$element.trigger(e.support.transition.end),this.cycle(!0)),clearInterval(this.interval),this.interval=null,this},next:function(){if(this.sliding)return;return this.slide("next")},prev:function(){if(this.sliding)return;return this.slide("prev")},slide:function(t,n){var r=this.$element.find(".item.active"),i=n||r[t](),s=this.interval,o=t=="next"?"left":"right",u=t=="next"?"first":"last",a=this,f;this.sliding=!0,s&&this.pause(),i=i.length?i:this.$element.find(".item")[u](),f=e.Event("slide",{relatedTarget:i[0],direction:o});if(i.hasClass("active"))return;this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid",function(){var t=e(a.$indicators.children()[a.getActiveIndex()]);t&&t.addClass("active")}));if(e.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(f);if(f.isDefaultPrevented())return;i.addClass(t),i[0].offsetWidth,r.addClass(o),i.addClass(o),this.$element.one(e.support.transition.end,function(){i.removeClass([t,o].join(" ")).addClass("active"),r.removeClass(["active",o].join(" ")),a.sliding=!1,setTimeout(function(){a.$element.trigger("slid")},0)})}else{this.$element.trigger(f);if(f.isDefaultPrevented())return;r.removeClass("active"),i.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return s&&this.cycle(),this}};var n=e.fn.carousel;e.fn.carousel=function(n){return this.each(function(){var r=e(this),i=r.data("carousel"),s=e.extend({},e.fn.carousel.defaults,typeof n=="object"&&n),o=typeof n=="string"?n:s.slide;i||r.data("carousel",i=new t(this,s)),typeof n=="number"?i.to(n):o?i[o]():s.interval&&i.pause().cycle()})},e.fn.carousel.defaults={interval:5e3,pause:"hover"},e.fn.carousel.Constructor=t,e.fn.carousel.noConflict=function(){return e.fn.carousel=n,this},e(document).on("click.carousel.data-api","[data-slide], [data-slide-to]",function(t){var n=e(this),r,i=e(n.attr("data-target")||(r=n.attr("href"))&&r.replace(/.*(?=#[^\s]+$)/,"")),s=e.extend({},i.data(),n.data()),o;i.carousel(s),(o=n.attr("data-slide-to"))&&i.data("carousel").pause().to(o).cycle(),t.preventDefault()})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.collapse.defaults,n),this.options.parent&&(this.$parent=e(this.options.parent)),this.options.toggle&&this.toggle()};t.prototype={constructor:t,dimension:function(){var e=this.$element.hasClass("width");return e?"width":"height"},show:function(){var t,n,r,i;if(this.transitioning||this.$element.hasClass("in"))return;t=this.dimension(),n=e.camelCase(["scroll",t].join("-")),r=this.$parent&&this.$parent.find("> .accordion-group > .in");if(r&&r.length){i=r.data("collapse");if(i&&i.transitioning)return;r.collapse("hide"),i||r.data("collapse",null)}this.$element[t](0),this.transition("addClass",e.Event("show"),"shown"),e.support.transition&&this.$element[t](this.$element[0][n])},hide:function(){var t;if(this.transitioning||!this.$element.hasClass("in"))return;t=this.dimension(),this.reset(this.$element[t]()),this.transition("removeClass",e.Event("hide"),"hidden"),this.$element[t](0)},reset:function(e){var t=this.dimension();return this.$element.removeClass("collapse")[t](e||"auto")[0].offsetWidth,this.$element[e!==null?"addClass":"removeClass"]("collapse"),this},transition:function(t,n,r){var i=this,s=function(){n.type=="show"&&i.reset(),i.transitioning=0,i.$element.trigger(r)};this.$element.trigger(n);if(n.isDefaultPrevented())return;this.transitioning=1,this.$element[t]("in"),e.support.transition&&this.$element.hasClass("collapse")?this.$element.one(e.support.transition.end,s):s()},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}};var n=e.fn.collapse;e.fn.collapse=function(n){return this.each(function(){var r=e(this),i=r.data("collapse"),s=e.extend({},e.fn.collapse.defaults,r.data(),typeof n=="object"&&n);i||r.data("collapse",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.collapse.defaults={toggle:!0},e.fn.collapse.Constructor=t,e.fn.collapse.noConflict=function(){return e.fn.collapse=n,this},e(document).on("click.collapse.data-api","[data-toggle=collapse]",function(t){var n=e(this),r,i=n.attr("data-target")||t.preventDefault()||(r=n.attr("href"))&&r.replace(/.*(?=#[^\s]+$)/,""),s=e(i).data("collapse")?"toggle":n.data();n[e(i).hasClass("in")?"addClass":"removeClass"]("collapsed"),e(i).collapse(s)})}(window.jQuery),!function(e){"use strict";function r(){e(t).each(function(){i(e(this)).removeClass("open")})}function i(t){var n=t.attr("data-target"),r;n||(n=t.attr("href"),n=n&&/#/.test(n)&&n.replace(/.*(?=#[^\s]*$)/,"")),r=n&&e(n);if(!r||!r.length)r=t.parent();return r}var t="[data-toggle=dropdown]",n=function(t){var n=e(t).on("click.dropdown.data-api",this.toggle);e("html").on("click.dropdown.data-api",function(){n.parent().removeClass("open")})};n.prototype={constructor:n,toggle:function(t){var n=e(this),s,o;if(n.is(".disabled, :disabled"))return;return s=i(n),o=s.hasClass("open"),r(),o||s.toggleClass("open"),n.focus(),!1},keydown:function(n){var r,s,o,u,a,f;if(!/(38|40|27)/.test(n.keyCode))return;r=e(this),n.preventDefault(),n.stopPropagation();if(r.is(".disabled, :disabled"))return;u=i(r),a=u.hasClass("open");if(!a||a&&n.keyCode==27)return n.which==27&&u.find(t).focus(),r.click();s=e("[role=menu] li:not(.divider):visible a",u);if(!s.length)return;f=s.index(s.filter(":focus")),n.keyCode==38&&f>0&&f--,n.keyCode==40&&f').appendTo(document.body),this.$backdrop.click(this.options.backdrop=="static"?e.proxy(this.$element[0].focus,this.$element[0]):e.proxy(this.hide,this)),i&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in");if(!t)return;i?this.$backdrop.one(e.support.transition.end,t):t()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),e.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(e.support.transition.end,t):t()):t&&t()}};var n=e.fn.modal;e.fn.modal=function(n){return this.each(function(){var r=e(this),i=r.data("modal"),s=e.extend({},e.fn.modal.defaults,r.data(),typeof n=="object"&&n);i||r.data("modal",i=new t(this,s)),typeof n=="string"?i[n]():s.show&&i.show()})},e.fn.modal.defaults={backdrop:!0,keyboard:!0,show:!0},e.fn.modal.Constructor=t,e.fn.modal.noConflict=function(){return e.fn.modal=n,this},e(document).on("click.modal.data-api",'[data-toggle="modal"]',function(t){var n=e(this),r=n.attr("href"),i=e(n.attr("data-target")||r&&r.replace(/.*(?=#[^\s]+$)/,"")),s=i.data("modal")?"toggle":e.extend({remote:!/#/.test(r)&&r},i.data(),n.data());t.preventDefault(),i.modal(s).one("hide",function(){n.focus()})})}(window.jQuery),!function(e){"use strict";var t=function(e,t){this.init("tooltip",e,t)};t.prototype={constructor:t,init:function(t,n,r){var i,s,o,u,a;this.type=t,this.$element=e(n),this.options=this.getOptions(r),this.enabled=!0,o=this.options.trigger.split(" ");for(a=o.length;a--;)u=o[a],u=="click"?this.$element.on("click."+this.type,this.options.selector,e.proxy(this.toggle,this)):u!="manual"&&(i=u=="hover"?"mouseenter":"focus",s=u=="hover"?"mouseleave":"blur",this.$element.on(i+"."+this.type,this.options.selector,e.proxy(this.enter,this)),this.$element.on(s+"."+this.type,this.options.selector,e.proxy(this.leave,this)));this.options.selector?this._options=e.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},getOptions:function(t){return t=e.extend({},e.fn[this.type].defaults,this.$element.data(),t),t.delay&&typeof t.delay=="number"&&(t.delay={show:t.delay,hide:t.delay}),t},enter:function(t){var n=e.fn[this.type].defaults,r={},i;this._options&&e.each(this._options,function(e,t){n[e]!=t&&(r[e]=t)},this),i=e(t.currentTarget)[this.type](r).data(this.type);if(!i.options.delay||!i.options.delay.show)return i.show();clearTimeout(this.timeout),i.hoverState="in",this.timeout=setTimeout(function(){i.hoverState=="in"&&i.show()},i.options.delay.show)},leave:function(t){var n=e(t.currentTarget)[this.type](this._options).data(this.type);this.timeout&&clearTimeout(this.timeout);if(!n.options.delay||!n.options.delay.hide)return n.hide();n.hoverState="out",this.timeout=setTimeout(function(){n.hoverState=="out"&&n.hide()},n.options.delay.hide)},show:function(){var t,n,r,i,s,o,u=e.Event("show");if(this.hasContent()&&this.enabled){this.$element.trigger(u);if(u.isDefaultPrevented())return;t=this.tip(),this.setContent(),this.options.animation&&t.addClass("fade"),s=typeof this.options.placement=="function"?this.options.placement.call(this,t[0],this.$element[0]):this.options.placement,t.detach().css({top:0,left:0,display:"block"}),this.options.container?t.appendTo(this.options.container):t.insertAfter(this.$element),n=this.getPosition(),r=t[0].offsetWidth,i=t[0].offsetHeight;switch(s){case"bottom":o={top:n.top+n.height,left:n.left+n.width/2-r/2};break;case"top":o={top:n.top-i,left:n.left+n.width/2-r/2};break;case"left":o={top:n.top+n.height/2-i/2,left:n.left-r};break;case"right":o={top:n.top+n.height/2-i/2,left:n.left+n.width}}this.applyPlacement(o,s),this.$element.trigger("shown")}},applyPlacement:function(e,t){var n=this.tip(),r=n[0].offsetWidth,i=n[0].offsetHeight,s,o,u,a;n.offset(e).addClass(t).addClass("in"),s=n[0].offsetWidth,o=n[0].offsetHeight,t=="top"&&o!=i&&(e.top=e.top+i-o,a=!0),t=="bottom"||t=="top"?(u=0,e.left<0&&(u=e.left*-2,e.left=0,n.offset(e),s=n[0].offsetWidth,o=n[0].offsetHeight),this.replaceArrow(u-r+s,s,"left")):this.replaceArrow(o-i,o,"top"),a&&n.offset(e)},replaceArrow:function(e,t,n){this.arrow().css(n,e?50*(1-e/t)+"%":"")},setContent:function(){var e=this.tip(),t=this.getTitle();e.find(".tooltip-inner")[this.options.html?"html":"text"](t),e.removeClass("fade in top bottom left right")},hide:function(){function i(){var t=setTimeout(function(){n.off(e.support.transition.end).detach()},500);n.one(e.support.transition.end,function(){clearTimeout(t),n.detach()})}var t=this,n=this.tip(),r=e.Event("hide");this.$element.trigger(r);if(r.isDefaultPrevented())return;return n.removeClass("in"),e.support.transition&&this.$tip.hasClass("fade")?i():n.detach(),this.$element.trigger("hidden"),this},fixTitle:function(){var e=this.$element;(e.attr("title")||typeof e.attr("data-original-title")!="string")&&e.attr("data-original-title",e.attr("title")||"").attr("title","")},hasContent:function(){return this.getTitle()},getPosition:function(){var t=this.$element[0];return e.extend({},typeof t.getBoundingClientRect=="function"?t.getBoundingClientRect():{width:t.offsetWidth,height:t.offsetHeight},this.$element.offset())},getTitle:function(){var e,t=this.$element,n=this.options;return e=t.attr("data-original-title")||(typeof n.title=="function"?n.title.call(t[0]):n.title),e},tip:function(){return this.$tip=this.$tip||e(this.options.template)},arrow:function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},validate:function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(t){var n=t?e(t.currentTarget)[this.type](this._options).data(this.type):this;n.tip().hasClass("in")?n.hide():n.show()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}};var n=e.fn.tooltip;e.fn.tooltip=function(n){return this.each(function(){var r=e(this),i=r.data("tooltip"),s=typeof n=="object"&&n;i||r.data("tooltip",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.tooltip.Constructor=t,e.fn.tooltip.defaults={animation:!0,placement:"top",selector:!1,template:'
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1},e.fn.tooltip.noConflict=function(){return e.fn.tooltip=n,this}}(window.jQuery),!function(e){"use strict";var t=function(e,t){this.init("popover",e,t)};t.prototype=e.extend({},e.fn.tooltip.Constructor.prototype,{constructor:t,setContent:function(){var e=this.tip(),t=this.getTitle(),n=this.getContent();e.find(".popover-title")[this.options.html?"html":"text"](t),e.find(".popover-content")[this.options.html?"html":"text"](n),e.removeClass("fade top bottom left right in")},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var e,t=this.$element,n=this.options;return e=(typeof n.content=="function"?n.content.call(t[0]):n.content)||t.attr("data-content"),e},tip:function(){return this.$tip||(this.$tip=e(this.options.template)),this.$tip},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}});var n=e.fn.popover;e.fn.popover=function(n){return this.each(function(){var r=e(this),i=r.data("popover"),s=typeof n=="object"&&n;i||r.data("popover",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.popover.Constructor=t,e.fn.popover.defaults=e.extend({},e.fn.tooltip.defaults,{placement:"right",trigger:"click",content:"",template:'

'}),e.fn.popover.noConflict=function(){return e.fn.popover=n,this}}(window.jQuery),!function(e){"use strict";function t(t,n){var r=e.proxy(this.process,this),i=e(t).is("body")?e(window):e(t),s;this.options=e.extend({},e.fn.scrollspy.defaults,n),this.$scrollElement=i.on("scroll.scroll-spy.data-api",r),this.selector=(this.options.target||(s=e(t).attr("href"))&&s.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.$body=e("body"),this.refresh(),this.process()}t.prototype={constructor:t,refresh:function(){var t=this,n;this.offsets=e([]),this.targets=e([]),n=this.$body.find(this.selector).map(function(){var n=e(this),r=n.data("target")||n.attr("href"),i=/^#\w/.test(r)&&e(r);return i&&i.length&&[[i.position().top+(!e.isWindow(t.$scrollElement.get(0))&&t.$scrollElement.scrollTop()),r]]||null}).sort(function(e,t){return e[0]-t[0]}).each(function(){t.offsets.push(this[0]),t.targets.push(this[1])})},process:function(){var e=this.$scrollElement.scrollTop()+this.options.offset,t=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,n=t-this.$scrollElement.height(),r=this.offsets,i=this.targets,s=this.activeTarget,o;if(e>=n)return s!=(o=i.last()[0])&&this.activate(o);for(o=r.length;o--;)s!=i[o]&&e>=r[o]&&(!r[o+1]||e<=r[o+1])&&this.activate(i[o])},activate:function(t){var n,r;this.activeTarget=t,e(this.selector).parent(".active").removeClass("active"),r=this.selector+'[data-target="'+t+'"],'+this.selector+'[href="'+t+'"]',n=e(r).parent("li").addClass("active"),n.parent(".dropdown-menu").length&&(n=n.closest("li.dropdown").addClass("active")),n.trigger("activate")}};var n=e.fn.scrollspy;e.fn.scrollspy=function(n){return this.each(function(){var r=e(this),i=r.data("scrollspy"),s=typeof n=="object"&&n;i||r.data("scrollspy",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.scrollspy.Constructor=t,e.fn.scrollspy.defaults={offset:10},e.fn.scrollspy.noConflict=function(){return e.fn.scrollspy=n,this},e(window).on("load",function(){e('[data-spy="scroll"]').each(function(){var t=e(this);t.scrollspy(t.data())})})}(window.jQuery),!function(e){"use strict";var t=function(t){this.element=e(t)};t.prototype={constructor:t,show:function(){var t=this.element,n=t.closest("ul:not(.dropdown-menu)"),r=t.attr("data-target"),i,s,o;r||(r=t.attr("href"),r=r&&r.replace(/.*(?=#[^\s]*$)/,""));if(t.parent("li").hasClass("active"))return;i=n.find(".active:last a")[0],o=e.Event("show",{relatedTarget:i}),t.trigger(o);if(o.isDefaultPrevented())return;s=e(r),this.activate(t.parent("li"),n),this.activate(s,s.parent(),function(){t.trigger({type:"shown",relatedTarget:i})})},activate:function(t,n,r){function o(){i.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),t.addClass("active"),s?(t[0].offsetWidth,t.addClass("in")):t.removeClass("fade"),t.parent(".dropdown-menu")&&t.closest("li.dropdown").addClass("active"),r&&r()}var i=n.find("> .active"),s=r&&e.support.transition&&i.hasClass("fade");s?i.one(e.support.transition.end,o):o(),i.removeClass("in")}};var n=e.fn.tab;e.fn.tab=function(n){return this.each(function(){var r=e(this),i=r.data("tab");i||r.data("tab",i=new t(this)),typeof n=="string"&&i[n]()})},e.fn.tab.Constructor=t,e.fn.tab.noConflict=function(){return e.fn.tab=n,this},e(document).on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(t){t.preventDefault(),e(this).tab("show")})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.$element=e(t),this.options=e.extend({},e.fn.typeahead.defaults,n),this.matcher=this.options.matcher||this.matcher,this.sorter=this.options.sorter||this.sorter,this.highlighter=this.options.highlighter||this.highlighter,this.updater=this.options.updater||this.updater,this.source=this.options.source,this.$menu=e(this.options.menu),this.shown=!1,this.listen()};t.prototype={constructor:t,select:function(){var e=this.$menu.find(".active").attr("data-value");return this.$element.val(this.updater(e)).change(),this.hide()},updater:function(e){return e},show:function(){var t=e.extend({},this.$element.position(),{height:this.$element[0].offsetHeight});return this.$menu.insertAfter(this.$element).css({top:t.top+t.height,left:t.left}).show(),this.shown=!0,this},hide:function(){return this.$menu.hide(),this.shown=!1,this},lookup:function(t){var n;return this.query=this.$element.val(),!this.query||this.query.length"+t+""})},render:function(t){var n=this;return t=e(t).map(function(t,r){return t=e(n.options.item).attr("data-value",r),t.find("a").html(n.highlighter(r)),t[0]}),t.first().addClass("active"),this.$menu.html(t),this},next:function(t){var n=this.$menu.find(".active").removeClass("active"),r=n.next();r.length||(r=e(this.$menu.find("li")[0])),r.addClass("active")},prev:function(e){var t=this.$menu.find(".active").removeClass("active"),n=t.prev();n.length||(n=this.$menu.find("li").last()),n.addClass("active")},listen:function(){this.$element.on("focus",e.proxy(this.focus,this)).on("blur",e.proxy(this.blur,this)).on("keypress",e.proxy(this.keypress,this)).on("keyup",e.proxy(this.keyup,this)),this.eventSupported("keydown")&&this.$element.on("keydown",e.proxy(this.keydown,this)),this.$menu.on("click",e.proxy(this.click,this)).on("mouseenter","li",e.proxy(this.mouseenter,this)).on("mouseleave","li",e.proxy(this.mouseleave,this))},eventSupported:function(e){var t=e in this.$element;return t||(this.$element.setAttribute(e,"return;"),t=typeof this.$element[e]=="function"),t},move:function(e){if(!this.shown)return;switch(e.keyCode){case 9:case 13:case 27:e.preventDefault();break;case 38:e.preventDefault(),this.prev();break;case 40:e.preventDefault(),this.next()}e.stopPropagation()},keydown:function(t){this.suppressKeyPressRepeat=~e.inArray(t.keyCode,[40,38,9,13,27]),this.move(t)},keypress:function(e){if(this.suppressKeyPressRepeat)return;this.move(e)},keyup:function(e){switch(e.keyCode){case 40:case 38:case 16:case 17:case 18:break;case 9:case 13:if(!this.shown)return;this.select();break;case 27:if(!this.shown)return;this.hide();break;default:this.lookup()}e.stopPropagation(),e.preventDefault()},focus:function(e){this.focused=!0},blur:function(e){this.focused=!1,!this.mousedover&&this.shown&&this.hide()},click:function(e){e.stopPropagation(),e.preventDefault(),this.select(),this.$element.focus()},mouseenter:function(t){this.mousedover=!0,this.$menu.find(".active").removeClass("active"),e(t.currentTarget).addClass("active")},mouseleave:function(e){this.mousedover=!1,!this.focused&&this.shown&&this.hide()}};var n=e.fn.typeahead;e.fn.typeahead=function(n){return this.each(function(){var r=e(this),i=r.data("typeahead"),s=typeof n=="object"&&n;i||r.data("typeahead",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.typeahead.defaults={source:[],items:8,menu:'',item:'
  • ',minLength:1},e.fn.typeahead.Constructor=t,e.fn.typeahead.noConflict=function(){return e.fn.typeahead=n,this},e(document).on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(t){var n=e(this);if(n.data("typeahead"))return;n.typeahead(n.data())})}(window.jQuery),!function(e){"use strict";var t=function(t,n){this.options=e.extend({},e.fn.affix.defaults,n),this.$window=e(window).on("scroll.affix.data-api",e.proxy(this.checkPosition,this)).on("click.affix.data-api",e.proxy(function(){setTimeout(e.proxy(this.checkPosition,this),1)},this)),this.$element=e(t),this.checkPosition()};t.prototype.checkPosition=function(){if(!this.$element.is(":visible"))return;var t=e(document).height(),n=this.$window.scrollTop(),r=this.$element.offset(),i=this.options.offset,s=i.bottom,o=i.top,u="affix affix-top affix-bottom",a;typeof i!="object"&&(s=o=i),typeof o=="function"&&(o=i.top()),typeof s=="function"&&(s=i.bottom()),a=this.unpin!=null&&n+this.unpin<=r.top?!1:s!=null&&r.top+this.$element.height()>=t-s?"bottom":o!=null&&n<=o?"top":!1;if(this.affixed===a)return;this.affixed=a,this.unpin=a=="bottom"?r.top-n:null,this.$element.removeClass(u).addClass("affix"+(a?"-"+a:""))};var n=e.fn.affix;e.fn.affix=function(n){return this.each(function(){var r=e(this),i=r.data("affix"),s=typeof n=="object"&&n;i||r.data("affix",i=new t(this,s)),typeof n=="string"&&i[n]()})},e.fn.affix.Constructor=t,e.fn.affix.defaults={offset:0},e.fn.affix.noConflict=function(){return e.fn.affix=n,this},e(window).on("load",function(){e('[data-spy="affix"]').each(function(){var t=e(this),n=t.data();n.offset=n.offset||{},n.offsetBottom&&(n.offset.bottom=n.offsetBottom),n.offsetTop&&(n.offset.top=n.offsetTop),t.affix(n)})})}(window.jQuery); \ No newline at end of file diff --git a/opendaylight/adsal/web/root/src/main/resources/js/datasource.js b/opendaylight/adsal/web/root/src/main/resources/js/datasource.js deleted file mode 100755 index 8226df0cfe..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/js/datasource.js +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Fuel UX Data components - static data source - * https://github.com/ExactTarget/fuelux-data - * - * Copyright (c) 2012 ExactTarget - * Licensed under the MIT license. - */ - -(function (root, factory) { - if (typeof define === 'function' && define.amd) { - define(['underscore'], factory); - } else { - root.StaticDataSource = factory(); - } -}(this, function () { - - var StaticDataSource = function (options) { - this._formatter = options.formatter; - this._columns = options.columns; - this._delay = options.delay || 0; - this._data = options.data; - }; - - StaticDataSource.prototype = { - - columns: function () { - return this._columns; - }, - - data: function (options, callback) { - var self = this; - - setTimeout(function () { - var data = $.extend(true, [], self._data); - - // SEARCHING - if (options.search) { - data = _.filter(data, function (item) { - var match = false; - - _.each(item, function (prop) { - if (_.isString(prop) || _.isFinite(prop)) { - if (prop.toString().toLowerCase().indexOf(options.search.toLowerCase()) !== -1) match = true; - } - }); - - return match; - }); - } - - // FILTERING - if (options.filter) { - data = _.filter(data, function (item) { - switch(options.filter.value) { - case 'lt5m': - if(item.population < 5000000) return true; - break; - case 'gte5m': - if(item.population >= 5000000) return true; - break; - default: - return true; - break; - } - }); - } - - var count = data.length; - - // SORTING - if (options.sortProperty) { - data = _.sortBy(data, options.sortProperty); - if (options.sortDirection === 'desc') data.reverse(); - } - - // PAGING - var startIndex = options.pageIndex * options.pageSize; - var endIndex = startIndex + options.pageSize; - var end = (endIndex > count) ? count : endIndex; - var pages = Math.ceil(count / options.pageSize); - var page = options.pageIndex + 1; - var start = startIndex + 1; - - data = data.slice(startIndex, endIndex); - - if (self._formatter) self._formatter(data); - - callback({ data: data, start: start, end: end, count: count, pages: pages, page: page }); - - }, this._delay) - } - }; - - return StaticDataSource; -})); diff --git a/opendaylight/adsal/web/root/src/main/resources/js/fuelux/COPYING b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/COPYING deleted file mode 100644 index 9b8ce79b51..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/js/fuelux/COPYING +++ /dev/null @@ -1,33 +0,0 @@ -Copyright (C) 2012, ExactTarget, Inc. -All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in the -Software without restriction, including without limitation the rights to use, copy, -modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, -and to permit persons to whom the Software is furnished to do so, subject to the -following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF -CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -==================================================================== - -The above license does not apply to the following bundled components: - -Â¥ jQuery located at lib/jquery.js -Â¥ Bootstrap Apache 2.0 Located under lib/bootstrap -Â¥ RequireJS located at lib/require.js -Â¥ QUnit located under lib/qunit -Â¥ Grunt located under node-modules/grunt -Â¥ Grunt-contrib located under node-modules/grunt-contrib -Â¥ Grunt-recess located under node-modules/grunt-recess - -Licensing information regarding the above packages can be found in the THIRD-PARTY file. \ No newline at end of file diff --git a/opendaylight/adsal/web/root/src/main/resources/js/fuelux/all.min.js b/opendaylight/adsal/web/root/src/main/resources/js/fuelux/all.min.js deleted file mode 100755 index 2f9e721648..0000000000 --- a/opendaylight/adsal/web/root/src/main/resources/js/fuelux/all.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! Fuel UX - v2.3.1 - 2013-08-02 -* https://github.com/ExactTarget/fuelux -* Copyright (c) 2013 ExactTarget; Licensed MIT */ -(function(){(function(a){var b;define("bootstrap/bootstrap-transition",["jquery"],function(){return function(){!function(a){a(function(){a.support.transition=function(){var a=function(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},c;for(c in b)if(a.style[c]!==undefined)return b[c]}();return a&&{end:a}}()})}(window.jQuery)}.call(a),b})})(this),function(a){var b;define("bootstrap/bootstrap-affix",["bootstrap/bootstrap-transition"],function(){return function(){!function(a){var b=function(b,c){this.options=a.extend({},a.fn.affix.defaults,c),this.$window=a(window).on("scroll.affix.data-api",a.proxy(this.checkPosition,this)).on("click.affix.data-api",a.proxy(function(){setTimeout(a.proxy(this.checkPosition,this),1)},this)),this.$element=a(b),this.checkPosition()};b.prototype.checkPosition=function(){if(!this.$element.is(":visible"))return;var b=a(document).height(),c=this.$window.scrollTop(),d=this.$element.offset(),e=this.options.offset,f=e.bottom,g=e.top,h="affix affix-top affix-bottom",i;typeof e!="object"&&(f=g=e),typeof g=="function"&&(g=e.top()),typeof f=="function"&&(f=e.bottom()),i=this.unpin!=null&&c+this.unpin<=d.top?!1:f!=null&&d.top+this.$element.height()>=b-f?"bottom":g!=null&&c<=g?"top":!1;if(this.affixed===i)return;this.affixed=i,this.unpin=i=="bottom"?d.top-c:null,this.$element.removeClass(h).addClass("affix"+(i?"-"+i:""))};var c=a.fn.affix;a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("affix"),f=typeof c=="object"&&c;e||d.data("affix",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.defaults={offset:0},a.fn.affix.noConflict=function(){return a.fn.affix=c,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(window.jQuery)}.call(a),b})}(this),function(a){var b;define("bootstrap/bootstrap-alert",["bootstrap/bootstrap-transition"],function(){return function(){!function(a){var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function f(){e.trigger("closed").remove()}var c=a(this),d=c.attr("data-target"),e;d||(d=c.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),e=a(d),b&&b.preventDefault(),e.length||(e=c.hasClass("alert")?c:c.parent()),e.trigger(b=a.Event("close"));if(b.isDefaultPrevented())return;e.removeClass("in"),a.support.transition&&e.hasClass("fade")?e.on(a.support.transition.end,f):f()};var d=a.fn.alert;a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("alert");e||d.data("alert",e=new c(this)),typeof b=="string"&&e[b].call(d)})},a.fn.alert.Constructor=c,a.fn.alert.noConflict=function(){return a.fn.alert=d,this},a(document).on("click.alert.data-api",b,c.prototype.close)}(window.jQuery)}.call(a),b})}(this),function(a){var b;define("bootstrap/bootstrap-button",["bootstrap/bootstrap-transition"],function(){return function(){!function(a){var b=function(b,c){this.$element=a(b),this.options=a.extend({},a.fn.button.defaults,c)};b.prototype.setState=function(a){var b="disabled",c=this.$element,d=c.data(),e=c.is("input")?"val":"html";a=a+"Text",d.resetText||c.data("resetText",c[e]()),c[e](d[a]||this.options[a]),setTimeout(function(){a=="loadingText"?c.addClass(b).attr(b,b):c.removeClass(b).removeAttr(b)},0)},b.prototype.toggle=function(){var a=this.$element.closest('[data-toggle="buttons-radio"]');a&&a.find(".active").removeClass("active"),this.$element.toggleClass("active")};var c=a.fn.button;a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("button"),f=typeof c=="object"&&c;e||d.data("button",e=new b(this,f)),c=="toggle"?e.toggle():c&&e.setState(c)})},a.fn.button.defaults={loadingText:"loading..."},a.fn.button.Constructor=b,a.fn.button.noConflict=function(){return a.fn.button=c,this},a(document).on("click.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle")})}(window.jQuery)}.call(a),b})}(this),function(a){var b;define("bootstrap/bootstrap-carousel",["bootstrap/bootstrap-transition"],function(){return function(){!function(a){var b=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.options.pause=="hover"&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.prototype={cycle:function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},getActiveIndex:function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},to:function(b){var c=this.getActiveIndex(),d=this;if(b>this.$items.length-1||b<0)return;return this.sliding?this.$element.one("slid",function(){d.to(b)}):c==b?this.pause().cycle():this.slide(b>c?"next":"prev",a(this.$items[b]))},pause:function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition.end&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),clearInterval(this.interval),this.interval=null,this},next:function(){if(this.sliding)return;return this.slide("next")},prev:function(){if(this.sliding)return;return this.slide("prev")},slide:function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g=b=="next"?"left":"right",h=b=="next"?"first":"last",i=this,j;this.sliding=!0,f&&this.pause(),e=e.length?e:this.$element.find(".item")[h](),j=a.Event("slide",{relatedTarget:e[0],direction:g});if(e.hasClass("active"))return;this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid",function(){var b=a(i.$indicators.children()[i.getActiveIndex()]);b&&b.addClass("active")}));if(a.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(j);if(j.isDefaultPrevented())return;e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),this.$element.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid")},0)})}else{this.$element.trigger(j);if(j.isDefaultPrevented())return;d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return f&&this.cycle(),this}};var c=a.fn.carousel;a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("carousel"),f=a.extend({},a.fn.carousel.defaults,typeof c=="object"&&c),g=typeof c=="string"?c:f.slide;e||d.data("carousel",e=new b(this,f)),typeof c=="number"?e.to(c):g?e[g]():f.interval&&e.pause().cycle()})},a.fn.carousel.defaults={interval:5e3,pause:"hover"},a.fn.carousel.Constructor=b,a.fn.carousel.noConflict=function(){return a.fn.carousel=c,this},a(document).on("click.carousel.data-api","[data-slide], [data-slide-to]",function(b){var c=a(this),d,e=a(c.attr("data-target")||(d=c.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,"")),f=a.extend({},e.data(),c.data()),g;e.carousel(f),(g=c.attr("data-slide-to"))&&e.data("carousel").pause().to(g).cycle(),b.preventDefault()})}(window.jQuery)}.call(a),b})}(this),function(a){var b;define("bootstrap/bootstrap-collapse",["bootstrap/bootstrap-transition"],function(){return function(){!function(a){var b=function(b,c){this.$element=a(b),this.options=a.extend({},a.fn.collapse.defaults,c),this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.prototype={constructor:b,dimension:function(){var a=this.$element.hasClass("width");return a?"width":"height"},show:function(){var b,c,d,e;if(this.transitioning||this.$element.hasClass("in"))return;b=this.dimension(),c=a.camelCase(["scroll",b].join("-")),d=this.$parent&&this.$parent.find("> .accordion-group > .in");if(d&&d.length){e=d.data("collapse");if(e&&e.transitioning)return;d.collapse("hide"),e||d.data("collapse",null)}this.$element[b](0),this.transition("addClass",a.Event("show"),"shown"),a.support.transition&&this.$element[b](this.$element[0][c])},hide:function(){var b;if(this.transitioning||!this.$element.hasClass("in"))return;b=this.dimension(),this.reset(this.$element[b]()),this.transition("removeClass",a.Event("hide"),"hidden"),this.$element[b](0)},reset:function(a){var b=this.dimension();return this.$element.removeClass("collapse")[b](a||"auto")[0].offsetWidth,this.$element[a!==null?"addClass":"removeClass"]("collapse"),this},transition:function(b,c,d){var e=this,f=function(){c.type=="show"&&e.reset(),e.transitioning=0,e.$element.trigger(d)};this.$element.trigger(c);if(c.isDefaultPrevented())return;this.transitioning=1,this.$element[b]("in"),a.support.transition&&this.$element.hasClass("collapse")?this.$element.one(a.support.transition.end,f):f()},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}};var c=a.fn.collapse;a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("collapse"),f=a.extend({},a.fn.collapse.defaults,d.data(),typeof c=="object"&&c);e||d.data("collapse",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.collapse.defaults={toggle:!0},a.fn.collapse.Constructor=b,a.fn.collapse.noConflict=function(){return a.fn.collapse=c,this},a(document).on("click.collapse.data-api","[data-toggle=collapse]",function(b){var c=a(this),d,e=c.attr("data-target")||b.preventDefault()||(d=c.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),f=a(e).data("collapse")?"toggle":c.data();c[a(e).hasClass("in")?"addClass":"removeClass"]("collapsed"),a(e).collapse(f)})}(window.jQuery)}.call(a),b})}(this),function(a){var b;define("bootstrap/bootstrap-dropdown",["bootstrap/bootstrap-transition"],function(){return function(){!function(a){function d(){a(".dropdown-backdrop").remove(),a(b).each(function(){e(a(this)).removeClass("open")})}function e(b){var c=b.attr("data-target"),d;c||(c=b.attr("href"),c=c&&/#/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,"")),d=c&&a(c);if(!d||!d.length)d=b.parent();return d}var b="[data-toggle=dropdown]",c=function(b){var c=a(b).on("click.dropdown.data-api",this.toggle);a("html").on("click.dropdown.data-api",function(){c.parent().removeClass("open")})};c.prototype={constructor:c,toggle:function(b){var c=a(this),f,g;if(c.is(".disabled, :disabled"))return;return f=e(c),g=f.hasClass("open"),d(),g||("ontouchstart"in document.documentElement&&a('