import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.experimenter.types.rev151020.experimenter.core.message.ExperimenterMessageOfChoice;
import org.opendaylight.yangtools.yang.binding.DataContainer;
-/**
- *
- */
public interface ExtensionConverterProvider {
/**
import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
-/**
- * Created by Martin Bobak mbobak@cisco.com on 10/15/14.
- */
public interface ExtensionSessionManager {
/**
- * @param extensionConverterProvider
+ * @param extensionConverterProvider extension converter provider
*/
void setExtensionConverterProvider(ExtensionConverterProvider extensionConverterProvider);
*/
package org.opendaylight.openflowplugin.api;
+import com.google.common.collect.ImmutableList;
import java.math.BigInteger;
+import java.util.List;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
/** Persistent ID of OpenFlowPlugin configuration file. */
public static final String CONFIG_FILE_ID = "org.opendaylight.openflowplugin";
-}
+
+ /** supported version ordered by height (highest version is at the beginning). */
+ public static final List<Short> VERSION_ORDER = ImmutableList
+ .<Short>builder()
+ .add((short) 0x04, (short) 0x01)
+ .build();
+}
\ No newline at end of file
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md;
-
-import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
-
-public abstract class AbstractModelDrivenSwitchRegistration
- extends AbstractObjectRegistration<ModelDrivenSwitch>
- implements ModelDrivenSwitchRegistration {
-
- protected AbstractModelDrivenSwitchRegistration(final ModelDrivenSwitch instance) {
- super(instance);
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md;
-
-import com.google.common.base.Optional;
-import java.math.BigInteger;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.OpendaylightFlowTableStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.SalGroupService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.OpendaylightGroupStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.SalMeterService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.OpendaylightMeterStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.NodeConfigService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.SalPortService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.OpendaylightQueueStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.SalTableService;
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * interface concatenating all md-sal services provided by OF-switch.
- */
-public interface ModelDrivenSwitch
- extends
- SalGroupService,
- SalFlowService,
- SalMeterService, SalTableService, SalPortService, PacketProcessingService, NodeConfigService,
- OpendaylightGroupStatisticsService, OpendaylightMeterStatisticsService, OpendaylightFlowStatisticsService,
- OpendaylightPortStatisticsService, OpendaylightFlowTableStatisticsService, OpendaylightQueueStatisticsService,
- Identifiable<InstanceIdentifier<Node>> {
-
- /**
- * Register.
- * @param rpcProviderRegistry rpc provider
- * @return wrapped list of {service provider + path} registration couples
- */
- ModelDrivenSwitchRegistration register(RpcProviderRegistry rpcProviderRegistry);
-
- /**
- * Getter.
- * @return id of encapsulated node (served by this impl)
- */
- NodeId getNodeId();
-
- /**
- * returnes the session context associated with this model-driven switch.
- *
- * @return session context object
- */
- SessionContext getSessionContext();
-
- /**
- * Returns whether this *instance* is entity owner or not.
- * @return true if it's entity owner, else false.
- */
- boolean isEntityOwner();
-
- /**
- * Set entity ownership satus of this switch in *this* instance.
- * @param isOwner is owner
- */
- void setEntityOwnership(boolean isOwner);
-
- /**
- * Send table feature to the switch to get tables features for all the tables.
- * @return Transaction id
- */
- Optional<BigInteger> sendEmptyTableFeatureRequest();
-
- /**
- * Method send port/desc multipart request to the switch to fetch the initial details.
- */
- void requestSwitchDetails();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md;
-
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
-
-public interface ModelDrivenSwitchRegistration extends ObjectRegistration<ModelDrivenSwitch> {
- @Override
- void close();
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.api.openflow.md.core;
-
-import com.google.common.collect.Lists;
-import java.util.List;
-import java.util.concurrent.Future;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-
-
-public interface ConnectionConductor {
-
- /** distinguished connection states. */
- @SuppressWarnings({"checkstyle:abbreviationaswordinname", "checkstyle:typename"})
- enum CONDUCTOR_STATE {
- /** initial phase of talking to switch. */
- HANDSHAKING,
- /** standard phase - interacting with switch. */
- WORKING,
- /** connection is idle, waiting for echo reply from switch. */
- TIMEOUTING,
- /** talking to switch is over - resting in pieces. */
- RIP
- }
-
- /** supported version ordered by height (highest version is at the beginning). */
- List<Short> VERSION_ORDER = Lists.newArrayList((short) 0x04, (short) 0x01);
-
- /**
- * initialize wiring around {@link ConnectionAdapter}.
- */
- void init();
-
- /**
- * return the negotiated version.
- */
- Short getVersion();
-
- /**
- * return the state of conductor.
- */
- CONDUCTOR_STATE getConductorState();
-
- /**
- * Setter.
- * @param conductorState state
- */
- void setConductorState(CONDUCTOR_STATE conductorState);
-
- /**
- * terminates owned connection.
- * @return future result of disconnect action
- */
- Future<Boolean> disconnect();
-
- /**
- * assign corresponding {@link SessionContext} to this conductor (to handle disconnect caused by switch).
- * @param context session context
- */
- void setSessionContext(SessionContext context);
-
- /**
- * assign corresponding {@link org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher}
- * to this conductor to handle disconnect caused by switch. This involves auxiliary conductors only.
- * @param auxiliaryKey key
- */
- void setConnectionCookie(SwitchConnectionDistinguisher auxiliaryKey);
-
- /**
- * return the sessionContext.
- */
- SessionContext getSessionContext();
-
- /**
- * return the auxiliaryKey (null if this is a primary connection).
- */
- SwitchConnectionDistinguisher getAuxiliaryKey();
-
- /**
- * return the connectionAdapter.
- */
- ConnectionAdapter getConnectionAdapter();
-
- /**
- * assign global queueKeeper.
- * @param queueKeeper keeper
- */
- void setQueueProcessor(QueueProcessor<OfHeader, DataObject> queueKeeper);
-
- /**
- * Setter.
- * @param errorHandler for internal exception handling
- */
- void setErrorHandler(ErrorHandler errorHandler);
-
- /**
- * Setter.
- * @param conductorId id
- */
- void setId(int conductorId);
-
-}
*/
package org.opendaylight.openflowplugin.api.openflow.md.core;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-
public interface ErrorHandler {
/**
* Exception handler.
* @param throwable cause
- * @param sessionContext of source
*/
- void handleException(Throwable throwable, SessionContext sessionContext);
+ void handleException(Throwable throwable);
}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md.core;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-
-/**
- * translates between messages.
- * @param <I> source message type (IN)
- * @param <O> result message type (OUT)
- */
-public interface IMDMessageTranslator<I, O> {
-
- /**
- * This method is called in order to translate message to MD-SAL or from MD-SAL.
- * @param cookie auxiliary connection identifier
- * @param sc The SessionContext which sent the OF message
- * @param msg The OF message
- * @return translated message
- */
- O translate(SwitchConnectionDistinguisher cookie, SessionContext sc, I msg);
-
-}
+++ /dev/null
-/*
- * 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.openflowplugin.api.openflow.md.core;
-
-/**
- * provider of wrapped notification enqueue.
- */
-public interface NotificationEnqueuer {
-
- /**
- * enqueue given notification into standard message processing queue.
- * @param notification notification
- */
- void enqueueNotification(NotificationQueueWrapper notification);
-
-}
+++ /dev/null
-/*
- * 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.openflowplugin.api.openflow.md.core;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.Notification;
-
-public class NotificationQueueWrapper implements OfHeader {
-
- private final Notification notification;
- private final Short version;
- private Long xid = -1L;
-
-
- /**
- * Notofication queue wrapper.
- * @param notification notofication
- * @param version version
- */
- public NotificationQueueWrapper(final Notification notification, final Short version) {
- Preconditions.checkArgument(notification != null, "wrapped notification must not be null");
- Preconditions.checkArgument(version != null, "message version of wrapped notification must not be null");
- this.notification = notification;
- this.version = version;
- }
-
- @Override
- public Class<? extends DataContainer> getImplementedInterface() {
- return NotificationQueueWrapper.class;
- }
-
- @Override
- public Short getVersion() {
- return version;
- }
-
- @Override
- public Long getXid() {
- return xid;
- }
-
- /**
- * return the notification.
- */
- public Notification getNotification() {
- return notification;
- }
-
- /**
- * Setter.
- * @param xid the xid to set
- */
- public void setXid(Long xid) {
- this.xid = xid;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.api.openflow.md.core;
-
-public interface SwitchConnectionDistinguisher {
-
- /**
- * Getter.
- * @return encoded switch session identifier
- */
- long getCookie();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md.core.sal;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
-import org.opendaylight.yangtools.yang.binding.Notification;
-
-/**
- * Notification composer.
- * @param <N> type of notification
- */
-public interface NotificationComposer<N extends Notification> {
-
- /**
- * Compose.
- * @param xid corresponding OF transaction id
- * @return notification instance
- */
- N compose(TransactionId xid);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM 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.openflowplugin.api.openflow.md.core.session;
-
-import java.util.concurrent.Future;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-
-/**
- * Message Dispatch Service to send the message to switch.
- */
-public interface IMessageDispatchService {
-
- String CONNECTION_ERROR_MESSAGE = "Session for the cookie is invalid. Reason: "
- + "the switch has been recently disconnected OR inventory provides outdated information.";
-
- /**
- * send barrier message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<BarrierOutput>> barrier(BarrierInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send experimenter message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<java.lang.Void>> experimenter(ExperimenterInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send flow modification message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<UpdateFlowOutput>> flowMod(FlowModInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send get async message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<GetAsyncOutput>> getAsync(GetAsyncInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send get config message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<GetConfigOutput>> getConfig(GetConfigInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send get features message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<GetFeaturesOutput>> getFeatures(GetFeaturesInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send get queue config message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<GetQueueConfigOutput>> getQueueConfig(GetQueueConfigInput input,
- SwitchConnectionDistinguisher cookie);
-
- /**
- * send group modification message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<UpdateGroupOutput>> groupMod(GroupModInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send meter modification message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<UpdateMeterOutput>> meterMod(MeterModInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send multipart request message to switch.
- *
- * @param input
- * - multipart request message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<java.lang.Void>> multipartRequest(
- MultipartRequestInput input,
- SwitchConnectionDistinguisher cookie);
-
- /**
- * send packet out message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<java.lang.Void>> packetOut(PacketOutInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send port modification message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<UpdatePortOutput>> portMod(PortModInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send role request message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<RoleRequestOutput>> roleRequest(RoleRequestInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send set async message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<java.lang.Void>> setAsync(SetAsyncInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send set config message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<java.lang.Void>> setConfig(SetConfigInput input, SwitchConnectionDistinguisher cookie);
-
- /**
- * send table modification message to switch.
- *
- * @param input
- * - message
- * @param cookie
- * - to identify connection if null then feel free to send via
- * any connection
- * @return - the future
- */
- Future<RpcResult<java.lang.Void>> tableMod(TableModInput input, SwitchConnectionDistinguisher cookie);
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.api.openflow.md.core.session;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
-
-public interface SessionContext {
-
- /**
- * return primary connection wrapper.
- */
- ConnectionConductor getPrimaryConductor();
-
- /**
- * return the features of corresponding switch.
- */
- GetFeaturesOutput getFeatures();
-
- /**
- * Auxiliary connections.
- * @param auxiliaryKey key under which the auxiliary conductor is stored
- * @return list of auxiliary connection wrappers
- */
- ConnectionConductor getAuxiliaryConductor(
- SwitchConnectionDistinguisher auxiliaryKey);
-
- /**
- * return entries of all auxiliary connections wrapped in conductors in this session.
- */
- Set<Entry<SwitchConnectionDistinguisher, ConnectionConductor>> getAuxiliaryConductors();
-
- /**
- * register new auxiliary connection wrapped in {@link ConnectionConductor}.
- *
- * @param auxiliaryKey key
- * @param conductor connection conductor
- */
- void addAuxiliaryConductor(SwitchConnectionDistinguisher auxiliaryKey,
- ConnectionConductor conductor);
-
- /**
- * Remove conductor.
- * @param connectionCookie cookie
- * @return removed connectionConductor
- */
- ConnectionConductor removeAuxiliaryConductor(
- SwitchConnectionDistinguisher connectionCookie);
-
- /**
- * return true if this session is valid.
- */
- boolean isValid();
-
- /**
- * Setter.
- * @param valid the valid to set
- */
- void setValid(boolean valid);
-
- /**
- * return the sessionKey.
- */
- SwitchSessionKeyOF getSessionKey();
-
- /**
- * Returns a map containing all OFPhysicalPorts of this switch.
- *
- * @return The Map of OFPhysicalPort
- */
- @Deprecated
- Map<Long, PortGrouping> getPhysicalPorts();
-
- /**
- * Returns a map containing all bandwidths for all OFPorts of this switch.
- *
- * @return The Map of bandwidths for all OFPorts
- */
- @Deprecated
- Map<Long, Boolean> getPortsBandwidth();
-
- /**
- * Returns a Set containing all port IDs of this switch.
- *
- * @return The Set of port ID
- */
- @Deprecated
- Set<Long> getPorts();
-
- /**
- * Returns OFPhysicalPort of the specified portNumber of this switch.
- *
- * @param portNumber The port ID
- * @return OFPhysicalPort for the specified PortNumber
- */
- PortGrouping getPhysicalPort(Long portNumber);
-
- /**
- * Returns the bandwidth of the specified portNumber of this switch.
- *
- * @param portNumber the port ID
- * @return bandwidth
- */
- Boolean getPortBandwidth(Long portNumber);
-
- /**
- * Returns True if the port is enabled.
- *
- * @param portNumber port number
- * @return True if the port is enabled
- */
- boolean isPortEnabled(long portNumber);
-
- /**
- * Returns True if the port is enabled.
- *
- * @param port port
- * @return True if the port is enabled
- */
- boolean isPortEnabled(PortGrouping port);
-
- /**
- * Returns a list containing all enabled ports of this switch.
- *
- * @return List containing all enabled ports of this switch
- */
- List<PortGrouping> getEnabledPorts();
-
- // TODO:: add listeners here, manager will set them and conductor use them
-
- /**
- * get message dispatch service to send the message to switch.
- *
- * @return the message service
- */
- IMessageDispatchService getMessageDispatchService();
-
- /**
- * return the unique xid for this session.
- * @return xid
- */
- Long getNextXid();
-
- /**
- * Setter.
- * @param registration provider composite registration
- */
- void setProviderRegistration(ModelDrivenSwitchRegistration registration);
-
- /**
- * return provider composite registration.
- * @return ModelDrivenSwitchRegistration
- */
- ModelDrivenSwitchRegistration getProviderRegistration();
-
- /**
- * return seed value for random operations.
- * @return int
- */
- int getSeed();
-
- /**
- * return (wrapped) notification enqueue service - {@link NotificationQueueWrapper}.
- * @return NotificationEnqueuer
- */
- NotificationEnqueuer getNotificationEnqueuer();
-
- /**
- * Setter.
- * @param roleOnDevice role
- */
- void setRoleOnDevice(ControllerRole roleOnDevice);
-
- /**
- * return actual role.
- * @return role
- */
- ControllerRole getRoleOnDevice();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md.core.session;
-
-import java.util.EventListener;
-
-/**
- * listens on session changes.
- */
-public interface SessionListener extends EventListener {
-
- /**
- * fired upon session added.
- * @param sessionKey session key
- * @param context context
- */
- void onSessionAdded(SwitchSessionKeyOF sessionKey, SessionContext context);
-
- /**
- * fired upon session removed.
- * @param context context
- */
- void onSessionRemoved(SessionContext context);
-
- void setRole(SessionContext context);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.api.openflow.md.core.session;
-
-import com.google.common.util.concurrent.ListeningExecutorService;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-
-public interface SessionManager extends AutoCloseable {
-
- /**
- * primary connection.
- * @param sessionKey session key
- * @return corresponding conductor, holding {@link ConnectionAdapter} to
- */
- SessionContext getSessionContext(SwitchSessionKeyOF sessionKey);
-
- /**
- * disconnect all underlying {@link ConnectionAdapter}s and notify listeners.
- *
- * @param sessionKey session key
- */
- void invalidateSessionContext(SwitchSessionKeyOF sessionKey);
-
- /**
- * register session context.
- *
- * @param sessionKey session key
- * @param context context
- */
- void addSessionContext(SwitchSessionKeyOF sessionKey, SessionContext context);
-
- void setRole(SessionContext context);
-
- /**
- * disconnect particular auxiliary {@link ConnectionAdapter}, identified by
- * sessionKey and connectionCookie.
- *
- * @param sessionKey session key
- * @param connectionCookie cookie
- */
- void invalidateAuxiliary(SwitchSessionKeyOF sessionKey,
- SwitchConnectionDistinguisher connectionCookie);
-
- /**
- * Invalidate on disconnect.
- * @param connectionConductor connection conductor.
- */
- void invalidateOnDisconnect(ConnectionConductor connectionConductor);
-
- /**
- * Setter.
- * @param translatorMapping translators
- */
- void setTranslatorMapping(
- Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping);
-
- /**
- * Getter.
- * @return translator mapping
- */
- Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> getTranslatorMapping();
-
- /**
- * Setter.
- * @param notificationProviderService notofication provider
- */
- void setNotificationProviderService(NotificationProviderService notificationProviderService);
-
- /**
- * Getter.
- * @return notificationServiceProvider
- */
- DataBroker getDataBroker();
-
- /**
- * Setter.
- * @param dataBroker databroker
- */
- void setDataBroker(DataBroker dataBroker);
-
- /**
- * Gatter.
- * @return notificationServiceProvider
- */
- NotificationProviderService getNotificationProviderService();
-
- /**
- * Session listener registration.
- * @param listener listener
- * @return registration
- */
- ListenerRegistration<SessionListener> registerSessionListener(SessionListener listener);
-
- /**
- * Getter.
- * @return popListener mapping, key=message type; value=collection of listeners
- */
- Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> getPopListenerMapping();
-
- /**
- * Setter.
- * @param popListenerMapping the popListenerMapping to set
- */
- void setPopListenerMapping(
- Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> popListenerMapping);
-
- /**
- * Setter.
- * @param rpcPoolDelegator rpc pool delegator
- */
- void setRpcPool(ListeningExecutorService rpcPoolDelegator);
-
- /**
- * Getter.
- * @return the rpcPool instance
- */
- ListeningExecutorService getRpcPool();
-
- /**
- * Setter.
- * @param messageSpy message spy
- */
- void setMessageSpy(MessageSpy<DataContainer> messageSpy);
-
- /**
- * Getter.
- * @return the messageSpy
- */
- MessageSpy<DataContainer> getMessageSpy();
-
- /**
- * Getter.
- * @return collection of current sessions
- */
- Collection<SessionContext> getAllSessions();
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.api.openflow.md.core.session;
-
-import java.math.BigInteger;
-
-public class SwitchSessionKeyOF {
-
- private BigInteger datapathId;
-
- /**
- * default ctor.
- */
- public SwitchSessionKeyOF() {
- // NOOP
- }
-
- /**
- * Setter.
- * @param datapathId the datapathId to set
- */
- public void setDatapathId(BigInteger datapathId) {
- this.datapathId = datapathId;
- }
-
- /**
- * Getter.
- * @return the datapathId
- */
- public byte[] getId() {
- return datapathId.toByteArray();
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result
- + ((datapathId == null) ? 0 : datapathId.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;
- }
- SwitchSessionKeyOF other = (SwitchSessionKeyOF) obj;
- if (datapathId == null) {
- if (other.datapathId != null) {
- return false;
- }
- } else if (!datapathId.equals(other.datapathId)) {
- return false;
- }
- return true;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md.queue;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-
-/**
- * Enqueuer.
- * @param <I> type of queue items (IN)
- */
-public interface Enqueuer<I> {
-
- /**
- * item to be enqueued.
- * @param queueItem item to be enqueued
- */
- void enqueueQueueItem(I queueItem);
-
- /**
- * for testing and comparing purposes - this strategy blocks netty threads.
- * @param queueItem item
- * @deprecated for testing and comparing purposes - this strategy blocks netty threads
- */
- @Deprecated
- void directProcessQueueItem(QueueItem<OfHeader> queueItem);
-}
+++ /dev/null
-/*
- * 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.openflowplugin.api.openflow.md.queue;
-
-/**
- * message harvester simple control.
- */
-public interface HarvesterHandle {
-
- /**
- * wakeup harvester in case it is in phase of starving sleep.
- */
- void ping();
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md.queue;
-
-import java.util.Collection;
-
-/**
- * MessageSourcePollRegistrator.
- * @param <I> message wrapping type (IN)
- *
- */
-public interface MessageSourcePollRegistrator<I> {
-
- /**
- * Message source to read from during processing.
- * @param messageSource to read from during processing
- * @return closeable registration
- */
- AutoCloseable registerMessageSource(I messageSource);
-
- /**
- * Unregister message source.
- * @param messageSource to be unregistered
- * @return true if successfully unregistered
- */
- boolean unregisterMessageSource(I messageSource);
-
- /**
- * Getter.
- * @return collection of registered message sources
- */
- Collection<I> getMessageSources();
-
- /**
- * Getter.
- * @return the harvest handle
- */
- HarvesterHandle getHarvesterHandle();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md.queue;
-
-
-/**
- * PopListener.
- * @param <T> result type
- *
- */
-public interface PopListener<T> {
- void onPop(T processedMessage);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md.queue;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-
-/**
- * Queue item.
- * @param <I> input message type (IN)
- */
-public interface QueueItem<I> {
-
- /**
- * Getter.
- * @return wrapped message
- */
- I getMessage();
-
- /**
- * Getter.
- * @return conductor the message arrived to
- */
- ConnectionConductor getConnectionConductor();
-
- /**
- * Getter.
- * @return queue type associated to this item
- */
- QueueKeeper.QueueType getQueueType();
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md.queue;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-
-/**
- * This processing mechanism based on queue. Processing consists of 2 steps: translate and publish.
- * Proposed workflow (might slightly deviate in implementations):
- * <ol>
- * <li>messages of input type are pushed in (via {@link QueueKeeper} and similar)</li>
- * <li>ticket (executable task) is build upon each pushed message and enqueued</li>
- * <li>ticket is translated using appropriate translator</li>
- * <li>ticket is dequeued and result is published by appropriate popListener</li>
- * </ol>
- * Message order might be not important, e.g. when speed is of the essence
- * @param <I> source type (IN)
- */
-public interface QueueKeeper<I> extends AutoCloseable {
-
- /** type of message enqueue. */
- enum QueueType {
- /** ordered processing. */
- DEFAULT,
- /** unordered processing - bypass fair processing. */
- UNORDERED
- }
-
- /**
- * enqueue message for processing.
- * @param message message
- * @param conductor source of message
- * @param queueType - {@link QueueType#DEFAULT} if message order matters, {@link QueueType#UNORDERED} otherwise
- */
- void push(I message, ConnectionConductor conductor, QueueType queueType);
-
- /**
- * oldest item from queue - if available and remove it from queue.
- * @return oldest item from queue
- */
- QueueItem<I> poll();
-
- /**
- * Setter.
- * @param processingRegistration the processingRegistration to set (in order to provide close method)
- */
- void setPollRegistration(AutoCloseable processingRegistration);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.api.openflow.md.queue;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
-
-/**
- * This processing mechanism based on queue. Processing consists of 2 steps: translate and publish.
- * Proposed workflow (might slightly deviate in implementations):
- * <ol>
- * <li>messages of input type are pushed in (via {@link QueueKeeper and similar})</li>
- * <li>ticket (executable task) is build upon each pushed message and enqueued</li>
- * <li>ticket is translated using appropriate translator</li>
- * <li>ticket is dequeued and result is published by appropriate popListener</li>
- * </ol>
- * Message order might be not important, e.g. when speed is of the essence
- * @param <I> source type (IN)
- * @param <O> result type (OUT)
- */
-public interface QueueProcessor<I, O> extends MessageSourcePollRegistrator<QueueKeeper<I>>, Enqueuer<QueueItem<I>> {
-
- /**
- * translators for message processing.
- * @param translatorMapping translators for message processing
- */
- void setTranslatorMapping(Map<TranslatorKey, Collection<IMDMessageTranslator<I, List<O>>>> translatorMapping);
-
- /**
- * listeners invoked when processing done.
- * @param popListenersMapping listeners invoked when processing done
- */
- void setPopListenersMapping(Map<Class<? extends O>, Collection<PopListener<O>>> popListenersMapping);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.api.openflow.md.queue;
-
-public interface WaterMarkListener {
-
- /**
- * When HighWaterMark reached and currently not flooded.
- */
- void onHighWaterMark();
-
- /**
- * When LowWaterMark reached and currently flooded.
- */
- void onLowWaterMark();
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.api.openflow.md.queue;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class WaterMarkListenerImpl implements WaterMarkListener {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(WaterMarkListenerImpl.class);
-
- private ConnectionAdapter connectionAdapter;
-
- public WaterMarkListenerImpl(ConnectionAdapter connectionAdapter) {
- this.connectionAdapter = Preconditions.checkNotNull(connectionAdapter);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.opendaylight.openflowplugin.api.openflow.md.queue.QueueListener#
- * onHighWaterMark
- * (org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter)
- */
- @Override
- public void onHighWaterMark() {
- connectionAdapter.setAutoRead(false);
- LOG.debug("AutoRead is set on false: {}", connectionAdapter.getRemoteAddress());
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.opendaylight.openflowplugin.api.openflow.md.queue.QueueListener#
- * onLowWaterMark
- * (org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter)
- */
- @Override
- public void onLowWaterMark() {
- connectionAdapter.setAutoRead(true);
- LOG.debug("AutoRead is set on true: {}", connectionAdapter.getRemoteAddress());
- }
-}
+++ /dev/null
-/*
- * 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.openflowplugin.api.openflow.md.util;
-
-import java.util.Queue;
-
-/**
- * Zipper groups together a list of queues and exposes one poll method. Polling
- * iterates through all groups and returns first not-null result of poll method
- * on each queue. If after polling each grouped queue for one time there is
- * still null result, poll will return null. <br>
- * Iterating keeps last position so this polling is supposed to be fairly
- * distributed.
- *
- * @param <T> common item type of zipped queues
- */
-public class PollableQueuesPriorityZipper<T> {
-
- private Queue<T> prioritizedSource;
- private PollableQueuesZipper<T> zipper;
-
- public PollableQueuesPriorityZipper() {
- zipper = new PollableQueuesZipper<>();
- }
-
- /**
- * Add all member queues before first invocation of {@link PollableQueuesPriorityZipper#poll()}.
- * @param queue to be added to group
- */
- public void addSource(Queue<T> queue) {
- zipper.addSource(queue);
- }
-
- /**
- * Next common product.
- * @return next common product of polling member groups
- */
- public T poll() {
- T item = null;
-
- item = prioritizedSource.poll();
- if (item == null) {
- item = zipper.poll();
- }
-
- return item;
- }
-
- public void setPrioritizedSource(Queue<T> prioritizedSource) {
- this.prioritizedSource = prioritizedSource;
- }
-}
+++ /dev/null
-/*
- * 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.openflowplugin.api.openflow.md.util;
-
-import com.google.common.collect.Iterators;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Queue;
-
-/**
- * Zipper groups together a list of queues and exposes one poll method. Polling iterates through
- * all groups and returns first not-null result of poll method on each queue. If after polling each
- * grouped queue for one time there is still null result, poll will return null.
- * <br>
- * Iterating keeps last position so this polling is supposed to be fairly distributed.
- *
- * @param <T> common item type of zipped queues
- */
-public class PollableQueuesZipper<T> {
-
- private List<Queue<T>> sources;
- private Iterator<Queue<T>> cursor;
-
- public PollableQueuesZipper() {
- sources = new ArrayList<>();
- }
-
- /**
- * Add all member queues before first invocation of {@link PollableQueuesZipper#poll()}.
- * @param queue to be added to group
- */
- public void addSource(Queue<T> queue) {
- sources.add(queue);
- }
-
- /**
- * Next common product.
- * @return next common product of polling member groups
- */
- public T poll() {
- T item = null;
- if (cursor == null) {
- cursor = Iterators.cycle(sources);
- }
-
- Queue<T> queue;
- for (int i = 0; i < sources.size(); i++) {
- queue = cursor.next();
- item = queue.poll();
- if (item != null) {
- break;
- }
- }
-
- return item;
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
- xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0">
-
- <odl:action-provider interface="org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService"/>
-</blueprint>
import java.util.concurrent.ThreadPoolExecutor;
import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
+import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionManager;
import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceConnectedHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceDisconnectedHandler;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeListener;
import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeManager;
import org.opendaylight.openflowplugin.impl.connection.listener.ConnectionReadyListenerImpl;
private HandshakeManager createHandshakeManager(final ConnectionAdapter connectionAdapter,
final HandshakeListener handshakeListener) {
HandshakeManagerImpl handshakeManager = new HandshakeManagerImpl(connectionAdapter,
- ConnectionConductor.VERSION_ORDER.get(0),
- ConnectionConductor.VERSION_ORDER);
+ OFConstants.VERSION_ORDER.get(0),
+ OFConstants.VERSION_ORDER);
handshakeManager.setUseVersionBitmap(BITMAP_NEGOTIATION_ENABLED);
handshakeManager.setHandshakeListener(handshakeListener);
handshakeManager.setErrorHandler(new ErrorHandlerSimpleImpl());
xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
odl:use-default-for-reference-types="true">
+ <odl:action-provider interface="org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService"/>
+
<bean id="ofPluginProviderFactory" class="org.opendaylight.openflowplugin.impl.OpenFlowPluginProviderFactoryImpl"/>
<service ref="ofPluginProviderFactory" interface="org.opendaylight.openflowplugin.api.openflow.OpenFlowPluginProviderFactory"/>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
</plugin>
- <plugin>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-maven-plugin</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>generate-sources</goal>
- </goals>
- <configuration>
- <codeGenerators>
- <generator>
- <codeGeneratorClass>
- org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl
- </codeGeneratorClass>
- <outputBaseDir>${project.build.directory}/generated-sources/sal</outputBaseDir>
- </generator>
- <generator>
- <codeGeneratorClass>org.opendaylight.mdsal.binding.yang.unified.doc.generator.maven.DocumentationGeneratorImpl</codeGeneratorClass>
- <outputBaseDir>${project.build.directory}/site/models</outputBaseDir>
- </generator>
- </codeGenerators>
- <inspectDependencies>true</inspectDependencies>
- </configuration>
- </execution>
- </executions>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>maven-sal-api-gen-plugin</artifactId>
- <version>${mdsal.model.version}</version>
- <type>jar</type>
- </dependency>
- </dependencies>
- </plugin>
</plugins>
</build>
<dependencies>
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core;
-
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-
-/**
- * @author mirehak
- *
- */
-public final class ConnectionConductorFactory {
-
- private static AtomicInteger conductorId = new AtomicInteger();
-
- private ConnectionConductorFactory() {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @param connectionAdapter connection conductor adaptor
- * @param queueProcessor message queue process
- * @return conductor for given connection
- */
- public static ConnectionConductor createConductor(ConnectionAdapter connectionAdapter,
- QueueProcessor<OfHeader, DataObject> queueProcessor) {
- ConnectionConductor connectionConductor = new ConnectionConductorImpl(connectionAdapter);
- connectionConductor.setQueueProcessor(queueProcessor);
- connectionConductor.setId(conductorId.getAndIncrement());
- connectionConductor.init();
- return connectionConductor;
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.util.concurrent.Futures;
-import java.util.concurrent.Future;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler;
-import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeListener;
-import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeManager;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper.QueueType;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListenerImpl;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
-import org.opendaylight.openflowplugin.openflow.md.core.session.PortFeaturesUtil;
-import org.opendaylight.openflowplugin.openflow.md.queue.QueueKeeperFactory;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author mirehak
- */
-public class ConnectionConductorImpl implements OpenflowProtocolListener,
- SystemNotificationsListener, ConnectionConductor,
- ConnectionReadyListener, HandshakeListener, NotificationEnqueuer,
- AutoCloseable {
-
- /**
- * ingress queue limit
- */
- private static final int INGRESS_QUEUE_MAX_SIZE = 200;
-
- protected static final Logger LOG = LoggerFactory
- .getLogger(ConnectionConductorImpl.class);
-
- /*
- * variable to make BitMap-based negotiation enabled / disabled. it will
- * help while testing and isolating issues related to processing of BitMaps
- * from switches.
- */
- private boolean isBitmapNegotiationEnable = true;
- protected ErrorHandler errorHandler;
-
- private final ConnectionAdapter connectionAdapter;
- private ConnectionConductor.CONDUCTOR_STATE conductorState;
- private Short version;
-
- protected SwitchConnectionDistinguisher auxiliaryKey;
-
- protected SessionContext sessionContext;
-
- private QueueProcessor<OfHeader, DataObject> queueProcessor;
- private QueueKeeper<OfHeader> queue;
- private ThreadPoolExecutor hsPool;
- private HandshakeManager handshakeManager;
-
- private boolean firstHelloProcessed;
-
- private PortFeaturesUtil portFeaturesUtils;
-
- private int conductorId;
-
- private int ingressMaxQueueSize;
- private HandshakeContext handshakeContext;
-
- /**
- * @param connectionAdapter connection adaptor for switch
- */
- public ConnectionConductorImpl(ConnectionAdapter connectionAdapter) {
- this(connectionAdapter, INGRESS_QUEUE_MAX_SIZE);
- }
-
- /**
- * @param connectionAdapter connection adaptor for switch
- * @param ingressMaxQueueSize ingress queue limit (blocking)
- */
- public ConnectionConductorImpl(ConnectionAdapter connectionAdapter,
- int ingressMaxQueueSize) {
- this.connectionAdapter = connectionAdapter;
- this.ingressMaxQueueSize = ingressMaxQueueSize;
- conductorState = CONDUCTOR_STATE.HANDSHAKING;
- firstHelloProcessed = false;
- handshakeManager = new HandshakeManagerImpl(connectionAdapter,
- ConnectionConductor.VERSION_ORDER.get(0),
- ConnectionConductor.VERSION_ORDER);
- handshakeManager.setUseVersionBitmap(isBitmapNegotiationEnable);
- handshakeManager.setHandshakeListener(this);
- portFeaturesUtils = PortFeaturesUtil.getInstance();
- }
-
- @Override
- public void init() {
- int handshakeThreadLimit = 1;
- hsPool = new ThreadPoolLoggingExecutor(handshakeThreadLimit,
- handshakeThreadLimit, 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<Runnable>(), "OFHandshake-"
- + conductorId);
-
- connectionAdapter.setMessageListener(this);
- connectionAdapter.setSystemListener(this);
- connectionAdapter.setConnectionReadyListener(this);
- WaterMarkListener waterMarkListener = new WaterMarkListenerImpl(
- connectionAdapter);
- queue = QueueKeeperFactory.createFairQueueKeeper(queueProcessor,
- ingressMaxQueueSize, waterMarkListener);
- }
-
- @Override
- public void setQueueProcessor(
- QueueProcessor<OfHeader, DataObject> queueProcessor) {
- this.queueProcessor = queueProcessor;
- }
-
- /**
- * @param errorHandler the errorHandler to set
- */
- @Override
- public void setErrorHandler(ErrorHandler errorHandler) {
- this.errorHandler = errorHandler;
- handshakeManager.setErrorHandler(errorHandler);
- }
-
- @Override
- public void onEchoRequestMessage(final EchoRequestMessage echoRequestMessage) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- LOG.debug("echo request received: "
- + echoRequestMessage.getXid());
- EchoReplyInputBuilder builder = new EchoReplyInputBuilder();
- builder.setVersion(echoRequestMessage.getVersion());
- builder.setXid(echoRequestMessage.getXid());
- builder.setData(echoRequestMessage.getData());
-
- getConnectionAdapter().echoReply(builder.build());
- }
- }).start();
- }
-
- @Override
- public void onErrorMessage(ErrorMessage errorMessage) {
- enqueueMessage(errorMessage);
- }
-
- /**
- * @param message
- */
- private void enqueueMessage(OfHeader message) {
- enqueueMessage(message, QueueType.DEFAULT);
- }
-
- @Override
- public void enqueueNotification(NotificationQueueWrapper notification) {
- enqueueMessage(notification);
- }
-
- /**
- * @param message
- * @param queueType enqueue type
- */
- private void enqueueMessage(OfHeader message, QueueType queueType) {
- queue.push(message, this, queueType);
- }
-
- @Override
- public void onExperimenterMessage(ExperimenterMessage experimenterMessage) {
- enqueueMessage(experimenterMessage);
- }
-
- @Override
- public void onFlowRemovedMessage(FlowRemovedMessage message) {
- enqueueMessage(message);
- }
-
- /**
- * version negotiation happened as per following steps: 1. If HelloMessage
- * version field has same version, continue connection processing. If
- * HelloMessage version is lower than supported versions, just disconnect.
- * 2. If HelloMessage contains bitmap and common version found in bitmap
- * then continue connection processing. if no common version found, just
- * disconnect. 3. If HelloMessage version is not supported, send
- * HelloMessage with lower supported version. 4. If Hello message received
- * again with not supported version, just disconnect.
- */
- @Override
- public void onHelloMessage(final HelloMessage hello) {
- LOG.debug("processing HELLO.xid: {}", hello.getXid());
- firstHelloProcessed = true;
- checkState(CONDUCTOR_STATE.HANDSHAKING);
- HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
- hello, handshakeManager, connectionAdapter);
- hsPool.submit(handshakeStepWrapper);
- }
-
- /**
- * @return rpc-response timeout in [ms]
- */
- protected long getMaxTimeout() {
- // TODO:: get from configuration
- return 2000;
- }
-
- /**
- * @return milliseconds
- */
- protected TimeUnit getMaxTimeoutUnit() {
- // TODO:: get from configuration
- return TimeUnit.MILLISECONDS;
- }
-
- @Override
- public void onMultipartReplyMessage(MultipartReplyMessage message) {
- enqueueMessage(message);
- }
-
- @Override
- public void onPacketInMessage(PacketInMessage message) {
- enqueueMessage(message, QueueKeeper.QueueType.UNORDERED);
- }
-
- @Override
- public void onPortStatusMessage(PortStatusMessage message) {
- try {
- processPortStatusMsg(message);
- } finally {
- enqueueMessage(message);
- }
- }
-
- protected void processPortStatusMsg(PortStatus msg) {
- if (msg.getReason().getIntValue() == 2) {
- updatePort(msg);
- } else if (msg.getReason().getIntValue() == 0) {
- updatePort(msg);
- } else if (msg.getReason().getIntValue() == 1) {
- deletePort(msg);
- }
- }
-
- protected void updatePort(PortStatus msg) {
- Long portNumber = msg.getPortNo();
- Boolean portBandwidth = portFeaturesUtils.getPortBandwidth(msg);
-
- if (portBandwidth == null) {
- LOG.debug(
- "can't get bandwidth info from port: {}, aborting port update",
- msg.toString());
- } else {
- if (null != this.sessionContext) {
- //FIXME these two properties are never used in code
- this.getSessionContext().getPhysicalPorts().put(portNumber, msg);
- this.getSessionContext().getPortsBandwidth()
- .put(portNumber, portBandwidth);
- } else {
- LOG.warn("Trying to process update port message before session context was created.");
- }
- }
- }
-
- protected void deletePort(PortGrouping port) {
- Long portNumber = port.getPortNo();
-
- this.getSessionContext().getPhysicalPorts().remove(portNumber);
- this.getSessionContext().getPortsBandwidth().remove(portNumber);
- }
-
- @Override
- public void onSwitchIdleEvent(SwitchIdleEvent notification) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- if (!CONDUCTOR_STATE.WORKING.equals(getConductorState())) {
- // idle state in any other conductorState than WORKING means
- // real
- // problem and wont be handled by echoReply, but
- // disconnection
- disconnect();
- OFSessionUtil.getSessionManager().invalidateOnDisconnect(
- ConnectionConductorImpl.this);
- } else {
- LOG.debug(
- "first idle state occured, sessionCtx={}|auxId={}",
- sessionContext, auxiliaryKey);
- EchoInputBuilder builder = new EchoInputBuilder();
- builder.setVersion(getVersion());
- builder.setXid(getSessionContext().getNextXid());
-
- Future<RpcResult<EchoOutput>> echoReplyFuture = getConnectionAdapter()
- .echo(builder.build());
-
- try {
- RpcResult<EchoOutput> echoReplyValue = echoReplyFuture
- .get(getMaxTimeout(), getMaxTimeoutUnit());
- if (echoReplyValue.isSuccessful()) {
- setConductorState(CONDUCTOR_STATE.WORKING);
- } else {
- for (RpcError replyError : echoReplyValue
- .getErrors()) {
- Throwable cause = replyError.getCause();
- LOG.error(
- "while receiving echoReply in TIMEOUTING state: "
- + cause.getMessage(), cause);
- }
- // switch issue occurred
- throw new Exception("switch issue occurred");
- }
- } catch (Exception e) {
- LOG.error("while waiting for echoReply in TIMEOUTING state: "
- + e.getMessage());
- errorHandler.handleException(e, sessionContext);
- // switch is not responding
- disconnect();
- OFSessionUtil.getSessionManager()
- .invalidateOnDisconnect(
- ConnectionConductorImpl.this);
- }
- }
- }
-
- }).start();
- }
-
- /**
- * @param conductorState the connectionState to set
- */
- @Override
- public void setConductorState(CONDUCTOR_STATE conductorState) {
- this.conductorState = conductorState;
- }
-
- @Override
- public CONDUCTOR_STATE getConductorState() {
- return conductorState;
- }
-
- /**
- * @param expectedState connection conductor state
- */
- protected void checkState(CONDUCTOR_STATE expectedState) {
- if (!conductorState.equals(expectedState)) {
- LOG.warn("State of connection to switch {} is not correct, "
- + "terminating the connection", connectionAdapter.getRemoteAddress());
- throw new IllegalStateException("Expected state: " + expectedState
- + ", actual state:" + conductorState);
- }
- }
-
- @Override
- public void onDisconnectEvent(DisconnectEvent arg0) {
- SessionManager sessionManager = OFSessionUtil.getSessionManager();
- sessionManager.invalidateOnDisconnect(this);
- close();
- }
-
- @Override
- public Short getVersion() {
- return version;
- }
-
- @Override
- public Future<Boolean> disconnect() {
- LOG.trace("disconnecting: sessionCtx={}|auxId={}", sessionContext,
- auxiliaryKey);
-
- Future<Boolean> result = null;
- if (connectionAdapter.isAlive()) {
- result = connectionAdapter.disconnect();
- } else {
- LOG.debug("connection already disconnected");
- result = Futures.immediateFuture(true);
- }
- close();
- return result;
- }
-
- @Override
- public void setConnectionCookie(SwitchConnectionDistinguisher auxiliaryKey) {
- this.auxiliaryKey = auxiliaryKey;
- }
-
- @Override
- public void setSessionContext(SessionContext sessionContext) {
- this.sessionContext = sessionContext;
- }
-
- @Override
- public SwitchConnectionDistinguisher getAuxiliaryKey() {
- return auxiliaryKey;
- }
-
- @Override
- public SessionContext getSessionContext() {
- return sessionContext;
- }
-
- @Override
- public ConnectionAdapter getConnectionAdapter() {
- return connectionAdapter;
- }
-
- @Override
- public void onConnectionReady() {
- LOG.debug("connection is ready-to-use");
- if (!firstHelloProcessed) {
- checkState(CONDUCTOR_STATE.HANDSHAKING);
- HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper(
- null, handshakeManager, connectionAdapter);
- hsPool.execute(handshakeStepWrapper);
- firstHelloProcessed = true;
- } else {
- LOG.debug("already touched by hello message");
- }
- }
-
- @Override
- public void onHandshakeSuccessful(GetFeaturesOutput featureOutput,
- Short negotiatedVersion) {
- postHandshakeBasic(featureOutput, negotiatedVersion);
- }
-
- @Override
- public void onHandshakeFailure() {
- LOG.info("OF handshake failed, doing cleanup.");
- close();
- }
-
- /**
- * used by tests
- *
- * @param featureOutput feature request output
- * @param negotiatedVersion negotiated openflow connection version
- */
- protected void postHandshakeBasic(GetFeaturesOutput featureOutput,
- Short negotiatedVersion) {
- version = negotiatedVersion;
- if (version == OFConstants.OFP_VERSION_1_0) {
- // Because the GetFeaturesOutput contains information about the port
- // in OF1.0 (that we would otherwise get from the PortDesc) we have
- // to pass
- // it up for parsing to convert into a NodeConnectorUpdate
- //
- // BUG-1988 - this must be the first item in queue in order not to
- // get behind link-up message
- enqueueMessage(featureOutput);
- }
-
- SessionContext sessionContext = OFSessionUtil.registerSession(this, featureOutput, negotiatedVersion);
- hsPool.shutdown();
- hsPool.purge();
- conductorState = CONDUCTOR_STATE.WORKING;
- QueueKeeperFactory.plugQueue(queueProcessor, queue);
- }
-
- /**
- * @param isBitmapNegotiationEnable the isBitmapNegotiationEnable to set
- */
- public void setBitmapNegotiationEnable(boolean isBitmapNegotiationEnable) {
- this.isBitmapNegotiationEnable = isBitmapNegotiationEnable;
- }
-
- @Override
- public void setId(int conductorId) {
- this.conductorId = conductorId;
- }
-
- @Override
- public void close() {
- conductorState = CONDUCTOR_STATE.RIP;
- if (handshakeContext != null) {
- try {
- handshakeContext.close();
- } catch (Exception e) {
- LOG.warn("Closing handshake context failed: {}", e.getMessage());
- LOG.debug("Detail in hanshake context close:", e);
- }
- } else {
- //This condition will occure when Old Helium openflowplugin implementation will be used.
- shutdownPoolPolitely();
- }
- }
-
- private void shutdownPoolPolitely() {
- LOG.debug("Terminating handshake pool for node {}", connectionAdapter.getRemoteAddress());
- hsPool.shutdown();
- try {
- hsPool.awaitTermination(1, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- LOG.debug("Error while awaiting termination of pool. Will force shutdown now.");
- } finally {
- hsPool.purge();
- if (!hsPool.isTerminated()) {
- hsPool.shutdownNow();
- }
- LOG.debug("is handshake pool for node {} is terminated : {}",
- connectionAdapter.getRemoteAddress(), hsPool.isTerminated());
- }
- }
-
- @Override
- public void setHandshakeContext(HandshakeContext handshakeContext) {
- this.handshakeContext = handshakeContext;
- }
-
- @VisibleForTesting
- ThreadPoolExecutor getHsPool() {
- return hsPool;
- }
-}
package org.opendaylight.openflowplugin.openflow.md.core;
-import java.util.Arrays;
-
import org.opendaylight.openflowplugin.api.ConnectionException;
import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* dumping all exceptions to log
- * @author mirehak
*/
public class ErrorHandlerSimpleImpl implements ErrorHandler {
.getLogger(ErrorHandlerSimpleImpl.class);
@Override
- public void handleException(Throwable e, SessionContext sessionContext) {
- String sessionKeyId = null;
- if (sessionContext != null) {
- sessionKeyId = Arrays.toString(sessionContext.getSessionKey().getId());
- }
-
+ public void handleException(Throwable e) {
if (e instanceof ConnectionException) {
- LOG.warn("exception -> {}, session -> {}", e.getMessage(), sessionKeyId, e);
+ LOG.warn("exception -> {}", e.getMessage(), e);
} else {
- LOG.error("exception -> {}, session -> {}", e.getMessage(), sessionKeyId, e);
+ LOG.error("exception -> {}", e.getMessage(), e);
}
}
}
*/
package org.opendaylight.openflowplugin.openflow.md.core;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.JdkFutureAdapters;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.SettableFuture;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Future;
-
import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
+import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler;
import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeListener;
import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.JdkFutureAdapters;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-
-/**
- * @author mirehak
- *
- */
public class HandshakeManagerImpl implements HandshakeManager {
private static final long activeXID = 20L;
handleStepByStepVersionNegotiation(remoteVersion);
}
} catch (Exception ex) {
- errorHandler.handleException(ex, null);
+ errorHandler.handleException(ex);
LOG.trace("ret - shake fail - closing");
handshakeListener.onHandshakeFailure();
}
try {
stepByStepVersionSubStep(remoteVersion, lastProposedVersion);
} catch (Exception e) {
- errorHandler.handleException(e, null);
+ errorHandler.handleException(e);
handshakeListener.onHandshakeFailure();
}
}
for(Elements element : list) {
List<Boolean> bitmap = element.getVersionBitmap();
// check for version bitmap
- for(short bitPos : ConnectionConductor.VERSION_ORDER) {
+ for(short bitPos : OFConstants.VERSION_ORDER) {
// with all the version it should work.
if(bitmap.get(bitPos % Integer.SIZE)) {
supportedHighestVersion = bitPos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/**
- * @author mirehak
- *
- */
public class HandshakeStepWrapper implements Runnable {
private static final Logger LOG = LoggerFactory
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM 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.openflowplugin.openflow.md.core;
-
-import java.util.List;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-
-public interface IMDController {
-
- /**
- * Allows application to start translating OF messages received from switches.
- *
- * @param messageType
- * the type of OF message that applications want to receive
- * @param version corresponding OF version
- * @param translator
- * : Object that implements the {@link org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator}
- */
- public void addMessageTranslator(Class<? extends DataObject> messageType, int version, IMDMessageTranslator<OfHeader, List<DataObject>> translator);
-
- /**
- * Allows application to stop receiving OF message received from switches.
- *
- * @param messageType
- * The type of OF message that applications want to stop
- * receiving
- * @param version TODO
- * @param translator
- * The object that implements the {@link IMDMessageTranslator}
- */
- public void removeMessageTranslator(Class<? extends DataObject> messageType, int version, IMDMessageTranslator<OfHeader, List<DataObject>> translator);
-
- /**
- * Allows application to start pop-listening MD-SAL messages received from switches.
- *
- * @param messageType
- * the type of OF message that applications want to receive
- * @param popListener
- * : Object that implements the {@link PopListener}
- */
- void removeMessagePopListener(Class<? extends DataObject> messageType, PopListener<DataObject> popListener);
-
- /**
- * Allows application to stop pop-listening MD-SAL messages received from switches.
- *
- * @param messageType
- * the type of OF message that applications want to receive
- * @param popListener
- * : Object that implements the {@link PopListener}
- */
- void addMessagePopListener(Class<? extends DataObject> messageType, PopListener<DataObject> popListener);
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core;
-
-import com.google.common.util.concurrent.ForwardingBlockingQueue;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.RejectedExecutionHandler;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import org.opendaylight.openflowjava.protocol.spi.connection.SwitchConnectionProvider;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;
-import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorTranslator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorV10Translator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.ExperimenterTranslator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.FeaturesV10ToNodeConnectorUpdatedTranslator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.FlowRemovedTranslator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.MultiPartMessageDescToNodeUpdatedTranslator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.MultiPartReplyPortToNodeConnectorUpdatedTranslator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.MultipartReplyTableFeaturesToTableUpdatedTranslator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.MultipartReplyTranslator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.NotificationPlainTranslator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.PacketInTranslator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.PacketInV10Translator;
-import org.opendaylight.openflowplugin.openflow.md.core.translator.PortStatusMessageToNodeConnectorUpdatedTranslator;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.NodeErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SwitchFlowRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.AggregateFlowStatisticsUpdate;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdate;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsUpdate;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupDescStatsUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupFeaturesUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupStatisticsUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterConfigStatsUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterFeaturesUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterStatisticsUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadActionErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadInstructionErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadMatchErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadRequestErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.ExperimenterErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.FlowModErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.GroupModErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.HelloFailedErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.MeterModErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.PortModErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.QueueOpErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.RoleRequestErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.SwitchConfigErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.TableFeaturesErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.TableModErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdate;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.QueueStatisticsUpdate;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.TableUpdated;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- *
- */
-public class MDController implements IMDController, AutoCloseable {
-
- private static final Logger LOG = LoggerFactory.getLogger(MDController.class);
- private final ConvertorExecutor convertorExecutor;
-
- private Collection<SwitchConnectionProvider> switchConnectionProviders;
-
- private ConcurrentMap<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> messageTranslators;
- private Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> popListeners;
- private MessageSpy<DataContainer> messageSpyCounter;
-
- final private int OF10 = OFConstants.OFP_VERSION_1_0;
- final private int OF13 = OFConstants.OFP_VERSION_1_3;
-
- private ErrorHandlerSimpleImpl errorHandler;
-
- private ExtensionConverterProvider extensionConverterProvider;
-
- public MDController(ConvertorExecutor convertorExecutor) {
- this.convertorExecutor = convertorExecutor;
- }
-
- /**
- * @return translator mapping
- */
- public Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> getMessageTranslators() {
- return messageTranslators;
- }
-
- /**
- * provisioning of translator mapping
- */
- public void init() {
- LOG.debug("init");
-
- messageTranslators = new ConcurrentHashMap<>();
- popListeners = new ConcurrentHashMap<>();
- //TODO: move registration to factory
- addMessageTranslator(ErrorMessage.class, OF10, new ErrorV10Translator());
- addMessageTranslator(ErrorMessage.class, OF13, new ErrorTranslator());
- addMessageTranslator(FlowRemovedMessage.class, OF10, new FlowRemovedTranslator(convertorExecutor));
- addMessageTranslator(FlowRemovedMessage.class, OF13, new FlowRemovedTranslator(convertorExecutor));
- addMessageTranslator(PacketInMessage.class,OF10, new PacketInV10Translator());
- addMessageTranslator(PacketInMessage.class,OF13, new PacketInTranslator(convertorExecutor));
- addMessageTranslator(PortStatusMessage.class,OF10, new PortStatusMessageToNodeConnectorUpdatedTranslator());
- addMessageTranslator(PortStatusMessage.class,OF13, new PortStatusMessageToNodeConnectorUpdatedTranslator());
- addMessageTranslator(MultipartReplyMessage.class,OF13,new MultiPartReplyPortToNodeConnectorUpdatedTranslator());
- addMessageTranslator(MultipartReplyMessage.class,OF10, new MultiPartMessageDescToNodeUpdatedTranslator());
- addMessageTranslator(MultipartReplyMessage.class,OF13, new MultiPartMessageDescToNodeUpdatedTranslator());
- addMessageTranslator(ExperimenterMessage.class, OF10, new ExperimenterTranslator());
- addMessageTranslator(MultipartReplyMessage.class,OF10, new MultipartReplyTranslator(convertorExecutor));
- addMessageTranslator(MultipartReplyMessage.class,OF13, new MultipartReplyTranslator(convertorExecutor));
- addMessageTranslator(MultipartReplyMessage.class,OF13,new MultipartReplyTableFeaturesToTableUpdatedTranslator(convertorExecutor));
- addMessageTranslator(GetFeaturesOutput.class,OF10, new FeaturesV10ToNodeConnectorUpdatedTranslator());
- addMessageTranslator(NotificationQueueWrapper.class, OF10, new NotificationPlainTranslator());
- addMessageTranslator(NotificationQueueWrapper.class, OF13, new NotificationPlainTranslator());
-
- NotificationPopListener<DataObject> notificationPopListener = new NotificationPopListener<DataObject>();
- notificationPopListener.setNotificationProviderService(
- OFSessionUtil.getSessionManager().getNotificationProviderService());
- notificationPopListener.setMessageSpy(messageSpyCounter);
-
- //TODO: move registration to factory
- addMessagePopListener(NodeErrorNotification.class, notificationPopListener);
- addMessagePopListener(BadActionErrorNotification.class, notificationPopListener);
- addMessagePopListener(BadInstructionErrorNotification.class, notificationPopListener);
- addMessagePopListener(BadMatchErrorNotification.class, notificationPopListener);
- addMessagePopListener(BadRequestErrorNotification.class, notificationPopListener);
- addMessagePopListener(ExperimenterErrorNotification.class, notificationPopListener);
- addMessagePopListener(FlowModErrorNotification.class, notificationPopListener);
- addMessagePopListener(GroupModErrorNotification.class, notificationPopListener);
- addMessagePopListener(HelloFailedErrorNotification.class, notificationPopListener);
- addMessagePopListener(MeterModErrorNotification.class, notificationPopListener);
- addMessagePopListener(PortModErrorNotification.class, notificationPopListener);
- addMessagePopListener(QueueOpErrorNotification.class, notificationPopListener);
- addMessagePopListener(RoleRequestErrorNotification.class, notificationPopListener);
- addMessagePopListener(SwitchConfigErrorNotification.class, notificationPopListener);
- addMessagePopListener(TableFeaturesErrorNotification.class, notificationPopListener);
- addMessagePopListener(TableModErrorNotification.class, notificationPopListener);
- addMessagePopListener(NodeConnectorUpdated.class,notificationPopListener);
- addMessagePopListener(NodeConnectorRemoved.class,notificationPopListener);
- addMessagePopListener(PacketReceived.class,notificationPopListener);
- addMessagePopListener(TransmitPacketInput.class, notificationPopListener);
- addMessagePopListener(NodeUpdated.class, notificationPopListener);
- addMessagePopListener(NodeRemoved.class, notificationPopListener);
-
- addMessagePopListener(SwitchFlowRemoved.class, notificationPopListener);
- addMessagePopListener(TableUpdated.class, notificationPopListener);
-
- //Notification registration for flow statistics
- addMessagePopListener(FlowsStatisticsUpdate.class, notificationPopListener);
- addMessagePopListener(AggregateFlowStatisticsUpdate.class, notificationPopListener);
-
- //Notification registrations for group-statistics
- addMessagePopListener(GroupStatisticsUpdated.class, notificationPopListener);
- addMessagePopListener(GroupFeaturesUpdated.class, notificationPopListener);
- addMessagePopListener(GroupDescStatsUpdated.class, notificationPopListener);
-
- //Notification registrations for meter-statistics
- addMessagePopListener(MeterStatisticsUpdated.class, notificationPopListener);
- addMessagePopListener(MeterConfigStatsUpdated.class, notificationPopListener);
- addMessagePopListener(MeterFeaturesUpdated.class, notificationPopListener);
-
- //Notification registration for port-statistics
- addMessagePopListener(NodeConnectorStatisticsUpdate.class, notificationPopListener);
-
- //Notification registration for flow-table statistics
- addMessagePopListener(FlowTableStatisticsUpdate.class, notificationPopListener);
-
- //Notification registration for queue-statistics
- addMessagePopListener(QueueStatisticsUpdate.class, notificationPopListener);
-
- // Push the updated Listeners to Session Manager which will be then picked up by ConnectionConductor eventually
- OFSessionUtil.getSessionManager().setTranslatorMapping(messageTranslators);
- OFSessionUtil.getSessionManager().setPopListenerMapping(popListeners);
- OFSessionUtil.getSessionManager().setMessageSpy(messageSpyCounter);
-
- // prepare worker pool for rpc
- // TODO: get size from configSubsystem
- int rpcThreadLimit = 10;
- ListeningExecutorService rpcPoolDelegator = createRpcPoolSpyDecorated(rpcThreadLimit, messageSpyCounter);
- OFSessionUtil.getSessionManager().setRpcPool(rpcPoolDelegator);
- OFSessionUtil.getSessionManager().setExtensionConverterProvider(extensionConverterProvider);
-
- }
-
- /**
- * @param rpcThreadLimit
- * @param messageSpy
- * @return
- */
- private static ListeningExecutorService createRpcPoolSpyDecorated(final int rpcThreadLimit, final MessageSpy<DataContainer> messageSpy) {
- final BlockingQueue<Runnable> delegate = new LinkedBlockingQueue<>(100000);
- final BlockingQueue<Runnable> queue = new ForwardingBlockingQueue<Runnable>() {
- @Override
- protected BlockingQueue<Runnable> delegate() {
- return delegate;
- }
-
- @Override
- public boolean offer(final Runnable r) {
- // ThreadPoolExecutor will spawn a new thread after core size is reached only
- // if the queue.offer returns false.
- return false;
- }
- };
-
- ThreadPoolLoggingExecutor rpcPool = new ThreadPoolLoggingExecutor(rpcThreadLimit, rpcThreadLimit, 0L,
- TimeUnit.MILLISECONDS, queue, "OFRpc");
- rpcPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
- @Override
- public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
- try {
- executor.getQueue().put(r);
- } catch (InterruptedException e) {
- throw new RejectedExecutionException("Interrupted while waiting on queue", e);
- }
-
- }
- });
- ListeningExecutorService listeningRpcPool = MoreExecutors.listeningDecorator(rpcPool);
- RpcListeningExecutorService rpcPoolDecorated = new RpcListeningExecutorService(listeningRpcPool);
- rpcPoolDecorated.setMessageSpy(messageSpy);
- return rpcPoolDecorated;
- }
-
- /**
- * @param switchConnectionProviders
- * the switchConnectionProviders to set
- */
- public void setSwitchConnectionProviders(final Collection<SwitchConnectionProvider> switchConnectionProviders) {
- this.switchConnectionProviders = switchConnectionProviders;
- }
-
- /**
- * 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() {
- LOG.debug("starting ..");
- LOG.debug("switchConnectionProvider: " + switchConnectionProviders);
- // setup handler
- SwitchConnectionHandlerImpl switchConnectionHandler = new SwitchConnectionHandlerImpl();
- switchConnectionHandler.setMessageSpy(messageSpyCounter);
-
- errorHandler = new ErrorHandlerSimpleImpl();
-
- switchConnectionHandler.setErrorHandler(errorHandler);
- switchConnectionHandler.init();
-
- List<ListenableFuture<Boolean>> starterChain = new ArrayList<>(switchConnectionProviders.size());
- for (SwitchConnectionProvider switchConnectionPrv : switchConnectionProviders) {
- switchConnectionPrv.setSwitchConnectionHandler(switchConnectionHandler);
- ListenableFuture<Boolean> isOnlineFuture = switchConnectionPrv.startup();
- starterChain.add(isOnlineFuture);
- }
-
- Future<List<Boolean>> srvStarted = Futures.allAsList(starterChain);
- }
-
- /**
- * 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("stopping");
- List<ListenableFuture<Boolean>> stopChain = new ArrayList<>(switchConnectionProviders.size());
- try {
- for (SwitchConnectionProvider switchConnectionPrv : switchConnectionProviders) {
- ListenableFuture<Boolean> shutdown = switchConnectionPrv.shutdown();
- stopChain.add(shutdown);
- }
- Futures.allAsList(stopChain).get(5000, TimeUnit.MILLISECONDS);
- } catch (InterruptedException | ExecutionException | TimeoutException e) {
- LOG.warn("failed to stop MDController: {}", e.getMessage());
- LOG.debug("failed to stop MDController.. ", e);
- }
- close();
- }
-
- /**
- * 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() {
- close();
- }
-
- @Override
- public void addMessageTranslator(final Class<? extends DataObject> messageType, final int version, final IMDMessageTranslator<OfHeader, List<DataObject>> translator) {
- TranslatorKey tKey = new TranslatorKey(version, messageType.getName());
-
- Collection<IMDMessageTranslator<OfHeader, List<DataObject>>> existingValues = messageTranslators.get(tKey);
- if (existingValues == null) {
- existingValues = new LinkedHashSet<>();
- messageTranslators.put(tKey, existingValues);
- }
- existingValues.add(translator);
- LOG.debug("{} is now translated by {}", messageType, translator);
- }
-
- @Override
- public void removeMessageTranslator(final Class<? extends DataObject> messageType, final int version, final IMDMessageTranslator<OfHeader, List<DataObject>> translator) {
- TranslatorKey tKey = new TranslatorKey(version, messageType.getName());
- Collection<IMDMessageTranslator<OfHeader, List<DataObject>>> values = messageTranslators.get(tKey);
- if (values != null) {
- values.remove(translator);
- if (values.isEmpty()) {
- messageTranslators.remove(tKey);
- }
- LOG.debug("{} is now removed from translators", translator);
- }
- }
-
- @Override
- public void addMessagePopListener(final Class<? extends DataObject> messageType, final PopListener<DataObject> popListener) {
- Collection<PopListener<DataObject>> existingValues = popListeners.get(messageType);
- if (existingValues == null) {
- existingValues = new LinkedHashSet<>();
- popListeners.put(messageType, existingValues);
- }
- existingValues.add(popListener);
- LOG.debug("{} is now popListened by {}", messageType, popListener);
- }
-
- @Override
- public void removeMessagePopListener(final Class<? extends DataObject> messageType, final PopListener<DataObject> popListener) {
- Collection<PopListener<DataObject>> values = popListeners.get(messageType);
- if (values != null) {
- values.remove(popListener);
- if (values.isEmpty()) {
- popListeners.remove(messageType);
- }
- LOG.debug("{} is now removed from popListeners", popListener);
- }
- }
-
- /**
- * @param messageSpyCounter the messageSpyCounter to set
- */
- public void setMessageSpyCounter(
- final MessageSpy<DataContainer> messageSpyCounter) {
- this.messageSpyCounter = messageSpyCounter;
- }
-
- @Override
- public void close() {
- LOG.debug("close");
- messageSpyCounter = null;
- messageTranslators = null;
- popListeners = null;
- for (SwitchConnectionProvider switchConnectionPrv : switchConnectionProviders) {
- switchConnectionPrv.setSwitchConnectionHandler(null);
- }
- switchConnectionProviders = null;
- OFSessionUtil.releaseSessionManager();
- errorHandler = null;
- }
-
- /**
- * @param extensionConverterProvider extension convertor provider
- */
- public void setExtensionConverterProvider(ExtensionConverterProvider extensionConverterProvider) {
- this.extensionConverterProvider = extensionConverterProvider;
- }
-}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.HelloElementType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.hello.Elements;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.hello.ElementsBuilder;
-/**
- * @author mirehak
- *
- */
public abstract class MessageFactory {
/**
* @param helloVersion openflow version for hello message to send to switch
- * @param helloXid transaction id for hello message
+ * @param helloXid transaction id for hello message
* @return HelloInput without elements
*/
public static HelloInput createHelloInput(short helloVersion, long helloXid) {
/**
* @param highestVersion highest openflow version
- * @param xid transaction id
+ * @param xid transaction id
* @return builder with prepared header
*/
private static HelloInputBuilder prepareHelloInputBuilder(
helloInputbuilder.setXid(xid);
return helloInputbuilder;
}
-
+
/**
* @param helloVersion openflow version for hello message to send to switch
- * @param helloXid transaction id for hello message
+ * @param helloXid transaction id for hello message
* @param versionOrder list of openflow version in order
* @return HelloInput with elements (version bitmap)
*/
public static HelloInput createHelloInput(short helloVersion, long helloXid, List<Short> versionOrder) {
HelloInputBuilder helloInputbuilder = prepareHelloInputBuilder(helloVersion, helloXid);
if (versionOrder != null) {
-
+
ElementsBuilder elementsBuilder = new ElementsBuilder();
elementsBuilder.setType(HelloElementType.VERSIONBITMAP);
int resultVersionListSize = 0;
resultVersionListSize = versionOrder.get(0) + 1;
}
List<Boolean> booleanList = new ArrayList<>(resultVersionListSize);
-
+
int versionOrderIndex = versionOrder.size() - 1;
-
+
while (versionOrderIndex >= 0) {
short version = versionOrder.get(versionOrderIndex);
if (version == booleanList.size()) {
booleanList.add(false);
}
}
-
+
elementsBuilder.setVersionBitmap(booleanList);
List<Elements> elementList = Collections.singletonList(elementsBuilder.build());
}
return result;
}
-
- /**
- * @param ofVersion openflow version
- * @param ofXid transaction id
- * @return barrier message
- */
- public static BarrierInput createBarrier(short ofVersion, long ofXid) {
- BarrierInputBuilder barrierInput = new BarrierInputBuilder();
- barrierInput.setVersion(ofVersion);
- barrierInput.setXid(ofXid);
- return barrierInput.build();
- }
-
-// /**
-// * @param input
-// * @param cookie
-// * @param session
-// * @param messageService
-// * @return barrier result
-// */
-// public static Future<RpcResult<BarrierOutput>> sendBarrier(
-// SwitchConnectionDistinguisher cookie, SessionContext session,
-// IMessageDispatchService messageService) {
-// BarrierInputBuilder barrierInput = new BarrierInputBuilder();
-// barrierInput.setVersion(session.getFeatures().getVersion());
-// barrierInput.setXid(session.getNextXid());
-// return messageService.barrier(barrierInput.build(), cookie);
-// }
}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core;
-
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.yangtools.yang.binding.Notification;
-
-/**
- * general publisher to MD-SAL
- *
- * @param <T> type of supported notification
- */
-public class NotificationPopListener<T> implements PopListener<T> {
-
- private MessageSpy<? super T> messageSpy;
- private NotificationProviderService notificationProviderService;
-
- /**
- * @param messageSpy the messageSpy to set
- */
- public void setMessageSpy(MessageSpy<? super T> messageSpy) {
- this.messageSpy = messageSpy;
- }
-
- /**
- * @param notificationProviderService the notificationProviderService to set
- */
- public void setNotificationProviderService(
- NotificationProviderService notificationProviderService) {
- this.notificationProviderService = notificationProviderService;
- }
-
- @Override
- public void onPop(T processedMessage) {
- boolean published = false;
- if(processedMessage instanceof Notification) {
- if (notificationProviderService != null) {
- notificationProviderService.publish((Notification) processedMessage);
- messageSpy.spyMessage(processedMessage, MessageSpy.StatisticsGroup.FROM_SWITCH_PUBLISHED_SUCCESS);
- published = true;
- }
- }
-
- if (! published) {
- messageSpy.spyMessage(processedMessage, MessageSpy.StatisticsGroup.FROM_SWITCH_PUBLISHED_FAILURE);
- }
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-import org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTask;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-
-/**
- *
- */
-public class RpcListeningExecutorService implements ListeningExecutorService {
-
- private MessageSpy<DataContainer> messageSpy;
- private ListeningExecutorService executorServiceDelegate;
- private DataContainer notSupportedTask = new NoDataContainerTask();
-
- /**
- * @param executorService executor service
- */
- public RpcListeningExecutorService(ListeningExecutorService executorService) {
- this.executorServiceDelegate = executorService;
- }
-
- /**
- * @param messageSpy the messageSpy to set
- */
- public void setMessageSpy(MessageSpy<DataContainer> messageSpy) {
- this.messageSpy = messageSpy;
- }
-
- @Override
- public void shutdown() {
- executorServiceDelegate.shutdown();
- }
-
- @Override
- public <T> ListenableFuture<T> submit(Callable<T> task) {
- ListenableFuture<T> resultFuture = executorServiceDelegate.submit(task);
-
- boolean covered = false;
- if (task instanceof OFRpcTask<?, ?>) {
- if (((OFRpcTask<?, ?>) task).getInput() instanceof DataContainer) {
- messageSpy.spyMessage((DataContainer) ((OFRpcTask<?, ?>) task).getInput(),
- MessageSpy.StatisticsGroup.TO_SWITCH_ENQUEUED_SUCCESS);
- covered = true;
- }
- }
-
- if (! covered) {
- messageSpy.spyMessage(notSupportedTask, MessageSpy.StatisticsGroup.TO_SWITCH_ENQUEUED_FAILED);
- }
-
- return resultFuture;
- }
-
- @Override
- public ListenableFuture<?> submit(Runnable task) {
- throw new IllegalAccessError("not supported");
- }
-
- @Override
- public <T> ListenableFuture<T> submit(Runnable task, T result) {
- throw new IllegalAccessError("not supported");
- }
-
- @Override
- public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
- throws InterruptedException {
- return executorServiceDelegate.invokeAll(tasks);
- }
-
- @Override
- public <T> List<Future<T>> invokeAll(
- Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
- throws InterruptedException {
- return executorServiceDelegate.invokeAll(tasks, timeout, unit);
- }
-
- @Override
- public void execute(Runnable command) {
- throw new IllegalAccessError("not supported");
- }
-
- @Override
- public List<Runnable> shutdownNow() {
- return executorServiceDelegate.shutdownNow();
- }
-
- @Override
- public boolean isShutdown() {
- return executorServiceDelegate.isShutdown();
- }
-
- @Override
- public boolean isTerminated() {
- return executorServiceDelegate.isTerminated();
- }
-
- @Override
- public boolean awaitTermination(long timeout, TimeUnit unit)
- throws InterruptedException {
- return executorServiceDelegate.awaitTermination(timeout, unit);
- }
-
- @Override
- public <T> T invokeAny(Collection<? extends Callable<T>> tasks)
- throws InterruptedException, ExecutionException {
- throw new IllegalAccessError("not supported");
- }
-
- @Override
- public <T> T invokeAny(Collection<? extends Callable<T>> tasks,
- long timeout, TimeUnit unit) throws InterruptedException,
- ExecutionException, TimeoutException {
- throw new IllegalAccessError("not supported");
- }
-
- protected static class NoDataContainerTask implements DataContainer {
- @Override
- public Class<? extends DataContainer> getImplementedInterface() {
- return null;
- }
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core;
-
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-
-/**
- * @author mirehak
- *
- */
-public abstract class RpcUtil {
-
- /**
- * @param result rpc result
- * @throws Exception exception thrown by method if rpc fails
- */
- public static void smokeRpc(RpcResult<?> result) throws Exception {
- if (!result.isSuccessful()) {
- Throwable firstCause = null;
- StringBuilder sb = new StringBuilder();
- for (RpcError error : result.getErrors()) {
- if (firstCause != null) {
- firstCause = error.getCause();
- }
-
- sb.append("rpcError:").append(error.getCause().getMessage()).append(';');
- }
- throw new Exception(sb.toString(), firstCause);
- }
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core;
-
-import java.net.InetAddress;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowjava.protocol.api.connection.SwitchConnectionHandler;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
-import org.opendaylight.openflowplugin.openflow.md.queue.QueueProcessorLightImpl;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-
-/**
- * basic interconnecting piece between plugin and library
- */
-public class SwitchConnectionHandlerImpl implements SwitchConnectionHandler {
-
- private ScheduledThreadPoolExecutor spyPool;
-
- private QueueProcessorLightImpl queueProcessor;
- private ErrorHandler errorHandler;
- private MessageSpy<DataContainer> messageSpy;
- private int spyRate = 10;
-
- /**
- *
- */
- public SwitchConnectionHandlerImpl() {
- queueProcessor = new QueueProcessorLightImpl();
-
- //TODO: implement shutdown invocation upon service stop event
- spyPool = new ScheduledThreadPoolExecutor(1);
- }
-
- /**
- * wire all up
- */
- public void init() {
- queueProcessor.setTranslatorMapping(OFSessionUtil.getTranslatorMap());
- queueProcessor.setPopListenersMapping(OFSessionUtil.getPopListenerMapping());
- queueProcessor.setMessageSpy(messageSpy);
-
- queueProcessor.init();
-
- spyPool.scheduleAtFixedRate(messageSpy, spyRate, spyRate, TimeUnit.SECONDS);
- }
-
- @Override
- public boolean accept(InetAddress address) {
- // TODO:: add policy derived rules
- return true;
- }
-
- @Override
- public void onSwitchConnected(ConnectionAdapter connectionAdapter) {
- ConnectionConductor conductor = ConnectionConductorFactory.createConductor(
- connectionAdapter, queueProcessor);
- conductor.setErrorHandler(errorHandler);
- }
-
- /**
- * @param messageSpy the messageSpy to set
- */
- public void setMessageSpy(MessageSpy<DataContainer> messageSpy) {
- this.messageSpy = messageSpy;
- }
-
- /**
- * @param errorHandler the errorHandler to set
- */
- public void setErrorHandler(ErrorHandler errorHandler) {
- this.errorHandler = errorHandler;
- }
-
-}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/**
- *
- */
public final class ActionExtensionHelper {
private static final Logger LOG = LoggerFactory
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchRpcUpdateGroupUpdatedSetField;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralExtensionListGrouping;
-/**
- *
- */
public class ExtensionResolvers {
private static GroupingLooseResolver<GeneralExtensionListGrouping> matchExtensionResolver =
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/**
- *
- */
public final class MatchExtensionHelper {
private static final Logger LOG = LoggerFactory
+++ /dev/null
-/**
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.role;
-
-import java.math.BigInteger;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException;
-import com.google.common.base.Optional;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
-import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitch;
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.OpenflowPluginConfig;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole;
-import org.opendaylight.openflowplugin.openflow.md.core.session.RolePushTask;
-import org.opendaylight.openflowplugin.openflow.md.core.session.RolePushException;
-import org.opendaylight.openflowplugin.openflow.md.util.RoleUtil;
-import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.ConcurrentHashMap;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.CheckedFuture;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class OfEntityManager implements TransactionChainListener{
- private static final Logger LOG = LoggerFactory.getLogger(OfEntityManager.class);
-
- private static final QName ENTITY_QNAME =
- org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.core.general.entity.rev150820.Entity.QNAME;
- private static final QName ENTITY_NAME = QName.create(ENTITY_QNAME, "name");
-
- private DataBroker dataBroker;
- private EntityOwnershipService entityOwnershipService;
- private final OpenflowOwnershipListener ownershipListener;
- private final AtomicBoolean registeredListener = new AtomicBoolean();
- private ConcurrentHashMap<Entity, MDSwitchMetaData> entsession;
- private ConcurrentHashMap<Entity, EntityOwnershipCandidateRegistration> entRegistrationMap;
- private final String DEVICE_TYPE = "openflow";
-
- private final ListeningExecutorService pool;
-
- private final OpenflowPluginConfig openflowPluginConfig;
-
- public OfEntityManager(EntityOwnershipService entityOwnershipService, OpenflowPluginConfig ofPluginConfig) {
- this.entityOwnershipService = entityOwnershipService;
- openflowPluginConfig = ofPluginConfig;
- ownershipListener = new OpenflowOwnershipListener(this);
- entsession = new ConcurrentHashMap<>();
- entRegistrationMap = new ConcurrentHashMap<>();
- ThreadPoolLoggingExecutor delegate = new ThreadPoolLoggingExecutor(
- 20, 20, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), "ofEntity");
- pool = MoreExecutors.listeningDecorator(delegate);
- }
-
- public void setDataBroker(DataBroker dbBroker) {
- this.dataBroker = dbBroker;
- }
-
- public void init(){
- registerEntityOwnershipChangeListener();
- }
-
- public void registerEntityOwnershipChangeListener() {
- if(entityOwnershipService!=null) {
- if(LOG.isDebugEnabled()) {
- LOG.debug("registerEntityOwnershipChangeListener: Registering entity ownership change listener for entitier of type {}", DEVICE_TYPE);
- }
- entityOwnershipService.registerListener(DEVICE_TYPE, ownershipListener);
- }
- }
-
- public void requestOpenflowEntityOwnership(final ModelDrivenSwitch ofSwitch,
- final SessionContext context,
- final NotificationQueueWrapper wrappedNotification,
- final RpcProviderRegistry rpcProviderRegistry) {
- MDSwitchMetaData entityMetaData =
- new MDSwitchMetaData(ofSwitch,context,wrappedNotification,rpcProviderRegistry);
-
- final Entity entity = new Entity(DEVICE_TYPE, ofSwitch.getNodeId().getValue());
- entsession.put(entity, entityMetaData);
-
- //Register as soon as possible to avoid missing any entity ownership change event
- final EntityOwnershipCandidateRegistration entityRegistration;
- try {
- entityRegistration = entityOwnershipService.registerCandidate(entity);
- entRegistrationMap.put(entity, entityRegistration);
- LOG.info("requestOpenflowEntityOwnership: Registered controller for the ownership of {}", ofSwitch.getNodeId() );
- } catch (CandidateAlreadyRegisteredException e) {
- // we can log and move for this error, as listener is present and role changes will be served.
- LOG.error("requestOpenflowEntityOwnership : Controller registration for ownership of {} failed ", ofSwitch.getNodeId(), e );
- }
-
- Optional <EntityOwnershipState> entityOwnershipStateOptional =
- entityOwnershipService.getOwnershipState(entity);
-
- if (entityOwnershipStateOptional.isPresent()) {
- final EntityOwnershipState entityOwnershipState = entityOwnershipStateOptional.get();
- if (entityOwnershipState.hasOwner()) {
- final OfpRole newRole ;
- if (entityOwnershipState.isOwner()) {
- LOG.info("requestOpenflowEntityOwnership: Set controller as a MASTER controller " +
- "because it's the OWNER of the {}", ofSwitch.getNodeId());
- newRole = OfpRole.BECOMEMASTER;
- setDeviceOwnershipState(entity,true);
- registerRoutedRPCForSwitch(entsession.get(entity));
- } else {
- LOG.info("requestOpenflowEntityOwnership: Set controller as a SLAVE controller " +
- "because it's is not the owner of the {}", ofSwitch.getNodeId());
- newRole = OfpRole.BECOMESLAVE;
- setDeviceOwnershipState(entity,false);
- }
- RolePushTask task = new RolePushTask(newRole, context);
- ListenableFuture<Boolean> rolePushResult = pool.submit(task);
- CheckedFuture<Boolean, RolePushException> rolePushResultChecked =
- RoleUtil.makeCheckedRuleRequestFxResult(rolePushResult);
- Futures.addCallback(rolePushResult, new FutureCallback<Boolean>(){
- @Override
- public void onSuccess(Boolean result){
- LOG.info("requestOpenflowEntityOwnership: Controller is now {} of the {}",
- newRole == OfpRole.BECOMEMASTER?"MASTER":"SLAVE",ofSwitch.getNodeId() );
-
- sendNodeAddedNotification(entsession.get(entity));
- }
- @Override
- public void onFailure(Throwable t){
- LOG.warn("requestOpenflowEntityOwnership: Controller is not able to set " +
- "the role for {}",ofSwitch.getNodeId(), t);
-
- if(newRole == OfpRole.BECOMEMASTER) {
- LOG.info("requestOpenflowEntityOwnership: ..and controller is the owner of the " +
- "device {}. Closing the registration, so other controllers can try to " +
- "become owner and attempt to be master controller.",ofSwitch.getNodeId());
-
- EntityOwnershipCandidateRegistration ownershipRegistrent = entRegistrationMap.get(entity);
- if (ownershipRegistrent != null) {
- ownershipRegistrent.close();
- entRegistrationMap.remove(entity);
- }
-
- LOG.info("requestOpenflowEntityOwnership: ..and registering it back to participate" +
- " in ownership of the entity.");
-
- EntityOwnershipCandidateRegistration entityRegistration;
- try {
- entityRegistration = entityOwnershipService.registerCandidate(entity);
- entRegistrationMap.put(entity, entityRegistration);
- LOG.info("requestOpenflowEntityOwnership: re-registered controller for " +
- "ownership of the {}", ofSwitch.getNodeId() );
- } catch (CandidateAlreadyRegisteredException e) {
- // we can log and move for this error, as listener is present and role changes will be served.
- LOG.error("requestOpenflowEntityOwnership: *Surprisingly* Entity is already " +
- "registered with EntityOwnershipService : {}", ofSwitch.getNodeId(), e );
- }
-
- } else {
- LOG.error("requestOpenflowEntityOwnership : Not able to set role {} for {}"
- , newRole == OfpRole.BECOMEMASTER?"MASTER":"SLAVE", ofSwitch.getNodeId());
- }
- }
- });
- }
- }
- }
-
- public void setSlaveRole(SessionContext sessionContext) {
- OfpRole newRole = OfpRole.BECOMESLAVE;
- if (sessionContext != null) {
- final BigInteger targetSwitchDPId = sessionContext.getFeatures().getDatapathId();
- LOG.debug("setSlaveRole: Set controller as a SLAVE controller for {}", targetSwitchDPId.toString());
-
- RolePushTask task = new RolePushTask(newRole, sessionContext);
- ListenableFuture<Boolean> rolePushResult = pool.submit(task);
- final CheckedFuture<Boolean, RolePushException> rolePushResultChecked =
- RoleUtil.makeCheckedRuleRequestFxResult(rolePushResult);
- Futures.addCallback(rolePushResult, new FutureCallback<Boolean>(){
- @Override
- public void onSuccess(Boolean result){
- LOG.debug("setSlaveRole: Controller is set as a SLAVE for {}", targetSwitchDPId.toString());
- }
- @Override
- public void onFailure(Throwable e){
- LOG.error("setSlaveRole: Role request to set controller as a SLAVE failed for {}",
- targetSwitchDPId.toString(), e);
- }
- });
- } else {
- LOG.warn("setSlaveRole: sessionContext is not set. Device is not connected anymore");
- }
- }
-
- public void onDeviceOwnershipChanged(final EntityOwnershipChange ownershipChange) {
- final OfpRole newRole;
- final Entity entity = ownershipChange.getEntity();
- SessionContext sessionContext = entsession.get(entity)!=null?entsession.get(entity).getContext():null;
- if (!ownershipChange.inJeopardy()) {
- if (ownershipChange.isOwner()) {
- LOG.info("onDeviceOwnershipChanged: Set controller as a MASTER controller because " +
- "it's the OWNER of the {}", entity);
- newRole = OfpRole.BECOMEMASTER;
- } else {
- newRole = OfpRole.BECOMESLAVE;
- if (sessionContext != null && ownershipChange.hasOwner()) {
- LOG.info("onDeviceOwnershipChanged: Set controller as a SLAVE controller because " +
- "it's not the OWNER of the {}", entity);
-
- if (ownershipChange.wasOwner()) {
- setDeviceOwnershipState(entity, false);
- deregisterRoutedRPCForSwitch(entsession.get(entity));
- // You don't have to explicitly set role to Slave in this case,
- // because other controller will be taking over the master role
- // and that will force other controller to become slave.
- } else {
- boolean isOwnershipInitialized = entsession.get(entity).getIsOwnershipInitialized();
- setDeviceOwnershipState(entity, false);
- if (!isOwnershipInitialized) {
- setSlaveRole(sessionContext);
- sendNodeAddedNotification(entsession.get(entity));
- }
- }
- }
- return;
- }
- } else {
- LOG.error("onDeviceOwnershipChanged: inJeopardy{}", ownershipChange.inJeopardy());
- //if i am the owner at present , i have lost quorum
- //thus transitioning to slave
- //if i am not the owner , election will be triggered
- if(entsession.get(entity).getOfSwitch().isEntityOwner()){
- newRole = OfpRole.BECOMESLAVE;
- setSlaveRole(sessionContext);
- setDeviceOwnershipState(entity, false);
- deregisterRoutedRPCForSwitch(entsession.get(entity));
- }else{
- LOG.error(" owner of the switch {}",entsession.get(entity).getOfSwitch().isEntityOwner());
- }
- return;
- }
-
- if (sessionContext != null) {
- //Register the RPC, given *this* controller instance is going to be master owner.
- //If role registration fails for this node, it will deregister as a candidate for
- //ownership and that will make this controller non-owner and it will deregister the
- // router rpc.
- setDeviceOwnershipState(entity,newRole==OfpRole.BECOMEMASTER);
- registerRoutedRPCForSwitch(entsession.get(entity));
-
- final String targetSwitchDPId = sessionContext.getFeatures().getDatapathId().toString();
- RolePushTask task = new RolePushTask(newRole, sessionContext);
- ListenableFuture<Boolean> rolePushResult = pool.submit(task);
-
- final CheckedFuture<Boolean, RolePushException> rolePushResultChecked =
- RoleUtil.makeCheckedRuleRequestFxResult(rolePushResult);
- Futures.addCallback(rolePushResult, new FutureCallback<Boolean>(){
- @Override
- public void onSuccess(Boolean result){
- LOG.info("onDeviceOwnershipChanged: Controller is successfully set as a " +
- "MASTER controller for {}", targetSwitchDPId);
- if(!openflowPluginConfig.skipTableFeatures()) {
- if(LOG.isDebugEnabled()){
- LOG.debug("Send table feature request for entity {}",entity.getId());
- }
- entsession.get(entity).getOfSwitch().sendEmptyTableFeatureRequest();
- }
- sendNodeAddedNotification(entsession.get(entity));
-
- }
- @Override
- public void onFailure(Throwable e){
-
- LOG.warn("onDeviceOwnershipChanged: Controller is not able to set the " +
- "MASTER role for {}.", targetSwitchDPId,e);
- if(newRole == OfpRole.BECOMEMASTER) {
- LOG.info("onDeviceOwnershipChanged: ..and this *instance* is owner of the device {}. " +
- "Closing the registration, so other entity can become owner " +
- "and attempt to be master controller.",targetSwitchDPId);
-
- EntityOwnershipCandidateRegistration ownershipRegistrent = entRegistrationMap.get(entity);
- if (ownershipRegistrent != null) {
- setDeviceOwnershipState(entity,false);
- ownershipRegistrent.close();
- MDSwitchMetaData switchMetadata = entsession.get(entity);
- if(switchMetadata != null){
- switchMetadata.setIsOwnershipInitialized(false);
- //We can probably leave deregistration till the node ownerhsip change.
- //But that can probably cause some race condition.
- deregisterRoutedRPCForSwitch(switchMetadata);
- }
- }
-
- LOG.info("onDeviceOwnershipChanged: ..and registering it back to participate in " +
- "ownership and re-try");
-
- EntityOwnershipCandidateRegistration entityRegistration;
- try {
- entityRegistration = entityOwnershipService.registerCandidate(entity);
- entRegistrationMap.put(entity, entityRegistration);
- LOG.info("onDeviceOwnershipChanged: re-registered candidate for " +
- "ownership of the {}", targetSwitchDPId );
- } catch (CandidateAlreadyRegisteredException ex) {
- // we can log and move for this error, as listener is present and role changes will be served.
- LOG.error("onDeviceOwnershipChanged: *Surprisingly* Entity is already " +
- "registered with EntityOwnershipService : {}", targetSwitchDPId, ex );
- }
-
- } else {
- LOG.error("onDeviceOwnershipChanged : Not able to set role {} for " +
- " {}", newRole == OfpRole.BECOMEMASTER?"MASTER":"SLAVE", targetSwitchDPId);
- }
- }
- });
- } else {
- LOG.warn("onDeviceOwnershipChanged: sessionContext is not available. Releasing ownership of the device");
- EntityOwnershipCandidateRegistration ownershipRegistrant = entRegistrationMap.get(entity);
- if (ownershipRegistrant != null) {
- ownershipRegistrant.close();
- }
- }
- }
-
- public void unregisterEntityOwnershipRequest(NodeId nodeId) {
- Entity entity = new Entity(DEVICE_TYPE, nodeId.getValue());
- entsession.remove(entity);
- EntityOwnershipCandidateRegistration entRegCandidate = entRegistrationMap.get(entity);
- if(entRegCandidate != null){
- LOG.info("unregisterEntityOwnershipRequest: Unregister controller entity ownership " +
- "request for {}", nodeId);
- entRegCandidate.close();
- entRegistrationMap.remove(entity);
- }
- }
-
- @Override
- public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction,
- final Throwable cause) {
- }
-
- @Override
- public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
- // NOOP
- }
-
- private static void registerRoutedRPCForSwitch(MDSwitchMetaData entityMetadata) {
- // Routed RPC registration is only done when *this* instance is owner of
- // the entity.
- if(entityMetadata.getOfSwitch().isEntityOwner()) {
- if (!entityMetadata.isRPCRegistrationDone.get()) {
- entityMetadata.setIsRPCRegistrationDone(true);
- ModelDrivenSwitchRegistration registration =
- entityMetadata.getOfSwitch().register(entityMetadata.getRpcProviderRegistry());
-
- entityMetadata.getContext().setProviderRegistration(registration);
-
- LOG.info("registerRoutedRPCForSwitch: Registered routed rpc for ModelDrivenSwitch {}",
- entityMetadata.getOfSwitch().getNodeId().getValue());
- }
- } else {
- LOG.info("registerRoutedRPCForSwitch: Skipping routed rpc registration for ModelDrivenSwitch {}",
- entityMetadata.getOfSwitch().getNodeId().getValue());
- }
- }
-
- private static void deregisterRoutedRPCForSwitch(MDSwitchMetaData entityMetadata) {
-
- ModelDrivenSwitchRegistration registration = entityMetadata.getContext().getProviderRegistration();
- if (null != registration) {
- registration.close();
- entityMetadata.getContext().setProviderRegistration(null);
- entityMetadata.setIsRPCRegistrationDone(false);
- }
- LOG.info("deregisterRoutedRPCForSwitch: De-registered routed rpc for ModelDrivenSwitch {}",
- entityMetadata.getOfSwitch().getNodeId().getValue());
- }
-
- private static void sendNodeAddedNotification(MDSwitchMetaData entityMetadata) {
- //Node added notification need to be sent irrespective of whether
- // *this* instance is owner of the entity or not. Because yang notifications
- // are local, and we should maintain the behavior across the application.
- if (entityMetadata != null && entityMetadata.getOfSwitch() != null) {
- LOG.info("sendNodeAddedNotification: Node Added notification is sent for ModelDrivenSwitch {}",
- entityMetadata.getOfSwitch().getNodeId().getValue());
-
- entityMetadata.getContext().getNotificationEnqueuer().enqueueNotification(
- entityMetadata.getWrappedNotification());
-
- //Send multipart request to get other details of the switch.
- entityMetadata.getOfSwitch().requestSwitchDetails();
- } else {
- LOG.debug("Switch got disconnected, skip node added notification.");
- }
- }
-
- private void setDeviceOwnershipState(Entity entity, boolean isMaster) {
- MDSwitchMetaData entityMetadata = entsession.get(entity);
- entityMetadata.setIsOwnershipInitialized(true);
- entityMetadata.getOfSwitch().setEntityOwnership(isMaster);
- }
-
- private class MDSwitchMetaData {
-
- final private ModelDrivenSwitch ofSwitch;
- final private SessionContext context;
- final private NotificationQueueWrapper wrappedNotification;
- final private RpcProviderRegistry rpcProviderRegistry;
- final private AtomicBoolean isRPCRegistrationDone = new AtomicBoolean(false);
- final private AtomicBoolean isOwnershipInitialized = new AtomicBoolean(false);
-
- MDSwitchMetaData(ModelDrivenSwitch ofSwitch,
- SessionContext context,
- NotificationQueueWrapper wrappedNotification,
- RpcProviderRegistry rpcProviderRegistry) {
- this.ofSwitch = ofSwitch;
- this.context = context;
- this.wrappedNotification = wrappedNotification;
- this.rpcProviderRegistry = rpcProviderRegistry;
- }
-
- public ModelDrivenSwitch getOfSwitch() {
- return ofSwitch;
- }
-
- public SessionContext getContext() {
- return context;
- }
-
- public NotificationQueueWrapper getWrappedNotification() {
- return wrappedNotification;
- }
-
- public RpcProviderRegistry getRpcProviderRegistry() {
- return rpcProviderRegistry;
- }
-
- public AtomicBoolean getIsRPCRegistrationDone() {
- return isRPCRegistrationDone;
- }
-
- public void setIsRPCRegistrationDone(boolean isRPCRegistrationDone) {
- this.isRPCRegistrationDone.set(isRPCRegistrationDone);
- }
-
- public boolean getIsOwnershipInitialized() {
- return isOwnershipInitialized.get();
- }
-
- public void setIsOwnershipInitialized( boolean ownershipState) {
- this.isOwnershipInitialized.set(ownershipState);
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/**
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.role;
-
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange;
-
-public class OpenflowOwnershipListener implements EntityOwnershipListener {
- private final OfEntityManager entManager;
-
- public OpenflowOwnershipListener(OfEntityManager entManager) {
- this.entManager = entManager;
- }
-
- @Override
- public void ownershipChanged(EntityOwnershipChange ownershipChange) {
- this.entManager.onDeviceOwnershipChanged(ownershipChange);
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2015, 2016 Dell. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.role;
-
-
-public class RoleChangeException extends Exception {
- private static final long serialVersionUID = -615991366447313972L;
-
- /**
- * default ctor
- *
- * @param message exception message
- */
- public RoleChangeException(String message) {
- super(message);
- }
-
- /**
- * @param message exception message
- * @param cause exception cause
- */
- public RoleChangeException(String message, Throwable cause) {
- super(message, cause);
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableList.Builder;
-import java.util.Collection;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.openflowplugin.api.openflow.md.AbstractModelDrivenSwitchRegistration;
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitch;
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.OpendaylightFlowTableStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.SalGroupService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.OpendaylightGroupStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContext;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.SalMeterService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.OpendaylightMeterStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.NodeConfigService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.SalPortService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.OpendaylightQueueStatisticsService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.SalTableService;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-/**
- * RPC abstract for MD-switch
- */
-public abstract class AbstractModelDrivenSwitch implements ModelDrivenSwitch {
-
- private final InstanceIdentifier<Node> identifier;
-
- protected final SessionContext sessionContext;
-
- private boolean isEntityOwner = false;
-
- protected AbstractModelDrivenSwitch(InstanceIdentifier<Node> identifier,SessionContext conductor) {
- this.identifier = identifier;
- this.sessionContext = conductor;
- }
-
- @Override
- public final InstanceIdentifier<Node> getIdentifier() {
- return this.identifier;
- }
-
- @Override
- public ModelDrivenSwitchRegistration register(RpcProviderRegistry rpcProviderRegistry) {
- final Builder<RoutedRpcRegistration<?>> builder = ImmutableList.builder();
-
- final RoutedRpcRegistration<SalFlowService> flowRegistration = rpcProviderRegistry.addRoutedRpcImplementation(SalFlowService.class, this);
- flowRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(flowRegistration);
-
- final RoutedRpcRegistration<SalPortService> portRegistration = rpcProviderRegistry.addRoutedRpcImplementation(SalPortService.class, this);
- portRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(portRegistration);
-
- final RoutedRpcRegistration<SalMeterService> meterRegistration = rpcProviderRegistry.addRoutedRpcImplementation(SalMeterService.class, this);
- meterRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(meterRegistration);
-
- final RoutedRpcRegistration<SalGroupService> groupRegistration = rpcProviderRegistry.addRoutedRpcImplementation(SalGroupService.class, this);
- groupRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(groupRegistration);
-
- final RoutedRpcRegistration<SalTableService> tableRegistration = rpcProviderRegistry.addRoutedRpcImplementation(SalTableService.class, this);
- tableRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(tableRegistration);
-
- final RoutedRpcRegistration<PacketProcessingService> packetRegistration = rpcProviderRegistry.addRoutedRpcImplementation(PacketProcessingService.class, this);
- packetRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(packetRegistration);
-
- final RoutedRpcRegistration<OpendaylightFlowStatisticsService> flowStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightFlowStatisticsService.class, this);
- flowStatisticsRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(flowStatisticsRegistration);
-
- final RoutedRpcRegistration<OpendaylightGroupStatisticsService> groupStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightGroupStatisticsService.class, this);
- groupStatisticsRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(groupStatisticsRegistration);
-
- final RoutedRpcRegistration<OpendaylightMeterStatisticsService> meterStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightMeterStatisticsService.class, this);
- meterStatisticsRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(meterStatisticsRegistration);
-
- final RoutedRpcRegistration<OpendaylightPortStatisticsService> portStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightPortStatisticsService.class, this);
- portStatisticsRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(portStatisticsRegistration);
-
- final RoutedRpcRegistration<NodeConfigService> nodeConfigRegistration = rpcProviderRegistry.addRoutedRpcImplementation(NodeConfigService.class, this);
- nodeConfigRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(nodeConfigRegistration);
-
- final RoutedRpcRegistration<OpendaylightFlowTableStatisticsService> flowTableStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightFlowTableStatisticsService.class, this);
- flowTableStatisticsRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(flowTableStatisticsRegistration);
-
- final RoutedRpcRegistration<OpendaylightQueueStatisticsService> queueStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightQueueStatisticsService.class, this);
- queueStatisticsRegistration.registerPath(NodeContext.class, getIdentifier());
- builder.add(queueStatisticsRegistration);
-
- final Collection<RoutedRpcRegistration<?>> registrations = builder.build();
- return new AbstractModelDrivenSwitchRegistration(this) {
- @Override
- protected void removeRegistration() {
- for (RoutedRpcRegistration<?> r : registrations) {
- r.close();
- }
- }
- };
- }
-
- /**
- * @return session context
- */
- public SessionContext getSessionContext() {
- return sessionContext;
- }
-
- @Override
- public boolean isEntityOwner() {
- return isEntityOwner;
- }
-
- @Override
- public void setEntityOwnership(boolean isOwner) {
- isEntityOwner = isOwner;
- }
-}
/**
* SwitchFeature builder for OF 1.0
- *
- * @author jsebin
- *
*/
public final class BuildSwitchCapabilitiesOF10 implements BuildSwitchFeatures {
/**
* SwitchFeature builder for OF 1.3
- *
- * @author jsebin
- *
*/
public final class BuildSwitchCapabilitiesOF13 implements BuildSwitchFeatures {
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.math.BigInteger;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.PacketOutConvertor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.PacketOutConvertorData;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
-import org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.SetConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.SetConfigOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestDescCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestPortDescCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestTableFeaturesCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.table.features._case.MultipartRequestTableFeaturesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.ConnectionCookie;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutput;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.slf4j.Logger;
-
-/**
- * RPC implementation of MD-switch
- */
-public class ModelDrivenSwitchImpl extends AbstractModelDrivenSwitch {
-
- private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(ModelDrivenSwitchImpl.class);
- private final NodeId nodeId;
- private final IMessageDispatchService messageService;
- private short version = 0;
- private final ConvertorExecutor convertorExecutor;
- private OFRpcTaskContext rpcTaskContext;
-
- // TODO:read timeout from configSubsystem
- protected long maxTimeout = 1000;
- protected TimeUnit maxTimeoutUnit = TimeUnit.MILLISECONDS;
-
- protected ModelDrivenSwitchImpl(final NodeId nodeId, final InstanceIdentifier<Node> identifier,
- final SessionContext sessionContext, final ConvertorExecutor convertorExecutor) {
- super(identifier, sessionContext);
- this.nodeId = nodeId;
- messageService = sessionContext.getMessageDispatchService();
- version = sessionContext.getPrimaryConductor().getVersion();
- this.convertorExecutor = convertorExecutor;
- final NotificationProviderService rpcNotificationProviderService = OFSessionUtil.getSessionManager().getNotificationProviderService();
-
- rpcTaskContext = new OFRpcTaskContext();
- rpcTaskContext.setSession(sessionContext);
- rpcTaskContext.setMessageService(messageService);
- rpcTaskContext.setRpcNotificationProviderService(rpcNotificationProviderService);
- rpcTaskContext.setMaxTimeout(maxTimeout);
- rpcTaskContext.setMaxTimeoutUnit(maxTimeoutUnit);
- rpcTaskContext.setRpcPool(OFSessionUtil.getSessionManager().getRpcPool());
- rpcTaskContext.setMessageSpy(OFSessionUtil.getSessionManager().getMessageSpy());
-
- }
-
- @Override
- public Future<RpcResult<AddFlowOutput>> addFlow(final AddFlowInput input) {
- LOG.debug("Calling the FlowMod RPC method on MessageDispatchService");
- // use primary connection
- SwitchConnectionDistinguisher cookie = null;
-
- OFRpcTask<AddFlowInput, RpcResult<UpdateFlowOutput>> task =
- OFRpcTaskFactory.createAddFlowTask(rpcTaskContext, input, cookie, convertorExecutor);
- ListenableFuture<RpcResult<UpdateFlowOutput>> result = task.submit();
-
- return Futures.transform(result, OFRpcFutureResultTransformFactory.createForAddFlowOutput());
- }
-
-
- @Override
- public Future<RpcResult<AddGroupOutput>> addGroup(final AddGroupInput input) {
- LOG.debug("Calling the GroupMod RPC method on MessageDispatchService");
-
- // use primary connection
- SwitchConnectionDistinguisher cookie = null;
-
- OFRpcTask<AddGroupInput, RpcResult<UpdateGroupOutput>> task =
- OFRpcTaskFactory.createAddGroupTask(rpcTaskContext, input, cookie, convertorExecutor);
- ListenableFuture<RpcResult<UpdateGroupOutput>> result = task.submit();
-
- return Futures.transform(result, OFRpcFutureResultTransformFactory.createForAddGroupOutput());
- }
-
- @Override
- public Future<RpcResult<AddMeterOutput>> addMeter(final AddMeterInput input) {
- LOG.debug("Calling the MeterMod RPC method on MessageDispatchService");
-
- // use primary connection
- SwitchConnectionDistinguisher cookie = null;
-
- OFRpcTask<AddMeterInput, RpcResult<UpdateMeterOutput>> task =
- OFRpcTaskFactory.createAddMeterTask(rpcTaskContext, input, cookie, convertorExecutor);
- ListenableFuture<RpcResult<UpdateMeterOutput>> result = task.submit();
-
- return Futures.transform(result, OFRpcFutureResultTransformFactory.createForAddMeterOutput());
- }
-
- @Override
- public Future<RpcResult<RemoveFlowOutput>> removeFlow(final RemoveFlowInput input) {
- LOG.debug("Calling the removeFlow RPC method on MessageDispatchService");
-
- // use primary connection
- SwitchConnectionDistinguisher cookie = null;
- OFRpcTask<RemoveFlowInput, RpcResult<UpdateFlowOutput>> task =
- OFRpcTaskFactory.createRemoveFlowTask(rpcTaskContext, input, cookie, convertorExecutor);
- ListenableFuture<RpcResult<UpdateFlowOutput>> result = task.submit();
-
- return Futures.transform(result, OFRpcFutureResultTransformFactory.createForRemoveFlowOutput());
- }
-
- @Override
- public Future<RpcResult<RemoveGroupOutput>> removeGroup(final RemoveGroupInput input) {
- LOG.debug("Calling the Remove Group RPC method on MessageDispatchService");
-
- SwitchConnectionDistinguisher cookie = null;
- OFRpcTask<RemoveGroupInput, RpcResult<UpdateGroupOutput>> task =
- OFRpcTaskFactory.createRemoveGroupTask(rpcTaskContext, input, cookie, convertorExecutor);
- ListenableFuture<RpcResult<UpdateGroupOutput>> result = task.submit();
-
- return Futures.transform(result, OFRpcFutureResultTransformFactory.createForRemoveGroupOutput());
- }
-
- @Override
- public Future<RpcResult<RemoveMeterOutput>> removeMeter(final RemoveMeterInput input) {
- LOG.debug("Calling the Remove MeterMod RPC method on MessageDispatchService");
-
- SwitchConnectionDistinguisher cookie = null;
- OFRpcTask<RemoveMeterInput, RpcResult<UpdateMeterOutput>> task =
- OFRpcTaskFactory.createRemoveMeterTask(rpcTaskContext, input, cookie, convertorExecutor);
- ListenableFuture<RpcResult<UpdateMeterOutput>> result = task.submit();
-
- return Futures.transform(result, OFRpcFutureResultTransformFactory.createForRemoveMeterOutput());
- }
-
- @Override
- public Future<RpcResult<Void>> transmitPacket(final TransmitPacketInput input) {
- LOG.debug("TransmitPacket - {}", input);
- // Convert TransmitPacket to PacketOutInput
- final PacketOutConvertorData data = new PacketOutConvertorData(version);
- data.setDatapathId(sessionContext.getFeatures().getDatapathId());
- data.setXid(sessionContext.getNextXid());
-
- final java.util.Optional<PacketOutInput> message = convertorExecutor.convert(input, data);
-
- SwitchConnectionDistinguisher cookie = null;
- ConnectionCookie connectionCookie = input.getConnectionCookie();
- if (connectionCookie != null && connectionCookie.getValue() != null) {
- cookie = new SwitchConnectionCookieOFImpl(connectionCookie.getValue());
- }
-
- LOG.debug("Calling the transmitPacket RPC method");
- return messageService.packetOut(message
- .orElse(PacketOutConvertor.defaultResult(version)), cookie);
- }
-
- @Override
- public Future<RpcResult<UpdateFlowOutput>> updateFlow(final UpdateFlowInput input) {
- LOG.debug("Calling the updateFlow RPC method on MessageDispatchService");
-
- // use primary connection
- SwitchConnectionDistinguisher cookie = null;
- final ReadWriteTransaction rwTx = OFSessionUtil.getSessionManager().getDataBroker().newReadWriteTransaction();
- OFRpcTask<UpdateFlowInput, RpcResult<UpdateFlowOutput>> task =
- OFRpcTaskFactory.createUpdateFlowTask(rpcTaskContext, input, cookie, rwTx, convertorExecutor);
- ListenableFuture<RpcResult<UpdateFlowOutput>> result = task.submit();
-
- return result;
- }
-
- @Override
- public Future<RpcResult<UpdateGroupOutput>> updateGroup(final UpdateGroupInput input) {
- LOG.debug("Calling the update Group Mod RPC method on MessageDispatchService");
-
- // use primary connection
- SwitchConnectionDistinguisher cookie = null;
-
- OFRpcTask<UpdateGroupInput, RpcResult<UpdateGroupOutput>> task =
- OFRpcTaskFactory.createUpdateGroupTask(rpcTaskContext, input, cookie, convertorExecutor);
- ListenableFuture<RpcResult<UpdateGroupOutput>> result = task.submit();
-
- return result;
- }
-
- @Override
- public Future<RpcResult<UpdateMeterOutput>> updateMeter(final UpdateMeterInput input) {
- LOG.debug("Calling the MeterMod RPC method on MessageDispatchService");
-
- // use primary connection
- SwitchConnectionDistinguisher cookie = null;
-
- OFRpcTask<UpdateMeterInput, RpcResult<UpdateMeterOutput>> task =
- OFRpcTaskFactory.createUpdateMeterTask(rpcTaskContext, input, cookie, convertorExecutor);
- ListenableFuture<RpcResult<UpdateMeterOutput>> result = task.submit();
-
- return result;
- }
-
- @Override
- public NodeId getNodeId() {
- return nodeId;
- }
-
-
- @Override
- public Future<RpcResult<GetAllGroupStatisticsOutput>> getAllGroupStatistics(final GetAllGroupStatisticsInput input) {
- // use primary connection
- LOG.debug("Calling the getAllGroupStatistics RPC method on MessageDispatchService");
- SwitchConnectionDistinguisher cookie = null;
-
- OFRpcTask<GetAllGroupStatisticsInput, RpcResult<GetAllGroupStatisticsOutput>> task =
- OFRpcTaskFactory.createGetAllGroupStatisticsTask(rpcTaskContext, input, cookie);
- ListenableFuture<RpcResult<GetAllGroupStatisticsOutput>> result = task.submit();
-
- return result;
-
- }
-
- @Override
- public Future<RpcResult<GetGroupDescriptionOutput>> getGroupDescription(final GetGroupDescriptionInput input) {
- LOG.debug("Calling the getGroupDescription RPC method on MessageDispatchService");
-
- OFRpcTask<GetGroupDescriptionInput, RpcResult<GetGroupDescriptionOutput>> task =
- OFRpcTaskFactory.createGetGroupDescriptionTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetGroupFeaturesOutput>> getGroupFeatures(final GetGroupFeaturesInput input) {
- LOG.debug("Calling the getGroupFeatures RPC method on MessageDispatchService");
-
- OFRpcTask<GetGroupFeaturesInput, RpcResult<GetGroupFeaturesOutput>> task =
- OFRpcTaskFactory.createGetGroupFeaturesTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetGroupStatisticsOutput>> getGroupStatistics(final GetGroupStatisticsInput input) {
- LOG.debug("Calling the getGroupStatistics RPC method on MessageDispatchService");
-
- OFRpcTask<GetGroupStatisticsInput, RpcResult<GetGroupStatisticsOutput>> task =
- OFRpcTaskFactory.createGetGroupStatisticsTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetAllMeterConfigStatisticsOutput>> getAllMeterConfigStatistics(
- final GetAllMeterConfigStatisticsInput input) {
- LOG.debug("Calling the getAllMeterConfigStatistics RPC method on MessageDispatchService");
-
- OFRpcTask<GetAllMeterConfigStatisticsInput, RpcResult<GetAllMeterConfigStatisticsOutput>> task =
- OFRpcTaskFactory.createGetAllMeterConfigStatisticsTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetAllMeterStatisticsOutput>> getAllMeterStatistics(
- final GetAllMeterStatisticsInput input) {
- LOG.debug("Calling the getAllMeterStatistics RPC method on MessageDispatchService");
-
- OFRpcTask<GetAllMeterStatisticsInput, RpcResult<GetAllMeterStatisticsOutput>> task =
- OFRpcTaskFactory.createGetAllMeterStatisticsTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetMeterFeaturesOutput>> getMeterFeatures(
- final GetMeterFeaturesInput input) {
- LOG.debug("Calling the getMeterFeatures RPC method on MessageDispatchService");
-
- OFRpcTask<GetMeterFeaturesInput, RpcResult<GetMeterFeaturesOutput>> task =
- OFRpcTaskFactory.createGetMeterFeaturesTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetMeterStatisticsOutput>> getMeterStatistics(
- final GetMeterStatisticsInput input) {
- LOG.debug("Calling the getMeterStatistics RPC method on MessageDispatchService");
-
- OFRpcTask<GetMeterStatisticsInput, RpcResult<GetMeterStatisticsOutput>> task =
- OFRpcTaskFactory.createGetMeterStatisticsTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetAllNodeConnectorsStatisticsOutput>> getAllNodeConnectorsStatistics(
- final GetAllNodeConnectorsStatisticsInput input) {
- LOG.debug("Calling the getAllNodeConnectorsStatistics RPC method on MessageDispatchService");
-
- OFRpcTask<GetAllNodeConnectorsStatisticsInput, RpcResult<GetAllNodeConnectorsStatisticsOutput>> task =
- OFRpcTaskFactory.createGetAllNodeConnectorsStatisticsTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetNodeConnectorStatisticsOutput>> getNodeConnectorStatistics(
- final GetNodeConnectorStatisticsInput input) {
- LOG.debug("Calling the getNodeConnectorStatistics RPC method on MessageDispatchService");
-
- OFRpcTask<GetNodeConnectorStatisticsInput, RpcResult<GetNodeConnectorStatisticsOutput>> task =
- OFRpcTaskFactory.createGetNodeConnectorStatisticsTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<UpdatePortOutput>> updatePort(final UpdatePortInput input) {
- LOG.debug("Calling the updatePort RPC method on MessageDispatchService");
-
- OFRpcTask<UpdatePortInput, RpcResult<UpdatePortOutput>> task =
- OFRpcTaskFactory.createUpdatePortTask(rpcTaskContext, input, null, convertorExecutor);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<UpdateTableOutput>> updateTable(final UpdateTableInput input) {
- LOG.debug("Calling the updateTable RPC method on MessageDispatchService");
-
- OFRpcTask<UpdateTableInput, RpcResult<UpdateTableOutput>> task =
- OFRpcTaskFactory.createUpdateTableTask(rpcTaskContext, input, null, convertorExecutor);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetAllFlowStatisticsFromFlowTableOutput>> getAllFlowStatisticsFromFlowTable(
- final GetAllFlowStatisticsFromFlowTableInput input) {
- LOG.debug("Calling the getAllFlowStatisticsFromFlowTable RPC method on MessageDispatchService");
-
- OFRpcTask<GetAllFlowStatisticsFromFlowTableInput, RpcResult<GetAllFlowStatisticsFromFlowTableOutput>> task =
- OFRpcTaskFactory.createGetAllFlowStatisticsFromFlowTableTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetAllFlowsStatisticsFromAllFlowTablesOutput>> getAllFlowsStatisticsFromAllFlowTables(
- final GetAllFlowsStatisticsFromAllFlowTablesInput input) {
- LOG.debug("Calling the getAllFlowsStatisticsFromAllFlowTables RPC method on MessageDispatchService");
-
- OFRpcTask<GetAllFlowsStatisticsFromAllFlowTablesInput, RpcResult<GetAllFlowsStatisticsFromAllFlowTablesOutput>> task =
- OFRpcTaskFactory.createGetAllFlowsStatisticsFromAllFlowTablesTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetFlowStatisticsFromFlowTableOutput>> getFlowStatisticsFromFlowTable(
- final GetFlowStatisticsFromFlowTableInput input) {
- LOG.debug("Calling the getFlowStatisticsFromFlowTable RPC method on MessageDispatchService");
-
- OFRpcTask<GetFlowStatisticsFromFlowTableInput, RpcResult<GetFlowStatisticsFromFlowTableOutput>> task =
- OFRpcTaskFactory.createGetFlowStatisticsFromFlowTableTask(rpcTaskContext, input, null, convertorExecutor);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput>> getAggregateFlowStatisticsFromFlowTableForAllFlows(
- final GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput input) {
- LOG.debug("Calling the getAggregateFlowStatisticsFromFlowTableForAllFlows RPC method on MessageDispatchService");
-
- OFRpcTask<GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput, RpcResult<GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput>> task =
- OFRpcTaskFactory.createGetAggregateFlowStatisticsFromFlowTableForAllFlowsTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput>> getAggregateFlowStatisticsFromFlowTableForGivenMatch(
- final GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput input) {
- LOG.debug("Calling the getAggregateFlowStatisticsFromFlowTableForGivenMatch RPC method on MessageDispatchService");
-
- OFRpcTask<GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput, RpcResult<GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput>> task =
- OFRpcTaskFactory.createGetAggregateFlowStatisticsFromFlowTableForGivenMatchTask(rpcTaskContext, input, null, convertorExecutor);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetFlowTablesStatisticsOutput>> getFlowTablesStatistics(
- final GetFlowTablesStatisticsInput input) {
- LOG.debug("Calling the getFlowTablesStatistics RPC method on MessageDispatchService");
-
- OFRpcTask<GetFlowTablesStatisticsInput, RpcResult<GetFlowTablesStatisticsOutput>> task =
- OFRpcTaskFactory.createGetFlowTablesStatisticsTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetAllQueuesStatisticsFromAllPortsOutput>> getAllQueuesStatisticsFromAllPorts(
- final GetAllQueuesStatisticsFromAllPortsInput input) {
- LOG.debug("Calling the getAllQueuesStatisticsFromAllPorts RPC method on MessageDispatchService");
-
- OFRpcTask<GetAllQueuesStatisticsFromAllPortsInput, RpcResult<GetAllQueuesStatisticsFromAllPortsOutput>> task =
- OFRpcTaskFactory.createGetAllQueuesStatisticsFromAllPortsTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetAllQueuesStatisticsFromGivenPortOutput>> getAllQueuesStatisticsFromGivenPort(
- final GetAllQueuesStatisticsFromGivenPortInput input) {
- LOG.debug("Calling the getAllQueuesStatisticsFromGivenPort RPC method on MessageDispatchService");
-
- OFRpcTask<GetAllQueuesStatisticsFromGivenPortInput, RpcResult<GetAllQueuesStatisticsFromGivenPortOutput>> task =
- OFRpcTaskFactory.createGetAllQueuesStatisticsFromGivenPortTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<GetQueueStatisticsFromGivenPortOutput>> getQueueStatisticsFromGivenPort(
- final GetQueueStatisticsFromGivenPortInput input) {
- LOG.debug("Calling the getQueueStatisticsFromGivenPort RPC method on MessageDispatchService");
-
- OFRpcTask<GetQueueStatisticsFromGivenPortInput, RpcResult<GetQueueStatisticsFromGivenPortOutput>> task =
- OFRpcTaskFactory.createGetQueueStatisticsFromGivenPortTask(rpcTaskContext, input, null);
- return task.submit();
- }
-
- @Override
- public Future<RpcResult<SetConfigOutput>> setConfig(SetConfigInput input) {
- OFRpcTask<SetConfigInput, RpcResult<SetConfigOutput>> task = OFRpcTaskFactory.createSetNodeConfigTask(rpcTaskContext, input, null);
- return task.submit();
- }
- @Override
- public Optional<BigInteger> sendEmptyTableFeatureRequest() {
- LOG.debug("Send table feature request to {}",nodeId);
-
- final Long xid = rpcTaskContext.getSession().getNextXid();
-
- MultipartRequestTableFeaturesCaseBuilder caseBuilder = new MultipartRequestTableFeaturesCaseBuilder();
- MultipartRequestTableFeaturesBuilder requestBuilder = new MultipartRequestTableFeaturesBuilder();
- caseBuilder.setMultipartRequestTableFeatures(requestBuilder.build());
-
- MultipartRequestInputBuilder mprInput = new MultipartRequestInputBuilder();
- mprInput.setType(MultipartType.OFPMPTABLEFEATURES);
- mprInput.setVersion(rpcTaskContext.getSession().getPrimaryConductor().getVersion());
- mprInput.setXid(xid);
- mprInput.setFlags(new MultipartRequestFlags(false));
-
- mprInput.setMultipartRequestBody(caseBuilder.build());
-
- Future<RpcResult<Void>> resultFromOFLib = rpcTaskContext.getMessageService()
- .multipartRequest(mprInput.build(), null);
-
- return Optional.of(BigInteger.valueOf(xid));
-
- }
-
- @Override
- public void requestSwitchDetails(){
- // post-handshake actions
- if (version == OFConstants.OFP_VERSION_1_3) {
- requestPorts();
- }
-
- requestDesc();
- }
-
- /*
- * Send an OFPMP_DESC request message to the switch
- */
- private void requestDesc() {
- MultipartRequestInputBuilder builder = new MultipartRequestInputBuilder();
- builder.setType(MultipartType.OFPMPDESC);
- builder.setVersion(version);
- builder.setFlags(new MultipartRequestFlags(false));
- builder.setMultipartRequestBody(new MultipartRequestDescCaseBuilder()
- .build());
- builder.setXid(getSessionContext().getNextXid());
- rpcTaskContext.getSession().getPrimaryConductor().getConnectionAdapter().multipartRequest(builder.build());
- }
-
- private void requestPorts() {
- MultipartRequestInputBuilder builder = new MultipartRequestInputBuilder();
- builder.setType(MultipartType.OFPMPPORTDESC);
- builder.setVersion(version);
- builder.setFlags(new MultipartRequestFlags(false));
- builder.setMultipartRequestBody(new MultipartRequestPortDescCaseBuilder()
- .build());
- builder.setXid(getSessionContext().getNextXid());
- rpcTaskContext.getSession().getPrimaryConductor().getConnectionAdapter().multipartRequest(builder.build());
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-import com.google.common.base.Function;
-import java.util.Collection;
-import org.opendaylight.controller.sal.common.util.Rpcs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * collection of transformation functions dedicated to rpc future results
- */
-public abstract class OFRpcFutureResultTransformFactory {
-
- private static final String MSG_ADD_FLOW_RPC = "Returning the Add Flow RPC result to MD-SAL";
- protected static final Logger LOG = LoggerFactory
- .getLogger(OFRpcFutureResultTransformFactory.class);
-
- /**
- *
- * @param input rpc result input
- * @param result results
- * @param <E> rpc result input type
- * @return rpc result
- */
- protected static <E> RpcResult<E> assembleRpcResult(RpcResult<?> input, E result) {
- Collection<RpcError> errors = input.getErrors();
- return Rpcs.getRpcResult(input.isSuccessful(), result, errors);
- }
-
- /**
- * @return translator from {@link UpdateFlowOutput} to {@link AddFlowOutput}
- */
- public static Function<RpcResult<UpdateFlowOutput>,RpcResult<AddFlowOutput>> createForAddFlowOutput() {
- return new Function<RpcResult<UpdateFlowOutput>,RpcResult<AddFlowOutput>>() {
-
- @Override
- public RpcResult<AddFlowOutput> apply(RpcResult<UpdateFlowOutput> input) {
-
- UpdateFlowOutput updateFlowOutput = input.getResult();
-
- AddFlowOutputBuilder addFlowOutput = new AddFlowOutputBuilder();
- addFlowOutput.setTransactionId(updateFlowOutput.getTransactionId());
- AddFlowOutput result = addFlowOutput.build();
-
- RpcResult<AddFlowOutput> rpcResult = assembleRpcResult(input, result);
- LOG.debug(MSG_ADD_FLOW_RPC);
- return rpcResult;
- }
-
- };
- }
-
- /**
- * @return translator from {@link UpdateFlowOutput} to {@link RemoveFlowOutput}
- */
- public static Function<RpcResult<UpdateFlowOutput>,RpcResult<RemoveFlowOutput>> createForRemoveFlowOutput() {
- return new Function<RpcResult<UpdateFlowOutput>,RpcResult<RemoveFlowOutput>>() {
-
- @Override
- public RpcResult<RemoveFlowOutput> apply(RpcResult<UpdateFlowOutput> input) {
-
- UpdateFlowOutput updateFlowOutput = input.getResult();
-
- RemoveFlowOutputBuilder removeFlowOutput = new RemoveFlowOutputBuilder();
- removeFlowOutput.setTransactionId(updateFlowOutput.getTransactionId());
- RemoveFlowOutput result = removeFlowOutput.build();
-
- RpcResult<RemoveFlowOutput> rpcResult = assembleRpcResult(input, result);
- LOG.debug("Returning the Remove Flow RPC result to MD-SAL");
- return rpcResult;
- }
-
- };
- }
-
- /**
- * @return translator from {@link UpdateGroupOutput} to {@link AddGroupOutput}
- */
- public static Function<RpcResult<UpdateGroupOutput>, RpcResult<AddGroupOutput>> createForAddGroupOutput() {
- return new Function<RpcResult<UpdateGroupOutput>,RpcResult<AddGroupOutput>>() {
-
- @Override
- public RpcResult<AddGroupOutput> apply(final RpcResult<UpdateGroupOutput> input) {
- UpdateGroupOutput updateGroupOutput = input.getResult();
-
- AddGroupOutputBuilder addGroupOutput = new AddGroupOutputBuilder();
- addGroupOutput.setTransactionId(updateGroupOutput.getTransactionId());
- AddGroupOutput result = addGroupOutput.build();
-
- RpcResult<AddGroupOutput> rpcResult = assembleRpcResult(input, result);
- LOG.debug("Returning the Add Group RPC result to MD-SAL");
- return rpcResult;
- }
- };
- }
-
- /**
- * @return rpc result function for group udpate
- */
- public static Function<RpcResult<UpdateGroupOutput>,RpcResult<RemoveGroupOutput>> createForRemoveGroupOutput() {
- return new Function<RpcResult<UpdateGroupOutput>,RpcResult<RemoveGroupOutput>>() {
-
- @Override
- public RpcResult<RemoveGroupOutput> apply(RpcResult<UpdateGroupOutput> input) {
-
- UpdateGroupOutput updateGroupOutput = input.getResult();
-
- RemoveGroupOutputBuilder removeGroupOutput = new RemoveGroupOutputBuilder();
- removeGroupOutput.setTransactionId(updateGroupOutput.getTransactionId());
- RemoveGroupOutput result = removeGroupOutput.build();
-
- RpcResult<RemoveGroupOutput> rpcResult = assembleRpcResult(input, result);
- LOG.debug("Returning the Remove Group RPC result to MD-SAL");
- return rpcResult;
- }
-
- };
- }
-
- /**
- * @return translator from {@link UpdateMeterOutput} to {@link AddMeterOutput}
- */
- public static Function<RpcResult<UpdateMeterOutput>, RpcResult<AddMeterOutput>> createForAddMeterOutput() {
- return new Function<RpcResult<UpdateMeterOutput>,RpcResult<AddMeterOutput>>() {
-
- @Override
- public RpcResult<AddMeterOutput> apply(final RpcResult<UpdateMeterOutput> input) {
- UpdateMeterOutput updateMeterOutput = input.getResult();
-
- AddMeterOutputBuilder addMeterOutput = new AddMeterOutputBuilder();
- addMeterOutput.setTransactionId(updateMeterOutput.getTransactionId());
- AddMeterOutput result = addMeterOutput.build();
-
- RpcResult<AddMeterOutput> rpcResult = assembleRpcResult(input, result);
- LOG.debug("Returning the Add Meter RPC result to MD-SAL");
- return rpcResult;
- }
- };
- }
-
-
- /**
- * @return return rpc result function
- */
- public static Function<RpcResult<UpdateMeterOutput>, RpcResult<RemoveMeterOutput>> createForRemoveMeterOutput() {
- return new Function<RpcResult<UpdateMeterOutput>,RpcResult<RemoveMeterOutput>>() {
-
- @Override
- public RpcResult<RemoveMeterOutput> apply(final RpcResult<UpdateMeterOutput> input) {
- UpdateMeterOutput updateMeterOutput = input.getResult();
-
- RemoveMeterOutputBuilder removeMeterOutput = new RemoveMeterOutputBuilder();
- removeMeterOutput.setTransactionId(updateMeterOutput.getTransactionId());
- RemoveMeterOutput result = removeMeterOutput.build();
-
- RpcResult<RemoveMeterOutput> rpcResult = assembleRpcResult(input, result);
- LOG.debug("Returning the Remove Meter RPC result to MD-SAL");
- return rpcResult;
- }
- };
- }
-
-
-
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-
-/**
- * @param <T> input type
- * @param <K> future output type
- */
-public abstract class OFRpcTask<T, K> implements Callable<ListenableFuture<K>> {
-
- private OFRpcTaskContext taskContext;
- private T input;
- private SwitchConnectionDistinguisher cookie;
-
- /**
- * @param taskContext rpc task context
- * @param input task input
- * @param cookie switch connection distinguisher cookie value
- */
- public OFRpcTask(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, T input) {
- this.taskContext = taskContext;
- this.cookie = cookie;
- this.input = input;
- }
-
- /**
- * @return the cookie
- */
- public SwitchConnectionDistinguisher getCookie() {
- return cookie;
- }
-
- /**
- * @param cookie the cookie to set
- */
- public void setCookie(SwitchConnectionDistinguisher cookie) {
- this.cookie = cookie;
- }
-
- /**
- * @return the input
- */
- public T getInput() {
- return input;
- }
-
- /**
- * @param input the input to set
- */
- public void setInput(T input) {
- this.input = input;
- }
-
- /**
- * @return the rpcNotificationProviderService
- */
- public NotificationProviderService getRpcNotificationProviderService() {
- return taskContext.getRpcNotificationProviderService();
- }
-
- /**
- * @return message service
- * @see org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskContext#getMessageService()
- */
- public IMessageDispatchService getMessageService() {
- return taskContext.getMessageService();
- }
-
- /**
- * @return session
- * @see org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskContext#getSession()
- */
- public SessionContext getSession() {
- return taskContext.getSession();
- }
-
- /**
- * @return max timeout
- * @see org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskContext#getMaxTimeout()
- */
- public long getMaxTimeout() {
- return taskContext.getMaxTimeout();
- }
-
- /**
- * @return time unit for max timeout
- * @see org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskContext#getMaxTimeoutUnit()
- */
- public TimeUnit getMaxTimeoutUnit() {
- return taskContext.getMaxTimeoutUnit();
- }
-
- /**
- * @return protocol version
- */
- public Short getVersion() {
- return taskContext.getSession().getFeatures().getVersion();
-
- }
-
- /**
- * @return the taskContext
- */
- public OFRpcTaskContext getTaskContext() {
- return taskContext;
- }
-
- /**
- * submit task into rpc worker pool
- * @return future result of task
- */
- public ListenableFuture<K> submit() {
- ListenableFuture<ListenableFuture<K>> compoundResult = getTaskContext().getRpcPool().submit(this);
- return Futures.dereference(compoundResult);
- }
-
- /**
- * @return required barrier value
- */
- public Boolean isBarrier() {
- return null;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-import java.util.concurrent.TimeUnit;
-
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-
-import com.google.common.util.concurrent.ListeningExecutorService;
-
-/**
- *
- */
-public class OFRpcTaskContext {
-
- private IMessageDispatchService messageService;
- private SessionContext session;
- private NotificationProviderService rpcNotificationProviderService;
- private long maxTimeout;
- private TimeUnit maxTimeoutUnit;
- private ListeningExecutorService rpcPool;
- private MessageSpy<DataContainer> messageSpy;
-
- /**
- * @return the messageService
- */
- public IMessageDispatchService getMessageService() {
- return messageService;
- }
- /**
- * @param messageService the messageService to set
- */
- public void setMessageService(IMessageDispatchService messageService) {
- this.messageService = messageService;
- }
- /**
- * @return the session
- */
- public SessionContext getSession() {
- return session;
- }
- /**
- * @param session the session to set
- */
- public void setSession(SessionContext session) {
- this.session = session;
- }
- /**
- * @return the rpcNotificationProviderService
- */
- public NotificationProviderService getRpcNotificationProviderService() {
- return rpcNotificationProviderService;
- }
- /**
- * @param rpcNotificationProviderService the rpcNotificationProviderService to set
- */
- public void setRpcNotificationProviderService(
- NotificationProviderService rpcNotificationProviderService) {
- this.rpcNotificationProviderService = rpcNotificationProviderService;
- }
- /**
- * @return the maxTimeout
- */
- public long getMaxTimeout() {
- return maxTimeout;
- }
- /**
- * @param maxTimeout the maxTimeout to set
- */
- public void setMaxTimeout(long maxTimeout) {
- this.maxTimeout = maxTimeout;
- }
- /**
- * @return the maxTimeoutUnit
- */
- public TimeUnit getMaxTimeoutUnit() {
- return maxTimeoutUnit;
- }
- /**
- * @param maxTimeoutUnit the maxTimeoutUnit to set
- */
- public void setMaxTimeoutUnit(TimeUnit maxTimeoutUnit) {
- this.maxTimeoutUnit = maxTimeoutUnit;
- }
- /**
- * @param rpcPool executor service pool for rpc
- */
- public void setRpcPool(ListeningExecutorService rpcPool) {
- this.rpcPool = rpcPool;
- }
-
- /**
- * @return the rpcPool
- */
- public ListeningExecutorService getRpcPool() {
- return rpcPool;
- }
-
- /**
- * @param messageSpy the message spy
- */
- public void setMessageSpy(MessageSpy<DataContainer> messageSpy) {
- this.messageSpy = messageSpy;
- }
- /**
- * @return the messageSpy
- */
- public MessageSpy<DataContainer> getMessageSpy() {
- return messageSpy;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.AsyncFunction;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.JdkFutureAdapters;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.Future;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.openflowjava.protocol.api.util.BinContent;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.sal.NotificationComposer;
-import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.GroupConvertor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.MeterConvertor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.PortConvertor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionConvertorData;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionDatapathIdConvertorData;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.match.MatchReactor;
-import org.opendaylight.openflowplugin.openflow.md.util.FlowCreatorUtil;
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowHashIdMapping;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.nodes.node.table.FlowHashIdMap;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.nodes.node.table.FlowHashIdMapKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowAdded;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowAddedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemovedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.Flow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupAdded;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupAddedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupRemovedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Group;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterAdded;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterAddedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterRemovedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.Meter;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.SetConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.SetConfigOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.SetConfigOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.GroupId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.SwitchConfigFlag;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestAggregateCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestFlowCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestGroupCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestGroupDescCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestGroupFeaturesCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestMeterCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestMeterConfigCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestMeterFeaturesCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestPortStatsCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestQueueCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestTableCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestTableFeaturesCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.aggregate._case.MultipartRequestAggregateBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.flow._case.MultipartRequestFlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.group._case.MultipartRequestGroupBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.meter._case.MultipartRequestMeterBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.meter.config._case.MultipartRequestMeterConfigBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.port.stats._case.MultipartRequestPortStatsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.queue._case.MultipartRequestQueueBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.table._case.MultipartRequestTableBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.table.features._case.MultipartRequestTableFeaturesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.table.features._case.multipart.request.table.features.TableFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutputBuilder;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- *
- */
-public abstract class OFRpcTaskFactory {
- protected static final Logger LOG = LoggerFactory.getLogger(OFRpcTaskFactory.class);
-
- private OFRpcTaskFactory() {
- // hiding implicit constructor
- }
-
- /**
- * @param taskContext task context
- * @param input flow object input
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return UpdateFlow task
- */
- public static OFRpcTask<AddFlowInput, RpcResult<UpdateFlowOutput>> createAddFlowTask(
- OFRpcTaskContext taskContext, AddFlowInput input,
- SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
-
- class OFRpcTaskImpl extends OFRpcTask<AddFlowInput, RpcResult<UpdateFlowOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
- private final VersionDatapathIdConvertorData data;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, AddFlowInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- data = new VersionDatapathIdConvertorData(getVersion());
- data.setDatapathId(getSession().getFeatures().getDatapathId());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdateFlowOutput>> call() {
- ListenableFuture<RpcResult<UpdateFlowOutput>> result = SettableFuture.create();
-
- // Convert the AddFlowInput to FlowModInput
- final java.util.Optional<List<FlowModInputBuilder>> ofFlowModInputs =
- convertorExecutor.convert(getInput(), data);
-
- final List<FlowModInputBuilder> flowModInputs = ofFlowModInputs.orElse(Collections.emptyList());
- LOG.debug("Number of flows to push to switch: {}", flowModInputs.size());
- result = chainFlowMods(flowModInputs, 0, getTaskContext(), getCookie());
- result = OFRpcTaskUtil.chainFutureBarrier(this, result);
- OFRpcTaskUtil.hookFutureNotification(this, result,
- getRpcNotificationProviderService(),
- createFlowAddedNotification(getInput()));
- return result;
- }
-
- @Override
- public Boolean isBarrier() {
- return getInput().isBarrier();
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
- /**
- * Recursive helper method for {@link OFRpcTaskFactory#createAddFlowTask(OFRpcTaskContext, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput, org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher, org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor)}
- * and {@link OFRpcTaskFactory#createUpdateFlowTask(OFRpcTaskContext, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput, org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher, org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction, org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor)} to chain results
- * of multiple flowmods.
- * The next flowmod gets executed if the earlier one is successful.
- * All the flowmods should have the same xid, in-order to cross-reference
- * the notification
- * @param taskContext task context
- * @param ofFlowModInputs list of flow mod as input
- * @param index starting index
- * @param cookie switch connection distinguisher
- * @return listenable future with update flow output
- *
- */
- protected static ListenableFuture<RpcResult<UpdateFlowOutput>> chainFlowMods(
- final List<FlowModInputBuilder> ofFlowModInputs, final int index,
- final OFRpcTaskContext taskContext, final SwitchConnectionDistinguisher cookie) {
-
- Future<RpcResult<UpdateFlowOutput>> resultFromOFLib =
- createResultForFlowMod(taskContext, ofFlowModInputs.get(index), cookie);
-
- ListenableFuture<RpcResult<UpdateFlowOutput>> result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- if (ofFlowModInputs.size() > index + 1) {
- // there are more flowmods to chain
- return Futures.transformAsync(result,
- new AsyncFunction<RpcResult<UpdateFlowOutput>, RpcResult<UpdateFlowOutput>>() {
- @Override
- public ListenableFuture<RpcResult<UpdateFlowOutput>> apply(RpcResult<UpdateFlowOutput> input) throws Exception {
- if (input.isSuccessful()) {
- return chainFlowMods(ofFlowModInputs, index + 1, taskContext, cookie);
- } else {
- LOG.warn("Flowmod failed. Any chained flowmods are ignored. xid:{}",
- ofFlowModInputs.get(index).getXid());
- return Futures.immediateFuture(input);
- }
- }
- }
- );
- } else {
- return result;
- }
- }
-
- private static Future<RpcResult<UpdateFlowOutput>> createResultForFlowMod(
- OFRpcTaskContext taskContext, FlowModInputBuilder flowModInput,
- SwitchConnectionDistinguisher cookie) {
- flowModInput.setXid(taskContext.getSession().getNextXid());
- return taskContext.getMessageService().flowMod(flowModInput.build(), cookie);
- }
-
-
- /**
- * @param input flow input
- * @return flow added notification
- */
- protected static NotificationComposer<FlowAdded> createFlowAddedNotification(
- final AddFlowInput input) {
- return new NotificationComposer<FlowAdded>() {
- @Override
- public FlowAdded compose(TransactionId tXid) {
- FlowAddedBuilder newFlow = new FlowAddedBuilder((Flow) input);
- newFlow.setTransactionId(tXid);
- newFlow.setFlowRef(input.getFlowRef());
- return newFlow.build();
- }
- };
- }
-
- /**
- * @param taskContext task context
- * @param input update flow input
- * @param cookie switch connection distinguisher cookie value
- * @param rwTx read write transaction
- * @param convertorExecutor
- * @return UpdateFlow task
- */
- public static OFRpcTask<UpdateFlowInput, RpcResult<UpdateFlowOutput>> createUpdateFlowTask(
- final OFRpcTaskContext taskContext, UpdateFlowInput input,
- SwitchConnectionDistinguisher cookie, final ReadWriteTransaction rwTx, ConvertorExecutor convertorExecutor) {
-
- class OFRpcTaskImpl extends OFRpcTask<UpdateFlowInput, RpcResult<UpdateFlowOutput>> {
- final ReadWriteTransaction rwTx;
- private final ConvertorExecutor convertorExecutor;
- private final VersionDatapathIdConvertorData data;
- InstanceIdentifier<Table> iiToTable = null;
- String flowId = null;
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- final UpdateFlowInput in, final ReadWriteTransaction rwTx, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, in);
- this.convertorExecutor = convertorExecutor;
- final FlowRef flowRef = in.getFlowRef();
- if (flowRef != null) {
- InstanceIdentifier<Flow> iiToFlow = (InstanceIdentifier<Flow>)(flowRef.getValue());
- iiToTable = flowRef.getValue().firstIdentifierOf(Table.class);
- FlowKey flowKey = iiToFlow.firstKeyOf(
- org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow.class, FlowKey.class);
- if (flowKey != null) {
- flowId = flowKey.getId().getValue();
- }
- }
- this.rwTx = rwTx;
- data = new VersionDatapathIdConvertorData(getVersion());
- data.setDatapathId(getSession().getFeatures().getDatapathId());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdateFlowOutput>> call() {
- ListenableFuture<RpcResult<UpdateFlowOutput>> result = null;
-
- UpdateFlowInput in = getInput();
- UpdatedFlow updated = in.getUpdatedFlow();
- OriginalFlow original = in.getOriginalFlow();
-
- List<FlowModInputBuilder> allFlowMods = new ArrayList<>();
- java.util.Optional<List<FlowModInputBuilder>> ofFlowModInputs;
-
- if (!FlowCreatorUtil.canModifyFlow(original, updated, getVersion())) {
- // We would need to remove original and add updated.
-
- //remove flow
- RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original);
- java.util.Optional<List<FlowModInputBuilder>> ofFlowRemoveInput =
- convertorExecutor.convert(removeflow.build(), data);
-
- if (ofFlowRemoveInput.isPresent()) {
- // remove flow should be the first
- allFlowMods.addAll(ofFlowRemoveInput.get());
- }
-
- AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated);
- ofFlowModInputs = convertorExecutor.convert(addFlowInputBuilder.build(), data);
- } else {
- ofFlowModInputs = convertorExecutor.convert(updated, data);
- }
-
- //deleting flow hash value from operational DS
- if (flowId != null) {
- CheckedFuture<Optional<FlowHashIdMapping>, ReadFailedException> hashDeletionFuture
- = readFlowHashIdMappingFromOperationalDS(rwTx);
- Futures.addCallback(hashDeletionFuture, new FutureCallback<Optional<FlowHashIdMapping>>() {
- @Override
- public void onSuccess(Optional<FlowHashIdMapping> optFlowHashIdMapping) {
- FlowHashIdMapKey flowHashIdMapKeyToDelete = null;
- if (optFlowHashIdMapping.isPresent()) {
- FlowHashIdMapping flowHashIdMapping = optFlowHashIdMapping.get();
- for (FlowHashIdMap flowHashId : flowHashIdMapping.getFlowHashIdMap()) {
- if (flowHashId.getFlowId().getValue().equals(flowId)) {
- flowHashIdMapKeyToDelete = flowHashId.getKey();
- break;
- }
- }
- }
- if (flowHashIdMapKeyToDelete != null) {
- final KeyedInstanceIdentifier<FlowHashIdMap, FlowHashIdMapKey> iiToFlowHashIdToDelete = iiToTable
- .augmentation(FlowHashIdMapping.class).child(FlowHashIdMap.class, flowHashIdMapKeyToDelete);
- final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.
- flow.inventory.rev130819.tables.table.Flow> flowRef = iiToTable.child(
- org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.
- Flow.class, new FlowKey(new FlowId(flowId)));
- //Clean-up the respective flow as well.
- rwTx.delete(LogicalDatastoreType.OPERATIONAL, flowRef);
- rwTx.delete(LogicalDatastoreType.OPERATIONAL, iiToFlowHashIdToDelete);
- rwTx.submit();
- }
- }
-
- @Override
- public void onFailure(Throwable t) {
- LOG.debug("Reading flow-hash-id map from operational DS wasn't successful");
- }
- });
-
- }
-
- if (ofFlowModInputs.isPresent()) {
- allFlowMods.addAll(ofFlowModInputs.get());
- }
-
- LOG.debug("Number of flows to push to switch: {}", allFlowMods.size());
- result = chainFlowMods(allFlowMods, 0, getTaskContext(), getCookie());
-
- result = OFRpcTaskUtil.chainFutureBarrier(this, result);
- OFRpcTaskUtil.hookFutureNotification(this, result,
- getRpcNotificationProviderService(),
- createFlowUpdatedNotification(in));
-
- return result;
- }
-
-
- CheckedFuture<Optional<FlowHashIdMapping>, ReadFailedException> readFlowHashIdMappingFromOperationalDS(final ReadWriteTransaction rwTx) {
- InstanceIdentifier<FlowHashIdMapping> iiToFlowHashIdMapping = iiToTable
- .augmentation(FlowHashIdMapping.class);
- return rwTx.read(LogicalDatastoreType.OPERATIONAL, iiToFlowHashIdMapping);
- }
-
- @Override
- public Boolean isBarrier() {
- return getInput().getUpdatedFlow().isBarrier();
- }
- }
- return new OFRpcTaskImpl(taskContext, cookie, input, rwTx, convertorExecutor);
- }
-
-
- /**
- * @param input update flow input
- * @return flow update notification
- */
- protected static NotificationComposer<FlowUpdated> createFlowUpdatedNotification(final UpdateFlowInput input) {
- return new NotificationComposer<FlowUpdated>() {
- @Override
- public FlowUpdated compose(TransactionId tXid) {
- FlowUpdatedBuilder updFlow = new FlowUpdatedBuilder(input.getUpdatedFlow());
- updFlow.setTransactionId(tXid);
- updFlow.setFlowRef(input.getFlowRef());
- return updFlow.build();
- }
- };
- }
-
- /**
- * @param taskContext taks context
- * @param input group update input
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return update group task
- */
- public static OFRpcTask<AddGroupInput, RpcResult<UpdateGroupOutput>> createAddGroupTask(
- final OFRpcTaskContext taskContext, AddGroupInput input,
- final SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
- class OFRpcTaskImpl extends OFRpcTask<AddGroupInput, RpcResult<UpdateGroupOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
- private final VersionDatapathIdConvertorData data;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, AddGroupInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- data = new VersionDatapathIdConvertorData(getVersion());
- data.setDatapathId(getSession().getFeatures().getDatapathId());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdateGroupOutput>> call() {
- ListenableFuture<RpcResult<UpdateGroupOutput>> result = SettableFuture.create();
-
- // Convert the AddGroupInput to GroupModInput
- final java.util.Optional<GroupModInputBuilder> ofGroupModInput = convertorExecutor.convert(getInput(), data);
- final GroupModInputBuilder groupModInputBuilder = ofGroupModInput
- .orElse(GroupConvertor.defaultResult(getVersion()))
- .setXid(getSession().getNextXid());
-
- Future<RpcResult<UpdateGroupOutput>> resultFromOFLib = getMessageService()
- .groupMod(groupModInputBuilder.build(), getCookie());
- result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
- result = OFRpcTaskUtil.chainFutureBarrier(this, result);
- OFRpcTaskUtil.hookFutureNotification(this, result,
- getRpcNotificationProviderService(), createGroupAddedNotification(getInput()));
-
- return result;
- }
-
- @Override
- public Boolean isBarrier() {
- return getInput().isBarrier();
- }
- };
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
-
- /**
- * @param input group add input
- * @return group added notification
- */
- protected static NotificationComposer<GroupAdded> createGroupAddedNotification(
- final AddGroupInput input) {
- return new NotificationComposer<GroupAdded>() {
- @Override
- public GroupAdded compose(TransactionId tXid) {
- GroupAddedBuilder groupMod = new GroupAddedBuilder((Group) input);
- groupMod.setTransactionId(tXid);
- groupMod.setGroupRef(input.getGroupRef());
- return groupMod.build();
- }
- };
- }
-
- /**
- * @param taskContext task context
- * @param input meter add input
- * @param cookie switch connection distinguisher
- * @param convertorExecutor
- * @return update meter task
- */
- public static OFRpcTask<AddMeterInput, RpcResult<UpdateMeterOutput>> createAddMeterTask(
- OFRpcTaskContext taskContext, AddMeterInput input,
- SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
- class OFRpcTaskImpl extends OFRpcTask<AddMeterInput, RpcResult<UpdateMeterOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
- private final VersionConvertorData data;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, AddMeterInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- data = new VersionConvertorData(getVersion());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdateMeterOutput>> call() {
- ListenableFuture<RpcResult<UpdateMeterOutput>> result = SettableFuture.create();
-
- // Convert the AddMeterInput to UpdateMeterOutput
- final java.util.Optional<MeterModInputBuilder> ofMeterModInput = convertorExecutor.convert(getInput(), data);
-
- final MeterModInputBuilder meterModInputBuilder = ofMeterModInput
- .orElse(MeterConvertor.defaultResult(getVersion()))
- .setXid(getSession().getNextXid());
-
- Future<RpcResult<UpdateMeterOutput>> resultFromOFLib = getMessageService()
- .meterMod(meterModInputBuilder.build(), getCookie());
- result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
- result = OFRpcTaskUtil.chainFutureBarrier(this, result);
- OFRpcTaskUtil.hookFutureNotification(this, result,
- getRpcNotificationProviderService(), createMeterAddedNotification(getInput()));
-
- return result;
- }
-
- @Override
- public Boolean isBarrier() {
- return getInput().isBarrier();
- }
- };
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
- /**
- * @param input add meter input
- * @return meter added notification composer
- */
- protected static NotificationComposer<MeterAdded> createMeterAddedNotification(
- final AddMeterInput input) {
- return new NotificationComposer<MeterAdded>() {
- @Override
- public MeterAdded compose(TransactionId tXid) {
- MeterAddedBuilder meterMod = new MeterAddedBuilder((Meter) input);
- meterMod.setTransactionId(tXid);
- meterMod.setMeterRef(input.getMeterRef());
- return meterMod.build();
- }
- };
- }
-
- /**
- * @param taskContext task context
- * @param input update group output
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return UpdateFlow task
- */
- public static OFRpcTask<UpdateGroupInput, RpcResult<UpdateGroupOutput>> createUpdateGroupTask(
- OFRpcTaskContext taskContext, UpdateGroupInput input,
- SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
- class OFRpcTaskImpl extends OFRpcTask<UpdateGroupInput, RpcResult<UpdateGroupOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
- private final VersionDatapathIdConvertorData data;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- UpdateGroupInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- data = new VersionDatapathIdConvertorData(getVersion());
- data.setDatapathId(getSession().getFeatures().getDatapathId());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdateGroupOutput>> call() {
- ListenableFuture<RpcResult<UpdateGroupOutput>> result = null;
-
- // Convert the UpdateGroupInput to GroupModInput
- final java.util.Optional<GroupModInputBuilder> ofGroupModInput =
- convertorExecutor.convert(getInput().getUpdatedGroup(), data);
-
- final GroupModInputBuilder groupModInputBuilder = ofGroupModInput
- .orElse(GroupConvertor.defaultResult(getVersion()))
- .setXid(getSession().getNextXid());
-
- Future<RpcResult<UpdateGroupOutput>> resultFromOFLib =
- getMessageService().groupMod(groupModInputBuilder.build(), getCookie());
- result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- result = OFRpcTaskUtil.chainFutureBarrier(this, result);
- OFRpcTaskUtil.hookFutureNotification(this, result,
- getRpcNotificationProviderService(), createGroupUpdatedNotification(getInput()));
-
- return result;
- }
-
- @Override
- public Boolean isBarrier() {
- return getInput().getUpdatedGroup().isBarrier();
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
- /**
- * @param input group update input
- * @return group updated notification composer
- */
- protected static NotificationComposer<GroupUpdated> createGroupUpdatedNotification(
- final UpdateGroupInput input) {
- return new NotificationComposer<GroupUpdated>() {
- @Override
- public GroupUpdated compose(TransactionId tXid) {
- GroupUpdatedBuilder groupMod = new GroupUpdatedBuilder(input.getUpdatedGroup());
- groupMod.setTransactionId(tXid);
- groupMod.setGroupRef(input.getGroupRef());
- return groupMod.build();
- }
- };
- }
-
- /**
- * @param taskContext task context
- * @param input update meter input
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return update meter task
- */
- public static OFRpcTask<UpdateMeterInput, RpcResult<UpdateMeterOutput>> createUpdateMeterTask(
- OFRpcTaskContext taskContext, UpdateMeterInput input,
- SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
- class OFRpcTaskImpl extends OFRpcTask<UpdateMeterInput, RpcResult<UpdateMeterOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
- private final VersionConvertorData data;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- UpdateMeterInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- data = new VersionConvertorData(getVersion());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdateMeterOutput>> call() {
- ListenableFuture<RpcResult<UpdateMeterOutput>> result = null;
-
- // Convert the UpdateMeterInput to MeterModInput
- final java.util.Optional<MeterModInputBuilder> ofMeterModInput = convertorExecutor.convert(getInput().getUpdatedMeter(), data);
-
- final MeterModInputBuilder meterModInputBuilder = ofMeterModInput
- .orElse(MeterConvertor.defaultResult(getVersion()))
- .setXid(getSession().getNextXid());
-
- Future<RpcResult<UpdateMeterOutput>> resultFromOFLib =
- getMessageService().meterMod(meterModInputBuilder.build(), getCookie());
- result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
- result = OFRpcTaskUtil.chainFutureBarrier(this, result);
- OFRpcTaskUtil.hookFutureNotification(this, result,
- getRpcNotificationProviderService(), createMeterUpdatedNotification(getInput()));
- return result;
- }
-
- @Override
- public Boolean isBarrier() {
- return getInput().getUpdatedMeter().isBarrier();
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
- /**
- * @param input meter update input
- * @return meter updated notification
- */
- protected static NotificationComposer<MeterUpdated> createMeterUpdatedNotification(
- final UpdateMeterInput input) {
- return new NotificationComposer<MeterUpdated>() {
- @Override
- public MeterUpdated compose(TransactionId tXid) {
- MeterUpdatedBuilder meterMod = new MeterUpdatedBuilder(input.getUpdatedMeter());
- meterMod.setTransactionId(tXid);
- meterMod.setMeterRef(input.getMeterRef());
- return meterMod.build();
- }
- };
- }
-
-
- /**
- * @param taskContext task context
- * @param input update flow input
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return task remove flow task
- */
- public static OFRpcTask<RemoveFlowInput, RpcResult<UpdateFlowOutput>> createRemoveFlowTask(
- OFRpcTaskContext taskContext, RemoveFlowInput input,
- SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
- class OFRpcTaskImpl extends OFRpcTask<RemoveFlowInput, RpcResult<UpdateFlowOutput>> {
-
- private final VersionDatapathIdConvertorData data;
- private final ConvertorExecutor convertorExecutor;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- RemoveFlowInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- data = new VersionDatapathIdConvertorData(getVersion());
- data.setDatapathId(getSession().getFeatures().getDatapathId());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdateFlowOutput>> call() {
- ListenableFuture<RpcResult<UpdateFlowOutput>> result = SettableFuture.create();
-
- // Convert the AddFlowInput to FlowModInput
- final java.util.Optional<List<FlowModInputBuilder>> ofFlowModInputs = convertorExecutor.convert(getInput(), data);
-
- result = chainFlowMods(ofFlowModInputs.orElse(Collections.emptyList()), 0, getTaskContext(), getCookie());
- result = OFRpcTaskUtil.chainFutureBarrier(this, result);
-
- OFRpcTaskUtil.hookFutureNotification(this, result,
- getRpcNotificationProviderService(),
- createFlowRemovedNotification(getInput()));
- return result;
- }
-
- @Override
- public Boolean isBarrier() {
- return getInput().isBarrier();
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
- /**
- * @param input remove flow input
- * @return flow removed notification
- */
- protected static NotificationComposer<FlowRemoved> createFlowRemovedNotification(
- final RemoveFlowInput input) {
- return new NotificationComposer<FlowRemoved>() {
- @Override
- public FlowRemoved compose(TransactionId tXid) {
- FlowRemovedBuilder removedFlow = new FlowRemovedBuilder((Flow) input);
- removedFlow.setTransactionId(tXid);
- removedFlow.setFlowRef(input.getFlowRef());
- return removedFlow.build();
- }
- };
- }
-
-
- /**
- * @param taskContext task context
- * @param input remove group input
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return task remove group task
- */
- public static OFRpcTask<RemoveGroupInput, RpcResult<UpdateGroupOutput>> createRemoveGroupTask(
- final OFRpcTaskContext taskContext, RemoveGroupInput input,
- final SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
- class OFRpcTaskImpl extends OFRpcTask<RemoveGroupInput, RpcResult<UpdateGroupOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
- private final VersionDatapathIdConvertorData data;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- RemoveGroupInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- data = new VersionDatapathIdConvertorData(getVersion());
- data.setDatapathId(getSession().getFeatures().getDatapathId());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdateGroupOutput>> call() {
- ListenableFuture<RpcResult<UpdateGroupOutput>> result = SettableFuture.create();
-
- // Convert the AddGroupInput to GroupModInput
- final java.util.Optional<GroupModInputBuilder> ofGroupModInput = convertorExecutor.convert(getInput(), data);
-
- final GroupModInputBuilder groupModInputBuilder = ofGroupModInput
- .orElse(GroupConvertor.defaultResult(getVersion()))
- .setXid(getSession().getNextXid());
-
- Future<RpcResult<UpdateGroupOutput>> resultFromOFLib = getMessageService()
- .groupMod(groupModInputBuilder.build(), getCookie());
- result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
- result = OFRpcTaskUtil.chainFutureBarrier(this, result);
- OFRpcTaskUtil.hookFutureNotification(this, result,
- getRpcNotificationProviderService(), createGroupRemovedNotification(getInput()));
-
- return result;
- }
-
- @Override
- public Boolean isBarrier() {
- return getInput().isBarrier();
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
- /**
- * @param input group remove input
- * @return group removed notification
- */
- protected static NotificationComposer<GroupRemoved> createGroupRemovedNotification(
- final RemoveGroupInput input) {
- return new NotificationComposer<GroupRemoved>() {
- @Override
- public GroupRemoved compose(TransactionId tXid) {
- GroupRemovedBuilder removedGroup = new GroupRemovedBuilder((Group) input);
- removedGroup.setTransactionId(tXid);
- removedGroup.setGroupRef(input.getGroupRef());
- return removedGroup.build();
- }
- };
- }
-
- /**
- * @param taskContext task context
- * @param input meter removed input
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return task meter remove task
- */
- public static OFRpcTask<RemoveMeterInput, RpcResult<UpdateMeterOutput>> createRemoveMeterTask(
- OFRpcTaskContext taskContext, RemoveMeterInput input,
- SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
-
- class OFRpcTaskImpl extends OFRpcTask<RemoveMeterInput, RpcResult<UpdateMeterOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
- private final VersionConvertorData data;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- RemoveMeterInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- data = new VersionConvertorData(getVersion());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdateMeterOutput>> call() {
- ListenableFuture<RpcResult<UpdateMeterOutput>> result = SettableFuture.create();
-
- // Convert the RemoveMeterInput to UpdateMeterOutput
- final java.util.Optional<MeterModInputBuilder> ofMeterModInput = convertorExecutor.convert(getInput(), data);
-
- final MeterModInputBuilder meterModInputBuilder = ofMeterModInput
- .orElse(MeterConvertor.defaultResult(getVersion()))
- .setXid(getSession().getNextXid());
-
- Future<RpcResult<UpdateMeterOutput>> resultFromOFLib = getMessageService()
- .meterMod(meterModInputBuilder.build(), getCookie());
- result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
- result = OFRpcTaskUtil.chainFutureBarrier(this, result);
- OFRpcTaskUtil.hookFutureNotification(this, result,
- getRpcNotificationProviderService(), createMeterRemovedNotification(getInput()));
-
- return result;
- }
-
- @Override
- public Boolean isBarrier() {
- return getInput().isBarrier();
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
-
- }
-
- /**
- * @param input remove meter input
- * @return meter removed notification composer
- */
- protected static NotificationComposer<MeterRemoved> createMeterRemovedNotification(
- final RemoveMeterInput input) {
- return new NotificationComposer<MeterRemoved>() {
- @Override
- public MeterRemoved compose(TransactionId tXid) {
- MeterRemovedBuilder meterRemoved = new MeterRemovedBuilder((Meter) input);
- meterRemoved.setTransactionId(tXid);
- meterRemoved.setMeterRef(input.getMeterRef());
- return meterRemoved.build();
- }
- };
- }
-
- /**
- * @param taskContext task context
- * @param input get all statistics input
- * @param cookie switch connection distinguisher cookie value
- * @return task get all group statistics task
- */
- public static OFRpcTask<GetAllGroupStatisticsInput, RpcResult<GetAllGroupStatisticsOutput>> createGetAllGroupStatisticsTask(
- final OFRpcTaskContext taskContext, GetAllGroupStatisticsInput input,
- SwitchConnectionDistinguisher cookie) {
-
- class OFRpcTaskImpl extends OFRpcTask<GetAllGroupStatisticsInput, RpcResult<GetAllGroupStatisticsOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetAllGroupStatisticsInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetAllGroupStatisticsOutput>> call() {
- final SettableFuture<RpcResult<GetAllGroupStatisticsOutput>> result = SettableFuture.create();
-
- if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
- RpcResult<GetAllGroupStatisticsOutput> rpcResult = RpcResultBuilder.success(
- new GetAllGroupStatisticsOutputBuilder().build()).build();
-
- return Futures.immediateFuture(rpcResult);
- } else {
-
- // Generate xid to associate it with the request
- final Long xid = taskContext.getSession().getNextXid();
-
- // Create multipart request body for fetch all the group stats
- MultipartRequestGroupCaseBuilder caseBuilder = new MultipartRequestGroupCaseBuilder();
- MultipartRequestGroupBuilder mprGroupBuild = new MultipartRequestGroupBuilder();
- mprGroupBuild.setGroupId(new GroupId(BinContent.intToUnsignedLong(
- org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731
- .Group.OFPGALL.getIntValue())));
- caseBuilder.setMultipartRequestGroup(mprGroupBuild.build());
-
- // Create multipart request header
- MultipartRequestInputBuilder mprInput = createMultipartHeader(MultipartType.OFPMPGROUP,
- taskContext, xid);
-
- // Set request body to main multipart request
- mprInput.setMultipartRequestBody(caseBuilder.build());
-
- // Send the request, no cookies associated, use any connection
-
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetAllGroupStatisticsOutput>(result) {
- @Override
- public GetAllGroupStatisticsOutput createResult() {
- GetAllGroupStatisticsOutputBuilder groupStatBuilder = new GetAllGroupStatisticsOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return groupStatBuilder.build();
- }
- });
-
- return result;
- }
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get group description input
- * @param cookie switch connection distinguisher cookie value
- * @return task get group description task
- */
- public static OFRpcTask<GetGroupDescriptionInput, RpcResult<GetGroupDescriptionOutput>> createGetGroupDescriptionTask(
- final OFRpcTaskContext taskContext, GetGroupDescriptionInput input,
- SwitchConnectionDistinguisher cookie) {
- class OFRpcTaskImpl extends OFRpcTask<GetGroupDescriptionInput, RpcResult<GetGroupDescriptionOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetGroupDescriptionInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetGroupDescriptionOutput>> call()
- throws Exception {
- final SettableFuture<RpcResult<GetGroupDescriptionOutput>> result = SettableFuture.create();
-
- if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
- RpcResult<GetGroupDescriptionOutput> rpcResult = RpcResultBuilder.success(
- new GetGroupDescriptionOutputBuilder().build()).build();
- return Futures.immediateFuture(rpcResult);
- } else {
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestGroupDescCaseBuilder mprGroupDescCaseBuild =
- new MultipartRequestGroupDescCaseBuilder();
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPGROUPDESC, taskContext, xid);
- mprInput.setMultipartRequestBody(mprGroupDescCaseBuild.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetGroupDescriptionOutput>(result) {
- @Override
- public GetGroupDescriptionOutput createResult() {
- GetGroupDescriptionOutputBuilder groupStatBuilder = new GetGroupDescriptionOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return groupStatBuilder.build();
- }
- });
- return result;
- }
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get group feature input
- * @param cookie switch connection distinguisher cookie value
- * @return task get group feature task
- */
- public static OFRpcTask<GetGroupFeaturesInput, RpcResult<GetGroupFeaturesOutput>> createGetGroupFeaturesTask(
- final OFRpcTaskContext taskContext, GetGroupFeaturesInput input,
- SwitchConnectionDistinguisher cookie) {
- class OFRpcTaskImpl extends OFRpcTask<GetGroupFeaturesInput, RpcResult<GetGroupFeaturesOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetGroupFeaturesInput input) {
- super(taskContext, cookie, input);
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public ListenableFuture<RpcResult<GetGroupFeaturesOutput>> call()
- throws Exception {
- final SettableFuture<RpcResult<GetGroupFeaturesOutput>> result = SettableFuture.create();
-
- if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
- RpcResult<GetGroupFeaturesOutput> rpcResult = RpcResultBuilder.success(
- new GetGroupFeaturesOutputBuilder().build()).build();
- return Futures.immediateFuture(rpcResult);
- } else {
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestGroupFeaturesCaseBuilder mprGroupFeaturesBuild =
- new MultipartRequestGroupFeaturesCaseBuilder();
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPGROUPFEATURES, taskContext, xid);
- mprInput.setMultipartRequestBody(mprGroupFeaturesBuild.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetGroupFeaturesOutput>(result) {
- @Override
- public GetGroupFeaturesOutput createResult() {
- GetGroupFeaturesOutputBuilder groupFeatureBuilder = new GetGroupFeaturesOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return groupFeatureBuilder.build();
- }
- });
- return result;
- }
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get group statistics input
- * @param cookie switch connection distinguisher cookie value
- * @return task get group statistics task
- */
- public static OFRpcTask<GetGroupStatisticsInput, RpcResult<GetGroupStatisticsOutput>> createGetGroupStatisticsTask(
- final OFRpcTaskContext taskContext, final GetGroupStatisticsInput input,
- SwitchConnectionDistinguisher cookie) {
-
- class OFRpcTaskImpl extends OFRpcTask<GetGroupStatisticsInput, RpcResult<GetGroupStatisticsOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetGroupStatisticsInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetGroupStatisticsOutput>> call()
- throws Exception {
- final SettableFuture<RpcResult<GetGroupStatisticsOutput>> result = SettableFuture.create();
-
- if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
- RpcResult<GetGroupStatisticsOutput> rpcResult = RpcResultBuilder.success(
- new GetGroupStatisticsOutputBuilder().build()).build();
- return Futures.immediateFuture(rpcResult);
- } else {
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestGroupCaseBuilder caseBuilder = new MultipartRequestGroupCaseBuilder();
- MultipartRequestGroupBuilder mprGroupBuild = new MultipartRequestGroupBuilder();
- mprGroupBuild.setGroupId(new GroupId(input.getGroupId().getValue()));
- caseBuilder.setMultipartRequestGroup(mprGroupBuild.build());
-
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPGROUP, taskContext, xid);
- mprInput.setMultipartRequestBody(caseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetGroupStatisticsOutput>(result) {
- @Override
- public GetGroupStatisticsOutput createResult() {
- GetGroupStatisticsOutputBuilder groupStatisticsBuilder =
- new GetGroupStatisticsOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return groupStatisticsBuilder.build();
- }
- });
- return result;
- }
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get meter config statistics input
- * @param cookie switch connection distinguisher cookie value
- * @return task get all mtere config statistics task
- */
- public static OFRpcTask<GetAllMeterConfigStatisticsInput, RpcResult<GetAllMeterConfigStatisticsOutput>> createGetAllMeterConfigStatisticsTask(
- final OFRpcTaskContext taskContext, final GetAllMeterConfigStatisticsInput input,
- SwitchConnectionDistinguisher cookie) {
- class OFRpcTaskImpl extends OFRpcTask<GetAllMeterConfigStatisticsInput, RpcResult<GetAllMeterConfigStatisticsOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetAllMeterConfigStatisticsInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetAllMeterConfigStatisticsOutput>> call()
- throws Exception {
- final SettableFuture<RpcResult<GetAllMeterConfigStatisticsOutput>> result = SettableFuture.create();
-
- if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
- RpcResult<GetAllMeterConfigStatisticsOutput> rpcResult = RpcResultBuilder.success(
- new GetAllMeterConfigStatisticsOutputBuilder().build()).build();
- return Futures.immediateFuture(rpcResult);
- } else {
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestMeterConfigCaseBuilder caseBuilder =
- new MultipartRequestMeterConfigCaseBuilder();
- MultipartRequestMeterConfigBuilder mprMeterConfigBuild =
- new MultipartRequestMeterConfigBuilder();
- mprMeterConfigBuild.setMeterId(new MeterId(BinContent.intToUnsignedLong(
- org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common
- .types.rev130731.Meter.OFPMALL.getIntValue())));
- caseBuilder.setMultipartRequestMeterConfig(mprMeterConfigBuild.build());
-
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPMETERCONFIG, taskContext, xid);
- mprInput.setMultipartRequestBody(caseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetAllMeterConfigStatisticsOutput>(result) {
- @Override
- public GetAllMeterConfigStatisticsOutput createResult() {
- GetAllMeterConfigStatisticsOutputBuilder allMeterConfStatBuilder =
- new GetAllMeterConfigStatisticsOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return allMeterConfStatBuilder.build();
- }
- });
- return result;
- }
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get all meter statistics input
- * @param cookie switch connection distinguisher cookie value
- * @return task get all meter statistics task
- */
- public static OFRpcTask<GetAllMeterStatisticsInput, RpcResult<GetAllMeterStatisticsOutput>> createGetAllMeterStatisticsTask(
- final OFRpcTaskContext taskContext, final GetAllMeterStatisticsInput input,
- SwitchConnectionDistinguisher cookie) {
- class OFRpcTaskImpl extends OFRpcTask<GetAllMeterStatisticsInput, RpcResult<GetAllMeterStatisticsOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetAllMeterStatisticsInput input) {
- super(taskContext, cookie, input);
- // TODO Auto-generated constructor stub
- }
-
- @Override
- public ListenableFuture<RpcResult<GetAllMeterStatisticsOutput>> call()
- throws Exception {
- final SettableFuture<RpcResult<GetAllMeterStatisticsOutput>> result = SettableFuture.create();
-
- if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
- RpcResult<GetAllMeterStatisticsOutput> rpcResult = RpcResultBuilder.success(
- new GetAllMeterStatisticsOutputBuilder().build()).build();
- return Futures.immediateFuture(rpcResult);
- } else {
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestMeterCaseBuilder caseBuilder =
- new MultipartRequestMeterCaseBuilder();
- MultipartRequestMeterBuilder mprMeterBuild =
- new MultipartRequestMeterBuilder();
- mprMeterBuild.setMeterId(new MeterId(BinContent.intToUnsignedLong(
- org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common
- .types.rev130731.Meter.OFPMALL.getIntValue())));
- caseBuilder.setMultipartRequestMeter(mprMeterBuild.build());
-
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPMETER, taskContext, xid);
- mprInput.setMultipartRequestBody(caseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetAllMeterStatisticsOutput>(result) {
- @Override
- public GetAllMeterStatisticsOutput createResult() {
- GetAllMeterStatisticsOutputBuilder allMeterStatBuilder =
- new GetAllMeterStatisticsOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return allMeterStatBuilder.build();
- }
- });
- return result;
- }
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get meter features input
- * @param cookie switch connection distinguisher cookie value
- * @return task get meter feature task
- */
- public static OFRpcTask<GetMeterFeaturesInput, RpcResult<GetMeterFeaturesOutput>> createGetMeterFeaturesTask(
- final OFRpcTaskContext taskContext, final GetMeterFeaturesInput input,
- SwitchConnectionDistinguisher cookie) {
-
- class OFRpcTaskImpl extends OFRpcTask<GetMeterFeaturesInput, RpcResult<GetMeterFeaturesOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetMeterFeaturesInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetMeterFeaturesOutput>> call()
- throws Exception {
- final SettableFuture<RpcResult<GetMeterFeaturesOutput>> result = SettableFuture.create();
-
- if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
- RpcResult<GetMeterFeaturesOutput> rpcResult = RpcResultBuilder.success(
- new GetMeterFeaturesOutputBuilder().build()).build();
- return Futures.immediateFuture(rpcResult);
- } else {
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestMeterFeaturesCaseBuilder mprMeterFeaturesBuild =
- new MultipartRequestMeterFeaturesCaseBuilder();
-
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPMETERFEATURES, taskContext, xid);
- mprInput.setMultipartRequestBody(mprMeterFeaturesBuild.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetMeterFeaturesOutput>(result) {
- @Override
- public GetMeterFeaturesOutput createResult() {
- GetMeterFeaturesOutputBuilder meterFeaturesBuilder =
- new GetMeterFeaturesOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return meterFeaturesBuilder.build();
- }
- });
- return result;
- }
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get meter statistics input
- * @param cookie switch connection distinguisher cookie value
- * @return task get meter statistics task
- */
- public static OFRpcTask<GetMeterStatisticsInput, RpcResult<GetMeterStatisticsOutput>> createGetMeterStatisticsTask(
- final OFRpcTaskContext taskContext, final GetMeterStatisticsInput input,
- SwitchConnectionDistinguisher cookie) {
-
- class OFRpcTaskImpl extends OFRpcTask<GetMeterStatisticsInput, RpcResult<GetMeterStatisticsOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetMeterStatisticsInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetMeterStatisticsOutput>> call()
- throws Exception {
- final SettableFuture<RpcResult<GetMeterStatisticsOutput>> result = SettableFuture.create();
-
- if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
- RpcResult<GetMeterStatisticsOutput> rpcResult = RpcResultBuilder.success(
- new GetMeterStatisticsOutputBuilder().build()).build();
- return Futures.immediateFuture(rpcResult);
- } else {
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestMeterCaseBuilder caseBuilder =
- new MultipartRequestMeterCaseBuilder();
- MultipartRequestMeterBuilder mprMeterBuild =
- new MultipartRequestMeterBuilder();
- mprMeterBuild.setMeterId(new MeterId(input.getMeterId().getValue()));
- caseBuilder.setMultipartRequestMeter(mprMeterBuild.build());
-
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPMETER, taskContext, xid);
- mprInput.setMultipartRequestBody(caseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetMeterStatisticsOutput>(result) {
- @Override
- public GetMeterStatisticsOutput createResult() {
- GetMeterStatisticsOutputBuilder meterStatBuilder =
- new GetMeterStatisticsOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return meterStatBuilder.build();
- }
- });
- return result;
- }
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get all node connector statistics input
- * @param cookie switch connection distinguisher cookie value
- * @return task get all node connector statistics task
- */
- public static OFRpcTask<GetAllNodeConnectorsStatisticsInput, RpcResult<GetAllNodeConnectorsStatisticsOutput>>
- createGetAllNodeConnectorsStatisticsTask(
- final OFRpcTaskContext taskContext, final GetAllNodeConnectorsStatisticsInput input,
- SwitchConnectionDistinguisher cookie) {
- class OFRpcTaskImpl extends OFRpcTask<GetAllNodeConnectorsStatisticsInput, RpcResult<GetAllNodeConnectorsStatisticsOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetAllNodeConnectorsStatisticsInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetAllNodeConnectorsStatisticsOutput>> call()
- throws Exception {
- final SettableFuture<RpcResult<GetAllNodeConnectorsStatisticsOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestPortStatsCaseBuilder caseBuilder =
- new MultipartRequestPortStatsCaseBuilder();
- MultipartRequestPortStatsBuilder mprPortStatsBuilder =
- new MultipartRequestPortStatsBuilder();
- // Select all ports
- mprPortStatsBuilder.setPortNo(OFConstants.OFPP_ANY);
- caseBuilder.setMultipartRequestPortStats(mprPortStatsBuilder.build());
-
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPPORTSTATS, taskContext, xid);
- mprInput.setMultipartRequestBody(caseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetAllNodeConnectorsStatisticsOutput>(result) {
- @Override
- public GetAllNodeConnectorsStatisticsOutput createResult() {
- GetAllNodeConnectorsStatisticsOutputBuilder allNodeConnectorStatBuilder =
- new GetAllNodeConnectorsStatisticsOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return allNodeConnectorStatBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get node connector statistics input
- * @param cookie switch connection distinguisher cookie value
- * @return task get node connector statistics task
- */
- public static OFRpcTask<GetNodeConnectorStatisticsInput, RpcResult<GetNodeConnectorStatisticsOutput>>
- createGetNodeConnectorStatisticsTask(
- final OFRpcTaskContext taskContext, final GetNodeConnectorStatisticsInput input,
- SwitchConnectionDistinguisher cookie) {
- class OFRpcTaskImpl extends OFRpcTask<GetNodeConnectorStatisticsInput, RpcResult<GetNodeConnectorStatisticsOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetNodeConnectorStatisticsInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetNodeConnectorStatisticsOutput>> call()
- throws Exception {
- final SettableFuture<RpcResult<GetNodeConnectorStatisticsOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestPortStatsCaseBuilder caseBuilder =
- new MultipartRequestPortStatsCaseBuilder();
- MultipartRequestPortStatsBuilder mprPortStatsBuilder =
- new MultipartRequestPortStatsBuilder();
- // Set specific port
- mprPortStatsBuilder
- .setPortNo(InventoryDataServiceUtil.portNumberfromNodeConnectorId(
- OpenflowVersion.get(taskContext.getSession().getFeatures().getVersion()),
- input.getNodeConnectorId()));
- caseBuilder.setMultipartRequestPortStats(mprPortStatsBuilder.build());
-
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPPORTSTATS, taskContext, xid);
- mprInput.setMultipartRequestBody(caseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetNodeConnectorStatisticsOutput>(result) {
- @Override
- public GetNodeConnectorStatisticsOutput createResult() {
- GetNodeConnectorStatisticsOutputBuilder allNodeConnectorStatBuilder =
- new GetNodeConnectorStatisticsOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return allNodeConnectorStatBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get all flow statistics from flow table
- * @param cookie switch connection distinguisher cookie value
- * @return task get all flow statistics from flow table task
- */
- public static OFRpcTask<GetAllFlowStatisticsFromFlowTableInput, RpcResult<GetAllFlowStatisticsFromFlowTableOutput>>
- createGetAllFlowStatisticsFromFlowTableTask(
- final OFRpcTaskContext taskContext,
- final GetAllFlowStatisticsFromFlowTableInput input,
- SwitchConnectionDistinguisher cookie) {
- class OFRpcTaskImpl extends OFRpcTask<GetAllFlowStatisticsFromFlowTableInput, RpcResult<GetAllFlowStatisticsFromFlowTableOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetAllFlowStatisticsFromFlowTableInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetAllFlowStatisticsFromFlowTableOutput>> call() throws Exception {
- final SettableFuture<RpcResult<GetAllFlowStatisticsFromFlowTableOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestFlowBuilder mprFlowRequestBuilder = new MultipartRequestFlowBuilder();
- mprFlowRequestBuilder.setTableId(input.getTableId().getValue());
- mprFlowRequestBuilder.setOutPort(OFConstants.OFPP_ANY);
- mprFlowRequestBuilder.setOutGroup(OFConstants.OFPG_ANY);
- mprFlowRequestBuilder.setCookie(OFConstants.DEFAULT_COOKIE);
- mprFlowRequestBuilder.setCookieMask(OFConstants.DEFAULT_COOKIE_MASK);
- FlowCreatorUtil.setWildcardedFlowMatch(taskContext.getSession()
- .getPrimaryConductor().getVersion(), mprFlowRequestBuilder);
-
- MultipartRequestFlowCaseBuilder multipartRequestFlowCaseBuilder = new MultipartRequestFlowCaseBuilder();
- multipartRequestFlowCaseBuilder.setMultipartRequestFlow(mprFlowRequestBuilder.build());
-
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPFLOW, taskContext, xid);
- mprInput.setMultipartRequestBody(multipartRequestFlowCaseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetAllFlowStatisticsFromFlowTableOutput>(result) {
- @Override
- public GetAllFlowStatisticsFromFlowTableOutput createResult() {
- GetAllFlowStatisticsFromFlowTableOutputBuilder allFlowStatsFromFlowTableBuilder =
- new GetAllFlowStatisticsFromFlowTableOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return allFlowStatsFromFlowTableBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get all flow statistics from all flow table
- * @param cookie switch connection distinguisher cookie value
- * @return task get all flow statistics from all flow table task
- */
- public static OFRpcTask<GetAllFlowsStatisticsFromAllFlowTablesInput, RpcResult<GetAllFlowsStatisticsFromAllFlowTablesOutput>>
- createGetAllFlowsStatisticsFromAllFlowTablesTask(
- final OFRpcTaskContext taskContext,
- final GetAllFlowsStatisticsFromAllFlowTablesInput input,
- SwitchConnectionDistinguisher cookie) {
- class OFRpcTaskImpl extends OFRpcTask<GetAllFlowsStatisticsFromAllFlowTablesInput,
- RpcResult<GetAllFlowsStatisticsFromAllFlowTablesOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetAllFlowsStatisticsFromAllFlowTablesInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetAllFlowsStatisticsFromAllFlowTablesOutput>> call() throws Exception {
- final SettableFuture<RpcResult<GetAllFlowsStatisticsFromAllFlowTablesOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- // Create multipart request body for fetch all the group stats
- MultipartRequestFlowCaseBuilder multipartRequestFlowCaseBuilder =
- new MultipartRequestFlowCaseBuilder();
- MultipartRequestFlowBuilder mprFlowRequestBuilder =
- new MultipartRequestFlowBuilder();
- mprFlowRequestBuilder.setTableId(OFConstants.OFPTT_ALL);
- mprFlowRequestBuilder.setOutPort(OFConstants.OFPP_ANY);
- mprFlowRequestBuilder.setOutGroup(OFConstants.OFPG_ANY);
- mprFlowRequestBuilder.setCookie(OFConstants.DEFAULT_COOKIE);
- mprFlowRequestBuilder.setCookieMask(OFConstants.DEFAULT_COOKIE_MASK);
- FlowCreatorUtil.setWildcardedFlowMatch(taskContext.getSession()
- .getPrimaryConductor().getVersion(), mprFlowRequestBuilder);
-
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPFLOW, taskContext, xid);
- multipartRequestFlowCaseBuilder.setMultipartRequestFlow(mprFlowRequestBuilder.build());
- mprInput.setMultipartRequestBody(multipartRequestFlowCaseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetAllFlowsStatisticsFromAllFlowTablesOutput>(result) {
- @Override
- public GetAllFlowsStatisticsFromAllFlowTablesOutput createResult() {
- GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder allFlowStatsFromAllFlowTableBuilder =
- new GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return allFlowStatsFromAllFlowTableBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input get flow statistics from flow table
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return task get flow statistics from flow table task
- */
- public static OFRpcTask<GetFlowStatisticsFromFlowTableInput, RpcResult<GetFlowStatisticsFromFlowTableOutput>>
- createGetFlowStatisticsFromFlowTableTask(
- final OFRpcTaskContext taskContext,
- final GetFlowStatisticsFromFlowTableInput input, SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
-
- class OFRpcTaskImpl extends OFRpcTask<GetFlowStatisticsFromFlowTableInput, RpcResult<GetFlowStatisticsFromFlowTableOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetFlowStatisticsFromFlowTableInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- }
-
- @Override
- public ListenableFuture<RpcResult<GetFlowStatisticsFromFlowTableOutput>> call() throws Exception {
- final SettableFuture<RpcResult<GetFlowStatisticsFromFlowTableOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- // Create multipart request body for fetch all the group stats
- MultipartRequestFlowCaseBuilder multipartRequestFlowCaseBuilder = new MultipartRequestFlowCaseBuilder();
- MultipartRequestFlowBuilder mprFlowRequestBuilder = new MultipartRequestFlowBuilder();
- mprFlowRequestBuilder.setTableId(input.getTableId());
-
- if (input.getOutPort() != null) {
- mprFlowRequestBuilder.setOutPort(input.getOutPort().longValue());
- } else {
- mprFlowRequestBuilder.setOutPort(OFConstants.OFPP_ANY);
- }
-
- if (input.getOutGroup() != null) {
- mprFlowRequestBuilder.setOutGroup(input.getOutGroup());
- } else {
- mprFlowRequestBuilder.setOutGroup(OFConstants.OFPG_ANY);
- }
-
- if (input.getCookie() != null) {
- mprFlowRequestBuilder.setCookie(input.getCookie().getValue());
- } else {
- mprFlowRequestBuilder.setCookie(OFConstants.DEFAULT_COOKIE);
- }
-
- if (input.getCookieMask() != null) {
- mprFlowRequestBuilder.setCookieMask(input.getCookieMask().getValue());
- } else {
- mprFlowRequestBuilder.setCookieMask(OFConstants.DEFAULT_COOKIE_MASK);
- }
-
- // convert and inject match
- MatchReactor.getInstance().convert(input.getMatch(), taskContext.getSession()
- .getPrimaryConductor().getVersion(), mprFlowRequestBuilder, convertorExecutor);
-
- // Set request body to main multipart request
- multipartRequestFlowCaseBuilder.setMultipartRequestFlow(mprFlowRequestBuilder.build());
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPFLOW, taskContext, xid);
- mprInput.setMultipartRequestBody(multipartRequestFlowCaseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetFlowStatisticsFromFlowTableOutput>(result) {
- @Override
- public GetFlowStatisticsFromFlowTableOutput createResult() {
- GetFlowStatisticsFromFlowTableOutputBuilder flowStatsFromFlowTableBuilder =
- new GetFlowStatisticsFromFlowTableOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return flowStatsFromFlowTableBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
- /**
- * @param taskContext task context
- * @param input get aggregate flow statistics from flow table for all flow input
- * @param cookie switch connection distinguisher cookie value
- * @return task get aggregate flow stats from flow table for all flow task
- */
- public static OFRpcTask<GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput, RpcResult<GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput>>
- createGetAggregateFlowStatisticsFromFlowTableForAllFlowsTask(
- final OFRpcTaskContext taskContext,
- final GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput input, SwitchConnectionDistinguisher cookie) {
- class OFRpcTaskImpl extends OFRpcTask<GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput, RpcResult<GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput>> call() throws Exception {
- final SettableFuture<RpcResult<GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- // Create multipart request body for fetch all the group stats
- MultipartRequestAggregateCaseBuilder multipartRequestAggregateCaseBuilder = new MultipartRequestAggregateCaseBuilder();
- MultipartRequestAggregateBuilder mprAggregateRequestBuilder = new MultipartRequestAggregateBuilder();
- mprAggregateRequestBuilder.setTableId(input.getTableId().getValue());
- mprAggregateRequestBuilder.setOutPort(OFConstants.OFPP_ANY);
- mprAggregateRequestBuilder.setOutGroup(OFConstants.OFPG_ANY);
- mprAggregateRequestBuilder.setCookie(OFConstants.DEFAULT_COOKIE);
- mprAggregateRequestBuilder.setCookieMask(OFConstants.DEFAULT_COOKIE_MASK);
-
- FlowCreatorUtil.setWildcardedFlowMatch(taskContext.getSession()
- .getPrimaryConductor().getVersion(), mprAggregateRequestBuilder);
-
- // Set request body to main multipart request
- multipartRequestAggregateCaseBuilder.setMultipartRequestAggregate(mprAggregateRequestBuilder.build());
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPAGGREGATE, taskContext, xid);
- mprInput.setMultipartRequestBody(multipartRequestAggregateCaseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput>(result) {
- @Override
- public GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput createResult() {
- GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder flowStatsFromFlowTableBuilder =
- new GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return flowStatsFromFlowTableBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input aggregate flow statistics input
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return task task to fetch the statistics
- */
- public static OFRpcTask<GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput, RpcResult<GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput>>
- createGetAggregateFlowStatisticsFromFlowTableForGivenMatchTask(
- final OFRpcTaskContext taskContext,
- final GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput input, SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
- class OFRpcTaskImpl extends OFRpcTask<GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput, RpcResult<GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- }
-
- @Override
- public ListenableFuture<RpcResult<GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput>> call() throws Exception {
- final SettableFuture<RpcResult<GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestAggregateCaseBuilder multipartRequestAggregateCaseBuilder = new MultipartRequestAggregateCaseBuilder();
- MultipartRequestAggregateBuilder mprAggregateRequestBuilder = new MultipartRequestAggregateBuilder();
- mprAggregateRequestBuilder.setTableId(input.getTableId());
- mprAggregateRequestBuilder.setOutPort(input.getOutPort().longValue());
- // TODO: repeating code
- if (taskContext.getSession().getPrimaryConductor().getVersion() ==
- OFConstants.OFP_VERSION_1_3) {
- mprAggregateRequestBuilder.setCookie(input.getCookie().getValue());
- mprAggregateRequestBuilder.setCookieMask(input.getCookieMask().getValue());
- mprAggregateRequestBuilder.setOutGroup(input.getOutGroup());
- } else {
- mprAggregateRequestBuilder.setOutGroup(OFConstants.OFPG_ANY);
- mprAggregateRequestBuilder.setCookie(OFConstants.DEFAULT_COOKIE);
- mprAggregateRequestBuilder.setCookieMask(OFConstants.DEFAULT_COOKIE_MASK);
- }
-
- MatchReactor.getInstance().convert(input.getMatch(), taskContext.getSession()
- .getPrimaryConductor().getVersion(), mprAggregateRequestBuilder, convertorExecutor);
-
- FlowCreatorUtil.setWildcardedFlowMatch(taskContext.getSession()
- .getPrimaryConductor().getVersion(), mprAggregateRequestBuilder);
-
- // Set request body to main multipart request
- multipartRequestAggregateCaseBuilder.setMultipartRequestAggregate(mprAggregateRequestBuilder.build());
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPAGGREGATE, taskContext, xid);
- mprInput.setMultipartRequestBody(multipartRequestAggregateCaseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput>(result) {
- @Override
- public GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput createResult() {
- GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder aggregFlowStatsFromFlowTableBuilder =
- new GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return aggregFlowStatsFromFlowTableBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
- /**
- * @param taskContext task context
- * @param input flow table statistics input
- * @param cookie switch connection distinguisher cookie value
- * @return task task to fetch table statistics
- */
- public static OFRpcTask<GetFlowTablesStatisticsInput, RpcResult<GetFlowTablesStatisticsOutput>> createGetFlowTablesStatisticsTask(
- final OFRpcTaskContext taskContext, final GetFlowTablesStatisticsInput input, SwitchConnectionDistinguisher cookie) {
-
- class OFRpcTaskImpl extends OFRpcTask<GetFlowTablesStatisticsInput, RpcResult<GetFlowTablesStatisticsOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetFlowTablesStatisticsInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetFlowTablesStatisticsOutput>> call() throws Exception {
- final SettableFuture<RpcResult<GetFlowTablesStatisticsOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- // Create multipart request body for fetch all the group stats
- MultipartRequestTableCaseBuilder multipartRequestTableCaseBuilder = new MultipartRequestTableCaseBuilder();
- MultipartRequestTableBuilder multipartRequestTableBuilder = new MultipartRequestTableBuilder();
- multipartRequestTableBuilder.setEmpty(true);
- multipartRequestTableCaseBuilder.setMultipartRequestTable(multipartRequestTableBuilder.build());
-
- // Set request body to main multipart request
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPTABLE, taskContext, xid);
- mprInput.setMultipartRequestBody(multipartRequestTableCaseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetFlowTablesStatisticsOutput>(result) {
- @Override
- public GetFlowTablesStatisticsOutput createResult() {
- GetFlowTablesStatisticsOutputBuilder flowTableStatsBuilder =
- new GetFlowTablesStatisticsOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return flowTableStatsBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input queue statistics input
- * @param cookie switch connection distinguisher cookie value
- * @return task task to fetch all queue statistics
- */
- public static OFRpcTask<GetAllQueuesStatisticsFromAllPortsInput, RpcResult<GetAllQueuesStatisticsFromAllPortsOutput>> createGetAllQueuesStatisticsFromAllPortsTask(
- final OFRpcTaskContext taskContext, final GetAllQueuesStatisticsFromAllPortsInput input, SwitchConnectionDistinguisher cookie) {
-
- class OFRpcTaskImpl extends OFRpcTask<GetAllQueuesStatisticsFromAllPortsInput, RpcResult<GetAllQueuesStatisticsFromAllPortsOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetAllQueuesStatisticsFromAllPortsInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetAllQueuesStatisticsFromAllPortsOutput>> call() throws Exception {
- final SettableFuture<RpcResult<GetAllQueuesStatisticsFromAllPortsOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestQueueCaseBuilder caseBuilder = new MultipartRequestQueueCaseBuilder();
- MultipartRequestQueueBuilder mprQueueBuilder = new MultipartRequestQueueBuilder();
- // Select all ports
- mprQueueBuilder.setPortNo(OFConstants.OFPP_ANY);
- // Select all the queues
- mprQueueBuilder.setQueueId(OFConstants.OFPQ_ALL);
- caseBuilder.setMultipartRequestQueue(mprQueueBuilder.build());
-
- // Set request body to main multipart request
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPQUEUE, taskContext, xid);
- mprInput.setMultipartRequestBody(caseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetAllQueuesStatisticsFromAllPortsOutput>(result) {
- @Override
- public GetAllQueuesStatisticsFromAllPortsOutput createResult() {
- GetAllQueuesStatisticsFromAllPortsOutputBuilder allQueueStatsBuilder =
- new GetAllQueuesStatisticsFromAllPortsOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return allQueueStatsBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input queue statist from specific port input
- * @param cookie switch connection distinguisher cookie value
- * @return task task to get queue statistics from specific port
- */
- public static OFRpcTask<GetAllQueuesStatisticsFromGivenPortInput, RpcResult<GetAllQueuesStatisticsFromGivenPortOutput>> createGetAllQueuesStatisticsFromGivenPortTask(
- final OFRpcTaskContext taskContext, final GetAllQueuesStatisticsFromGivenPortInput input, SwitchConnectionDistinguisher cookie) {
-
- class OFRpcTaskImpl extends OFRpcTask<GetAllQueuesStatisticsFromGivenPortInput, RpcResult<GetAllQueuesStatisticsFromGivenPortOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetAllQueuesStatisticsFromGivenPortInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetAllQueuesStatisticsFromGivenPortOutput>> call() throws Exception {
- final SettableFuture<RpcResult<GetAllQueuesStatisticsFromGivenPortOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestQueueCaseBuilder caseBuilder = new MultipartRequestQueueCaseBuilder();
- MultipartRequestQueueBuilder mprQueueBuilder = new MultipartRequestQueueBuilder();
- // Select all queues
- mprQueueBuilder.setQueueId(OFConstants.OFPQ_ALL);
- // Select specific port
- mprQueueBuilder.setPortNo(InventoryDataServiceUtil.portNumberfromNodeConnectorId(
- OpenflowVersion.get(taskContext.getSession().getFeatures().getVersion()),
- input.getNodeConnectorId()));
- caseBuilder.setMultipartRequestQueue(mprQueueBuilder.build());
-
- // Set request body to main multipart request
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPQUEUE, taskContext, xid);
- mprInput.setMultipartRequestBody(caseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetAllQueuesStatisticsFromGivenPortOutput>(result) {
- @Override
- public GetAllQueuesStatisticsFromGivenPortOutput createResult() {
- GetAllQueuesStatisticsFromGivenPortOutputBuilder allQueueStatsBuilder =
- new GetAllQueuesStatisticsFromGivenPortOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return allQueueStatsBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- /**
- * @param taskContext task context
- * @param input queue statistics from given port
- * @param cookie switch connection distinguisher cookie value
- * @return task task to get queue statistics from given port
- */
- public static OFRpcTask<GetQueueStatisticsFromGivenPortInput, RpcResult<GetQueueStatisticsFromGivenPortOutput>> createGetQueueStatisticsFromGivenPortTask(
- final OFRpcTaskContext taskContext, final GetQueueStatisticsFromGivenPortInput input, SwitchConnectionDistinguisher cookie) {
-
- class OFRpcTaskImpl extends OFRpcTask<GetQueueStatisticsFromGivenPortInput, RpcResult<GetQueueStatisticsFromGivenPortOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- GetQueueStatisticsFromGivenPortInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<GetQueueStatisticsFromGivenPortOutput>> call() throws Exception {
- final SettableFuture<RpcResult<GetQueueStatisticsFromGivenPortOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestQueueCaseBuilder caseBuilder = new MultipartRequestQueueCaseBuilder();
- MultipartRequestQueueBuilder mprQueueBuilder = new MultipartRequestQueueBuilder();
- // Select specific queue
- mprQueueBuilder.setQueueId(input.getQueueId().getValue());
- // Select specific port
- mprQueueBuilder.setPortNo(InventoryDataServiceUtil.portNumberfromNodeConnectorId(
- OpenflowVersion.get(taskContext.getSession().getFeatures().getVersion()),
- input.getNodeConnectorId()));
- caseBuilder.setMultipartRequestQueue(mprQueueBuilder.build());
-
- // Set request body to main multipart request
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPQUEUE, taskContext, xid);
- mprInput.setMultipartRequestBody(caseBuilder.build());
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<GetQueueStatisticsFromGivenPortOutput>(result) {
- @Override
- public GetQueueStatisticsFromGivenPortOutput createResult() {
- GetQueueStatisticsFromGivenPortOutputBuilder queueStatsFromPortBuilder =
- new GetQueueStatisticsFromGivenPortOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return queueStatsFromPortBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-
- static MultipartRequestInputBuilder createMultipartHeader(MultipartType multipart,
- OFRpcTaskContext taskContext, Long xid) {
- MultipartRequestInputBuilder mprInput = new MultipartRequestInputBuilder();
- mprInput.setType(multipart);
- mprInput.setVersion(taskContext.getSession().getPrimaryConductor().getVersion());
- mprInput.setXid(xid);
- mprInput.setFlags(new MultipartRequestFlags(false));
- return mprInput;
- }
-
- private abstract static class ResultCallback<T> implements FutureCallback<RpcResult<Void>> {
-
- private SettableFuture<RpcResult<T>> result;
-
- /**
- * @param result result
- */
- public ResultCallback(SettableFuture<RpcResult<T>> result) {
- this.result = result;
- }
-
- public abstract T createResult();
-
- @Override
- public void onSuccess(RpcResult<Void> resultArg) {
- result.set(RpcResultBuilder.success(createResult()).build());
- }
-
- @Override
- public void onFailure(Throwable t) {
- result.set(RpcResultBuilder.<T>failed().withWarning(
- ErrorType.RPC,
- OFConstants.ERROR_TAG_TIMEOUT,
- "something wrong happened",
- OFConstants.APPLICATION_TAG,
- "", t).build());
- }
- }
-
- /**
- * @param taskContext task context
- * @param input update port input
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return task task to update port
- */
- public static OFRpcTask<UpdatePortInput, RpcResult<UpdatePortOutput>> createUpdatePortTask(
- final OFRpcTaskContext taskContext, final UpdatePortInput input,
- final SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
-
- class OFRpcTaskImpl extends OFRpcTask<UpdatePortInput, RpcResult<UpdatePortOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
- private final VersionConvertorData data;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- UpdatePortInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- data = new VersionConvertorData(getVersion());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdatePortOutput>> call() {
- ListenableFuture<RpcResult<UpdatePortOutput>> result = SettableFuture.create();
- final Port inputPort = input.getUpdatedPort().getPort().getPort().get(0);
-
- final java.util.Optional<PortModInput> ofPortModInput = convertorExecutor.convert(inputPort, data);
-
- PortModInputBuilder mdInput = new PortModInputBuilder(ofPortModInput
- .orElse(PortConvertor.defaultResult(getVersion())))
- .setXid(taskContext.getSession().getNextXid());
-
- Future<RpcResult<UpdatePortOutput>> resultFromOFLib = getMessageService()
- .portMod(mdInput.build(), cookie);
- result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
- /**
- * @param taskContext task context
- * @param input update table input
- * @param cookie switch connection distinguisher cookie value
- * @param convertorExecutor
- * @return task task to udpate table input
- */
- public static OFRpcTask<UpdateTableInput, RpcResult<UpdateTableOutput>> createUpdateTableTask(
- final OFRpcTaskContext taskContext, final UpdateTableInput input,
- final SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) {
-
- class OFRpcTaskImpl extends OFRpcTask<UpdateTableInput, RpcResult<UpdateTableOutput>> {
-
- private final ConvertorExecutor convertorExecutor;
- private final VersionConvertorData data;
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- UpdateTableInput input, ConvertorExecutor convertorExecutor) {
- super(taskContext, cookie, input);
- this.convertorExecutor = convertorExecutor;
- data = new VersionConvertorData(getVersion());
- }
-
- @Override
- public ListenableFuture<RpcResult<UpdateTableOutput>> call() {
- final SettableFuture<RpcResult<UpdateTableOutput>> result = SettableFuture.create();
-
- final Long xid = taskContext.getSession().getNextXid();
-
- MultipartRequestTableFeaturesCaseBuilder caseBuilder = new MultipartRequestTableFeaturesCaseBuilder();
- MultipartRequestTableFeaturesBuilder requestBuilder = new MultipartRequestTableFeaturesBuilder();
-
- final java.util.Optional<List<TableFeatures>> ofTableFeatureList = convertorExecutor.convert(input.getUpdatedTable(), data);
- requestBuilder.setTableFeatures(ofTableFeatureList.orElse(Collections.emptyList()));
- caseBuilder.setMultipartRequestTableFeatures(requestBuilder.build());
-
- // Set request body to main multipart request
- MultipartRequestInputBuilder mprInput =
- createMultipartHeader(MultipartType.OFPMPTABLEFEATURES, taskContext, xid);
- mprInput.setMultipartRequestBody(caseBuilder.build());
-
- Future<RpcResult<Void>> resultFromOFLib = getMessageService()
- .multipartRequest(mprInput.build(), getCookie());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib);
-
- Futures.addCallback(resultLib, new ResultCallback<UpdateTableOutput>(result) {
- @Override
- public UpdateTableOutput createResult() {
- UpdateTableOutputBuilder queueStatsFromPortBuilder =
- new UpdateTableOutputBuilder()
- .setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return queueStatsFromPortBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor);
- }
-
- public static OFRpcTask<SetConfigInput, RpcResult<SetConfigOutput>> createSetNodeConfigTask(final OFRpcTaskContext taskContext,
- final SetConfigInput input,
- final SwitchConnectionDistinguisher cookie) {
- class OFRpcTaskImpl extends OFRpcTask<SetConfigInput, RpcResult<SetConfigOutput>> {
-
- public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie,
- SetConfigInput input) {
- super(taskContext, cookie, input);
- }
-
- @Override
- public ListenableFuture<RpcResult<SetConfigOutput>> call() throws Exception {
-
- final SettableFuture<RpcResult<SetConfigOutput>> result = SettableFuture.create();
- final Long xid = taskContext.getSession().getNextXid();
-
- SetConfigInputBuilder builder = new SetConfigInputBuilder();
- SwitchConfigFlag flag = SwitchConfigFlag.valueOf(input.getFlag());
- builder.setXid(xid);
- builder.setFlags(flag);
- builder.setMissSendLen(input.getMissSearchLength());
- builder.setVersion(getVersion());
- ListenableFuture<RpcResult<Void>> resultLib = JdkFutureAdapters.listenInPoolThread(taskContext.getSession().getPrimaryConductor().getConnectionAdapter().setConfig(builder.build()));
- Futures.addCallback(resultLib, new ResultCallback<SetConfigOutput>(result) {
- @Override
- public SetConfigOutput createResult() {
- SetConfigOutputBuilder setConfigOutputBuilder = new SetConfigOutputBuilder();
- setConfigOutputBuilder.setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
- return setConfigOutputBuilder.build();
- }
- });
- return result;
- }
- }
-
- return new OFRpcTaskImpl(taskContext, cookie, input);
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-import com.google.common.base.Function;
-import com.google.common.base.MoreObjects;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.AsyncFunction;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.Future;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.sal.NotificationComposer;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.openflowplugin.openflow.md.util.RpcInputOutputTuple;
-import org.opendaylight.openflowplugin.openflow.md.util.TaskUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionAware;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.Notification;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- *
- */
-public abstract class OFRpcTaskUtil {
- protected static final Logger LOG = LoggerFactory.getLogger(OFRpcTaskUtil.class);
- private OFRpcTaskUtil() {
- //hiding implicit constructor
- }
-
- public static Collection<RpcError> manageBarrier(final OFRpcTaskContext taskContext, final Boolean isBarrier,
- final SwitchConnectionDistinguisher cookie) {
- Collection<RpcError> errors = null;
- if (MoreObjects.firstNonNull(isBarrier, Boolean.FALSE)) {
- RpcInputOutputTuple<BarrierInput, ListenableFuture<RpcResult<BarrierOutput>>> sendBarrierRpc =
- TaskUtil.sendBarrier(taskContext.getSession(), cookie, taskContext.getMessageService());
- Future<RpcResult<BarrierOutput>> barrierFuture = sendBarrierRpc.getOutput();
- try {
- RpcResult<BarrierOutput> barrierResult = barrierFuture.get(
- taskContext.getMaxTimeout(), taskContext.getMaxTimeoutUnit());
- if (!barrierResult.isSuccessful()) {
- errors = barrierResult.getErrors();
- }
- } catch (Exception e) {
- RpcError rpcError = RpcResultBuilder.newWarning(
- ErrorType.RPC,
- OFConstants.ERROR_TAG_TIMEOUT,
- "barrier sending failed",
- OFConstants.APPLICATION_TAG,
- "switch failed to respond on barrier request - message ordering is not preserved",
- e);
- errors = Lists.newArrayList(rpcError);
- }
- }
-
- if (errors == null) {
- errors = Collections.emptyList();
- }
-
- return errors;
- }
-
- /**
- * @param task task
- * @param originalResult original result
- * @param notificationProviderService notification provider service
- * @param notificationComposer lazy notification composer
- * @param <I> data container
- * @param <N> notification
- * @param <R> R
- */
- public static <R extends RpcResult<? extends TransactionAware>, N extends Notification, I extends DataContainer>
- void hookFutureNotification(
- final OFRpcTask<I, R> task,
- final ListenableFuture<R> originalResult,
- final NotificationProviderService notificationProviderService,
- final NotificationComposer<N> notificationComposer) {
-
- class FutureCallbackImpl implements FutureCallback<R> {
- @Override
- public void onSuccess(final R result) {
- if(null == notificationProviderService) {
- LOG.warn("onSuccess(): notificationServiceProvider is null, could not publish result {}",result);
- } else if (notificationComposer == null) {
- LOG.warn("onSuccess(): notificationComposer is null, could not publish result {}",result);
- } else if(result == null) {
- LOG.warn("onSuccess(): result is null, could not publish result {}",result);
- } else if (result.getResult() == null) {
- LOG.warn("onSuccess(): result.getResult() is null, could not publish result {}",result);
- } else if (result.getResult().getTransactionId() == null) {
- LOG.warn("onSuccess(): result.getResult().getTransactionId() is null, could not publish result {}",result);
- } else {
- notificationProviderService.publish(notificationComposer.compose(result.getResult().getTransactionId()));
- task.getTaskContext().getMessageSpy().spyMessage(
- task.getInput(), MessageSpy.StatisticsGroup.TO_SWITCH_SUBMITTED_SUCCESS);
- }
- }
-
- @Override
- public void onFailure(final Throwable t) {
- //TODO: good place to notify MD-SAL about errors
- task.getTaskContext().getMessageSpy().spyMessage(
- task.getInput(), MessageSpy.StatisticsGroup.TO_SWITCH_SUBMITTED_FAILURE);
- }
- }
-
- Futures.addCallback(originalResult, new FutureCallbackImpl());
- }
-
- /**
- * @param task of rpc
- * @param originalResult original result
- * @param <T> R
- * @param <I> I
- * @return chained result with barrier
- */
- public static <T extends TransactionAware, I extends DataContainer>
- ListenableFuture<RpcResult<T>> chainFutureBarrier(
- final OFRpcTask<I, RpcResult<T>> task,
- final ListenableFuture<RpcResult<T>> originalResult) {
-
- ListenableFuture<RpcResult<T>> chainResult = originalResult;
- if (MoreObjects.firstNonNull(task.isBarrier(), Boolean.FALSE)) {
-
- chainResult = Futures.transformAsync(originalResult, new AsyncFunction<RpcResult<T>, RpcResult<T>>() {
-
- @Override
- public ListenableFuture<RpcResult<T>> apply(final RpcResult<T> input) throws Exception {
- if (input.isSuccessful()) {
- RpcInputOutputTuple<BarrierInput, ListenableFuture<RpcResult<BarrierOutput>>> sendBarrierRpc = TaskUtil.sendBarrier(
- task.getSession(), task.getCookie(), task.getMessageService());
- ListenableFuture<RpcResult<T>> barrierTxResult = Futures.transform(
- sendBarrierRpc.getOutput(),
- transformBarrierToTransactionAware(input, sendBarrierRpc.getInput()));
- return barrierTxResult;
- } else {
- return Futures.immediateFuture(input);
- }
- }
-
- });
- }
-
- return chainResult;
- }
-
- /**
- * @param originalInput original input
- * @param barrierInput barrier input
- * @param <T> T
- * @return result
- */
- protected static <T extends TransactionAware> Function<RpcResult<BarrierOutput>, RpcResult<T>> transformBarrierToTransactionAware(
- final RpcResult<T> originalInput, final BarrierInput barrierInput) {
-
- class FunctionImpl implements Function<RpcResult<BarrierOutput>, RpcResult<T>> {
-
- @Override
- public RpcResult<T> apply(final RpcResult<BarrierOutput> barrierResult) {
- RpcResultBuilder<T> rpcBuilder = null;
- if (barrierResult.isSuccessful()) {
- rpcBuilder = RpcResultBuilder.<T>success();
- } else {
- rpcBuilder = RpcResultBuilder.<T>failed();
- RpcError rpcError = RpcResultBuilder.newWarning(
- ErrorType.RPC,
- OFConstants.ERROR_TAG_TIMEOUT,
- "barrier sending failed",
- OFConstants.APPLICATION_TAG,
- "switch failed to respond on barrier request, barrier.xid = "+barrierInput.getXid(),
- null);
- List<RpcError> chainedErrors = new ArrayList<>();
- chainedErrors.add(rpcError);
- chainedErrors.addAll(barrierResult.getErrors());
- rpcBuilder.withRpcErrors(chainedErrors);
- }
-
- rpcBuilder.withResult(originalInput.getResult());
-
- return rpcBuilder.build();
- }
- }
-
- return new FunctionImpl();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Ericsson Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-/**
- * Created by eshuvka on 5/16/2016.
- */
-public class OpenflowPluginConfig {
-
- private final boolean skipTableFeatures;
-
- private OpenflowPluginConfig (OpenflowPluginConfigBuilder builder){
- skipTableFeatures = builder.skipTableFeatures();
- }
-
- public boolean skipTableFeatures(){
- return skipTableFeatures;
- }
-
- public static OpenflowPluginConfigBuilder builder(){
- return new OpenflowPluginConfigBuilder();
- }
-
- public static class OpenflowPluginConfigBuilder{
- private boolean skipTableFeatures;
-
- public boolean skipTableFeatures(){
- return skipTableFeatures;
- }
-
- public void setSkipTableFeatures(boolean skip){
- skipTableFeatures = skip;
- }
-
- public OpenflowPluginConfig build() {return new OpenflowPluginConfig(this);}
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-import com.google.common.annotations.VisibleForTesting;
-import java.util.Collection;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.openflowjava.protocol.spi.connection.SwitchConnectionProvider;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageCountDumper;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageObservatory;
-import org.opendaylight.openflowplugin.extension.api.ExtensionConverterRegistrator;
-import org.opendaylight.openflowplugin.extension.api.OpenFlowPluginExtensionRegistratorProvider;
-import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterManager;
-import org.opendaylight.openflowplugin.openflow.md.core.MDController;
-import org.opendaylight.openflowplugin.openflow.md.core.extension.ExtensionConverterManagerImpl;
-import org.opendaylight.openflowplugin.openflow.md.core.role.OfEntityManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
-import org.opendaylight.openflowplugin.statistics.MessageSpyCounterImpl;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * OFPlugin provider implementation
- */
-public class OpenflowPluginProvider implements AutoCloseable, OpenFlowPluginExtensionRegistratorProvider {
-
- private static final Logger LOG = LoggerFactory.getLogger(OpenflowPluginProvider.class);
-
- private static final boolean SKIP_TABLE_FEATURES = false;
-
- private Collection<SwitchConnectionProvider> switchConnectionProviders;
-
- private MDController mdController;
-
- private MessageObservatory<DataContainer> messageCountProvider;
-
- private SalRegistrationManager registrationManager;
-
- private ExtensionConverterManager extensionConverterManager;
-
- private OfpRole role;
- private Boolean skipTableFeatures;
-
- private OFRoleManager roleManager;
- private OfEntityManager entManager;
- private DataBroker dataBroker;
- private NotificationProviderService notificationService;
- private RpcProviderRegistry rpcRegistry;
- private EntityOwnershipService entityOwnershipService;
-
- private OpenflowPluginConfig openflowPluginConfig;
-
-
-
- /**
- * Initialization of services and msgSpy counter
- */
- public void initialization() {
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
-
- messageCountProvider = new MessageSpyCounterImpl();
- extensionConverterManager = new ExtensionConverterManagerImpl();
- roleManager = new OFRoleManager(OFSessionUtil.getSessionManager());
- openflowPluginConfig = readConfig(skipTableFeatures);
- entManager = new OfEntityManager(entityOwnershipService,getOpenflowPluginConfig());
- entManager.setDataBroker(dataBroker);
- entManager.init();
-
- LOG.debug("dependencies gathered..");
- registrationManager = new SalRegistrationManager(convertorManager);
- registrationManager.setDataService(dataBroker);
- registrationManager.setPublishService(notificationService);
- registrationManager.setRpcProviderRegistry(rpcRegistry);
- registrationManager.setOfEntityManager(entManager);
- registrationManager.init();
-
- mdController = new MDController(convertorManager);
- mdController.setSwitchConnectionProviders(switchConnectionProviders);
- mdController.setMessageSpyCounter(messageCountProvider);
- mdController.setExtensionConverterProvider(extensionConverterManager);
- mdController.init();
- mdController.start();
- }
-
- /**
- * @param switchConnectionProvider switch connection provider
- */
- public void setSwitchConnectionProviders(Collection<SwitchConnectionProvider> switchConnectionProvider) {
- this.switchConnectionProviders = switchConnectionProvider;
- }
-
- @Override
- public void close() {
- LOG.debug("close");
-
- if(mdController != null) {
- mdController.stop();
- mdController = null;
- }
-
- if(registrationManager != null) {
- registrationManager.close();
- registrationManager = null;
- }
- }
-
- public MessageCountDumper getMessageCountDumper() {
- return messageCountProvider;
- }
-
- /**
- * @return the extensionConverterRegistry
- */
- @Override
- public ExtensionConverterRegistrator getExtensionConverterRegistrator() {
- return extensionConverterManager;
- }
-
- /**
- * @param role of instance
- */
- public void setRole(OfpRole role) {
- this.role = role;
- }
-
- /**
- * @param newRole new controller role
- */
- public void fireRoleChange(OfpRole newRole) {
- if (!role.equals(newRole)) {
- LOG.debug("Controller role was changed from {} to {}", role, newRole);
- role = newRole;
- switch (role) {
- case BECOMEMASTER:
- //TODO: implement appropriate action
- roleManager.manageRoleChange(role);
- break;
- case BECOMESLAVE:
- //TODO: implement appropriate action
- roleManager.manageRoleChange(role);
- break;
- case NOCHANGE:
- //TODO: implement appropriate action
- roleManager.manageRoleChange(role);
- break;
- default:
- LOG.warn("role not supported: {}", role);
- break;
- }
- }
- }
-
- private OpenflowPluginConfig readConfig(Boolean skipTableFeatures){
-
- final OpenflowPluginConfig.OpenflowPluginConfigBuilder openflowCfgBuilder = OpenflowPluginConfig.builder();
-
- if(skipTableFeatures !=null){
- openflowCfgBuilder.setSkipTableFeatures(skipTableFeatures.booleanValue());
- } else{
- LOG.warn("Could not load XML configuration file via ConfigSubsystem! Fallback to default config value(s)");
- openflowCfgBuilder.setSkipTableFeatures(SKIP_TABLE_FEATURES);
- }
-
- return openflowCfgBuilder.build();
- }
-
- public void setDataBroker(DataBroker dataBroker) {
- this.dataBroker = dataBroker;
- }
-
- public void setNotificationService(NotificationProviderService notificationService) {
- this.notificationService = notificationService;
- }
-
- public void setRpcRegistry(RpcProviderRegistry rpcRegistry) {
- this.rpcRegistry = rpcRegistry;
- }
-
- public void setEntityOwnershipService(EntityOwnershipService entityOwnershipService) {
- this.entityOwnershipService = entityOwnershipService;
- }
-
- public void setSkipTableFeatures(Boolean skipTableFeatures) {
- this.skipTableFeatures = skipTableFeatures;
- }
-
- @VisibleForTesting
- public OpenflowPluginConfig getOpenflowPluginConfig() {
- return openflowPluginConfig;
- }
-
- @VisibleForTesting
- protected RpcProviderRegistry getRpcRegistry() {
- return rpcRegistry;
- }
-
- @VisibleForTesting
- protected NotificationProviderService getNotificationService() {
- return notificationService;
- }
-
- @VisibleForTesting
- protected DataBroker getDataBroker() {
- return dataBroker;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-import com.google.common.base.Preconditions;
-import java.math.BigInteger;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitch;
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionListener;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF;
-import org.opendaylight.openflowplugin.openflow.md.core.role.OfEntityManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRemovedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * session and inventory listener implementation
- */
-public class SalRegistrationManager implements SessionListener, AutoCloseable {
-
- private static final Logger LOG = LoggerFactory.getLogger(SalRegistrationManager.class);
- private final ConvertorExecutor convertorExecutor;
-
- private NotificationProviderService publishService;
-
- private DataBroker dataService;
-
- private RpcProviderRegistry rpcProviderRegistry;
-
- private final SwitchFeaturesUtil swFeaturesUtil;
-
- private ListenerRegistration<SessionListener> sessionListenerRegistration;
-
- private OfEntityManager entManager;
-
- public SalRegistrationManager(ConvertorExecutor convertorExecutor) {
- this.convertorExecutor = convertorExecutor;
- swFeaturesUtil = SwitchFeaturesUtil.getInstance();
- }
-
- public NotificationProviderService getPublishService() {
- return publishService;
- }
-
- public void setPublishService(final NotificationProviderService publishService) {
- this.publishService = publishService;
- }
-
- public void setDataService(final DataBroker dataService) {
- this.dataService = dataService;
- }
-
- public void setRpcProviderRegistry(final RpcProviderRegistry rpcProviderRegistry) {
- this.rpcProviderRegistry = rpcProviderRegistry;
- }
-
- public void setOfEntityManager(OfEntityManager entManager) {
- this.entManager = entManager;
- }
-
- public void init() {
- LOG.debug("init..");
- sessionListenerRegistration = getSessionManager().registerSessionListener(this);
- getSessionManager().setNotificationProviderService(publishService);
- getSessionManager().setDataBroker(dataService);
- LOG.debug("SalRegistrationManager initialized");
- }
-
- @Override
- public void onSessionAdded(final SwitchSessionKeyOF sessionKey, final SessionContext context) {
- GetFeaturesOutput features = context.getFeatures();
- BigInteger datapathId = features.getDatapathId();
- InstanceIdentifier<Node> identifier = identifierFromDatapathId(datapathId);
- NodeRef nodeRef = new NodeRef(identifier);
- NodeId nodeId = nodeIdFromDatapathId(datapathId);
- ModelDrivenSwitch ofSwitch = new ModelDrivenSwitchImpl(nodeId, identifier, context, convertorExecutor);
-
- NotificationQueueWrapper wrappedNotification = new NotificationQueueWrapper(
- nodeAdded(ofSwitch, features, nodeRef),
- context.getFeatures().getVersion());
-
- reqOpenflowEntityOwnership(ofSwitch, context, wrappedNotification, rpcProviderRegistry);
- }
-
- @Override
- public void setRole (SessionContext context) {
- entManager.setSlaveRole(context);
- }
-
- @Override
- public void onSessionRemoved(final SessionContext context) {
- GetFeaturesOutput features = context.getFeatures();
- BigInteger datapathId = features.getDatapathId();
- InstanceIdentifier<Node> identifier = identifierFromDatapathId(datapathId);
- NodeRef nodeRef = new NodeRef(identifier);
- NodeId nodeId = nodeIdFromDatapathId(datapathId);
- unregOpenflowEntityOwnership(nodeId);
- NodeRemoved nodeRemoved = nodeRemoved(nodeRef);
-
- ModelDrivenSwitchRegistration registration = context.getProviderRegistration();
- if (null != registration) {
- registration.close();
- context.setProviderRegistration(null);
- }
- LOG.debug("ModelDrivenSwitch for {} unregistered from MD-SAL.", datapathId);
-
- NotificationQueueWrapper wrappedNotification = new NotificationQueueWrapper(
- nodeRemoved, context.getFeatures().getVersion());
- context.getNotificationEnqueuer().enqueueNotification(wrappedNotification);
- }
-
- private NodeUpdated nodeAdded(final ModelDrivenSwitch sw, final GetFeaturesOutput features, final NodeRef nodeRef) {
- NodeUpdatedBuilder builder = new NodeUpdatedBuilder();
- builder.setId(sw.getNodeId());
- builder.setNodeRef(nodeRef);
-
- FlowCapableNodeUpdatedBuilder builder2 = new FlowCapableNodeUpdatedBuilder();
- try {
- builder2.setIpAddress(getIpAddressOf(sw));
- builder2.setPortNumber(getPortNumberOf(sw));
- } catch (Exception e) {
- LOG.warn("IP address/Port Number of the node {} cannot be obtained.", sw.getNodeId(), e);
- }
- builder2.setSwitchFeatures(swFeaturesUtil.buildSwitchFeatures(features));
- builder.addAugmentation(FlowCapableNodeUpdated.class, builder2.build());
-
- return builder.build();
- }
-
- private static IpAddress getIpAddressOf(final ModelDrivenSwitch sw) {
- SessionContext sessionContext = sw.getSessionContext();
- Preconditions.checkNotNull(sessionContext.getPrimaryConductor(),
- "primary conductor must not be NULL -> " + sw.getNodeId());
- Preconditions.checkNotNull(sessionContext.getPrimaryConductor().getConnectionAdapter(),
- "connection adapter of primary conductor must not be NULL -> " + sw.getNodeId());
- InetSocketAddress remoteAddress = sessionContext.getPrimaryConductor().getConnectionAdapter()
- .getRemoteAddress();
- if (remoteAddress == null) {
- LOG.warn("IP address of the node {} cannot be obtained. No connection with switch.", sw.getNodeId());
- return null;
- }
- return resolveIpAddress(remoteAddress.getAddress());
- }
-
- private static IpAddress resolveIpAddress(final InetAddress address) {
- String hostAddress = address.getHostAddress();
- if (address instanceof Inet4Address) {
- return new IpAddress(new Ipv4Address(hostAddress));
- }
- if (address instanceof Inet6Address) {
- return new IpAddress(new Ipv6Address(hostAddress));
- }
- throw new IllegalArgumentException("Unsupported IP address type!");
- }
-
- private static PortNumber getPortNumberOf(ModelDrivenSwitch sw) {
- SessionContext sessionContext = sw.getSessionContext();
-
- Preconditions.checkNotNull(sessionContext.getPrimaryConductor(),
- "primary conductor must not be NULL -> " + sw.getNodeId());
- Preconditions.checkNotNull(sessionContext.getPrimaryConductor().getConnectionAdapter(),
- "connection adapter of primary conductor must not be NULL -> " + sw.getNodeId());
- InetSocketAddress remoteAddress = sessionContext.getPrimaryConductor().getConnectionAdapter()
- .getRemoteAddress();
- if (remoteAddress == null) {
- LOG.warn("Port Number of the node {} cannot be obtained. No connection with switch.", sw.getNodeId());
- return null;
- }
- return resolvePortNumber(remoteAddress.getPort());
- }
-
- private static PortNumber resolvePortNumber(int port) {
- PortNumber portNo = new PortNumber(port);
- return portNo;
- }
-
- private static NodeRemoved nodeRemoved(final NodeRef nodeRef) {
- NodeRemovedBuilder builder = new NodeRemovedBuilder();
- builder.setNodeRef(nodeRef);
- return builder.build();
- }
-
- public static InstanceIdentifier<Node> identifierFromDatapathId(final BigInteger datapathId) {
- NodeKey nodeKey = nodeKeyFromDatapathId(datapathId);
- InstanceIdentifierBuilder<Node> builder = InstanceIdentifier.builder(Nodes.class).child(Node.class, nodeKey);
- return builder.build();
- }
-
- public static NodeKey nodeKeyFromDatapathId(final BigInteger datapathId) {
- return new NodeKey(nodeIdFromDatapathId(datapathId));
- }
-
- public static NodeId nodeIdFromDatapathId(final BigInteger datapathId) {
- // FIXME: Convert to textual representation of datapathID
- String current = String.valueOf(datapathId);
- return new NodeId("openflow:" + current);
- }
-
- public SessionManager getSessionManager() {
- return OFSessionUtil.getSessionManager();
- }
-
- @Override
- public void close() {
- dataService = null;
- rpcProviderRegistry = null;
- publishService = null;
- if (sessionListenerRegistration != null) {
- sessionListenerRegistration.close();
- }
- }
-
- private void reqOpenflowEntityOwnership(ModelDrivenSwitch ofSwitch,
- SessionContext context,
- NotificationQueueWrapper wrappedNotification,
- RpcProviderRegistry rpcProviderRegistry) {
- context.setValid(true);
- entManager.requestOpenflowEntityOwnership(ofSwitch, context, wrappedNotification, rpcProviderRegistry);
- }
-
- private void unregOpenflowEntityOwnership(NodeId nodeId) {
- entManager.unregisterEntityOwnershipRequest(nodeId);
- }
-
-}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-/**
- * @author jsebin
- *
- */
public final class SwitchFeaturesUtil {
private static final Logger LOG = LoggerFactory.getLogger(SwitchFeaturesUtil.class);
+++ /dev/null
-/*
- * 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.openflowplugin.openflow.md.core.session;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager;
-import org.opendaylight.openflowplugin.extension.api.core.session.ExtensionSessionManager;
-
-/**
- * Created by Martin Bobak mbobak@cisco.com on 10/16/14.
- */
-public interface ConjunctSessionManager extends SessionManager, ExtensionSessionManager {
-}
--- /dev/null
+/**
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.openflowplugin.openflow.md.core.session;
+
+import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
+import org.opendaylight.openflowplugin.extension.api.core.session.ExtensionSessionManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ExtensionSessionManagerImpl implements ExtensionSessionManager {
+
+ protected static final Logger LOG = LoggerFactory.getLogger(ExtensionSessionManagerImpl.class);
+ private static ExtensionSessionManagerImpl INSTANCE;
+ private ExtensionConverterProvider extensionConverterProvider;
+
+
+ /**
+ * @return singleton instance
+ */
+ public static ExtensionSessionManager getInstance() {
+ if (INSTANCE == null) {
+ INSTANCE = new ExtensionSessionManagerImpl();
+ }
+
+ return INSTANCE;
+ }
+
+ private ExtensionSessionManagerImpl() {
+ }
+
+ @Override
+ public void setExtensionConverterProvider(
+ ExtensionConverterProvider extensionConverterProvider) {
+ this.extensionConverterProvider = extensionConverterProvider;
+ }
+
+ @Override
+ public ExtensionConverterProvider getExtensionConverterProvider() {
+ return extensionConverterProvider;
+ }
+}
\ No newline at end of file
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.session;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
-
-/**
- *
- * @author jsebin
- *
- * Singleton for extracting port features for OF 1.0
- */
-public class FeaturesV10Bandwidth implements IGetBandwith {
-
- private static FeaturesV10Bandwidth instance = new FeaturesV10Bandwidth();
-
- private FeaturesV10Bandwidth() {}
-
- /**
- *
- * @return instance of class
- */
- public static FeaturesV10Bandwidth getInstance(){
- return instance;
- }
-
- @Override
- public boolean getBandwidth(PortGrouping port) {
- return (port.getCurrentFeaturesV10().is_100mbFd() | port.getCurrentFeaturesV10().is_100mbHd() | port.getCurrentFeaturesV10().is_10gbFd() |
- port.getCurrentFeaturesV10().is_10mbFd() | port.getCurrentFeaturesV10().is_10mbHd() | port.getCurrentFeaturesV10().is_1gbFd() |
- port.getCurrentFeaturesV10().is_1gbHd() | port.getCurrentFeaturesV10().isAutoneg() | port.getCurrentFeaturesV10().isCopper() |
- port.getCurrentFeaturesV10().isFiber() | port.getCurrentFeaturesV10().isPause() | port.getCurrentFeaturesV10().isPauseAsym());
- }
-
-
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.session;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
-
-/**
- *
- * @author jsebin
- *
- * Singleton for extracting port features for OF 1.3
- */
-public class FeaturesV13Bandwidth implements IGetBandwith {
-
- private static FeaturesV13Bandwidth instance = new FeaturesV13Bandwidth();
-
- private FeaturesV13Bandwidth() {}
-
- /**
- *
- * @return instance of class
- */
- public static FeaturesV13Bandwidth getInstance(){
- return instance;
- }
-
- @Override
- public boolean getBandwidth(PortGrouping port) {
- return (port.getCurrentFeatures().is_100gbFd() | port.getCurrentFeatures().is_100mbFd() | port.getCurrentFeatures().is_100mbHd() |
- port.getCurrentFeatures().is_10gbFd() | port.getCurrentFeatures().is_10mbFd() | port.getCurrentFeatures().is_10mbHd() |
- port.getCurrentFeatures().is_1gbFd() | port.getCurrentFeatures().is_1gbHd() | port.getCurrentFeatures().is_1tbFd() |
- port.getCurrentFeatures().is_40gbFd() | port.getCurrentFeatures().isAutoneg() | port.getCurrentFeatures().isCopper() |
- port.getCurrentFeatures().isFiber() | port.getCurrentFeatures().isOther() | port.getCurrentFeatures().isPause() |
- port.getCurrentFeatures().isPauseAsym());
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.session;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
-
-/**
- * Utility for extracting bandwith from port according to port version
- *
- * @author jsebin
- *
- */
-public interface IGetBandwith {
-
- /**
- *
- * @param port port group
- * @return port bandwidth
- */
- public boolean getBandwidth(PortGrouping port);
-}
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM 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.openflowplugin.openflow.md.core.session;
-
-import com.google.common.base.Function;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.JdkFutureAdapters;
-import com.google.common.util.concurrent.ListenableFuture;
-
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowplugin.api.ConnectionException;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.util.RpcResultUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.*;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutputBuilder;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.math.BigInteger;
-import java.util.concurrent.Future;
-
-/**
- * message dispatch service to send the message to switch.
- *
- * @author AnilGujele
- */
-public class MessageDispatchServiceImpl implements IMessageDispatchService {
-
- private static final Logger LOG = LoggerFactory.getLogger(MessageDispatchServiceImpl.class);
- private SessionContext session;
-
- /**
- * constructor
- *
- * @param session - MessageDispatchService for this session
- */
- public MessageDispatchServiceImpl(SessionContext session) {
- this.session = session;
- }
-
- /**
- * get proper connection adapter to send the message to switch.
- *
- * @param cookie to identify the right connection, it can be null also.
- * @return connectionAdapter associated with cookie, otherwise return best
- * suitable connection.
- */
-
- private ConnectionAdapter getConnectionAdapter(SwitchConnectionDistinguisher cookie) throws ConnectionException {
-
- if (!session.isValid()) {
- LOG.warn("No valid connection found for the node [datapath-id : {}]", session.getSessionKey().getId());
- throw new ConnectionException(CONNECTION_ERROR_MESSAGE);
- }
- LOG.debug("finding connecton for cookie value {}. ", cookie);
- // set main connection as default
- ConnectionAdapter connectionAdapter = session.getPrimaryConductor().getConnectionAdapter();
- if (null != cookie) {
- ConnectionConductor conductor = session.getAuxiliaryConductor(cookie);
- // check if auxiliary connection exist
- if (null != conductor) {
- LOG.debug("found auxiliary connection for the cookie.");
- connectionAdapter = conductor.getConnectionAdapter();
- }
- } else {
- // TODO: pick connection to utilize all the available connection.
- }
- return connectionAdapter;
- }
-
- @Override
- public Future<RpcResult<BarrierOutput>> barrier(BarrierInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).barrier(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<Void>> experimenter(ExperimenterInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).experimenter(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<UpdateFlowOutput>> flowMod(final FlowModInput input, SwitchConnectionDistinguisher cookie) {
- LOG.debug("Calling OFLibrary flowMod");
- Future<RpcResult<Void>> response = null;
- try {
- response = getConnectionAdapter(cookie).flowMod(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
-
- // appending xid
- ListenableFuture<RpcResult<UpdateFlowOutput>> xidResult = Futures.transform(
- JdkFutureAdapters.listenInPoolThread(response),
- new Function<RpcResult<Void>, RpcResult<UpdateFlowOutput>>() {
-
- @Override
- public RpcResult<UpdateFlowOutput> apply(final RpcResult<Void> inputArg) {
- UpdateFlowOutputBuilder flowModOutput = new UpdateFlowOutputBuilder();
- BigInteger bigIntXid = BigInteger.valueOf(input.getXid());
- flowModOutput.setTransactionId(new TransactionId(bigIntXid));
-
- UpdateFlowOutput result = flowModOutput.build();
- RpcResult<UpdateFlowOutput> rpcResult = RpcResultBuilder
- .<UpdateFlowOutput>status(inputArg.isSuccessful())
- .withResult(result).withRpcErrors(inputArg.getErrors())
- .build();
- return rpcResult;
- }
- });
-
- return xidResult;
- }
-
- @Override
- public Future<RpcResult<GetAsyncOutput>> getAsync(GetAsyncInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).getAsync(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<GetConfigOutput>> getConfig(GetConfigInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).getConfig(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<GetFeaturesOutput>> getFeatures(GetFeaturesInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).getFeatures(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<GetQueueConfigOutput>> getQueueConfig(GetQueueConfigInput input,
- SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).getQueueConfig(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<UpdateGroupOutput>> groupMod(final GroupModInput input, SwitchConnectionDistinguisher cookie) {
- LOG.debug("Calling OFLibrary groupMod");
- Future<RpcResult<Void>> response = null;
- try {
- response = getConnectionAdapter(cookie).groupMod(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
-
- // appending xid
- ListenableFuture<RpcResult<UpdateGroupOutput>> xidResult = Futures.transform(
- JdkFutureAdapters.listenInPoolThread(response),
- new Function<RpcResult<Void>, RpcResult<UpdateGroupOutput>>() {
-
- @Override
- public RpcResult<UpdateGroupOutput> apply(final RpcResult<Void> inputArg) {
- UpdateGroupOutputBuilder groupModOutput = new UpdateGroupOutputBuilder();
- BigInteger bigIntXid = BigInteger.valueOf(input.getXid());
- groupModOutput.setTransactionId(new TransactionId(bigIntXid));
-
- UpdateGroupOutput result = groupModOutput.build();
- RpcResult<UpdateGroupOutput> rpcResult = RpcResultBuilder
- .<UpdateGroupOutput>status(inputArg.isSuccessful()).withResult(result)
- .withRpcErrors(inputArg.getErrors()).build();
- return rpcResult;
- }
- });
-
- return xidResult;
- }
-
- @Override
- public Future<RpcResult<UpdateMeterOutput>> meterMod(final MeterModInput input, SwitchConnectionDistinguisher cookie) {
- LOG.debug("Calling OFLibrary meterMod");
- Future<RpcResult<Void>> response = null;
- try {
- response = getConnectionAdapter(cookie).meterMod(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
-
- // appending xid
- ListenableFuture<RpcResult<UpdateMeterOutput>> xidResult = Futures.transform(
- JdkFutureAdapters.listenInPoolThread(response),
- new Function<RpcResult<Void>, RpcResult<UpdateMeterOutput>>() {
-
- @Override
- public RpcResult<UpdateMeterOutput> apply(final RpcResult<Void> inputArg) {
- UpdateMeterOutputBuilder meterModOutput = new UpdateMeterOutputBuilder();
- BigInteger bigIntXid = BigInteger.valueOf(input.getXid());
- meterModOutput.setTransactionId(new TransactionId(bigIntXid));
-
- UpdateMeterOutput result = meterModOutput.build();
- RpcResult<UpdateMeterOutput> rpcResult = RpcResultBuilder
- .<UpdateMeterOutput>status(inputArg.isSuccessful()).withResult(result)
- .withRpcErrors(inputArg.getErrors()).build();
- return rpcResult;
- }
- });
-
- return xidResult;
- }
-
- @Override
- public Future<RpcResult<java.lang.Void>> multipartRequest(MultipartRequestInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).multipartRequest(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<Void>> packetOut(PacketOutInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).packetOut(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<UpdatePortOutput>> portMod(final PortModInput input, SwitchConnectionDistinguisher cookie) {
- LOG.debug("Calling OFLibrary portMod");
- Future<RpcResult<Void>> response = null;
- try {
- response = getConnectionAdapter(cookie).portMod(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
-
- // appending xid
- ListenableFuture<RpcResult<UpdatePortOutput>> xidResult = Futures.transform(
- JdkFutureAdapters.listenInPoolThread(response),
- new Function<RpcResult<Void>, RpcResult<UpdatePortOutput>>() {
-
- @Override
- public RpcResult<UpdatePortOutput> apply(final RpcResult<Void> inputArg) {
- UpdatePortOutputBuilder portModOutput = new UpdatePortOutputBuilder();
- BigInteger bigIntXid = BigInteger.valueOf(input.getXid());
- portModOutput.setTransactionId(new TransactionId(bigIntXid));
-
- UpdatePortOutput result = portModOutput.build();
- RpcResult<UpdatePortOutput> rpcResult = RpcResultBuilder
- .<UpdatePortOutput>status(inputArg.isSuccessful()).withResult(result)
- .withRpcErrors(inputArg.getErrors()).build();
- return rpcResult;
- }
- });
-
- return xidResult;
- }
-
- @Override
- public Future<RpcResult<RoleRequestOutput>> roleRequest(RoleRequestInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).roleRequest(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<Void>> setAsync(SetAsyncInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).setAsync(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<Void>> setConfig(SetConfigInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).setConfig(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-
- @Override
- public Future<RpcResult<Void>> tableMod(TableModInput input, SwitchConnectionDistinguisher cookie) {
- try {
- return getConnectionAdapter(cookie).tableMod(input);
- } catch (ConnectionException e) {
- return RpcResultUtil.getRpcErrorFuture(e);
- }
- }
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.core.session;
-
-import com.google.common.base.MoreObjects;
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import java.math.BigInteger;
-import java.util.Comparator;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.PriorityBlockingQueue;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager;
-import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor;
-import org.opendaylight.openflowplugin.openflow.md.util.RoleUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * manage OF-role propagation to devices
- */
-public class OFRoleManager implements AutoCloseable {
-
- /**
- * starting value of generationId
- */
- public static final BigInteger MAX_GENERATION_ID = new BigInteger("ffffffffffffffff", 16);
-
- private static final Logger LOG = LoggerFactory.getLogger(OFRoleManager.class);
-
- private static final long TIMEOUT = 2000;
-
- private static final TimeUnit TIMEOUT_UNIT = TimeUnit.MILLISECONDS;
-
- private static final int RETRY_LIMIT = 42;
-
- private final ListeningExecutorService broadcastPool;
-
- private final BlockingQueue<RolePushTask> workQueue;
-
- private final SessionManager sessionManager;
-
- /**
- * @param sessionManager switch connection session manager
- */
- public OFRoleManager(final SessionManager sessionManager) {
- Preconditions.checkNotNull("Session manager can not be empty.", sessionManager);
- this.sessionManager = sessionManager;
- workQueue = new PriorityBlockingQueue<>(500, new Comparator<RolePushTask>() {
- @Override
- public int compare(final RolePushTask o1, final RolePushTask o2) {
- return Integer.compare(o1.getPriority(), o2.getPriority());
- }
- });
- ThreadPoolLoggingExecutor delegate = new ThreadPoolLoggingExecutor(
- 1, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), "ofRoleBroadcast");
- broadcastPool = MoreExecutors.listeningDecorator(
- delegate);
- }
-
- /**
- * change role on each connected device
- *
- * @param role openflow role
- */
- public void manageRoleChange(final OfpRole role) {
- for (final SessionContext session : sessionManager.getAllSessions()) {
- try {
- workQueue.put(new RolePushTask(role, session));
- } catch (InterruptedException e) {
- LOG.warn("Processing of role request failed while enqueueing role task: {}", e.getMessage());
- }
- }
-
- while (!workQueue.isEmpty()) {
- RolePushTask task = workQueue.poll();
- ListenableFuture<Boolean> rolePushResult = broadcastPool.submit(task);
- CheckedFuture<Boolean, RolePushException> rolePushResultChecked =
- RoleUtil.makeCheckedRuleRequestFxResult(rolePushResult);
- try {
- Boolean succeeded = rolePushResultChecked.checkedGet(TIMEOUT, TIMEOUT_UNIT);
- if (!MoreObjects.firstNonNull(succeeded, Boolean.FALSE)) {
- if (task.getRetryCounter() < RETRY_LIMIT) {
- workQueue.offer(task);
- }
- }
- } catch (RolePushException | TimeoutException e) {
- LOG.warn("failed to process role request: {}", e);
- }
- }
- }
-
- @Override
- public void close() throws Exception {
- broadcastPool.shutdown();
- }
-}
package org.opendaylight.openflowplugin.openflow.md.core.session;
-import java.math.BigInteger;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF;
-import org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.opendaylight.openflowplugin.extension.api.core.session.ExtensionSessionManager;
-/**
- * @author mirehak
- */
public abstract class OFSessionUtil {
- private static final Logger LOG = LoggerFactory
- .getLogger(OFSessionUtil.class);
-
- /**
- * @param connectionConductor switch connection conductor
- * @param features switch feature output
- * @param version openflow version
- */
- // public static void registerSession(ConnectionConductorImpl connectionConductor,
- public static SessionContext registerSession(ConnectionConductorImpl connectionConductor,
- GetFeaturesOutput features, short version) {
- SwitchSessionKeyOF sessionKey = createSwitchSessionKey(features
- .getDatapathId());
- SessionContext sessionContext = getSessionManager().getSessionContext(sessionKey);
- if (LOG.isDebugEnabled()) {
- LOG.debug("registering sessionKey: {}", Arrays.toString(sessionKey.getId()));
- }
-
- if (features.getAuxiliaryId() == null || features.getAuxiliaryId() == 0) {
- // handle primary
- if (sessionContext != null) {
- LOG.warn("duplicate datapathId occured while registering new switch session: "
- + dumpDataPathId(features.getDatapathId()));
- getSessionManager().invalidateSessionContext(sessionKey);
- }
- // register new session context (based primary conductor)
- SessionContextOFImpl context = new SessionContextOFImpl();
- context.setPrimaryConductor(connectionConductor);
- context.setNotificationEnqueuer(connectionConductor);
- context.setFeatures(features);
- context.setSessionKey(sessionKey);
- context.setSeed((int) System.currentTimeMillis());
- connectionConductor.setSessionContext(context);
- getSessionManager().addSessionContext(sessionKey, context);
- } else {
- // handle auxiliary
- if (sessionContext == null) {
- throw new IllegalStateException("unexpected auxiliary connection - primary connection missing: "
- + dumpDataPathId(features.getDatapathId()));
- } else {
- // register auxiliary conductor into existing sessionContext
- SwitchConnectionDistinguisher auxiliaryKey = createConnectionCookie(features, sessionContext.getSeed());
- if (sessionContext.getAuxiliaryConductor(auxiliaryKey) != null) {
- LOG.warn("duplicate datapathId+auxiliary occured while registering switch session: "
- + dumpDataPathId(features.getDatapathId())
- + " | "
- + features.getAuxiliaryId());
- getSessionManager().invalidateAuxiliary(sessionKey,
- auxiliaryKey);
- }
-
- sessionContext.addAuxiliaryConductor(auxiliaryKey,
- connectionConductor);
- connectionConductor.setSessionContext(sessionContext);
- connectionConductor.setConnectionCookie(auxiliaryKey);
- }
- }
-
- // check registration result
- SessionContext resulContext = getSessionManager().getSessionContext(sessionKey);
- if (resulContext == null) {
- throw new IllegalStateException("session context registration failed");
- } else {
- if (!resulContext.isValid()) {
- throw new IllegalStateException("registered session context is invalid");
- }
- }
- return(resulContext);
- }
-
- public static void setRole(SessionContext sessionContext)
- {
- getSessionManager().setRole(sessionContext);
- }
-
- /**
- * @param datapathId switch datapath id
- * @return readable version of datapathId (hex)
- */
- public static String dumpDataPathId(BigInteger datapathId) {
- return datapathId.toString(16);
- }
-
- /**
- * @param datapathId switch datapath id
- * @return new session key
- */
- public static SwitchSessionKeyOF createSwitchSessionKey(
- BigInteger datapathId) {
- SwitchSessionKeyOF key = new SwitchSessionKeyOF();
- key.setDatapathId(datapathId);
- return key;
- }
-
- /**
- * @param features switch feature output
- * @param seed seed value
- * @return connection cookie key
- * @see #createConnectionCookie(BigInteger,short, int)
- */
- public static SwitchConnectionDistinguisher createConnectionCookie(
- GetFeaturesOutput features, int seed) {
- return createConnectionCookie(features.getDatapathId(),
- features.getAuxiliaryId(), seed);
- }
-
- /**
- * @param datapathId switch datapath id
- * @param auxiliaryId connection aux id
- * @param seed seed value
- * @return connection cookie key
- */
- public static SwitchConnectionDistinguisher createConnectionCookie(
- BigInteger datapathId, short auxiliaryId, int seed) {
- SwitchConnectionCookieOFImpl cookie = null;
- cookie = new SwitchConnectionCookieOFImpl();
- cookie.setAuxiliaryId(auxiliaryId);
- cookie.init(datapathId.intValue() + seed);
- return cookie;
- }
-
/**
* @return session manager singleton instance
*/
- public static ConjunctSessionManager getSessionManager() {
- return SessionManagerOFImpl.getInstance();
- }
-
- /**
- * release session manager singleton instance
- */
- public static void releaseSessionManager() {
- SessionManagerOFImpl.releaseInstance();
- }
-
- /**
- * @return session manager listener Map
- */
- public static Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> getTranslatorMap() {
- return getSessionManager().getTranslatorMapping();
- }
-
- /**
- * @return pop listener Map
- */
- public static Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> getPopListenerMapping() {
- return getSessionManager().getPopListenerMapping();
+ public static ExtensionSessionManager getSessionManager() {
+ return ExtensionSessionManagerImpl.getInstance();
}
/**
return getSessionManager().getExtensionConverterProvider();
}
- /**
- * @return collection of all sessions
- */
- public static Collection<SessionContext> getAllSessions() {
- return getSessionManager().getAllSessions();
- }
-
}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.session;
-
-import java.util.HashMap;
-import java.util.Map;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Wrapper for bandwidth extracting utilities
- *
- * @author jsebin
- *
- */
-public class PortFeaturesUtil {
-
- private static PortFeaturesUtil instance = new PortFeaturesUtil();
-
- private final Map<Short, IGetBandwith> portVersionBandwidth;
- private static final Logger LOG = LoggerFactory.getLogger(PortFeaturesUtil.class);
-
- private PortFeaturesUtil() {
- this.portVersionBandwidth = new HashMap<>();
-
- portVersionBandwidth.put((short) 1, FeaturesV10Bandwidth.getInstance());
- portVersionBandwidth.put((short) 4, FeaturesV13Bandwidth.getInstance());
- }
-
- /**
- *
- * @return instance
- */
- public static PortFeaturesUtil getInstance() {
- return instance;
- }
-
- /**
- *
- * @param msg {@link org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus}
- * @return port bandwidth
- */
- public Boolean getPortBandwidth(PortStatus msg) {
-
- if(portVersionBandwidth.containsKey(msg.getVersion()) == true) {
- try {
- return portVersionBandwidth.get(msg.getVersion()).getBandwidth(msg);
- } catch (NullPointerException e) {
- LOG.warn("error while getting port features: {}", e.getMessage());
- LOG.debug("error while getting port features.. ", e);
- }
- }
- else {
- LOG.warn("unknown port version: {}", msg.getVersion());
- }
-
- return null;
- }
-
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.core.session;
-
-/**
- * covers role pushing issues
- */
-public class RolePushException extends Exception {
-
- private static final long serialVersionUID = -615991366447313972L;
-
- /**
- * default ctor
- *
- * @param message exception message
- */
- public RolePushException(String message) {
- super(message);
- }
-
- /**
- * @param message exception message
- * @param cause exception cause
- */
- public RolePushException(String message, Throwable cause) {
- super(message, cause);
- }
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.core.session;
-
-import com.google.common.base.Preconditions;
-import java.math.BigInteger;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.core.MessageFactory;
-import org.opendaylight.openflowplugin.openflow.md.util.RoleUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import java.util.Date;
-
-/**
- * push role to device - basic step:
- * <ul>
- * <li>here we read generationId from device and</li>
- * <li>push role request with incremented generationId</li>
- * <li>{@link #call()} returns true if role request was successful</li>
- * </ul>
- */
-//final class RolePushTask implements Callable<Boolean> {
-public class RolePushTask implements Callable<Boolean> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(RolePushTask.class);
-
- public static final long TIMEOUT = 7000;
- public static final TimeUnit TIMEOUT_UNIT = TimeUnit.MILLISECONDS;
- private OfpRole role;
- private SessionContext session;
- private int priority;
- private int retryCounter;
-
- /**
- * @param role openflow controller role
- * @param session switch session context
- */
- public RolePushTask(OfpRole role, SessionContext session) {
- Preconditions.checkNotNull("OfpRole can not be empty.", role);
- Preconditions.checkNotNull("Session context can not be empty.", session);
- this.role = role;
- this.session = session;
- }
-
- /**
- * @return the retryCounter
- */
- public int getRetryCounter() {
- return retryCounter;
- }
-
- /**
- * @return the priority
- */
- public int getPriority() {
- return priority;
- }
-
- /**
- * @param priority the priority to set
- */
- public void setPriority(int priority) {
- this.priority = priority;
- }
-
- @Override
- public Boolean call() throws RolePushException {
- if (session.getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) {
- LOG.info("OpenFlow 1.0 devices don't support multi controller features, skipping role push.");
- return true;
- }
- if (!session.isValid()) {
- String msg = "Giving up role change: current session is invalid";
- LOG.error(msg);
- throw new RolePushException(msg);
- }
-
- // adopt actual generationId from device (first shot failed and this is retry)
- BigInteger generationId = null;
- String dpId = new BigInteger(session.getSessionKey().getId()).toString();
- LOG.info("Pushing {} role configuration to device openflow:{}",
- role==OfpRole.BECOMEMASTER?"MASTER":"SLAVE", dpId);
- try {
- Date date = new Date();
- Future<BigInteger> generationIdFuture = RoleUtil.readGenerationIdFromDevice(session);
- // flush election result with barrier
- BarrierInput barrierInput = MessageFactory.createBarrier(
- session.getFeatures().getVersion(), session.getNextXid());
- Future<RpcResult<BarrierOutput>> barrierResult = session.getPrimaryConductor().getConnectionAdapter().barrier(barrierInput);
- try {
- barrierResult.get(TIMEOUT, TIMEOUT_UNIT);
- } catch (Exception e) {
- String msg = String.format("Giving up role change: barrier after read generation-id failed : %s", e.getMessage());
- LOG.warn(msg);
- throw new RolePushException(msg);
- }
- try {
- generationId = generationIdFuture.get(0, TIMEOUT_UNIT);
- } catch (Exception e) {
- String msg = String.format("Giving up role change: read generation-id failed %s", e.getMessage());
- throw new RolePushException(msg);
- }
-
- LOG.info("Received generation-id {} for role change request from device {}",
- generationId, dpId);
- } catch (Exception e) {
- LOG.error("Role push request failed for device {}",session.getSessionKey().getId(), e);
- }
-
- if (generationId == null) {
- LOG.error("Generation ID is NULL for device {}",session.getSessionKey().getId());
- String msg = "Giving up role change: current generation-id can not be read";
- throw new RolePushException(msg);
- }
-
- generationId = RoleUtil.getNextGenerationId(generationId);
- LOG.info("Pushing role change {} config request with generation-id {} to device {}",
- role==OfpRole.BECOMEMASTER?"MASTER":"SLAVE", generationId, dpId);
-
-
- // try to possess role on device
- Future<RpcResult<RoleRequestOutput>> roleReply = RoleUtil.sendRoleChangeRequest(session, role, generationId);
- // flush election result with barrier
- BarrierInput barrierInput = MessageFactory.createBarrier(
- session.getFeatures().getVersion(), session.getNextXid());
- Future<RpcResult<BarrierOutput>> barrierResult = session.getPrimaryConductor().getConnectionAdapter().barrier(barrierInput);
- try {
- barrierResult.get(TIMEOUT, TIMEOUT_UNIT);
- } catch (Exception e) {
- String msg = String.format("Giving up role change: barrier after role change failed: %s", e.getMessage());
- LOG.warn(msg);
- throw new RolePushException(msg);
- }
- // after barrier replied there must be election result or error
- try {
- roleReply.get(0, TimeUnit.MILLISECONDS);
- } catch (Exception e) {
- // no election result received - let's retry
- retryCounter += 1;
- return false;
- }
-
- // here we expect that role on device is successfully possessed
- LOG.info("Successfully pushing {} role to the device openflow:{}",
- role==OfpRole.BECOMEMASTER?"MASTER":"SLAVE", dpId);
- return true;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.session;
-
-import com.google.common.base.Preconditions;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-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.atomic.AtomicLong;
-
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
-
-/**
- * @author mirehak
- */
-public class SessionContextOFImpl implements SessionContext {
-
- private GetFeaturesOutput features;
- private ConnectionConductor primaryConductor;
- private NotificationEnqueuer notificationEnqueuer;
- private ConcurrentHashMap<SwitchConnectionDistinguisher, ConnectionConductor> auxiliaryConductors;
- private boolean valid;
- private SwitchSessionKeyOF sessionKey;
- private IMessageDispatchService mdService;
- private final AtomicLong xid;
- private final Map<Long, PortGrouping> physicalPorts;
- private final Map<Long, Boolean> portBandwidth;
- private ModelDrivenSwitchRegistration providerRegistration;
- private int seed;
- private ControllerRole roleOnDevice = ControllerRole.OFPCRROLEEQUAL;
-
-
- /**
- * default ctor
- */
- public SessionContextOFImpl() {
- auxiliaryConductors = new ConcurrentHashMap<>();
- mdService = new MessageDispatchServiceImpl(this);
- xid = new AtomicLong();
- this.physicalPorts = new HashMap<Long, PortGrouping>();
- this.portBandwidth = new HashMap<Long, Boolean>();
- }
-
- @Override
- public ConnectionConductor getPrimaryConductor() {
- return primaryConductor;
- }
-
- @Override
- public ConnectionConductor getAuxiliaryConductor(
- SwitchConnectionDistinguisher auxiliaryKey) {
- return auxiliaryConductors.get(auxiliaryKey);
- }
-
- @Override
- public void addAuxiliaryConductor(
- SwitchConnectionDistinguisher auxiliaryKey,
- ConnectionConductor conductor) {
- auxiliaryConductors.put(auxiliaryKey, conductor);
- }
-
- @Override
- public Set<Entry<SwitchConnectionDistinguisher, ConnectionConductor>> getAuxiliaryConductors() {
- return Collections.unmodifiableSet(auxiliaryConductors.entrySet());
- }
-
- @Override
- public GetFeaturesOutput getFeatures() {
- return features;
- }
-
- /**
- * @param features
- * the features to set
- */
- public void setFeatures(GetFeaturesOutput features) {
- this.features = features;
- }
-
- /**
- * @param primaryConductor
- * the primaryConductor to set
- */
- public void setPrimaryConductor(ConnectionConductor primaryConductor) {
- this.primaryConductor = primaryConductor;
- }
-
- @Override
- public ConnectionConductor removeAuxiliaryConductor(
- SwitchConnectionDistinguisher connectionCookie) {
- return auxiliaryConductors.remove(connectionCookie);
- }
-
- @Override
- public boolean isValid() {
- return valid;
- }
-
- @Override
- public void setValid(boolean valid) {
- this.valid = valid;
- }
-
- /**
- * @param sessionKey the sessionKey to set
- */
- public void setSessionKey(SwitchSessionKeyOF sessionKey) {
- this.sessionKey = sessionKey;
- }
-
- /**
- * @param seed the seed to set
- */
- public void setSeed(int seed) {
- this.seed = seed;
- }
-
- @Override
- public SwitchSessionKeyOF getSessionKey() {
- return sessionKey;
- }
-
- @Override
- public IMessageDispatchService getMessageDispatchService() {
- return mdService;
- }
-
- @Override
- public Long getNextXid() {
- return xid.incrementAndGet();
- }
-
- @Override
- public Map<Long, PortGrouping> getPhysicalPorts() {
- return this.physicalPorts;
- }
-
- @Override
- public Map<Long, Boolean> getPortsBandwidth() {
- return this.portBandwidth;
- }
-
- @Override
- public Set<Long> getPorts() {
- return this.physicalPorts.keySet();
- }
-
- @Override
- public PortGrouping getPhysicalPort(Long portNumber) {
- return this.physicalPorts.get(portNumber);
- }
-
- @Override
- public Boolean getPortBandwidth(Long portNumber) {
- return this.portBandwidth.get(portNumber);
- }
-
- @Override
- public boolean isPortEnabled(long portNumber) {
- return isPortEnabled(physicalPorts.get(portNumber));
- }
-
- @Override
- public boolean isPortEnabled(PortGrouping port) {
- if (port == null) {
- return false;
- }
- if (port.getConfig().isPortDown()) {
- return false;
- }
- if (port.getState().isLinkDown()) {
- return false;
- }
- if (port.getState().isBlocked()) {
- return false;
- }
- return true;
- }
-
- @Override
- public List<PortGrouping> getEnabledPorts() {
- List<PortGrouping> result = new ArrayList<PortGrouping>();
- synchronized (this.physicalPorts) {
- for (PortGrouping port : physicalPorts.values()) {
- if (isPortEnabled(port)) {
- result.add(port);
- }
- }
- }
- return result;
- }
-
- @Override
- public void setProviderRegistration(ModelDrivenSwitchRegistration providerRegistration) {
- this.providerRegistration = providerRegistration;
- }
-
- @Override
- public ModelDrivenSwitchRegistration getProviderRegistration() {
- return providerRegistration;
- }
-
- @Override
- public int getSeed() {
- return seed;
- }
-
- /**
- * @param notificationEnqueuer the notificationEnqueuer to set
- */
- public void setNotificationEnqueuer(
- NotificationEnqueuer notificationEnqueuer) {
- this.notificationEnqueuer = notificationEnqueuer;
- }
-
- @Override
- public NotificationEnqueuer getNotificationEnqueuer() {
- return notificationEnqueuer;
- }
-
- /**
- * @return the roleOnDevice
- */
- @Override
- public ControllerRole getRoleOnDevice() {
- return roleOnDevice;
- }
-
- /**
- * @param roleOnDevice the roleOnDevice to set
- */
- @Override
- public void setRoleOnDevice(ControllerRole roleOnDevice) {
- Preconditions.checkNotNull("Proposed controller role can not be empty.", roleOnDevice);
- this.roleOnDevice = roleOnDevice;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.session;
-
-import com.google.common.util.concurrent.ListeningExecutorService;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.concurrent.ConcurrentHashMap;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionListener;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.util.ListenerRegistry;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author mirehak
- */
-public class SessionManagerOFImpl implements ConjunctSessionManager {
-
- protected static final Logger LOG = LoggerFactory.getLogger(SessionManagerOFImpl.class);
- private static SessionManagerOFImpl instance;
- private ConcurrentHashMap<SwitchSessionKeyOF, SessionContext> sessionLot;
- private Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping;
- private Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> popListenerMapping;
-
- protected ListenerRegistry<SessionListener> sessionListeners;
- private NotificationProviderService notificationProviderService;
-
- private DataBroker dataBroker;
- private ListeningExecutorService rpcPool;
-
-
- /**
- * @return singleton instance
- */
- public static ConjunctSessionManager getInstance() {
- if (instance == null) {
- synchronized (SessionContextOFImpl.class) {
- if (instance == null) {
- instance = new SessionManagerOFImpl();
- }
- }
- }
- return instance;
- }
-
- /**
- * close and release singleton instance
- */
- public static void releaseInstance() {
- if (instance != null) {
- synchronized (SessionManagerOFImpl.class) {
- if (instance != null) {
- instance.close();
- instance = null;
- }
- }
- }
- }
-
- private SessionManagerOFImpl() {
- LOG.debug("singleton creating");
- sessionLot = new ConcurrentHashMap<>();
- sessionListeners = new ListenerRegistry<>();
- }
-
- @Override
- public SessionContext getSessionContext(SwitchSessionKeyOF sessionKey) {
- return sessionLot.get(sessionKey);
- }
-
- @Override
- public void invalidateSessionContext(SwitchSessionKeyOF sessionKey) {
- SessionContext context = getSessionContext(sessionKey);
- if (context == null) {
- LOG.info("context for invalidation not found");
- } else {
- synchronized (context) {
- if (context.isValid()) {
- for (Entry<SwitchConnectionDistinguisher, ConnectionConductor> auxEntry : context.getAuxiliaryConductors()) {
- invalidateAuxiliary(sessionKey, auxEntry.getKey());
- }
- context.getPrimaryConductor().disconnect();
- context.setValid(false);
- removeSessionContext(context);
- // TODO:: notify listeners
- } else {
- LOG.warn("Ignore invalid session context: {}",
- Arrays.toString(sessionKey.getId()));
- }
- }
- }
- }
-
- private void invalidateDeadSessionContext(SessionContext sessionContext) {
- if (sessionContext == null) {
- LOG.info("context for invalidation not found");
- } else {
- synchronized (sessionContext) {
- if (sessionContext.isValid()) {
- for (Entry<SwitchConnectionDistinguisher, ConnectionConductor> auxEntry : sessionContext
- .getAuxiliaryConductors()) {
- invalidateAuxiliary(sessionContext, auxEntry.getKey(), true);
- }
- sessionContext.setValid(false);
- removeSessionContext(sessionContext);
- // TODO:: notify listeners
- } else {
- LOG.warn("Ignore invalid dead session context: {}",
- Arrays.toString(
- sessionContext.getSessionKey().getId()));
- }
- }
- }
- }
-
- private void removeSessionContext(SessionContext sessionContext) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("removing session: {}", Arrays.toString(sessionContext.getSessionKey().getId()));
- }
- if (sessionLot.remove(sessionContext.getSessionKey(), sessionContext)) {
- sessionNotifier.onSessionRemoved(sessionContext);
- } else {
- // This should never happen.
- LOG.warn("Ignore session context that was already removed: {}",
- Arrays.toString(sessionContext.getSessionKey().getId()));
- }
- }
-
- @Override
- public void addSessionContext(SwitchSessionKeyOF sessionKey, SessionContext context) {
- synchronized (context) {
- sessionLot.put(sessionKey, context);
- sessionNotifier.onSessionAdded(sessionKey, context);
- context.setValid(true);
- }
- }
-
- @Override
- public void setRole(SessionContext context) {
- sessionNotifier.setRole(context);
- }
- @Override
- public void invalidateAuxiliary(SwitchSessionKeyOF sessionKey,
- SwitchConnectionDistinguisher connectionCookie) {
- SessionContext context = getSessionContext(sessionKey);
- invalidateAuxiliary(context, connectionCookie, true);
- }
-
- /**
- * @param context
- * @param connectionCookie
- * @param disconnect true if auxiliary connection is to be disconnected
- */
- private static void invalidateAuxiliary(SessionContext context, SwitchConnectionDistinguisher connectionCookie,
- boolean disconnect) {
- if (context == null) {
- LOG.info("context for invalidation not found");
- } else {
- ConnectionConductor auxiliaryConductor = context.removeAuxiliaryConductor(connectionCookie);
- if (auxiliaryConductor == null) {
- LOG.warn("auxiliary conductor not found");
- } else {
- if (disconnect) {
- auxiliaryConductor.disconnect();
- }
- }
- }
- }
-
- @Override
- public void invalidateOnDisconnect(ConnectionConductor conductor) {
- if (conductor.getAuxiliaryKey() == null) {
- invalidateDeadSessionContext(conductor.getSessionContext());
- // TODO:: notify listeners
- } else {
- invalidateAuxiliary(conductor.getSessionContext(), conductor.getAuxiliaryKey(), false);
- }
- }
-
- @Override
- public void setTranslatorMapping(Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping) {
- this.translatorMapping = translatorMapping;
- }
-
- @Override
- public ListenerRegistration<SessionListener> registerSessionListener(SessionListener listener) {
- LOG.debug("registerSessionListener");
- return sessionListeners.register(listener);
- }
-
- private final SessionListener sessionNotifier = new SessionListener() {
-
- @Override
- public void onSessionAdded(SwitchSessionKeyOF sessionKey, SessionContext context) {
- for (ListenerRegistration<SessionListener> listener : sessionListeners) {
- try {
- listener.getInstance().onSessionAdded(sessionKey, context);
- } catch (Exception e) {
- LOG.error("Unhandled exeption occured while invoking onSessionAdded on listener", e);
- }
- }
- }
-
- @Override
- public void setRole(SessionContext context) {
- for (ListenerRegistration<SessionListener> listener : sessionListeners) {
- try {
- listener.getInstance().setRole(context);
- } catch (Exception e) {
- LOG.error("Unhandled exeption occured while invoking setRole on listener", e);
- }
- }
- }
-
- @Override
- public void onSessionRemoved(SessionContext context) {
- for (ListenerRegistration<SessionListener> listener : sessionListeners) {
- try {
- listener.getInstance().onSessionRemoved(context);
- } catch (Exception e) {
- LOG.error("Unhandled exeption occured while invoking onSessionRemoved on listener", e);
- }
- }
- }
- };
- private MessageSpy<DataContainer> messageSpy;
- private ExtensionConverterProvider extensionConverterProvider;
-
-
- @Override
- public Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> getTranslatorMapping() {
- return this.translatorMapping;
- }
-
- @Override
- public void setNotificationProviderService(
- NotificationProviderService notificationProviderService) {
- this.notificationProviderService = notificationProviderService;
-
- }
-
- @Override
- public DataBroker getDataBroker() {
- return dataBroker;
- }
-
- @Override
- public void setDataBroker(DataBroker dataBroker) {
- this.dataBroker = dataBroker;
-
- }
-
- @Override
- public NotificationProviderService getNotificationProviderService() {
- return notificationProviderService;
- }
-
- @Override
- public Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> getPopListenerMapping() {
- return popListenerMapping;
- }
-
- @Override
- public void setPopListenerMapping(
- Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> popListenerMapping) {
- this.popListenerMapping = popListenerMapping;
- }
-
- @Override
- public void close() {
- LOG.debug("close");
- synchronized (sessionLot) {
- for (SessionContext sessionContext : sessionLot.values()) {
- sessionContext.getPrimaryConductor().disconnect();
- }
- // TODO: handle timeouted shutdown
- rpcPool.shutdown();
- }
-
- for (ListenerRegistration<SessionListener> listenerRegistration : sessionListeners) {
- SessionListener listener = listenerRegistration.getInstance();
- if (listener instanceof AutoCloseable) {
- try {
- ((AutoCloseable) listener).close();
- } catch (Exception e) {
- LOG.warn("closing of sessionListenerRegistration failed", e);
- }
- }
- }
- }
-
- @Override
- public void setRpcPool(ListeningExecutorService rpcPool) {
- this.rpcPool = rpcPool;
- }
-
- @Override
- public ListeningExecutorService getRpcPool() {
- return rpcPool;
- }
-
- @Override
- public void setMessageSpy(MessageSpy<DataContainer> messageSpy) {
- this.messageSpy = messageSpy;
- }
-
- @Override
- public MessageSpy<DataContainer> getMessageSpy() {
- return messageSpy;
- }
-
- @Override
- public void setExtensionConverterProvider(
- ExtensionConverterProvider extensionConverterProvider) {
- this.extensionConverterProvider = extensionConverterProvider;
- }
-
- /**
- * @return the extensionConverterProvider
- */
- @Override
- public ExtensionConverterProvider getExtensionConverterProvider() {
- return extensionConverterProvider;
- }
-
- @Override
- public Collection<SessionContext> getAllSessions() {
- return sessionLot.values();
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.session;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-
-import com.google.common.hash.HashFunction;
-import com.google.common.hash.Hasher;
-import com.google.common.hash.Hashing;
-
-/**
- * @author mirehak
- */
-public class SwitchConnectionCookieOFImpl implements SwitchConnectionDistinguisher {
-
- private short auxiliaryId;
- private long cookie;
-
- /**
- * @param cookie switch connection cookie
- */
- public SwitchConnectionCookieOFImpl(long cookie) {
- this.cookie = cookie;
- }
-
- /**
- * default ctor
- */
- public SwitchConnectionCookieOFImpl() {
- // NOOP
- }
-
- /**
- * @param auxiliaryId the auxiliaryId to set
- */
- public void setAuxiliaryId(short auxiliaryId) {
- this.auxiliaryId = auxiliaryId;
- }
-
- /**
- * compute pseudorandom key unique for given seed and {@link #auxiliaryId}
- * @param seed random int but fixed per session
- */
- public void init(int seed) {
- if (auxiliaryId <= 0) {
- throw new IllegalStateException("auxiliaryId must be greater than 0");
- }
-
- HashFunction mm32Hf = Hashing.murmur3_32(seed);
- Hasher hasher = mm32Hf.newHasher(8);
- hasher.putInt(auxiliaryId);
- long hash = 0xFFFFFFFFL & hasher.hash().asInt();
- cookie = (auxiliaryId << 24) | (hash >> 8);
- }
-
- @Override
- public long getCookie() {
- return cookie;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (int) (cookie ^ (cookie >>> 32));
- 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 (getClass() != obj.getClass())
- return false;
- SwitchConnectionCookieOFImpl other = (SwitchConnectionCookieOFImpl) obj;
- if (cookie != other.cookie)
- return false;
- return true;
- }
-
-
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.util.ByteUtil;
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * general support for errorMessage OF-API to MD-SAL translation
- */
-public abstract class AbstractErrorTranslator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
-
- private static final Logger LOG = LoggerFactory.getLogger(AbstractErrorTranslator.class);
-
- @Override
- public List<DataObject> translate(SwitchConnectionDistinguisher cookie, SessionContext sc, OfHeader msg) {
- if (msg instanceof ErrorMessage) {
- ErrorMessage message = (ErrorMessage) msg;
- List<DataObject> list = new CopyOnWriteArrayList<DataObject>();
- if (LOG.isDebugEnabled()) {
- String hexData = "n/a";
- if (message.getData() != null) {
- hexData = ByteUtil.bytesToHexstring(message.getData(), " ");
- }
- LOG.debug(" Error Message received: type={}[{}], code={}[{}], data=[{}] ", message.getType(),
- message.getTypeString(), message.getCode(), message.getCodeString(),
- hexData);
-
- }
-
- // TODO -- Augmentation is not handled
- ErrorType type = decodeErrorType(message.getType());
- NodeRef node = new NodeRef(
- InventoryDataServiceUtil.identifierFromDatapathId(
- sc.getFeatures().getDatapathId()));
- list.add(getGranularNodeErrors(message, type, node));
- return list;
- } else {
- LOG.error("Message is not of Error Message ");
- return Collections.emptyList();
- }
- }
-
- /**
- * @param message error message
- * @param errorType error type
- * @param node node ref
- * @return error message
- */
- protected abstract org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage getGranularNodeErrors(ErrorMessage message, ErrorType errorType, NodeRef node);
-
- /**
- * @param type error type in source message
- * @return enum for errorType
- */
- public abstract ErrorType decodeErrorType(int type);
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadActionErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadInstructionErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadMatchErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadRequestErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.ExperimenterErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.FlowModErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.GroupModErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.HelloFailedErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.MeterModErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.PortModErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.QueueOpErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.RoleRequestErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.SwitchConfigErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.TableFeaturesErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.TableModErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
-
-/**
- * OF-1.3 errorMessage support
- */
-public class ErrorTranslator extends AbstractErrorTranslator {
-
- @Override
- public ErrorType decodeErrorType(int type) {
- return ErrorType.forValue(type);
- }
-
- @Override
- public org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage getGranularNodeErrors(ErrorMessage message, ErrorType errorType, NodeRef node){
- org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage outErrorMessage = null;
- TransactionId txnId = new TransactionId(BigInteger.valueOf(message.getXid()));
-
- //currently in yang , generation of builders does not support an interface
- //so each notification is put in a separate if-else
- if (errorType == ErrorType.HelloFailed) {
- HelloFailedErrorNotificationBuilder builder = new HelloFailedErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.BadRequest) {
- BadRequestErrorNotificationBuilder builder = new BadRequestErrorNotificationBuilder ();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.BadAction) {
- BadActionErrorNotificationBuilder builder = new BadActionErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.BadInstruction) {
- BadInstructionErrorNotificationBuilder builder = new BadInstructionErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.BadMatch) {
- BadMatchErrorNotificationBuilder builder = new BadMatchErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.FlowModFailed) {
- FlowModErrorNotificationBuilder builder = new FlowModErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.GroupModFailed) {
- GroupModErrorNotificationBuilder builder = new GroupModErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.PortModFailed) {
- PortModErrorNotificationBuilder builder = new PortModErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.QueueOpFailed) {
- QueueOpErrorNotificationBuilder builder = new QueueOpErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.SwitchConfigFailed) {
- SwitchConfigErrorNotificationBuilder builder = new SwitchConfigErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.RoleRequestFailed) {
- RoleRequestErrorNotificationBuilder builder = new RoleRequestErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.MeterModFailed) {
- MeterModErrorNotificationBuilder builder = new MeterModErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.TableModFailed) {
- TableModErrorNotificationBuilder builder = new TableModErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.TableFeaturesFailed) {
- TableFeaturesErrorNotificationBuilder builder = new TableFeaturesErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- } else if (errorType == ErrorType.Experimenter) {
- ExperimenterErrorNotificationBuilder builder = new ExperimenterErrorNotificationBuilder();
- builder.setTransactionId(txnId);
- builder.setType(errorType);
- builder.setCode(message.getCode());
- builder.setNode(node);
- if (message.getData() != null) {
- builder.setData(new String(message.getData()));
- }
- outErrorMessage = builder.build();
- }
-
- return outErrorMessage;
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.NodeErrorNotificationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
-
-/**
- * OF-1.0 errorMessage support
- */
-public class ErrorV10Translator extends AbstractErrorTranslator {
-
- @Override
- public ErrorType decodeErrorType(int typeArg) {
- ErrorType type = ErrorType.forValue(typeArg);
- switch (type.ordinal()) {
- case 3:
- type = ErrorType.FlowModFailed;
- break;
- case 4:
- type = ErrorType.PortModFailed;
- break;
- case 5:
- type = ErrorType.QueueOpFailed;
- break;
- }
- return type;
- }
-
- /**
- * @param message error message
- * @param errorType error type
- * @param node reference to node, that sent the error message
- * @return translated error message of general type (OF-1.0)
- */
- @Override
- public org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage getGranularNodeErrors(ErrorMessage message, ErrorType errorType, NodeRef node){
- NodeErrorNotificationBuilder nodeErrBuilder = new NodeErrorNotificationBuilder();
- nodeErrBuilder.setTransactionId(new TransactionId(BigInteger.valueOf(message.getXid())));
- nodeErrBuilder.setType(errorType);
- nodeErrBuilder.setCode(message.getCode());
- nodeErrBuilder.setNode(node);
-
- if (message.getData() != null) {
- nodeErrBuilder.setData(new String(message.getData()));
- }
- return nodeErrBuilder.build();
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2014 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class ExperimenterTranslator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
-
- private static final Logger LOG = LoggerFactory.getLogger(ExperimenterTranslator.class);
-
- @Override
- public List<DataObject> translate(SwitchConnectionDistinguisher cookie,
- SessionContext sc, OfHeader msg) {
- if( msg instanceof ExperimenterMessage) {
- // TODO - implement functionality to fully support Experimenter framework
- return null;
- }else {
- LOG.error( "Message is not of Experimenter Error Message " ) ;
- return Collections.emptyList();
- }
- }
-
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.util.PortTranslatorUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPort;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class FeaturesV10ToNodeConnectorUpdatedTranslator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
- private static final Logger LOG = LoggerFactory
- .getLogger(FeaturesV10ToNodeConnectorUpdatedTranslator.class);
-
- @Override
- public List<DataObject> translate(SwitchConnectionDistinguisher cookie,
- SessionContext sc, OfHeader msg) {
- if (msg instanceof GetFeaturesOutput) {
- GetFeaturesOutput features = (GetFeaturesOutput) msg;
- List<DataObject> list = new CopyOnWriteArrayList<DataObject>();
- BigInteger datapathId = sc.getFeatures().getDatapathId();
- if( features.getPhyPort() != null ) {
- for (PhyPort port : features.getPhyPort()) {
- list.add(PortTranslatorUtil.translatePort(msg.getVersion(), datapathId, port.getPortNo(), port));
- }
- }
- return list;
- } else {
- // TODO - Do something smarter than returning null if translation fails... what Exception should we throw here?
- return Collections.emptyList();
- }
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2014 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Objects;
-import java.util.concurrent.CopyOnWriteArrayList;
-import org.opendaylight.openflowjava.util.ByteBufUtils;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
-import org.opendaylight.openflowplugin.extension.api.AugmentTuple;
-import org.opendaylight.openflowplugin.extension.api.path.MatchPath;
-import org.opendaylight.openflowplugin.openflow.md.core.extension.MatchExtensionHelper;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.common.IpConversionUtil;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionDatapathIdConvertorData;
-import org.opendaylight.openflowplugin.openflow.md.util.ByteUtil;
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6FlowLabel;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SwitchFlowRemovedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.RemovedFlowReason;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.mod.removed.Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.mod.removed.MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpSourceHardwareAddressBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpTargetHardwareAddressBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetSourceBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetTypeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ipv6.match.fields.Ipv6ExtHeaderBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ipv6.match.fields.Ipv6LabelBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv6MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.IpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.MetadataBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.ProtocolMatchFieldsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TunnelBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv6MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.SctpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.TcpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.protocol.match.fields.PbbBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.vlan.match.fields.VlanIdBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Ipv6ExthdrFlags;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpOp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpSha;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpSpa;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpTha;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpTpa;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthDst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthSrc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv4Code;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv4Type;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv6Code;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv6Type;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.InPhyPort;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.InPort;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpDscp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpEcn;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpProto;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv4Dst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv4Src;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Dst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Exthdr;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Flabel;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdSll;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdTarget;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdTll;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Src;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MatchField;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Metadata;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsBos;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsLabel;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsTc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.PbbIsid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.SctpDst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.SctpSrc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TcpDst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TcpSrc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TunnelId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.UdpDst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.UdpSrc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.VlanPcp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.VlanVid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpOpCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpShaCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpSpaCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpThaCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpTpaCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthDstCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthSrcCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthTypeCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv4CodeCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv4TypeCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv6CodeCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv6TypeCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.InPhyPortCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.InPortCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpDscpCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpEcnCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpProtoCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv4DstCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv4SrcCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6DstCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6ExthdrCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6FlabelCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdSllCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdTargetCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdTllCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6SrcCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MetadataCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsBosCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsLabelCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsTcCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.PbbIsidCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.SctpDstCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.SctpSrcCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TcpDstCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TcpSrcCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TunnelIdCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.UdpDstCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.UdpSrcCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.VlanPcpCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.VlanVidCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TunnelIpv4Dst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TunnelIpv4Src;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class FlowRemovedTranslator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
-
- private static final Logger LOG = LoggerFactory.getLogger(FlowRemovedTranslator.class);
- private static final String PREFIX_SEPARATOR = "/";
- private final ConvertorExecutor convertorExecutor;
-
- public FlowRemovedTranslator(ConvertorExecutor convertorExecutor) {
- this.convertorExecutor = convertorExecutor;
- }
-
- @Override
- public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sc, final OfHeader msg) {
- if (msg instanceof FlowRemovedMessage) {
- FlowRemovedMessage ofFlow = (FlowRemovedMessage) msg;
- List<DataObject> list = new CopyOnWriteArrayList<DataObject>();
- LOG.debug("Flow Removed Message received: Table Id={}, Flow removed reason={} ", ofFlow.getTableId(),
- ofFlow.getReason());
-
- SwitchFlowRemovedBuilder salFlowRemoved = new SwitchFlowRemovedBuilder();
-
- if (ofFlow.getCookie() != null) {
- salFlowRemoved.setCookie(new FlowCookie(ofFlow.getCookie()));
- }
- salFlowRemoved.setPriority(ofFlow.getPriority());
-
- if (ofFlow.getTableId() != null) {
- salFlowRemoved.setTableId(ofFlow.getTableId().getValue().shortValue());
- }
-
- salFlowRemoved.setDurationSec(ofFlow.getDurationSec());
- salFlowRemoved.setDurationNsec(ofFlow.getDurationNsec());
- salFlowRemoved.setIdleTimeout(ofFlow.getIdleTimeout());
- salFlowRemoved.setHardTimeout(ofFlow.getHardTimeout());
- salFlowRemoved.setPacketCount(ofFlow.getPacketCount());
- salFlowRemoved.setByteCount(ofFlow.getByteCount());
-
- if(Objects.nonNull(ofFlow.getReason())) {
- salFlowRemoved.setRemovedReason(translateReason(ofFlow));
- }
-
- OpenflowVersion ofVersion = OpenflowVersion.get(sc.getPrimaryConductor().getVersion());
- org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.Match ofMatch = ofFlow
- .getMatch();
- if (ofMatch != null) {
- salFlowRemoved.setMatch(fromMatch(ofMatch, sc.getFeatures().getDatapathId(), ofVersion));
- } else if (ofFlow.getMatchV10() != null) {
- final VersionDatapathIdConvertorData data = new VersionDatapathIdConvertorData(sc.getPrimaryConductor().getVersion());
- data.setDatapathId(sc.getFeatures().getDatapathId());
-
- final Optional<MatchBuilder> matchBuilderOptional = convertorExecutor.convert(ofFlow.getMatchV10(), data);
- salFlowRemoved.setMatch(matchBuilderOptional.orElse(new MatchBuilder()).build());
- }
- salFlowRemoved.setNode(new NodeRef(InventoryDataServiceUtil.identifierFromDatapathId(sc.getFeatures()
- .getDatapathId())));
- list.add(salFlowRemoved.build());
- return list;
- } else {
- LOG.error("Message is not a flow removed message ");
- return Collections.emptyList();
- }
- }
- private RemovedFlowReason translateReason(FlowRemoved removedFlow) {
- LOG.debug("--Entering translateReason within FlowRemovedTranslator with reason:{} " + removedFlow.getReason());
- switch (removedFlow.getReason()) {
- case OFPRRIDLETIMEOUT:
- return RemovedFlowReason.OFPRRIDLETIMEOUT;
- case OFPRRHARDTIMEOUT:
- return RemovedFlowReason.OFPRRHARDTIMEOUT;
- case OFPRRDELETE:
- return RemovedFlowReason.OFPRRDELETE;
- case OFPRRGROUPDELETE:
- return RemovedFlowReason.OFPRRGROUPDELETE;
- default:
- LOG.debug("The flow being default and hence deleting it ");
- return RemovedFlowReason.OFPRRDELETE;
- }
- }
-
- public Match fromMatch(final org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.Match ofMatch,
- final BigInteger datapathid, final OpenflowVersion ofVersion) {
- MatchBuilder matchBuilder = new MatchBuilder();
- EthernetMatchBuilder ethernetMatch = null;
- VlanMatchBuilder vlanMatch = null;
- IpMatchBuilder ipMatch = null;
- TcpMatchBuilder tcpMatch = null;
- UdpMatchBuilder udpMatch = null;
- SctpMatchBuilder sctpMatch = null;
- Icmpv4MatchBuilder icmpv4Match = null;
- Icmpv6MatchBuilder icmpv6Match = null;
- Ipv4MatchBuilder ipv4Match = null;
- ArpMatchBuilder arpMatch = null;
- Ipv6MatchBuilder ipv6Match = null;
- ProtocolMatchFieldsBuilder protocolMatchFields = null;
-
- for (MatchEntry entry : ofMatch.getMatchEntry()) {
- Class<? extends MatchField> field = entry.getOxmMatchField();
- if (field.equals(InPort.class)) {
- matchBuilder.setInPort(InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(datapathid,
- ((InPortCase) entry.getMatchEntryValue()).getInPort().getPortNumber().getValue(), ofVersion));
- } else if (field.equals(InPhyPort.class)) {
- matchBuilder.setInPhyPort(InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(datapathid,
- ((InPhyPortCase) entry.getMatchEntryValue()).getInPhyPort().getPortNumber().getValue(), ofVersion));
- } else if (field.equals(Metadata.class)) {
- MetadataBuilder metadata = new MetadataBuilder();
- MetadataCase metadataCase = ((MetadataCase) entry.getMatchEntryValue());
- metadata.setMetadata(new BigInteger(OFConstants.SIGNUM_UNSIGNED, metadataCase.getMetadata().getMetadata()));
- if (entry.isHasMask()) {
- metadata.setMetadataMask(new BigInteger(OFConstants.SIGNUM_UNSIGNED, metadataCase.getMetadata().getMask()));
- }
- matchBuilder.setMetadata(metadata.build());
- } else if (field.equals(EthDst.class) || field.equals(EthSrc.class) || field.equals(EthType.class)) {
- if (ethernetMatch == null) {
- ethernetMatch = new EthernetMatchBuilder();
- }
- if (field.equals(EthDst.class)) {
- EthernetDestinationBuilder ethDst = new EthernetDestinationBuilder();
- EthDstCase ethDstCase = (EthDstCase) entry.getMatchEntryValue();
- ethDst.setAddress(ethDstCase.getEthDst().getMacAddress());
- if (entry.isHasMask()) {
- ethDst.setMask(new MacAddress(ByteUtil.bytesToHexstring(ethDstCase.getEthDst().getMask(), ":")));
- }
- ethernetMatch.setEthernetDestination(ethDst.build());
- } else if (field.equals(EthSrc.class)) {
- EthernetSourceBuilder ethSrc = new EthernetSourceBuilder();
- EthSrcCase ethSrcCase = ((EthSrcCase) entry.getMatchEntryValue());
- ethSrc.setAddress(ethSrcCase.getEthSrc().getMacAddress());
- if (entry.isHasMask()) {
- ethSrc.setMask(new MacAddress(ByteUtil.bytesToHexstring(ethSrcCase.getEthSrc().getMask(), ":")));
- }
- ethernetMatch.setEthernetSource(ethSrc.build());
- } else if (field.equals(EthType.class)) {
- EthernetTypeBuilder ethType = new EthernetTypeBuilder();
- EthTypeCase ethTypeCase = ((EthTypeCase) entry.getMatchEntryValue());
- ethType.setType(new EtherType(ethTypeCase.getEthType().getEthType().getValue().longValue()));
- ethernetMatch.setEthernetType(ethType.build());
- }
- } else if (field.equals(VlanVid.class) || field.equals(VlanPcp.class)) {
- if (vlanMatch == null) {
- vlanMatch = new VlanMatchBuilder();
- }
- if (field.equals(VlanVid.class)) {
- boolean vlanIdPresent = false;
- VlanIdBuilder vlanId = new VlanIdBuilder();
- VlanVidCase vlanVidCase = ((VlanVidCase) entry.getMatchEntryValue());
- Integer vlanVidValue = vlanVidCase.getVlanVid().getVlanVid();
- if (vlanVidCase.getVlanVid().isCfiBit()) {
- vlanIdPresent = true;
- }
- vlanId.setVlanIdPresent(vlanIdPresent);
- if (vlanVidValue != null) {
- vlanId.setVlanId(new VlanId(vlanVidValue));
- }
- vlanMatch.setVlanId(vlanId.build());
- } else if (field.equals(VlanPcp.class)) {
- VlanPcpCase vlanPcpCase = ((VlanPcpCase) entry.getMatchEntryValue());
- vlanMatch.setVlanPcp(new org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanPcp(vlanPcpCase.getVlanPcp().getVlanPcp()));
- }
- } else if (field.equals(IpDscp.class) || field.equals(IpEcn.class) || field.equals(IpProto.class)) {
- if (ipMatch == null) {
- ipMatch = new IpMatchBuilder();
- }
- if (field.equals(IpDscp.class)) {
- IpDscpCase ipDscpCase = ((IpDscpCase) entry.getMatchEntryValue());
- ipMatch.setIpDscp(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Dscp(
- ipDscpCase.getIpDscp().getDscp()));
- } else if (field.equals(IpEcn.class)) {
- IpEcnCase ipEcnCase = ((IpEcnCase) entry.getMatchEntryValue());
- ipMatch.setIpEcn(ipEcnCase.getIpEcn().getEcn());
- } else if (field.equals(IpProto.class)) {
- IpProtoCase ipProtoCase = ((IpProtoCase) entry.getMatchEntryValue());
- ipMatch.setIpProtocol(ipProtoCase.getIpProto().getProtocolNumber());
- }
- } else if (field.equals(TcpSrc.class) || field.equals(TcpDst.class)) {
- if (tcpMatch == null) {
- tcpMatch = new TcpMatchBuilder();
- }
- if (field.equals(TcpSrc.class)) {
- TcpSrcCase tcpSrcCase = ((TcpSrcCase) entry.getMatchEntryValue());
- tcpMatch.setTcpSourcePort(new PortNumber(tcpSrcCase.getTcpSrc().getPort().getValue()));
- } else if (field.equals(TcpDst.class)) {
- TcpDstCase tcpDstCase = ((TcpDstCase) entry.getMatchEntryValue());
- tcpMatch.setTcpDestinationPort(new PortNumber(tcpDstCase.getTcpDst().getPort().getValue()));
- }
- } else if (field.equals(UdpSrc.class) || field.equals(UdpDst.class)) {
- if (udpMatch == null) {
- udpMatch = new UdpMatchBuilder();
- }
- if (field.equals(UdpSrc.class)) {
- UdpSrcCase udpSrcCase = ((UdpSrcCase) entry.getMatchEntryValue());
- udpMatch.setUdpSourcePort(new PortNumber(udpSrcCase.getUdpSrc().getPort().getValue()));
- } else if (field.equals(UdpDst.class)) {
- UdpDstCase udpDstCase = ((UdpDstCase) entry.getMatchEntryValue());
- udpMatch.setUdpDestinationPort(new PortNumber(udpDstCase.getUdpDst().getPort()));
- }
- } else if (field.equals(SctpSrc.class) || field.equals(SctpDst.class)) {
- if (sctpMatch == null) {
- sctpMatch = new SctpMatchBuilder();
- }
- if (field.equals(SctpSrc.class)) {
- SctpSrcCase sctpSrcCase = ((SctpSrcCase) entry.getMatchEntryValue());
- sctpMatch.setSctpSourcePort(new PortNumber(sctpSrcCase.getSctpSrc().getPort()));
- } else if (field.equals(SctpDst.class)) {
- SctpDstCase sctpDstCase = ((SctpDstCase) entry.getMatchEntryValue());
- sctpMatch.setSctpDestinationPort(new PortNumber(sctpDstCase.getSctpDst().getPort()));
- }
- } else if (field.equals(Icmpv4Type.class) || field.equals(Icmpv4Code.class)) {
- if (icmpv4Match == null) {
- icmpv4Match = new Icmpv4MatchBuilder();
- }
- if (field.equals(Icmpv4Type.class)) {
- Icmpv4TypeCase icmpv4TypeCase = ((Icmpv4TypeCase) entry.getMatchEntryValue());
- icmpv4Match.setIcmpv4Type(icmpv4TypeCase.getIcmpv4Type().getIcmpv4Type());
- } else if (field.equals(Icmpv4Code.class)) {
- Icmpv4CodeCase icmpv4CodeCase = ((Icmpv4CodeCase) entry.getMatchEntryValue());
- icmpv4Match.setIcmpv4Code(icmpv4CodeCase.getIcmpv4Code().getIcmpv4Code());
- }
- } else if (field.equals(Icmpv6Type.class) || field.equals(Icmpv6Code.class)) {
- if (icmpv6Match == null) {
- icmpv6Match = new Icmpv6MatchBuilder();
- }
- if (field.equals(Icmpv6Type.class)) {
- Icmpv6TypeCase icmpv6TypeCase = ((Icmpv6TypeCase) entry.getMatchEntryValue());
- icmpv6Match.setIcmpv6Type(icmpv6TypeCase.getIcmpv6Type().getIcmpv6Type());
- } else if (field.equals(Icmpv6Code.class)) {
- Icmpv6CodeCase icmpv6CodeCase = ((Icmpv6CodeCase) entry.getMatchEntryValue());
- icmpv6Match.setIcmpv6Code(icmpv6CodeCase.getIcmpv6Code().getIcmpv6Code());
- }
- } else if (field.equals(Ipv4Src.class) || field.equals(Ipv4Dst.class)) {
- if (ipv4Match == null) {
- ipv4Match = new Ipv4MatchBuilder();
- }
- if (field.equals(Ipv4Src.class)) {
- Ipv4SrcCase ipv4SrcCase = ((Ipv4SrcCase) entry.getMatchEntryValue());
- int prefix;
- if (entry.isHasMask()) {
- prefix = IpConversionUtil.countBits(ipv4SrcCase.getIpv4Src().getMask());
- } else {
- prefix = 32;
- }
- ipv4Match.setIpv4Source(
- IpConversionUtil.createPrefix(ipv4SrcCase.getIpv4Src().getIpv4Address(), prefix)
- );
-
- } else if (field.equals(Ipv4Dst.class)) {
- Ipv4DstCase ipv4DstCase = ((Ipv4DstCase) entry.getMatchEntryValue());
- int prefix;
- if (entry.isHasMask()) {
- prefix = IpConversionUtil.countBits(ipv4DstCase.getIpv4Dst().getMask());
- } else {
- prefix = 32;
- }
- ipv4Match.setIpv4Destination(
- IpConversionUtil.createPrefix(ipv4DstCase.getIpv4Dst().getIpv4Address(), prefix)
- );
- }
- } else if (field.equals(ArpOp.class) || field.equals(ArpSpa.class) || field.equals(ArpTpa.class)
- || field.equals(ArpSha.class) || field.equals(ArpTha.class)) {
- if (arpMatch == null) {
- arpMatch = new ArpMatchBuilder();
- }
- if (field.equals(ArpOp.class)) {
- ArpOpCase arpOpCase = ((ArpOpCase) entry.getMatchEntryValue());
- arpMatch.setArpOp(arpOpCase.getArpOp().getOpCode());
- } else if (field.equals(ArpSpa.class)) {
-
- ArpSpaCase arpSpaCase = ((ArpSpaCase) entry.getMatchEntryValue());
- int prefix;
- if (entry.isHasMask()) {
- prefix = IpConversionUtil.countBits(arpSpaCase.getArpSpa().getMask());
- } else {
- prefix = 32;
- }
- arpMatch.setArpSourceTransportAddress(
- IpConversionUtil.createPrefix(arpSpaCase.getArpSpa().getIpv4Address(), prefix)
- );
- } else if (field.equals(ArpTpa.class)) {
- ArpTpaCase arpTpaCase = ((ArpTpaCase) entry.getMatchEntryValue());
- int prefix;
- if (entry.isHasMask()) {
- prefix = IpConversionUtil.countBits(arpTpaCase.getArpTpa().getMask());
- } else {
- prefix = 32;
- }
-
- arpMatch.setArpTargetTransportAddress(
- IpConversionUtil.createPrefix(arpTpaCase.getArpTpa().getIpv4Address(), prefix)
- );
- } else if (field.equals(ArpSha.class)) {
- ArpSourceHardwareAddressBuilder arpSha = new ArpSourceHardwareAddressBuilder();
- ArpShaCase arpShaCase = ((ArpShaCase) entry.getMatchEntryValue());
- arpSha.setAddress(arpShaCase.getArpSha().getMacAddress());
- if (entry.isHasMask()) {
- arpSha.setMask(new MacAddress(ByteUtil.bytesToHexstring(arpShaCase.getArpSha().getMask(), ":")));
- }
- arpMatch.setArpSourceHardwareAddress(arpSha.build());
- } else if (field.equals(ArpTha.class)) {
- ArpThaCase arpThaCase = ((ArpThaCase) entry.getMatchEntryValue());
- ArpTargetHardwareAddressBuilder arpTha = new ArpTargetHardwareAddressBuilder();
- arpTha.setAddress(arpThaCase.getArpTha().getMacAddress());
- if (entry.isHasMask()) {
- arpTha.setMask(new MacAddress(ByteUtil.bytesToHexstring(arpThaCase.getArpTha().getMask(), ":")));
- }
- arpMatch.setArpTargetHardwareAddress(arpTha.build());
- }
- } else if (field.equals(TunnelIpv4Src.class) || field.equals(TunnelIpv4Dst.class)) {
- if (ipv4Match == null) {
- ipv4Match = new Ipv4MatchBuilder();
- }
- if (field.equals(TunnelIpv4Src.class)) {
- Ipv4SrcCase ipv4SrcCase = ((Ipv4SrcCase) entry.getMatchEntryValue());
- int prefix;
- if (entry.isHasMask()) {
- prefix = IpConversionUtil.countBits(ipv4SrcCase.getIpv4Src().getMask());
- } else {
- prefix = 32;
- }
-
- ipv4Match.setIpv4Source(
- IpConversionUtil.createPrefix(ipv4SrcCase.getIpv4Src().getIpv4Address(), prefix)
- );
- } else if (field.equals(TunnelIpv4Dst.class)) {
- Ipv4DstCase ipv4DstCase = ((Ipv4DstCase) entry.getMatchEntryValue());
- int prefix;
- if (entry.isHasMask()) {
- prefix = IpConversionUtil.countBits(ipv4DstCase.getIpv4Dst().getMask());
- } else {
- prefix = 32;
- }
-
- ipv4Match.setIpv4Destination(
- IpConversionUtil.createPrefix(ipv4DstCase.getIpv4Dst().getIpv4Address(), prefix)
- ); }
- } else if (field.equals(Ipv6Src.class) || field.equals(Ipv6Dst.class) || field.equals(Ipv6Flabel.class)
- || field.equals(Ipv6NdTarget.class) || field.equals(Ipv6NdSll.class)
- || field.equals(Ipv6NdTll.class) || field.equals(Ipv6Exthdr.class)) {
- if (ipv6Match == null) {
- ipv6Match = new Ipv6MatchBuilder();
- }
- if (field.equals(Ipv6Src.class)) {
- Ipv6SrcCase ipv6SrcCase = ((Ipv6SrcCase) entry.getMatchEntryValue());
- int prefix ;
- if (entry.isHasMask()) {
- prefix = IpConversionUtil.countBits(ipv6SrcCase.getIpv6Src().getMask());
- } else {
- prefix = 128;
- }
- ipv6Match.setIpv6Source(
- IpConversionUtil.createPrefix(ipv6SrcCase.getIpv6Src().getIpv6Address(), prefix)
- );
- } else if (field.equals(Ipv6Dst.class)) {
- Ipv6DstCase ipv6DstCase = ((Ipv6DstCase) entry.getMatchEntryValue());
- int prefix;
- if (entry.isHasMask()) {
- prefix = IpConversionUtil.countBits(ipv6DstCase.getIpv6Dst().getMask());
- } else {
- prefix = 128;
- }
- ipv6Match.setIpv6Destination(
- IpConversionUtil.createPrefix(ipv6DstCase.getIpv6Dst().getIpv6Address(), prefix)
- );
- } else if (field.equals(Ipv6Flabel.class)) {
- Ipv6LabelBuilder ipv6Label = new Ipv6LabelBuilder();
- Ipv6FlabelCase ipv6FlabelCase = ((Ipv6FlabelCase) entry.getMatchEntryValue());
- ipv6Label.setIpv6Flabel(ipv6FlabelCase.getIpv6Flabel().getIpv6Flabel());
- if (entry.isHasMask()) {
- ipv6Label.setFlabelMask(new Ipv6FlowLabel(ByteUtil.bytesToUnsignedInt(ipv6FlabelCase.getIpv6Flabel().getMask())));
- }
- ipv6Match.setIpv6Label(ipv6Label.build());
- } else if (field.equals(Ipv6NdTarget.class)) {
- Ipv6NdTargetCase ipv6NdTargetCase = ((Ipv6NdTargetCase) entry.getMatchEntryValue());
- ipv6Match.setIpv6NdTarget(ipv6NdTargetCase.getIpv6NdTarget().getIpv6Address());
- } else if (field.equals(Ipv6NdSll.class)) {
- Ipv6NdSllCase ipv6NdSllCase = ((Ipv6NdSllCase) entry.getMatchEntryValue());
- ipv6Match.setIpv6NdSll(ipv6NdSllCase.getIpv6NdSll().getMacAddress());
- } else if (field.equals(Ipv6NdTll.class)) {
- Ipv6NdTllCase ipv6NdTllCase = ((Ipv6NdTllCase) entry.getMatchEntryValue());
- ipv6Match.setIpv6NdTll(ipv6NdTllCase.getIpv6NdTll().getMacAddress());
- } else if (field.equals(Ipv6Exthdr.class)) {
- Ipv6ExthdrCase ipv6ExthdrCase = ((Ipv6ExthdrCase) entry.getMatchEntryValue());
- // verify
- Ipv6ExtHeaderBuilder ipv6ExtHeaderBuilder = new Ipv6ExtHeaderBuilder();
- Ipv6ExthdrFlags pseudoField = ipv6ExthdrCase.getIpv6Exthdr().getPseudoField();
- Map<Integer, Boolean> map = new HashMap<>();
- map.put(0, pseudoField.isNonext());
- map.put(1, pseudoField.isEsp());
- map.put(2, pseudoField.isAuth());
- map.put(3, pseudoField.isDest());
- map.put(4, pseudoField.isFrag());
- map.put(5, pseudoField.isRouter());
- map.put(6, pseudoField.isHop());
- map.put(7, pseudoField.isUnrep());
- map.put(8, pseudoField.isUnseq());
- int bitmap = ByteBufUtils.fillBitMaskFromMap(map);
- ipv6ExtHeaderBuilder.setIpv6Exthdr(bitmap);
- if (entry.isHasMask()) {
- ipv6ExtHeaderBuilder.setIpv6ExthdrMask(
- ByteUtil.bytesToUnsignedShort(ipv6ExthdrCase.getIpv6Exthdr().getMask()));
- }
- ipv6Match.setIpv6ExtHeader(ipv6ExtHeaderBuilder.build());
- }
- } else if (field.equals(MplsLabel.class) || field.equals(MplsTc.class) || field.equals(MplsBos.class)
- || field.equals(PbbIsid.class)) {
- if (protocolMatchFields == null) {
- protocolMatchFields = new ProtocolMatchFieldsBuilder();
- }
- if (field.equals(MplsLabel.class)) {
- MplsLabelCase mplsLabelCase = ((MplsLabelCase) entry.getMatchEntryValue());
- protocolMatchFields.setMplsLabel(mplsLabelCase.getMplsLabel().getMplsLabel());
- } else if (field.equals(MplsTc.class)) {
- MplsTcCase mplsTcCase = ((MplsTcCase) entry.getMatchEntryValue());
- protocolMatchFields.setMplsTc(mplsTcCase.getMplsTc().getTc());
- } else if (field.equals(MplsBos.class)) {
- MplsBosCase mplsBosCase = ((MplsBosCase) entry.getMatchEntryValue());
- protocolMatchFields
- .setMplsBos((short) (mplsBosCase.getMplsBos().isBos() ? 1 : 0));
- } else if (field.equals(PbbIsid.class)) {
- PbbIsidCase pbbIsidCase = ((PbbIsidCase) entry.getMatchEntryValue());
- PbbBuilder pbb = new PbbBuilder();
- pbb.setPbbIsid(pbbIsidCase.getPbbIsid().getIsid());
- if (entry.isHasMask()) {
- pbb.setPbbMask(ByteUtil.bytesToUnsignedInt(pbbIsidCase.getPbbIsid().getMask()));
- }
- protocolMatchFields.setPbb(pbb.build());
- }
- } else if (field.equals(TunnelId.class)) {
- TunnelIdCase tunnelIdCase = ((TunnelIdCase) entry.getMatchEntryValue());
- TunnelBuilder tunnel = new TunnelBuilder();
- tunnel.setTunnelId(new BigInteger(OFConstants.SIGNUM_UNSIGNED, tunnelIdCase.getTunnelId().getTunnelId()));
- if (entry.isHasMask()) {
- tunnel.setTunnelMask(new BigInteger(OFConstants.SIGNUM_UNSIGNED, tunnelIdCase.getTunnelId().getMask()));
- }
- matchBuilder.setTunnel(tunnel.build());
- }
- }
-
- AugmentTuple<Match> matchExtensionWrap =
- MatchExtensionHelper.processAllExtensions(
- ofMatch.getMatchEntry(), ofVersion, MatchPath.SWITCHFLOWREMOVED_MATCH);
- if (matchExtensionWrap != null) {
- matchBuilder.addAugmentation(matchExtensionWrap.getAugmentationClass(), matchExtensionWrap.getAugmentationObject());
- }
-
-
- if (ethernetMatch != null) {
- matchBuilder.setEthernetMatch(ethernetMatch.build());
- }
- if (vlanMatch != null) {
- matchBuilder.setVlanMatch(vlanMatch.build());
- }
- if (ipMatch != null) {
- matchBuilder.setIpMatch(ipMatch.build());
- }
-
- if (tcpMatch != null) {
- matchBuilder.setLayer4Match(tcpMatch.build());
- } else if (udpMatch != null) {
- matchBuilder.setLayer4Match(udpMatch.build());
- } else if (sctpMatch != null) {
- matchBuilder.setLayer4Match(sctpMatch.build());
- }
-
- if (icmpv4Match != null) {
- matchBuilder.setIcmpv4Match(icmpv4Match.build());
- } else if (icmpv6Match != null) {
- matchBuilder.setIcmpv6Match(icmpv6Match.build());
- }
-
- if (ipv4Match != null) {
- matchBuilder.setLayer3Match(ipv4Match.build());
- } else if (arpMatch != null) {
- matchBuilder.setLayer3Match(arpMatch.build());
- } else if (ipv6Match != null) {
- matchBuilder.setLayer3Match(ipv6Match.build());
- }
- if (protocolMatchFields != null) {
- matchBuilder.setProtocolMatchFields(protocolMatchFields.build());
- }
- return matchBuilder.build();
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyDescCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.desc._case.MultipartReplyDesc;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MultiPartMessageDescToNodeUpdatedTranslator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
- private static final Logger LOG = LoggerFactory.getLogger(MultiPartMessageDescToNodeUpdatedTranslator.class);
- @Override
- public List<DataObject> translate(SwitchConnectionDistinguisher cookie,
- SessionContext sc, OfHeader msg) {
- if(msg instanceof MultipartReply && ((MultipartReply) msg).getType() == MultipartType.OFPMPDESC) {
- LOG.debug("MultipartReplyMessage - MultipartReplyDesc Being translated to NodeUpdated ");
- MultipartReplyMessage message = (MultipartReplyMessage) msg;
- List<DataObject> list = new CopyOnWriteArrayList<DataObject>();
- BigInteger datapathId = sc.getFeatures().getDatapathId();
- NodeUpdatedBuilder builder = InventoryDataServiceUtil.nodeUpdatedBuilderFromDataPathId(datapathId);
- FlowCapableNodeUpdatedBuilder fnub = new FlowCapableNodeUpdatedBuilder();
- MultipartReplyDescCase caseBody = (MultipartReplyDescCase) message.getMultipartReplyBody();
- MultipartReplyDesc body = caseBody.getMultipartReplyDesc();
- fnub.setHardware(body.getHwDesc());
- fnub.setManufacturer(body.getMfrDesc());
- fnub.setSerialNumber(body.getSerialNum());
- fnub.setDescription(body.getDpDesc());
- fnub.setSoftware(body.getSwDesc());
- builder.addAugmentation(FlowCapableNodeUpdated.class, fnub.build());
- NodeUpdated nodeUpdated = builder.build();
- list.add(nodeUpdated);
- return list;
- } else {
- return Collections.emptyList();
- }
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.util.PortTranslatorUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortDescCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.MultipartReplyPortDesc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.multipart.reply.port.desc.Ports;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MultiPartReplyPortToNodeConnectorUpdatedTranslator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
- private static final Logger LOG = LoggerFactory.getLogger(MultiPartReplyPortToNodeConnectorUpdatedTranslator.class);
- @Override
- public List<DataObject> translate(SwitchConnectionDistinguisher cookie,
- SessionContext sc, OfHeader msg) {
- if(msg instanceof MultipartReply && ((MultipartReply) msg).getType() == MultipartType.OFPMPPORTDESC) {
- BigInteger datapathId = sc.getFeatures().getDatapathId();
- LOG.trace("MultiPartReplyPortToNodeConnectorUpdatedTranslator Being translated to NodeConnectorUpdated ");
- MultipartReplyMessage message = (MultipartReplyMessage) msg;
- MultipartReplyPortDescCase caseBody = (MultipartReplyPortDescCase) message.getMultipartReplyBody();
- MultipartReplyPortDesc body = caseBody.getMultipartReplyPortDesc();
- List<DataObject> list = new CopyOnWriteArrayList<DataObject>();
- for ( Ports port : body.getPorts() ) {
- LOG.debug("Port: " + port);
- list.add(PortTranslatorUtil.translatePort(msg.getVersion(), datapathId, port.getPortNo(), port));
- }
- return list;
- } else {
- return Collections.emptyList();
- }
- }
-
-
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2014 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-import java.util.concurrent.CopyOnWriteArrayList;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionConvertorData;
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableFeaturesCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.TableUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MultipartReplyTableFeaturesToTableUpdatedTranslator implements
- IMDMessageTranslator<OfHeader, List<DataObject>> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(MultipartReplyTableFeaturesToTableUpdatedTranslator.class);
- private final ConvertorExecutor convertorExecutor;
-
- public MultipartReplyTableFeaturesToTableUpdatedTranslator(ConvertorExecutor convertorExecutor) {
- this.convertorExecutor = convertorExecutor;
- }
-
- @Override
- public List<DataObject> translate(SwitchConnectionDistinguisher cookie, SessionContext sc, OfHeader msg) {
- if (msg instanceof MultipartReply && ((MultipartReply) msg).getType() == MultipartType.OFPMPTABLEFEATURES) {
- LOG.debug("MultipartReply Being translated to TableUpdated ");
- MultipartReplyMessage mpReply = (MultipartReplyMessage) msg;
-
- List<DataObject> listDataObject = new CopyOnWriteArrayList<>();
-
- TableUpdatedBuilder message = new TableUpdatedBuilder();
- message.setNode((new NodeRef(InventoryDataServiceUtil.identifierFromDatapathId(sc.getFeatures()
- .getDatapathId()))));
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(new TransactionId(BigInteger.valueOf(mpReply.getXid())));
- MultipartReplyTableFeaturesCase caseBody = (MultipartReplyTableFeaturesCase) mpReply.getMultipartReplyBody();
- MultipartReplyTableFeatures body = caseBody.getMultipartReplyTableFeatures();
-
- final VersionConvertorData data = new VersionConvertorData(sc.getPrimaryConductor().getVersion());
- final Optional<List<TableFeatures>> tableFeaturesList = convertorExecutor.convert(body, data);
- message.setTableFeatures(tableFeaturesList.orElse(Collections.emptyList()));
- listDataObject.add( message.build()) ;
-
- return listDataObject ;
-
- }
- return Collections.emptyList();
-
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2013, 2015 IBM 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.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-import java.util.concurrent.CopyOnWriteArrayList;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
-import org.opendaylight.openflowplugin.extension.api.path.MatchPath;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.FlowStatsResponseConvertorData;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionDatapathIdConvertorData;
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Counter32;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Counter64;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.AggregateFlowStatisticsUpdateBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdateBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.and.statistics.map.list.FlowAndStatisticsMapList;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsUpdateBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.and.statistics.map.FlowTableAndStatisticsMap;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.and.statistics.map.FlowTableAndStatisticsMapBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.queue.rev130925.QueueId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupDescStatsUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupFeaturesUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupStatisticsUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.Chaining;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.ChainingChecks;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupAll;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupCapability;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupFf;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupIndirect;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupSelect;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.SelectLiveness;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.SelectWeight;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.desc.stats.reply.GroupDescStats;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.statistics.reply.GroupStats;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterConfigStatsUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterFeaturesUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterStatisticsUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBand;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBandDrop;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBandDscpRemark;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBurst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterCapability;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterKbps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterPktps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterStats;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.config.stats.reply.MeterConfigStats;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.statistics.types.rev130925.duration.DurationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.statistics.types.rev130925.node.connector.statistics.BytesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.statistics.types.rev130925.node.connector.statistics.PacketsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyAggregateCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyFlowCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupDescCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupFeaturesCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterConfigCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterFeaturesCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortStatsCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyQueueCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.aggregate._case.MultipartReplyAggregate;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.MultipartReplyFlow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.MultipartReplyGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.desc._case.MultipartReplyGroupDesc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.features._case.MultipartReplyGroupFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.MultipartReplyMeter;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.MultipartReplyMeterConfig;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.features._case.MultipartReplyMeterFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.stats._case.MultipartReplyPortStats;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.stats._case.multipart.reply.port.stats.PortStats;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.queue._case.MultipartReplyQueue;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.queue._case.multipart.reply.queue.QueueStats;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table._case.MultipartReplyTable;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table._case.multipart.reply.table.TableStats;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdateBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMap;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMapBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMapKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.QueueStatisticsUpdateBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMap;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMapBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Class converts multipart reply messages to the notification objects defined
- * by statistics provider (manager ).
- *
- * @author avishnoi@in.ibm.com
- *
- */
-public class MultipartReplyTranslator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
-
- protected static final Logger LOG = LoggerFactory
- .getLogger(MultipartReplyTranslator.class);
- private final ConvertorExecutor convertorExecutor;
-
- public MultipartReplyTranslator(ConvertorExecutor convertorExecutor) {
- this.convertorExecutor = convertorExecutor;
- }
-
-
- @Override
- public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sc, final OfHeader msg) {
-
- List<DataObject> listDataObject = new CopyOnWriteArrayList<DataObject>();
-
- OpenflowVersion ofVersion = OpenflowVersion.get(sc.getPrimaryConductor().getVersion());
- final VersionDatapathIdConvertorData data = new VersionDatapathIdConvertorData(sc.getPrimaryConductor().getVersion());
- data.setDatapathId(sc.getFeatures().getDatapathId());
-
- if(msg instanceof MultipartReplyMessage){
- MultipartReplyMessage mpReply = (MultipartReplyMessage)msg;
- NodeId node = MultipartReplyTranslator.nodeIdFromDatapathId(sc.getFeatures().getDatapathId());
- switch (mpReply.getType()){
- case OFPMPFLOW: {
- LOG.debug("Received flow statistics reponse from openflow {} switch",msg.getVersion()==1?"1.0":"1.3+");
- FlowStatsResponseConvertorData flowData = new FlowStatsResponseConvertorData(data.getVersion());
- flowData.setDatapathId(data.getDatapathId());
- flowData.setMatchPath(MatchPath.FLOWSSTATISTICSUPDATE_FLOWANDSTATISTICSMAPLIST_MATCH);
- FlowsStatisticsUpdateBuilder message = new FlowsStatisticsUpdateBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
- MultipartReplyFlowCase caseBody = (MultipartReplyFlowCase)mpReply.getMultipartReplyBody();
- MultipartReplyFlow replyBody = caseBody.getMultipartReplyFlow();
-
- final Optional<List<FlowAndStatisticsMapList>> flowAndStatisticsMapLists = convertorExecutor.convert(replyBody.getFlowStats(), flowData);
-
- message.setFlowAndStatisticsMapList(flowAndStatisticsMapLists.orElse(Collections.emptyList()));
- LOG.debug("Converted flow statistics : {}",message.build().toString());
- listDataObject.add(message.build());
- return listDataObject;
- }
- case OFPMPAGGREGATE: {
- LOG.debug("Received aggregate flow statistics reponse from openflow {} switch",msg.getVersion()==1?"1.0":"1.3+");
- AggregateFlowStatisticsUpdateBuilder message = new AggregateFlowStatisticsUpdateBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
-
- MultipartReplyAggregateCase caseBody = (MultipartReplyAggregateCase)mpReply.getMultipartReplyBody();
- MultipartReplyAggregate replyBody = caseBody.getMultipartReplyAggregate();
- message.setByteCount(new Counter64(replyBody.getByteCount()));
- message.setPacketCount(new Counter64(replyBody.getPacketCount()));
- message.setFlowCount(new Counter32(replyBody.getFlowCount()));
-
- LOG.debug("Converted aggregate flow statistics : {}",message.build().toString());
- listDataObject.add(message.build());
- return listDataObject;
- }
- case OFPMPPORTSTATS: {
-
- LOG.debug("Received port statistics multipart response");
-
- NodeConnectorStatisticsUpdateBuilder message = new NodeConnectorStatisticsUpdateBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
-
- MultipartReplyPortStatsCase caseBody = (MultipartReplyPortStatsCase)mpReply.getMultipartReplyBody();
- MultipartReplyPortStats replyBody = caseBody.getMultipartReplyPortStats();
-
- List<NodeConnectorStatisticsAndPortNumberMap> statsMap =
- new ArrayList<NodeConnectorStatisticsAndPortNumberMap>();
- for (PortStats portStats: replyBody.getPortStats()){
-
- NodeConnectorStatisticsAndPortNumberMapBuilder statsBuilder =
- new NodeConnectorStatisticsAndPortNumberMapBuilder();
- statsBuilder.setNodeConnectorId(
- InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(sc.getFeatures().getDatapathId(),
- portStats.getPortNo(), ofVersion));
-
- BytesBuilder bytesBuilder = new BytesBuilder();
- bytesBuilder.setReceived(portStats.getRxBytes());
- bytesBuilder.setTransmitted(portStats.getTxBytes());
- statsBuilder.setBytes(bytesBuilder.build());
-
- PacketsBuilder packetsBuilder = new PacketsBuilder();
- packetsBuilder.setReceived(portStats.getRxPackets());
- packetsBuilder.setTransmitted(portStats.getTxPackets());
- statsBuilder.setPackets(packetsBuilder.build());
-
- DurationBuilder durationBuilder = new DurationBuilder();
- if (portStats.getDurationSec() != null) {
- durationBuilder.setSecond(new Counter32(portStats.getDurationSec()));
- }
- if (portStats.getDurationNsec() != null) {
- durationBuilder.setNanosecond(new Counter32(portStats.getDurationNsec()));
- }
- statsBuilder.setDuration(durationBuilder.build());
- statsBuilder.setCollisionCount(portStats.getCollisions());
- statsBuilder.setKey(new NodeConnectorStatisticsAndPortNumberMapKey(statsBuilder.getNodeConnectorId()));
- statsBuilder.setReceiveCrcError(portStats.getRxCrcErr());
- statsBuilder.setReceiveDrops(portStats.getRxDropped());
- statsBuilder.setReceiveErrors(portStats.getRxErrors());
- statsBuilder.setReceiveFrameError(portStats.getRxFrameErr());
- statsBuilder.setReceiveOverRunError(portStats.getRxOverErr());
- statsBuilder.setTransmitDrops(portStats.getTxDropped());
- statsBuilder.setTransmitErrors(portStats.getTxErrors());
-
- statsMap.add(statsBuilder.build());
- }
- message.setNodeConnectorStatisticsAndPortNumberMap(statsMap);
-
- LOG.debug("Converted ports statistics : {}",message.build().toString());
-
- listDataObject.add(message.build());
- return listDataObject;
- }
- case OFPMPGROUP:{
- LOG.debug("Received group statistics multipart reponse");
- GroupStatisticsUpdatedBuilder message = new GroupStatisticsUpdatedBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
- MultipartReplyGroupCase caseBody = (MultipartReplyGroupCase)mpReply.getMultipartReplyBody();
- MultipartReplyGroup replyBody = caseBody.getMultipartReplyGroup();
- final Optional<List<GroupStats>> groupStatsList = convertorExecutor.convert(replyBody.getGroupStats(), data);
- message.setGroupStats(groupStatsList.orElse(Collections.emptyList()));
- LOG.debug("Converted group statistics : {}",message.toString());
- listDataObject.add(message.build());
- return listDataObject;
- }
- case OFPMPGROUPDESC:{
- LOG.debug("Received group description statistics multipart reponse");
-
- GroupDescStatsUpdatedBuilder message = new GroupDescStatsUpdatedBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
- MultipartReplyGroupDescCase caseBody = (MultipartReplyGroupDescCase)mpReply.getMultipartReplyBody();
- MultipartReplyGroupDesc replyBody = caseBody.getMultipartReplyGroupDesc();
-
- final Optional<List<GroupDescStats>> groupDescStatsList = convertorExecutor.convert(replyBody.getGroupDesc(), data);
- message.setGroupDescStats(groupDescStatsList.orElse(Collections.emptyList()));
- LOG.debug("Converted group statistics : {}",message.toString());
- listDataObject.add(message.build());
- return listDataObject;
- }
- case OFPMPGROUPFEATURES: {
- LOG.debug("Received group features multipart reponse");
- GroupFeaturesUpdatedBuilder message = new GroupFeaturesUpdatedBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
- MultipartReplyGroupFeaturesCase caseBody = (MultipartReplyGroupFeaturesCase)mpReply.getMultipartReplyBody();
- MultipartReplyGroupFeatures replyBody = caseBody.getMultipartReplyGroupFeatures();
- List<Class<? extends GroupType>> supportedGroups =
- new ArrayList<Class<? extends GroupType>>();
-
- if(replyBody.getTypes().isOFPGTALL()){
- supportedGroups.add(GroupAll.class);
- }
- if(replyBody.getTypes().isOFPGTSELECT()){
- supportedGroups.add(GroupSelect.class);
- }
- if(replyBody.getTypes().isOFPGTINDIRECT()){
- supportedGroups.add(GroupIndirect.class);
- }
- if(replyBody.getTypes().isOFPGTFF()){
- supportedGroups.add(GroupFf.class);
- }
- message.setGroupTypesSupported(supportedGroups);
- message.setMaxGroups(replyBody.getMaxGroups());
-
- List<Class<? extends GroupCapability>> supportedCapabilities =
- new ArrayList<Class<? extends GroupCapability>>();
-
- if(replyBody.getCapabilities().isOFPGFCCHAINING()){
- supportedCapabilities.add(Chaining.class);
- }
- if(replyBody.getCapabilities().isOFPGFCCHAININGCHECKS()){
- supportedCapabilities.add(ChainingChecks.class);
- }
- if(replyBody.getCapabilities().isOFPGFCSELECTLIVENESS()){
- supportedCapabilities.add(SelectLiveness.class);
- }
- if(replyBody.getCapabilities().isOFPGFCSELECTWEIGHT()){
- supportedCapabilities.add(SelectWeight.class);
- }
-
- message.setGroupCapabilitiesSupported(supportedCapabilities);
-
- message.setActions(getGroupActionsSupportBitmap(replyBody.getActionsBitmap()));
- listDataObject.add(message.build());
-
- return listDataObject;
- }
- case OFPMPMETER: {
- LOG.debug("Received meter statistics multipart reponse");
- MeterStatisticsUpdatedBuilder message = new MeterStatisticsUpdatedBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
-
- MultipartReplyMeterCase caseBody = (MultipartReplyMeterCase)mpReply.getMultipartReplyBody();
- MultipartReplyMeter replyBody = caseBody.getMultipartReplyMeter();
-
- final Optional<List<org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply.MeterStats>> meterStatsList =
- convertorExecutor.convert(replyBody.getMeterStats(), data);
-
- message.setMeterStats(meterStatsList.orElse(Collections.emptyList()));
- listDataObject.add(message.build());
- return listDataObject;
- }
- case OFPMPMETERCONFIG:{
- LOG.debug("Received meter config statistics multipart reponse");
-
- MeterConfigStatsUpdatedBuilder message = new MeterConfigStatsUpdatedBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
-
- MultipartReplyMeterConfigCase caseBody = (MultipartReplyMeterConfigCase)mpReply.getMultipartReplyBody();
- MultipartReplyMeterConfig replyBody = caseBody.getMultipartReplyMeterConfig();
-
- final Optional<List<MeterConfigStats>> meterConfigStatsList = convertorExecutor.convert(replyBody.getMeterConfig(), data);
-
- message.setMeterConfigStats(meterConfigStatsList.orElse(Collections.emptyList()));
- listDataObject.add(message.build());
- return listDataObject;
- }
- case OFPMPMETERFEATURES:{
- LOG.debug("Received meter features multipart reponse");
- //Convert OF message and send it to SAL listener
- MeterFeaturesUpdatedBuilder message = new MeterFeaturesUpdatedBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
-
- MultipartReplyMeterFeaturesCase caseBody = (MultipartReplyMeterFeaturesCase)mpReply.getMultipartReplyBody();
- MultipartReplyMeterFeatures replyBody = caseBody.getMultipartReplyMeterFeatures();
- message.setMaxBands(replyBody.getMaxBands());
- message.setMaxColor(replyBody.getMaxColor());
- message.setMaxMeter(new Counter32(replyBody.getMaxMeter()));
-
- List<Class<? extends MeterCapability>> supportedCapabilities =
- new ArrayList<Class<? extends MeterCapability>>();
- if(replyBody.getCapabilities().isOFPMFBURST()){
- supportedCapabilities.add(MeterBurst.class);
- }
- if(replyBody.getCapabilities().isOFPMFKBPS()){
- supportedCapabilities.add(MeterKbps.class);
-
- }
- if(replyBody.getCapabilities().isOFPMFPKTPS()){
- supportedCapabilities.add(MeterPktps.class);
-
- }
- if(replyBody.getCapabilities().isOFPMFSTATS()){
- supportedCapabilities.add(MeterStats.class);
-
- }
- message.setMeterCapabilitiesSupported(supportedCapabilities);
-
- List<Class<? extends MeterBand>> supportedMeterBand =
- new ArrayList<Class <? extends MeterBand>>();
- if(replyBody.getBandTypes().isOFPMBTDROP()){
- supportedMeterBand.add(MeterBandDrop.class);
- }
- if(replyBody.getBandTypes().isOFPMBTDSCPREMARK()){
- supportedMeterBand.add(MeterBandDscpRemark.class);
- }
- message.setMeterBandSupported(supportedMeterBand);
- listDataObject.add(message.build());
-
- return listDataObject;
- }
- case OFPMPTABLE: {
- LOG.debug("Received flow table statistics reponse from openflow {} switch",msg.getVersion()==1?"1.0":"1.3+");
-
- FlowTableStatisticsUpdateBuilder message = new FlowTableStatisticsUpdateBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
-
- MultipartReplyTableCase caseBody = (MultipartReplyTableCase)mpReply.getMultipartReplyBody();
- MultipartReplyTable replyBody = caseBody.getMultipartReplyTable();
- List<TableStats> swTablesStats = replyBody.getTableStats();
-
- List<FlowTableAndStatisticsMap> salFlowStats = new ArrayList<FlowTableAndStatisticsMap>();
- for(TableStats swTableStats : swTablesStats){
- FlowTableAndStatisticsMapBuilder statisticsBuilder = new FlowTableAndStatisticsMapBuilder();
-
- statisticsBuilder.setActiveFlows(new Counter32(swTableStats.getActiveCount()));
- statisticsBuilder.setPacketsLookedUp(new Counter64(swTableStats.getLookupCount()));
- statisticsBuilder.setPacketsMatched(new Counter64(swTableStats.getMatchedCount()));
- statisticsBuilder.setTableId(new TableId(swTableStats.getTableId()));
- salFlowStats.add(statisticsBuilder.build());
- }
-
- message.setFlowTableAndStatisticsMap(salFlowStats);
-
- LOG.debug("Converted flow table statistics : {}",message.build().toString());
- listDataObject.add(message.build());
- return listDataObject;
- }
- case OFPMPQUEUE: {
- LOG.debug("Received queue statistics multipart response");
-
- QueueStatisticsUpdateBuilder message = new QueueStatisticsUpdateBuilder();
- message.setId(node);
- message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE());
- message.setTransactionId(generateTransactionId(mpReply.getXid()));
-
- MultipartReplyQueueCase caseBody = (MultipartReplyQueueCase)mpReply.getMultipartReplyBody();
- MultipartReplyQueue replyBody = caseBody.getMultipartReplyQueue();
-
- List<QueueIdAndStatisticsMap> statsMap =
- new ArrayList<QueueIdAndStatisticsMap>();
-
- for (QueueStats queueStats: replyBody.getQueueStats()){
-
- QueueIdAndStatisticsMapBuilder statsBuilder =
- new QueueIdAndStatisticsMapBuilder();
- statsBuilder.setNodeConnectorId(
- InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(sc.getFeatures().getDatapathId(),
- queueStats.getPortNo(), ofVersion));
- statsBuilder.setTransmissionErrors(new Counter64(queueStats.getTxErrors()));
- statsBuilder.setTransmittedBytes(new Counter64(queueStats.getTxBytes()));
- statsBuilder.setTransmittedPackets(new Counter64(queueStats.getTxPackets()));
-
- DurationBuilder durationBuilder = new DurationBuilder();
- durationBuilder.setSecond(new Counter32(queueStats.getDurationSec()));
- durationBuilder.setNanosecond(new Counter32(queueStats.getDurationNsec()));
- statsBuilder.setDuration(durationBuilder.build());
-
- statsBuilder.setQueueId(new QueueId(queueStats.getQueueId()));
- statsBuilder.setNodeConnectorId(InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(sc.getFeatures().getDatapathId(),
- queueStats.getPortNo(), ofVersion));
-
- statsMap.add(statsBuilder.build());
- }
- message.setQueueIdAndStatisticsMap(statsMap);
-
- LOG.debug("Converted queue statistics : {}",message.build().toString());
- listDataObject.add(message.build());
- return listDataObject;
- }
-
- default:
- return listDataObject;
- }
- }
-
- return listDataObject;
- }
-
- private static NodeId nodeIdFromDatapathId(final BigInteger datapathId) {
- String current = datapathId.toString();
- return new NodeId("openflow:" + current);
- }
-
- private static TransactionId generateTransactionId(final Long xid){
- BigInteger bigIntXid = BigInteger.valueOf(xid);
- return new TransactionId(bigIntXid);
- }
-
- /*
- * Method returns the bitmap of actions supported by each group.
- * TODO: My recommendation would be, its good to have a respective model of
- * 'type bits', which will generate a class where all these flags will eventually
- * be stored as boolean. It will be convenient for application to check the
- * supported action, rather then doing bitmap operation.
- * @param actionsSupported
- * @return
- */
- private static List<Long> getGroupActionsSupportBitmap(final List<org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ActionType> actionsSupported){
- List<Long> supportActionByGroups = new ArrayList<Long>();
- for(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ActionType supportedActions : actionsSupported){
- long supportActionBitmap = 0;
- supportActionBitmap |= supportedActions.isOFPATOUTPUT()?(1 << 0): 0;
- supportActionBitmap |= supportedActions.isOFPATCOPYTTLOUT()?(1 << 11): 0;
- supportActionBitmap |= supportedActions.isOFPATCOPYTTLIN()?(1 << 12): 0;
- supportActionBitmap |= supportedActions.isOFPATSETMPLSTTL()?(1 << 15): 0;
- supportActionBitmap |= supportedActions.isOFPATDECMPLSTTL()?(1 << 16): 0;
- supportActionBitmap |= supportedActions.isOFPATPUSHVLAN()?(1 << 17): 0;
- supportActionBitmap |= supportedActions.isOFPATPOPVLAN()?(1 << 18): 0;
- supportActionBitmap |= supportedActions.isOFPATPUSHMPLS()?(1 << 19): 0;
- supportActionBitmap |= supportedActions.isOFPATPOPMPLS()?(1 << 20): 0;
- supportActionBitmap |= supportedActions.isOFPATSETQUEUE()?(1 << 21): 0;
- supportActionBitmap |= supportedActions.isOFPATGROUP()?(1 << 22): 0;
- supportActionBitmap |= supportedActions.isOFPATSETNWTTL()?(1 << 23): 0;
- supportActionBitmap |= supportedActions.isOFPATDECNWTTL()?(1 << 24): 0;
- supportActionBitmap |= supportedActions.isOFPATSETFIELD()?(1 << 25): 0;
- supportActionBitmap |= supportedActions.isOFPATPUSHPBB()?(1 << 26): 0;
- supportActionBitmap |= supportedActions.isOFPATPOPPBB()?(1 << 27): 0;
- supportActionByGroups.add(Long.valueOf(supportActionBitmap));
- }
- return supportActionByGroups;
- }
-
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.List;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Lists;
-
-/**
- *
- */
-public class NotificationPlainTranslator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(NotificationPlainTranslator.class);
-
- @Override
- public List<DataObject> translate(SwitchConnectionDistinguisher cookie,
- SessionContext sc, OfHeader msg) {
- List<DataObject> results = null;
-
- if(msg instanceof NotificationQueueWrapper) {
- NotificationQueueWrapper wrappedNotification = (NotificationQueueWrapper) msg;
- BigInteger datapathId = sc.getFeatures().getDatapathId();
- Short version = wrappedNotification.getVersion();
- LOG.debug("NotificationQueueWrapper: version {} dataPathId {} notification {}", version, datapathId, wrappedNotification.getImplementedInterface());
- results = Lists.newArrayList((DataObject) wrappedNotification.getNotification());
- } else {
- // TODO - Do something smarter than returning null if translation fails... what Exception should we throw here?
- results = Collections.emptyList();
- }
- return results;
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
-import org.opendaylight.openflowplugin.extension.api.AugmentTuple;
-import org.opendaylight.openflowplugin.extension.api.path.MatchPath;
-import org.opendaylight.openflowplugin.openflow.md.core.extension.MatchExtensionHelper;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionDatapathIdConvertorData;
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
-import org.opendaylight.openflowplugin.openflow.md.util.PacketInUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.InPortCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.ConnectionCookie;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceivedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.packet.received.MatchBuilder;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * translates packetIn from OF-API model to MD-SAL model, supports OF-1.3
- */
-public class PacketInTranslator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(PacketInTranslator.class);
- private final ConvertorExecutor convertorExecutor;
-
- public PacketInTranslator(ConvertorExecutor convertorExecutor) {
- this.convertorExecutor = convertorExecutor;
- }
-
- @Override
- public List<DataObject> translate(final SwitchConnectionDistinguisher cookie,
- final SessionContext sc, final OfHeader msg) {
-
- List<DataObject> salPacketIn = Collections.emptyList();
-
- if (sc != null && msg instanceof PacketInMessage) {
- PacketInMessage message = (PacketInMessage) msg;
- LOG.trace("PacketIn[v{}]: Cookie: {} Match.type: {}",
- message.getVersion(), message.getCookie(),
- message.getMatch() != null ? message.getMatch().getType() : message.getMatch());
-
- // create a packet received event builder
- PacketReceivedBuilder pktInBuilder = new PacketReceivedBuilder();
- pktInBuilder.setPayload(message.getData());
- if (cookie != null) {
- pktInBuilder.setConnectionCookie(new ConnectionCookie(cookie.getCookie()));
- }
-
- // get the DPID
- GetFeaturesOutput features = sc.getFeatures();
- // Make sure we actually have features, some naughty switches start sending packetIn before they send us the FeatureReply
- if (features == null) {
- LOG.warn("Received packet_in, but there is no device datapathId received yet");
- } else {
- BigInteger dpid = features.getDatapathId();
-
- // get the Cookie if it exists
- if (message.getCookie() != null) {
- pktInBuilder.setFlowCookie(new FlowCookie(message.getCookie()));
- }
-
- // extract the port number
- Long port = null;
- if (message.getMatch() != null && message.getMatch().getMatchEntry() != null) {
- List<MatchEntry> entries = message.getMatch().getMatchEntry();
- for (MatchEntry entry : entries) {
- if(InPortCase.class.equals(entry.getMatchEntryValue().getImplementedInterface())) {
- InPortCase inPortCase = ((InPortCase) entry.getMatchEntryValue());
- org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.in.port._case.InPort inPort = inPortCase.getInPort();
- if (inPort != null) {
- port = inPort.getPortNumber().getValue();
- break;
- }
- }
- }
- }
-
- if (port == null) {
- // no incoming port, so drop the event
- LOG.warn("Received packet_in, but couldn't find an input port");
- } else {
- LOG.trace("Received packet_in from {} on port {}", dpid, port);
- final VersionDatapathIdConvertorData datapathIdConvertorData = new VersionDatapathIdConvertorData(sc.getPrimaryConductor().getVersion());
- datapathIdConvertorData.setDatapathId(dpid);
-
- final OpenflowVersion ofVersion = OpenflowVersion.get(sc.getPrimaryConductor().getVersion());
- final Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder> matchOptional = convertorExecutor.convert(message.getMatch(), datapathIdConvertorData);
- final MatchBuilder matchBuilder = new MatchBuilder(matchOptional.orElse(new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder()).build());
-
- AugmentTuple<org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.packet.received.Match> matchExtensionWrap =
- MatchExtensionHelper.processAllExtensions(
- message.getMatch().getMatchEntry(), ofVersion, MatchPath.PACKETRECEIVED_MATCH);
- if (matchExtensionWrap != null) {
- matchBuilder.addAugmentation(matchExtensionWrap.getAugmentationClass(), matchExtensionWrap.getAugmentationObject());
- }
-
- org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.packet.received.Match packetInMatch = matchBuilder.build();
- pktInBuilder.setMatch(packetInMatch);
-
- pktInBuilder.setPacketInReason(PacketInUtil.getMdSalPacketInReason(message.getReason()));
- pktInBuilder.setTableId(new org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId(message.getTableId().getValue().shortValue()));
- pktInBuilder.setIngress(InventoryDataServiceUtil.nodeConnectorRefFromDatapathIdPortno(dpid, port, ofVersion));
- PacketReceived pktInEvent = pktInBuilder.build();
- salPacketIn = Collections.<DataObject>singletonList(pktInEvent);
- }
- }
- }
- return salPacketIn;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
-import org.opendaylight.openflowplugin.openflow.md.util.PacketInUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceivedBuilder;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * translates packetIn from OF-API model to MD-SAL model, supports OF-1.0
- */
-public class PacketInV10Translator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(PacketInV10Translator.class);
- @Override
- public List<DataObject> translate(final SwitchConnectionDistinguisher cookie,
- final SessionContext sc, final OfHeader msg) {
-
- List<DataObject> salPacketIn = Collections.emptyList();
-
- if (sc != null && msg instanceof PacketInMessage) {
- PacketInMessage message = (PacketInMessage)msg;
- LOG.trace("PacketIn[v{}]: InPort: {}",
- msg.getVersion(), message.getInPort());
-
- // create a packet received event builder
- PacketReceivedBuilder pktInBuilder = new PacketReceivedBuilder();
- pktInBuilder.setPayload(message.getData());
-
- // get the DPID
- GetFeaturesOutput features = sc.getFeatures();
- // Make sure we actually have features, some naughty switches start sending packetIn before they send us the FeatureReply
- if ( features == null) {
- LOG.warn("Received packet_in, but there is no device datapathId received yet");
- } else {
- BigInteger dpid = features.getDatapathId();
-
- // extract the port number
- Long port = null;
- if (message.getInPort() != null) {
- port = message.getInPort().longValue();
- }
-
- if (port == null) {
- // no incoming port, so drop the event
- LOG.warn("Received packet_in, but couldn't find an input port");
- } else {
- LOG.trace("Received packet_in from {} on port {}", dpid, port);
- pktInBuilder.setPacketInReason(PacketInUtil.getMdSalPacketInReason(message.getReason()));
- pktInBuilder.setIngress(InventoryDataServiceUtil.nodeConnectorRefFromDatapathIdPortno(dpid, port,
- OpenflowVersion.get(sc.getPrimaryConductor().getVersion())));
- PacketReceived pktInEvent = pktInBuilder.build();
- salPacketIn = Collections.<DataObject>singletonList(pktInEvent);
- }
- }
- }
- return salPacketIn;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.translator;
-
-import java.math.BigInteger;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.util.PortTranslatorUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * translates {@link PortStatusMessage} from OF-API model to MD-SAL model,
- * supports OF-{1.0; 1.3}
- */
-public class PortStatusMessageToNodeConnectorUpdatedTranslator implements IMDMessageTranslator<OfHeader, List<DataObject>> {
- private static final Logger LOG = LoggerFactory
- .getLogger(PortStatusMessageToNodeConnectorUpdatedTranslator.class);
-
- @Override
- public List<DataObject> translate(SwitchConnectionDistinguisher cookie,
- SessionContext sc, OfHeader msg) {
- if(msg instanceof PortStatusMessage) {
- PortStatusMessage port = (PortStatusMessage)msg;
- List<DataObject> list = new CopyOnWriteArrayList<DataObject>();
- BigInteger datapathId = sc.getFeatures().getDatapathId();
- Long portNo = port.getPortNo();
- Short version = port.getVersion();
- if(port.getReason() == PortReason.OFPPRDELETE){
- LOG.debug("PortStatusMessage: version {} dataPathId {} portNo {} reason {}",version, datapathId,portNo,port.getReason());
- list.add(PortTranslatorUtil.translatePortRemoved(version, datapathId, portNo, port));
-
- }else{
- LOG.debug("PortStatusMessage: version {} dataPathId {} portNo {}",version, datapathId,portNo);
- list.add(PortTranslatorUtil.translatePort(version, datapathId, portNo, port));
- }
- return list;
- } else {
- // TODO - Do something smarter than returning null if translation fails... what Exception should we throw here?
- return Collections.emptyList();
- }
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-
-import org.opendaylight.openflowplugin.api.openflow.md.queue.MessageSourcePollRegistrator;
-
-/**
- * closable registration for {@link org.opendaylight.openflowplugin.api.openflow.md.queue.MessageSourcePollRegistrator}
- * @param <IN> queue input message type
- */
-public class MessageSourcePollRegistration<IN> implements AutoCloseable {
-
- private MessageSourcePollRegistrator<IN> messageSourceRegistry;
- private IN messageSource;
-
- /**
- * @param messageSourceRegistry message source registry
- * @param messageSource message source
- */
- public MessageSourcePollRegistration(MessageSourcePollRegistrator<IN> messageSourceRegistry,
- IN messageSource) {
- this.messageSourceRegistry = messageSourceRegistry;
- this.messageSource = messageSource;
- }
-
- @Override
- public void close() throws Exception {
- messageSourceRegistry.unregisterMessageSource(messageSource);
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueItem;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper.QueueType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-
-/**
- * QueueItem implementation based on {@link OfHeader}
- */
-public class QueueItemOFImpl implements QueueItem<OfHeader> {
-
- private OfHeader message;
- private ConnectionConductor connectionConductor;
- private QueueType queueType;
-
-
-
- /**
- * @param message openflow message
- * @param connectionConductor switch connection conductor
- * @param queueType queue type
- */
- public QueueItemOFImpl(OfHeader message,
- ConnectionConductor connectionConductor, QueueType queueType) {
- this.message = message;
- this.connectionConductor = connectionConductor;
- this.queueType = queueType;
- }
-
- @Override
- public OfHeader getMessage() {
- return message;
- }
-
- @Override
- public ConnectionConductor getConnectionConductor() {
- return connectionConductor;
- }
-
- @Override
- public QueueType getQueueType() {
- return queueType;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import org.opendaylight.openflowplugin.api.openflow.md.queue.MessageSourcePollRegistrator;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-
-/**
- * factory for
- * {@link org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper}
- * implementations
- */
-public abstract class QueueKeeperFactory {
-
- /**
- * @param sourceRegistrator source registrator
- * @param capacity blocking queue capacity
- * @param waterMarkListener water mark listener
- * @return fair reading implementation of
- * {@link org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper}
- * (not registered = not started yet)
- */
- public static QueueKeeper<OfHeader> createFairQueueKeeper(
- MessageSourcePollRegistrator<QueueKeeper<OfHeader>> sourceRegistrator,
- int capacity, WaterMarkListener waterMarkListener) {
- QueueKeeperFairImpl queueKeeper = new QueueKeeperFairImpl();
- queueKeeper.setCapacity(capacity);
- queueKeeper.setHarvesterHandle(sourceRegistrator.getHarvesterHandle());
- queueKeeper.setWaterMarkListener(waterMarkListener);
- queueKeeper.init();
-
- return queueKeeper;
- }
-
- /**
- * register queue by harvester, start processing it. Use
- * {@link QueueKeeperFairImpl#close()} to kill the queue and stop
- * processing.
- *
- * @param sourceRegistrator source registrator
- * @param queueKeeper queue keeper
- */
- public static <V> void plugQueue(
- MessageSourcePollRegistrator<QueueKeeper<V>> sourceRegistrator,
- QueueKeeper<V> queueKeeper) {
- AutoCloseable registration = sourceRegistrator
- .registerMessageSource(queueKeeper);
- queueKeeper.setPollRegistration(registration);
- sourceRegistrator.getHarvesterHandle().ping();
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import com.google.common.base.Preconditions;
-import java.util.Queue;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.BlockingQueue;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.HarvesterHandle;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueItem;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener;
-import org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesPriorityZipper;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * QueueKeeper implementation based on {@link OfHeader}
- */
-public class QueueKeeperFairImpl implements QueueKeeper<OfHeader> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(QueueKeeperFairImpl.class);
-
- private Queue<QueueItem<OfHeader>> queueDefault;
- private BlockingQueue<QueueItem<OfHeader>> queueUnordered;
- private AutoCloseable pollRegistration;
- private int capacity = 5000;
- private HarvesterHandle harvesterHandle;
- private PollableQueuesPriorityZipper<QueueItem<OfHeader>> queueZipper;
-
- private WaterMarkListener waterMarkListener;
-
- @Override
- public void close() throws Exception {
- Preconditions.checkNotNull(pollRegistration,
- "pollRegistration not available");
- pollRegistration.close();
- }
-
- @Override
- public void push(OfHeader message, ConnectionConductor conductor,
- QueueKeeper.QueueType queueType) {
- QueueItemOFImpl qItem = new QueueItemOFImpl(message, conductor,
- queueType);
- boolean enqueued = false;
-
- switch (queueType) {
- case DEFAULT:
- enqueued = queueDefault.offer(qItem);
- break;
- case UNORDERED:
- enqueued = queueUnordered.offer(qItem);
- break;
- default:
- LOG.warn("unsupported queue type: [{}] -> dropping message [{}]",
- queueType, message.getImplementedInterface());
- }
-
- if (enqueued) {
- harvesterHandle.ping();
- } else {
- LOG.debug("ingress throttling is use -> {}", queueType);
- }
-
- // if enqueueing fails -> message will be dropped
- }
-
- /**
- * @return the ingressQueue
- */
- @Override
- public QueueItem<OfHeader> poll() {
- return queueZipper.poll();
- }
-
- /**
- * @param processingRegistration
- * the processingRegistration to set
- */
- @Override
- public void setPollRegistration(AutoCloseable processingRegistration) {
- this.pollRegistration = processingRegistration;
- }
-
- /**
- * @param capacity
- * the capacity of internal blocking queue
- */
- public void setCapacity(int capacity) {
- this.capacity = capacity;
- }
-
- /**
- * init blocking queue
- */
- public void init() {
- Preconditions.checkNotNull(waterMarkListener);
- queueUnordered = new ArrayBlockingQueue<>(capacity);
- queueDefault = new ArrayBlockingQueue<>(capacity);
- WrapperQueueImpl<QueueItem<OfHeader>> wrapperQueue = new WrapperQueueImpl<>(
- capacity, queueDefault, waterMarkListener);
- queueZipper = new PollableQueuesPriorityZipper<>();
- queueZipper.addSource(queueUnordered);
- queueZipper.setPrioritizedSource(wrapperQueue);
- }
-
- public void setWaterMarkListener(WaterMarkListener waterMarkListener) {
- this.waterMarkListener = waterMarkListener;
- }
-
- /**
- * @param harvesterHandle harvester handle
- */
- public void setHarvesterHandle(HarvesterHandle harvesterHandle) {
- this.harvesterHandle = harvesterHandle;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import java.util.Collection;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.Enqueuer;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.HarvesterHandle;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueItem;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @param <IN> Type of queue keeper harvester
- *
- */
-public class QueueKeeperHarvester<IN> implements Runnable, HarvesterHandle {
- private static final Logger LOG = LoggerFactory.getLogger(QueueKeeperHarvester.class);
-
- private final Collection<QueueKeeper<IN>> messageSources;
- private final Enqueuer<QueueItem<IN>> enqueuer;
- private final Object harvestLock = new Object();
- private volatile boolean finishing = false;
- private volatile boolean wakeMe = false;
-
- /**
- * @param enqueuer queue enqueuer
- * @param messageSources source of message
- */
- public QueueKeeperHarvester(final Enqueuer<QueueItem<IN>> enqueuer,
- final Collection<QueueKeeper<IN>> messageSources) {
- this.enqueuer = enqueuer;
- this.messageSources = messageSources;
- }
-
- @Override
- public void run() {
- while (!finishing) {
- boolean starving = true;
- for (QueueKeeper<IN> source : messageSources) {
- QueueItem<IN> qItem = source.poll();
- if (qItem != null) {
- starving = false;
- enqueuer.enqueueQueueItem(qItem);
- }
- }
-
- if (starving) {
- LOG.trace("messageHarvester is about to make a starve sleep");
- synchronized (harvestLock) {
- wakeMe = true;
- try {
- this.harvestLock.wait();
- LOG.trace("messageHarvester is waking up from a starve sleep");
- } catch (InterruptedException e) {
- LOG.warn("message harvester has been interrupted during starve sleep", e);
- } finally {
- wakeMe = false;
- }
- }
- }
- }
- }
-
- /**
- * finish harvester
- */
- public void shutdown() {
- this.finishing = true;
- ping();
- }
-
- @Override
- public void ping() {
- if (wakeMe) {
- synchronized (harvestLock) {
- // Might've raced while waiting for lock, so need to recheck
- if (wakeMe) {
- LOG.debug("pinging message harvester in starve status");
- harvestLock.notify();
- }
- }
- }
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.CopyOnWriteArraySet;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Future;
-import java.util.concurrent.RejectedExecutionHandler;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.HarvesterHandle;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueItem;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy.StatisticsGroup;
-import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-/**
- * {@link org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper} implementation focused to keep order and use up mutiple threads for translation phase.
- * <br>
- * There is internal thread pool of limited size ({@link QueueProcessorLightImpl#setProcessingPoolSize(int)})
- * dedicated to translation. Then there is singleThreadPool dedicated to publishing (via popListeners)
- * <br>
- * Workflow:
- * <ol>
- * <li>upon message push ticket is created and enqueued</li>
- * <li>available threads from internal pool translate the massage wrapped in ticket</li>
- * <li>when translation of particular message is finished, result is set in future result of wrapping ticket<br>
- * (order of tickets in queue is not touched during translate)
- * </li>
- * <li>at the end of queue there is {@link TicketFinisher} running in singleThreadPool and for each ticket it does:
- * <ol>
- * <li>invoke blocking {@link BlockingQueue#take()} method in order to get the oldest ticket</li>
- * <li>invoke blocking {@link Future#get()} on the dequeued ticket</li>
- * <li>as soon as the result of translation is available, appropriate popListener is invoked</li>
- * </ol>
- * and this way the order of messages is preserved and also multiple threads are used by translating
- * </li>
- * </ol>
- *
- *
- */
-public class QueueProcessorLightImpl implements QueueProcessor<OfHeader, DataObject> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(QueueProcessorLightImpl.class);
-
- private BlockingQueue<TicketResult<DataObject>> ticketQueue;
- private ThreadPoolExecutor processorPool;
- private int processingPoolSize = 4;
- private ExecutorService harvesterPool;
- private ExecutorService finisherPool;
-
- protected Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> popListenersMapping;
- private Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping;
- private TicketProcessorFactory<OfHeader, DataObject> ticketProcessorFactory;
- private MessageSpy<DataContainer> messageSpy;
- protected Collection<QueueKeeper<OfHeader>> messageSources;
- private QueueKeeperHarvester<OfHeader> harvester;
-
- protected TicketFinisher<DataObject> finisher;
-
- /**
- * prepare queue
- */
- public void init() {
- int ticketQueueCapacity = 1500;
- ticketQueue = new ArrayBlockingQueue<>(ticketQueueCapacity);
- /*
- * TODO FIXME - DOES THIS REALLY NEED TO BE CONCURRENT? Can we figure out
- * a better lifecycle? Why does this have to be a Set?
- */
- messageSources = new CopyOnWriteArraySet<>();
-
- processorPool = new ThreadPoolLoggingExecutor(processingPoolSize, processingPoolSize, 0,
- TimeUnit.MILLISECONDS,
- new ArrayBlockingQueue<Runnable>(ticketQueueCapacity),
- "OFmsgProcessor");
- // force blocking when pool queue is full
- processorPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
- @Override
- public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
- try {
- executor.getQueue().put(r);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- throw new IllegalStateException(e);
- }
- }
- });
-
- harvesterPool = new ThreadPoolLoggingExecutor(1, 1, 0,
- TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), "OFmsgHarvester");
- finisherPool = new ThreadPoolLoggingExecutor(1, 1, 0,
- TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), "OFmsgFinisher");
- finisher = new TicketFinisherImpl(
- ticketQueue, popListenersMapping);
- finisherPool.execute(finisher);
-
- harvester = new QueueKeeperHarvester<OfHeader>(this, messageSources);
- harvesterPool.execute(harvester);
-
- ticketProcessorFactory = new TicketProcessorFactoryImpl();
- ticketProcessorFactory.setTranslatorMapping(translatorMapping);
- ticketProcessorFactory.setSpy(messageSpy);
- ticketProcessorFactory.setTicketFinisher(finisher);
- }
-
- /**
- * stop processing queue
- */
- public void shutdown() {
- processorPool.shutdown();
- }
-
- @Override
- public void enqueueQueueItem(QueueItem<OfHeader> queueItem) {
- messageSpy.spyMessage(queueItem.getMessage(), StatisticsGroup.FROM_SWITCH_ENQUEUED);
- TicketImpl<OfHeader, DataObject> ticket = new TicketImpl<>();
- ticket.setConductor(queueItem.getConnectionConductor());
- ticket.setMessage(queueItem.getMessage());
- ticket.setQueueType(queueItem.getQueueType());
-
- LOG.trace("ticket scheduling: {}, ticket: {}",
- queueItem.getMessage().getImplementedInterface().getSimpleName(),
- System.identityHashCode(queueItem));
- scheduleTicket(ticket);
- }
-
-
- @Override
- public void directProcessQueueItem(QueueItem<OfHeader> queueItem) {
- messageSpy.spyMessage(queueItem.getMessage(), StatisticsGroup.FROM_SWITCH_ENQUEUED);
- TicketImpl<OfHeader, DataObject> ticket = new TicketImpl<>();
- ticket.setConductor(queueItem.getConnectionConductor());
- ticket.setMessage(queueItem.getMessage());
-
- LOG.debug("ticket scheduling: {}, ticket: {}",
- queueItem.getMessage().getImplementedInterface().getSimpleName(),
- System.identityHashCode(queueItem));
-
- ticketProcessorFactory.createProcessor(ticket).run();
-
- // publish notification
- finisher.firePopNotification(ticket.getDirectResult());
- }
-
- /**
- * @param ticket
- */
- private void scheduleTicket(Ticket<OfHeader, DataObject> ticket) {
- switch (ticket.getQueueType()) {
- case DEFAULT:
- Runnable ticketProcessor = ticketProcessorFactory.createProcessor(ticket);
- processorPool.execute(ticketProcessor);
- try {
- ticketQueue.put(ticket);
- } catch (InterruptedException e) {
- LOG.warn("enqeueue of unordered message ticket failed", e);
- }
- break;
- case UNORDERED:
- Runnable ticketProcessorSync = ticketProcessorFactory.createSyncProcessor(ticket);
- processorPool.execute(ticketProcessorSync);
- break;
- default:
- LOG.warn("unsupported enqueue type: {}", ticket.getQueueType());
- }
- }
-
- /**
- * @param poolSize the poolSize to set
- */
- public void setProcessingPoolSize(int poolSize) {
- this.processingPoolSize = poolSize;
- }
-
- @Override
- public void setTranslatorMapping(
- Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping) {
- this.translatorMapping = translatorMapping;
- }
-
- @Override
- public void setPopListenersMapping(
- Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> popListenersMapping) {
- this.popListenersMapping = popListenersMapping;
- }
-
- /**
- * @param messageSpy the messageSpy to set
- */
- public void setMessageSpy(MessageSpy<DataContainer> messageSpy) {
- this.messageSpy = messageSpy;
- }
-
- @Override
- public AutoCloseable registerMessageSource(QueueKeeper<OfHeader> queue) {
- boolean added = messageSources.add(queue);
- if (! added) {
- LOG.debug("registration of message source queue failed - already registered");
- }
- MessageSourcePollRegistration<QueueKeeper<OfHeader>> queuePollRegistration =
- new MessageSourcePollRegistration<>(this, queue);
- return queuePollRegistration;
- }
-
- @Override
- public boolean unregisterMessageSource(QueueKeeper<OfHeader> queue) {
- return messageSources.remove(queue);
- }
-
- @Override
- public Collection<QueueKeeper<OfHeader>> getMessageSources() {
- return messageSources;
- }
-
- @Override
- public HarvesterHandle getHarvesterHandle() {
- return harvester;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper.QueueType;
-
-/**
- * @author mirehak
- *
- * @param <IN> source type of process ticket
- * @param <OUT> resulting type of process ticket
- */
-public interface Ticket<IN, OUT> extends TicketResult<OUT> {
-
- /**
- * @return connection wrapper
- */
- ConnectionConductor getConductor();
-
- /**
- * @return processed message
- */
- IN getMessage();
-
- /**
- * @return queue type associated with ticket
- */
- QueueType getQueueType();
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import java.util.List;
-
-/**
- * @param <OUT> result type
- *
- */
-public interface TicketFinisher<OUT> extends Runnable {
-
- /**
- * initiate shutdown of this worker
- */
- void finish();
-
- /**
- * notify popListeners
- * @param processedMessages processed message
- */
- void firePopNotification(List<OUT> processedMessages);
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-
-import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- *
- */
-public class TicketFinisherImpl implements TicketFinisher<DataObject> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(TicketFinisherImpl.class);
-
- private final Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> popListenersMapping;
-
- private boolean finished;
-
- private BlockingQueue<TicketResult<DataObject>> queue;
-
- /**
- * @param queue ticket queue
- * @param popListenersMapping message pop listener
- */
- public TicketFinisherImpl(BlockingQueue<TicketResult<DataObject>> queue,
- Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> popListenersMapping) {
- this.queue = queue;
- this.popListenersMapping = popListenersMapping;
- }
-
- @Override
- public void run() {
- while (! finished ) {
- try {
- //TODO:: handle shutdown of queue
- TicketResult<DataObject> result = queue.take();
- List<DataObject> processedMessages = result.getResult().get();
- firePopNotification(processedMessages);
- } catch (Exception e) {
- LOG.warn("processing (translate, publish) of ticket failed", e);
- }
- }
- }
-
- @Override
- public void firePopNotification(List<DataObject> processedMessages) {
- for (DataObject msg : processedMessages) {
- Class<? extends Object> registeredType =
- msg.getImplementedInterface();
- Collection<PopListener<DataObject>> popListeners = popListenersMapping.get(registeredType);
- if (popListeners == null) {
- LOG.warn("no popListener registered for type {}", registeredType);
- } else {
- for (PopListener<DataObject> consumer : popListeners) {
- try {
- consumer.onPop(msg);
- } catch (Exception e){
- LOG.warn("firePopNotification: processing (translate, publish) of ticket failed for consumer {} msg {} Exception: ", consumer, msg,e);
- }
- }
- }
- }
- }
-
- /**
- * initiate shutdown of this worker
- */
- @Override
- public void finish() {
- finished = true;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import java.util.List;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper.QueueType;
-
-import com.google.common.util.concurrent.SettableFuture;
-
-/**
- * @param <IN> source type
- * @param <OUT> result type
- */
-public class TicketImpl<IN, OUT> implements Ticket<IN, OUT> {
-
- private IN message;
- private ConnectionConductor conductor;
- private SettableFuture<List<OUT>> future;
- private QueueType queueType;
- private List<OUT> directResult;
-
- /**
- * default ctor
- */
- public TicketImpl() {
- future = SettableFuture.create();
- }
-
- @Override
- public SettableFuture<List<OUT>> getResult() {
- return future;
- }
-
- /**
- * @return the message
- */
- @Override
- public IN getMessage() {
- return message;
- }
-
- /**
- * @param message the message to set
- */
- public void setMessage(IN message) {
- this.message = message;
- }
-
- /**
- * @return the conductor
- */
- @Override
- public ConnectionConductor getConductor() {
- return conductor;
- }
-
- /**
- * @param conductor the conductor to set
- */
- public void setConductor(ConnectionConductor conductor) {
- this.conductor = conductor;
- }
-
- /**
- * @param queueType the queueType to set
- */
- public void setQueueType(QueueType queueType) {
- this.queueType = queueType;
- }
-
- @Override
- public QueueType getQueueType() {
- return queueType;
- }
-
- /**
- * @return the directResult
- */
- @Override
- public List<OUT> getDirectResult() {
- return directResult;
- }
-
- /**
- * @param directResult the directResult to set
- */
- @Override
- public void setDirectResult(List<OUT> directResult) {
- this.directResult = directResult;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-
-/**
- * @param <IN> type of DataObject
- * @param <OUT> type of DataObject
- */
-public interface TicketProcessorFactory<IN extends DataObject, OUT extends DataObject> {
-
- /**
- * @param ticket ticket
- * @return runnable ticket processor
- */
- Runnable createProcessor(final Ticket<IN, OUT> ticket);
-
- /**
- * @param ticket ticket
- * @return runnable ticket processor
- */
- Runnable createSyncProcessor(final Ticket<IN, OUT> ticket);
-
- /**
- * @param ticket ticket
- * @return translated messages
- *
- */
- List<OUT> translate(Ticket<IN, OUT> ticket);
-
- /**
- * @param ticketFinisher setter
- */
- void setTicketFinisher(TicketFinisher<OUT> ticketFinisher);
-
- /**
- * @param spy setter
- */
- void setSpy(MessageSpy<DataContainer> spy);
-
- /**
- * @param translatorMapping setter
- */
- void setTranslatorMapping(Map<TranslatorKey, Collection<IMDMessageTranslator<IN, List<OUT>>>> translatorMapping);
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import com.google.common.collect.ImmutableMap;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * OfHeader to DataObject implementation
- */
-public class TicketProcessorFactoryImpl implements TicketProcessorFactory<OfHeader, DataObject> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(TicketProcessorFactoryImpl.class);
-
- protected Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping;
- protected MessageSpy<DataContainer> spy;
- protected TicketFinisher<DataObject> ticketFinisher;
-
- /**
- * @param translatorMapping the translatorMapping to set
- */
- @Override
- public void setTranslatorMapping(
- Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping) {
- this.translatorMapping = ImmutableMap.copyOf(translatorMapping);
- }
-
- /**
- * @param spy the spy to set
- */
- @Override
- public void setSpy(MessageSpy<DataContainer> spy) {
- this.spy = spy;
- }
-
- /**
- * @param ticketFinisher the finisher to set
- */
- @Override
- public void setTicketFinisher(TicketFinisher<DataObject> ticketFinisher) {
- this.ticketFinisher = ticketFinisher;
- }
-
- /**
- * @param ticket ticket
- * @return runnable ticket processor
- */
- @Override
- public Runnable createProcessor(final Ticket<OfHeader, DataObject> ticket) {
-
- Runnable ticketProcessor = new Runnable() {
- @Override
- public void run() {
- LOG.debug("message received, type: {}", ticket.getMessage().getImplementedInterface().getSimpleName());
- List<DataObject> translate;
- try {
- translate = translate(ticket);
- ticket.getResult().set(translate);
- ticket.setDirectResult(translate);
- // spying on result
- if (spy != null) {
- spy.spyIn(ticket.getMessage());
- for (DataObject outMessage : translate) {
- spy.spyOut(outMessage);
- }
- }
- } catch (Exception e) {
- LOG.warn("translation problem: {}", e.getMessage());
- ticket.getResult().setException(e);
- }
- LOG.debug("message processing done (type: {}, ticket: {})",
- ticket.getMessage().getImplementedInterface().getSimpleName(),
- System.identityHashCode(ticket));
- }
- };
-
-
- return ticketProcessor;
- }
-
- /**
- * @param ticket ticket
- * @return runnable ticket processor
- */
- @Override
- public Runnable createSyncProcessor(final Ticket<OfHeader, DataObject> ticket) {
-
- Runnable ticketProcessor = new Runnable() {
- @Override
- public void run() {
- List<DataObject> translate;
- try {
- translate = translate(ticket);
- // spying on result
- if (spy != null) {
- spy.spyIn(ticket.getMessage());
- for (DataObject outMessage : translate) {
- spy.spyOut(outMessage);
- }
- }
- ticketFinisher.firePopNotification(translate);
- } catch (Exception e) {
- LOG.error("translation problem: {}", e.getMessage());
- ticket.getResult().setException(e);
- }
- }
- };
-
-
- return ticketProcessor;
- }
-
-
- /**
- * @param ticket ticket
- *
- */
- @Override
- public List<DataObject> translate(Ticket<OfHeader, DataObject> ticket) {
- List<DataObject> result = new ArrayList<>();
-
- OfHeader message = ticket.getMessage();
- Class<? extends DataContainer> messageType = ticket.getMessage().getImplementedInterface();
- ConnectionConductor conductor = ticket.getConductor();
- Collection<IMDMessageTranslator<OfHeader, List<DataObject>>> translators = null;
- LOG.trace("translating ticket: {}, ticket: {}", messageType.getSimpleName(), System.identityHashCode(ticket));
-
- Short version = message.getVersion();
- if (version == null) {
- throw new IllegalArgumentException("version is NULL");
- }
- TranslatorKey tKey = new TranslatorKey(version, messageType.getName());
- translators = translatorMapping.get(tKey);
-
- LOG.debug("translatorKey: {} + {}", version, messageType.getName());
-
- if (translators != null) {
- for (IMDMessageTranslator<OfHeader, List<DataObject>> translator : translators) {
- SwitchConnectionDistinguisher cookie = null;
- // Pass cookie only for PACKT_OfHeader
- if (messageType.equals("PacketInMessage.class")) {
- cookie = conductor.getAuxiliaryKey();
- }
- long start = System.nanoTime();
- List<DataObject> translatorOutput = translator.translate(cookie, conductor.getSessionContext(), message);
- long end = System.nanoTime();
- LOG.trace("translator: {} elapsed time {} ns",translator,end-start);
- if(translatorOutput != null && !translatorOutput.isEmpty()) {
- result.addAll(translatorOutput);
- }
- }
- } else {
- LOG.warn("No translators for this message Type: {}", messageType);
- }
-
- return result;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import java.util.List;
-
-import com.google.common.util.concurrent.SettableFuture;
-
-/**
- * @author mirehak
- * @param <T> result typer
- */
-public interface TicketResult<T> {
-
- /**
- * @return processed result
- */
- SettableFuture<List<T>> getResult();
-
- /**
- * @return direct access to result
- */
- List<T> getDirectResult();
-
- /**
- * @param directResult setter for direct result
- */
- void setDirectResult(List<T> directResult);
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.queue;
-
-import com.google.common.base.Preconditions;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Queue;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueItem;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class WrapperQueueImpl<E> implements Queue<E> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(WrapperQueueImpl.class);
-
- private int lowWaterMark;
- private int highWaterMark;
-
- private WaterMarkListener queueListenerMark;
-
- private Queue<E> queueDefault;
-
- private boolean flooded;
-
- /**
- * @param capacity
- */
- public WrapperQueueImpl(int capacity, Queue<E> queueDefault,
- WaterMarkListener queueListenerMark) {
- this.queueListenerMark = queueListenerMark;
- this.queueDefault = Preconditions.checkNotNull(queueDefault);
-
- this.highWaterMark = (int) (capacity * 0.8);
- this.lowWaterMark = (int) (capacity * 0.65);
- }
-
- /**
- * Marking checks size of {@link #queueDefault} and on the basis of this is
- * set autoRead
- */
- private void marking() {
- if (queueDefault.size() >= highWaterMark && !flooded) {
- queueListenerMark.onHighWaterMark();
- flooded = true;
- } else if (queueDefault.size() <= lowWaterMark && flooded) {
- queueListenerMark.onLowWaterMark();
- flooded = false;
- }
- }
-
- /**
- * @return true if flooded
- */
- public boolean isFlooded() {
- return flooded;
- }
-
- /**
- * poll {@link QueueItem} and call {@link #marking()} for check marks and
- * set autoRead if it need it
- *
- * @return polled item
- */
- public E poll() {
- E nextQueueItem = queueDefault.poll();
- marking();
- return nextQueueItem;
- }
-
- public boolean add(E e) {
- return queueDefault.add(e);
- }
-
- public int size() {
- return queueDefault.size();
- }
-
- public boolean isEmpty() {
- return queueDefault.isEmpty();
- }
-
- public boolean contains(Object o) {
- return queueDefault.contains(o);
- }
-
- public boolean offer(E e) {
- boolean enqueueResult = queueDefault.offer(e);
- marking();
- return enqueueResult;
- }
-
- public Iterator<E> iterator() {
- return queueDefault.iterator();
- }
-
- public E remove() {
- return queueDefault.remove();
- }
-
- public Object[] toArray() {
- return queueDefault.toArray();
- }
-
- public E element() {
- return queueDefault.element();
- }
-
- public E peek() {
- return queueDefault.peek();
- }
-
- public <T> T[] toArray(T[] a) {
- return queueDefault.toArray(a);
- }
-
- public boolean remove(Object o) {
- return queueDefault.remove(o);
- }
-
- public boolean containsAll(Collection<?> c) {
- return queueDefault.containsAll(c);
- }
-
- public boolean addAll(Collection<? extends E> c) {
- return queueDefault.addAll(c);
- }
-
- public boolean removeAll(Collection<?> c) {
- return queueDefault.removeAll(c);
- }
-
- public boolean retainAll(Collection<?> c) {
- return queueDefault.retainAll(c);
- }
-
- public void clear() {
- queueDefault.clear();
- }
-
- public boolean equals(Object o) {
- return queueDefault.equals(o);
- }
-
- public int hashCode() {
- return queueDefault.hashCode();
- }
-
-}
import com.google.common.base.Preconditions;
import com.google.common.io.BaseEncoding;
-/**
- * @author mirehak
- */
public abstract class ByteUtil {
/** default hex string separator */
package org.opendaylight.openflowplugin.openflow.md.util;
import com.google.common.base.Optional;
+import com.google.common.base.Splitter;
import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.ExecutionException;
-
-import com.google.common.base.Splitter;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdatedBuilder;
*/
private static final InstanceIdentifier<Nodes> NODES_IDENTIFIER = InstanceIdentifier.create(Nodes.class);
- public static Nodes checkForNodes() {
- Nodes nodes = null;
- LOG.error("Before Nodes - nodes: " + nodes);
- try {
- nodes = getDataObject(OFSessionUtil.getSessionManager().getDataBroker().newReadOnlyTransaction(), NODES_IDENTIFIER);
- } catch (Exception e) {
- LOG.error(
- "Caught exception from OFSessionUtil.getSessionManager().getDataBroker().newReadWriteTransaction()",
- e);
- }
- LOG.error("After Nodes- nodes: " + nodes);
- return nodes;
- }
-
- public static List<Node> readAllNodes() {
- Nodes nodes = getDataObject(OFSessionUtil.getSessionManager().getDataBroker().newReadOnlyTransaction(), NODES_IDENTIFIER);
- return nodes.getNode();
- }
-
- public static Node readNode(final InstanceIdentifier<Node> instance) {
- return getDataObject(OFSessionUtil.getSessionManager().getDataBroker().newReadOnlyTransaction(), instance);
- }
-
- public static void putNodeConnector(final InstanceIdentifier<Node> instance, final NodeConnector nodeConnector) {
- WriteTransaction transaction = OFSessionUtil.getSessionManager().getDataBroker().newWriteOnlyTransaction();
- InstanceIdentifier<NodeConnector> nodeConnectorID = instance.child(NodeConnector.class, nodeConnector.getKey());
- transaction.merge(LogicalDatastoreType.OPERATIONAL, nodeConnectorID, nodeConnector);
- transaction.submit();
- }
-
- public static void putNodeConnector(final NodeKey nodeKey, final NodeConnector nodeConnector) {
- InstanceIdentifier<Node> instance = nodeKeyToInstanceIdentifier(nodeKey);
- putNodeConnector(instance, nodeConnector);
- }
-
- public static void putNodeConnector(final NodeId nodeId, final NodeConnector nodeConnector) {
- putNodeConnector(new NodeKey(nodeId), nodeConnector);
- }
-
public static InstanceIdentifier<Node> identifierFromDatapathId(final BigInteger datapathId) {
NodeKey nodeKey = nodeKeyFromDatapathId(datapathId);
return NODES_IDENTIFIER.child(Node.class, nodeKey);
* Class which integrates the port constants defined and used by MDSAL and the ports defined in openflow java
* This class is responsible for converting MDSAL given logical names to port numbers and back.
* Any newer version of openflow can have a similar mapping or can/should be extended.
- *
- * @author Kamal Rameshan on 5/2/14.
*/
public class OpenflowPortsUtil {
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketInReason;
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.SendToController;
-/**
- *
- */
public final class PacketInUtil {
private PacketInUtil(){
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.util;
-
-import com.google.common.base.Function;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.JdkFutureAdapters;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-import java.math.BigInteger;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager;
-import org.opendaylight.openflowplugin.openflow.md.core.session.RolePushException;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- *
- */
-public final class RoleUtil {
-
- private static final Logger LOG = LoggerFactory.getLogger(RoleUtil.class);
- private static final Function<Exception, RolePushException> exceptionFunction = new Function<Exception, RolePushException>() {
- @Override
- public RolePushException apply(Exception input) {
- RolePushException output = null;
- if (input instanceof ExecutionException) {
- if (input.getCause() instanceof RolePushException) {
- output = (RolePushException) input.getCause();
- }
- }
-
- if (output == null) {
- output = new RolePushException(input.getMessage(), input);
- }
-
- return output;
- }
- };
-
- private RoleUtil() {
- throw new UnsupportedOperationException("RoleUtil is not expected to be instantiated.");
- }
-
- /**
- * @param role openflow role for controller
- * @return protocol role
- */
- public static ControllerRole toOFJavaRole(OfpRole role) {
- ControllerRole ofJavaRole = null;
- switch (role) {
- case BECOMEMASTER:
- ofJavaRole = ControllerRole.OFPCRROLEMASTER;
- break;
- case BECOMESLAVE:
- ofJavaRole = ControllerRole.OFPCRROLESLAVE;
- break;
- case NOCHANGE:
- ofJavaRole = ControllerRole.OFPCRROLENOCHANGE;
- break;
- default:
- // no intention
- LOG.warn("given role is not supported by protocol roles: {}", role);
- break;
- }
- return ofJavaRole;
- }
-
- /**
- * @param session switch session context
- * @param role controller openflow role
- * @param generationId generate id for role negotiation
- * @return input builder
- */
- public static RoleRequestInputBuilder createRoleRequestInput(
- final SessionContext session, OfpRole role, BigInteger generationId) {
-
- ControllerRole ofJavaRole = RoleUtil.toOFJavaRole(role);
-
- return new RoleRequestInputBuilder()
- .setGenerationId(generationId)
- .setRole(ofJavaRole)
- .setVersion(session.getFeatures().getVersion())
- .setXid(session.getNextXid());
- }
-
- /**
- * @param sessionContext switch session context
- * @param ofpRole controller openflow role
- * @param generationId generate id for role negotiation
- * @return roleRequest future result
- */
- public static Future<RpcResult<RoleRequestOutput>> sendRoleChangeRequest(SessionContext sessionContext, OfpRole ofpRole, BigInteger generationId) {
- RoleRequestInputBuilder ruleRequestInputBld = RoleUtil.createRoleRequestInput(sessionContext, ofpRole, generationId);
- Future<RpcResult<RoleRequestOutput>> roleReply = sessionContext.getPrimaryConductor().getConnectionAdapter()
- .roleRequest(ruleRequestInputBld.build());
- return roleReply;
- }
-
- /**
- * @param sessionContext switch session context
- * @return generationId from future RpcResult
- */
- public static Future<BigInteger> readGenerationIdFromDevice(SessionContext sessionContext) {
- Future<RpcResult<RoleRequestOutput>> roleReply = sendRoleChangeRequest(sessionContext, OfpRole.NOCHANGE, BigInteger.ZERO);
- final SettableFuture<BigInteger> result = SettableFuture.create();
-
- Futures.addCallback(JdkFutureAdapters.listenInPoolThread(roleReply), new FutureCallback<RpcResult<RoleRequestOutput>>() {
- @Override
- public void onSuccess(RpcResult<RoleRequestOutput> input) {
- if(input != null && input.getResult() != null) {
- result.set(input.getResult().getGenerationId());
- }
- }
- @Override
- public void onFailure(Throwable t) {
- //TODO
- }
- });
- return result;
- }
-
- /**
- * @param generationId generate id for role negotiation
- * @return next (incremented value)
- */
- public static BigInteger getNextGenerationId(BigInteger generationId) {
- BigInteger nextGenerationId = null;
- if (generationId.compareTo(OFRoleManager.MAX_GENERATION_ID) < 0) {
- nextGenerationId = generationId.add(BigInteger.ONE);
- } else {
- nextGenerationId = BigInteger.ZERO;
- }
-
- return nextGenerationId;
- }
-
- /**
- * @param rolePushResult result of role push request
- * @return future which throws {@link RolePushException}
- */
- public static CheckedFuture<Boolean, RolePushException> makeCheckedRuleRequestFxResult(
- ListenableFuture<Boolean> rolePushResult) {
- return Futures.makeChecked(
- rolePushResult, exceptionFunction
- );
- }
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.util;
-
-/**
- * @param <IN> rpc input value type
- * @param <OUT> rpc output value type
- */
-public class RpcInputOutputTuple<IN, OUT> {
-
- private IN input;
- private OUT output;
-
-
- /**
- * @param input input
- * @param output output
- */
- public RpcInputOutputTuple(IN input, OUT output) {
- this.input = input;
- this.output = output;
- }
-
- /**
- * @return the input
- */
- public IN getInput() {
- return input;
- }
- /**
- * @return the output
- */
- public OUT getOutput() {
- return output;
- }
-
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.util;
-
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.ArrayList;
-import java.util.List;
-import org.opendaylight.openflowplugin.api.ConnectionException;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-
-/**
- *
- */
-public final class RpcResultUtil {
-
- private RpcResultUtil() {
- throw new UnsupportedOperationException("RpcResultUtil is not expected to be instantiated.");
- }
-
- /**
- * @param e connection exception
- * @param <T> rpc result return type
- * @return error wrapped inside {@link RpcResult} which is wrapped inside future
- */
- public static <T> SettableFuture<RpcResult<T>> getRpcErrorFuture(ConnectionException e) {
- List<RpcError> rpcErrorList = wrapConnectionErrorIntoRpcErrors(e);
- SettableFuture<RpcResult<T>> futureWithError = SettableFuture.create();
- futureWithError.set(RpcResultBuilder.<T>failed().withRpcErrors(rpcErrorList).build());
- return futureWithError;
- }
-
- private static List<RpcError> wrapConnectionErrorIntoRpcErrors(ConnectionException e) {
- List<RpcError> rpcErrorList = new ArrayList<>();
- rpcErrorList.add(RpcResultBuilder.newError(
- RpcError.ErrorType.TRANSPORT,
- OFConstants.ERROR_TAG_TIMEOUT,
- e.getMessage(),
- OFConstants.APPLICATION_TAG,
- IMessageDispatchService.CONNECTION_ERROR_MESSAGE,
- e.getCause()));
- return rpcErrorList;
- }
-
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.util;
-
-import com.google.common.util.concurrent.JdkFutureAdapters;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.util.concurrent.Future;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.core.MessageFactory;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-
-/**
- *
- */
-public final class TaskUtil {
-
- private TaskUtil() {
- throw new AssertionError("TaskUtil is not expected to be instantiated.");
- }
-
- /**
- * @param session switch session context
- * @param cookie connection distinguisher cookie value
- * @param messageService message dispatch service instance
- * @return barrier response
- */
- public static RpcInputOutputTuple<BarrierInput, ListenableFuture<RpcResult<BarrierOutput>>> sendBarrier(SessionContext session,
- SwitchConnectionDistinguisher cookie, IMessageDispatchService messageService) {
- BarrierInput barrierInput = MessageFactory.createBarrier(
- session.getFeatures().getVersion(), session.getNextXid());
- Future<RpcResult<BarrierOutput>> barrierResult = messageService.barrier(barrierInput, cookie);
- ListenableFuture<RpcResult<BarrierOutput>> output = JdkFutureAdapters.listenInPoolThread(barrierResult);
-
- return new RpcInputOutputTuple<>(barrierInput, output);
- }
-
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.statistics;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.atomic.AtomicLongFieldUpdater;
-
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageObservatory;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * message counter (by type)
- */
-public class MessageSpyCounterImpl implements MessageObservatory<DataContainer> {
-
- private static final Logger LOG = LoggerFactory.getLogger(MessageSpyCounterImpl.class);
-
- private static final class MessageCounters {
- private static final AtomicLongFieldUpdater<MessageCounters> UPDATER = AtomicLongFieldUpdater.newUpdater(MessageCounters.class, "current");
- private volatile long current;
- private long cumulative;
-
- public synchronized long accumulate() {
- final long inc = UPDATER.getAndSet(this, 0);
- cumulative += inc;
- return inc;
- }
-
- public synchronized long getCumulative() {
- return cumulative;
- }
-
- public long increment() {
- return UPDATER.incrementAndGet(this);
- }
- }
-
- private final ConcurrentMap<StatisticsGroup, ConcurrentMap<Class<? extends DataContainer>, MessageCounters>> inputStats = new ConcurrentHashMap<>();
-
- @Override
- public void spyIn(final DataContainer message) {
- getCounters(message, StatisticsGroup.FROM_SWITCH_TRANSLATE_IN_SUCCESS).increment();
- }
-
- @Override
- public void spyOut(final DataContainer message) {
- getCounters(message, StatisticsGroup.FROM_SWITCH_TRANSLATE_OUT_SUCCESS).increment();
- }
-
- @Override
- public void spyMessage(final DataContainer message, final StatisticsGroup statGroup) {
- getCounters(message, statGroup).increment();
- }
-
- /**
- * @param message
- * @param statGroup TODO
- * @return
- */
- private MessageCounters getCounters(final DataContainer message, final StatisticsGroup statGroup) {
- Class<? extends DataContainer> msgType = message.getImplementedInterface();
- ConcurrentMap<Class<? extends DataContainer>, MessageCounters> groupData = getOrCreateGroupData(statGroup);
- MessageCounters counters = getOrCreateCountersPair(msgType, groupData);
- return counters;
- }
-
- private static MessageCounters getOrCreateCountersPair(final Class<? extends DataContainer> msgType, final ConcurrentMap<Class<? extends DataContainer>,MessageCounters> groupData) {
- final MessageCounters lookup = groupData.get(msgType);
- if (lookup != null) {
- return lookup;
- }
-
- final MessageCounters newCounters = new MessageCounters();
- final MessageCounters check = groupData.putIfAbsent(msgType, newCounters);
- return check == null ? newCounters : check;
-
- }
-
- private ConcurrentMap<Class<? extends DataContainer>, MessageCounters> getOrCreateGroupData(final StatisticsGroup statGroup) {
- final ConcurrentMap<Class<? extends DataContainer>, MessageCounters> lookup = inputStats.get(statGroup);
- if (lookup != null) {
- return lookup;
- }
-
- final ConcurrentMap<Class<? extends DataContainer>, MessageCounters> newmap = new ConcurrentHashMap<>();
- final ConcurrentMap<Class<? extends DataContainer>, MessageCounters> check = inputStats.putIfAbsent(statGroup, newmap);
-
- return check == null ? newmap : check;
- }
-
- @Override
- public void run() {
- // log current counters and cleans it
- if (LOG.isDebugEnabled()) {
- for (String counterItem : dumpMessageCounts()) {
- LOG.debug(counterItem);
- }
- }
- }
-
- @Override
- public List<String> dumpMessageCounts() {
- List<String> dump = new ArrayList<>();
-
- for (StatisticsGroup statGroup : StatisticsGroup.values()) {
- Map<Class<? extends DataContainer>, MessageCounters> groupData = inputStats.get(statGroup);
- if (groupData != null) {
- for (Entry<Class<? extends DataContainer>, MessageCounters> statEntry : groupData.entrySet()) {
- long amountPerInterval = statEntry.getValue().accumulate();
- long cumulativeAmount = statEntry.getValue().getCumulative();
- dump.add(String.format("%s: MSG[%s] -> +%d | %d",
- statGroup,
- statEntry.getKey().getSimpleName(),
- amountPerInterval, cumulativeAmount));
- }
- } else {
- dump.add(String.format("%s: no activity detected", statGroup));
- }
- }
- return dump;
- }
-}
+++ /dev/null
-module openflow-provider-impl {
- yang-version 1;
- namespace "urn:opendaylight:params:xml:ns:yang:openflow:common:config:impl";
- prefix "ofplugin-cfg-impl";
-
- description
- "openflow-plugin-custom-config-impl";
-
- revision "2014-03-26" {
- description
- "Initial revision";
- }
-
- // role of OFPlugin instance
- typedef ofp-role {
- type enumeration {
- enum NOCHANGE {
- description "no change to role";
- }
- enum BECOMEMASTER {
- description "promote current role to MASTER";
- }
- enum BECOMESLAVE {
- description "demote current role to SLAVE";
- }
- }
- }
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.core;
-
-import static org.junit.Assert.assertNotNull;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Stack;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Matchers;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.openflowplugin.openflow.md.core.plan.ConnectionAdapterStackImpl;
-import org.opendaylight.openflowplugin.openflow.md.core.plan.EventFactory;
-import org.opendaylight.openflowplugin.openflow.md.core.plan.SwitchTestEvent;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
-import org.opendaylight.openflowplugin.openflow.md.queue.QueueProcessorLightImpl;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeaturesV10;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessageBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessageBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessageBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessageBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessageBuilder;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@RunWith(MockitoJUnitRunner.class)
-public class ConnectionConductorImplTest {
-
- protected static final Logger LOG = LoggerFactory
- .getLogger(ConnectionConductorImplTest.class);
-
- /**
- * in [ms]
- */
- private final int maxProcessingTimeout = 500;
-
- protected ConnectionAdapterStackImpl adapter;
- private ConnectionConductorImpl connectionConductor;
- private MDController controller;
- private Stack<SwitchTestEvent> eventPlan;
-
- private Thread libSimulation;
- private final ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(
- 8);
-
- protected QueueProcessorLightImpl queueProcessor;
-
- private PopListenerCountingImpl<DataObject> popListener;
-
- private int experimenterMessageCounter;
- private int packetinMessageCounter;
- private int flowremovedMessageCounter;
- private int portstatusAddMessageCounter;
- private int portstatusDeleteMessageCounter;
- private int portstatusModifyMessageCounter;
- private int errorMessageCounter;
-
- @Mock
- private ErrorHandlerSimpleImpl errorHandler;
-
- private final int expectedErrors = 0;
- @Mock
- private MessageSpy<DataContainer> messageSpy;
- @Mock
- HandshakeContext handshakeContext;
- private ErrorMessageService objErms;
-
- public void incrExperimenterMessageCounter() {
- this.experimenterMessageCounter++;
- }
-
- public void incrPacketinMessageCounter() {
- this.packetinMessageCounter++;
- }
-
- public void incrFlowremovedMessageCounter() {
- this.flowremovedMessageCounter++;
- }
-
- public void incrPortstatusAddMessageCounter() {
- this.portstatusAddMessageCounter++;
- }
-
- public void incrPortstatusDeleteMessageCounter() {
- this.portstatusDeleteMessageCounter++;
- }
-
- public void incrPortstatusModifyMessageCounter() {
- this.portstatusModifyMessageCounter++;
- }
-
- public void incrErrorMessageCounter() {
- this.errorMessageCounter++;
- }
-
- @Test
- /**
- * Test for ConnectionConductorFactory#createConductor
- */
- public void testCreateConductor() {
- ConnectionConductor connectionConductor = ConnectionConductorFactory.createConductor(adapter, queueProcessor);
- assertNotNull(connectionConductor);
- }
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- adapter = new ConnectionAdapterStackImpl();
-
- popListener = new PopListenerCountingImpl<>();
-
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
- controller = new MDController(convertorManager);
- controller.init();
- controller.getMessageTranslators().putAll(assembleTranslatorMapping());
-
- queueProcessor = new QueueProcessorLightImpl();
- queueProcessor.setMessageSpy(messageSpy);
- queueProcessor.setPopListenersMapping(assemblePopListenerMapping());
- queueProcessor.setTranslatorMapping(controller.getMessageTranslators());
- queueProcessor.init();
-
- connectionConductor = new ConnectionConductorImpl(adapter);
- connectionConductor.setQueueProcessor(queueProcessor);
- connectionConductor.setErrorHandler(errorHandler);
- connectionConductor.init();
- connectionConductor.setHandshakeContext(handshakeContext);
- eventPlan = new Stack<>();
- adapter.setEventPlan(eventPlan);
- adapter.setProceedTimeout(5000L);
- adapter.checkListeners();
- }
-
- /**
- * @return
- */
- private Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> assemblePopListenerMapping() {
- Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> mapping = new HashMap<>();
- Collection<PopListener<DataObject>> popListenerBag = new ArrayList<>();
- popListenerBag.add(popListener);
- //TODO: add testing registered types
- mapping.put(DataObject.class, popListenerBag);
- return mapping;
- }
-
- /**
- * @throws java.lang.Exception
- */
- @After
- public void tearDown() throws Exception {
- if (libSimulation != null) {
- libSimulation.join();
- }
- queueProcessor.shutdown();
- connectionConductor.getHsPool().shutdown();
-
- for (Exception problem : adapter.getOccuredExceptions()) {
- LOG.error("during simulation on adapter side: "
- + problem.getMessage());
- }
- Assert.assertEquals(0, adapter.getOccuredExceptions().size());
- adapter = null;
- if (LOG.isDebugEnabled()) {
- if (eventPlan.size() > 0) {
- LOG.debug("eventPlan size: " + eventPlan.size());
- for (SwitchTestEvent event : eventPlan) {
- LOG.debug(" # EVENT:: " + event);
- }
- }
- }
- Assert.assertTrue("plan is not finished", eventPlan.isEmpty());
- eventPlan = null;
- controller = null;
-
- // logging errors if occurred
- ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
- Mockito.verify(errorHandler, Mockito.atMost(1)).handleException(
- errorCaptor.capture(), Matchers.any(SessionContext.class));
- for (Throwable problem : errorCaptor.getAllValues()) {
- LOG.warn(problem.getMessage(), problem);
- }
-
- Mockito.verify(errorHandler, Mockito.times(expectedErrors)).handleException(
- Matchers.any(Throwable.class), Matchers.any(SessionContext.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onEchoRequestMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage)}
- * .
- *
- * @throws Exception
- */
- @Test
- public void testOnEchoRequestMessage() throws Exception {
- simulateV13PostHandshakeState(connectionConductor);
-
- eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L,
- EventFactory.DEFAULT_VERSION, new EchoRequestMessageBuilder()));
- eventPlan.add(0,
- EventFactory.createDefaultWaitForRpcEvent(42, "echoReply"));
- executeNow();
- }
-
- /**
- * Test of handshake, covering version negotiation and features.
- * Switch delivers first helloMessage with default version.
- *
- * @throws Exception
- */
- @Test
- public void testHandshake1() throws Exception {
- eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L,
- EventFactory.DEFAULT_VERSION, new HelloMessageBuilder()));
- eventPlan.add(0, EventFactory.createDefaultWaitForAllEvent(
- EventFactory.createDefaultWaitForRpcEvent(43, "helloReply"),
- EventFactory.createDefaultWaitForRpcEvent(44, "getFeatures")));
- eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(44,
- EventFactory.DEFAULT_VERSION, getFeatureResponseMsg()));
-
- int i = 1;
- executeNow();
-
- Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING,
- connectionConductor.getConductorState());
- Assert.assertEquals((short) 0x04, connectionConductor.getVersion()
- .shortValue());
- }
-
- /**
- * Test of handshake, covering version negotiation and features.
- * Controller sends first helloMessage with default version
- *
- * @throws Exception
- */
- @Test
- public void testHandshake1SwitchStarts() throws Exception {
- eventPlan.add(0, EventFactory.createConnectionReadyCallback(connectionConductor));
- eventPlan.add(0, EventFactory.createDefaultWaitForRpcEvent(21, "helloReply"));
- eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L,
- EventFactory.DEFAULT_VERSION, new HelloMessageBuilder()));
- eventPlan.add(0, EventFactory.createDefaultWaitForRpcEvent(43, "getFeatures"));
- eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(43,
- EventFactory.DEFAULT_VERSION, getFeatureResponseMsg()));
-
- executeNow();
-
- Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING,
- connectionConductor.getConductorState());
- Assert.assertEquals((short) 0x04, connectionConductor.getVersion()
- .shortValue());
- }
-
- /**
- * Test of handshake, covering version negotiation and features.
- * Switch delivers first helloMessage with version 0x05
- * and negotiates following versions: 0x03, 0x01
- *
- * @throws Exception
- */
- @Test
- public void testHandshake2() throws Exception {
- connectionConductor.setBitmapNegotiationEnable(false);
- eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L,
- (short) 0x05, new HelloMessageBuilder()));
- eventPlan.add(0,
- EventFactory.createDefaultWaitForRpcEvent(43, "helloReply"));
- eventPlan.add(0, EventFactory.createDefaultNotificationEvent(43L,
- (short) 0x03, new HelloMessageBuilder()));
- eventPlan.add(0,
- EventFactory.createDefaultWaitForRpcEvent(44, "helloReply"));
- eventPlan.add(0, EventFactory.createDefaultNotificationEvent(44L,
- (short) 0x01, new HelloMessageBuilder()));
- eventPlan.add(0,
- EventFactory.createDefaultWaitForRpcEvent(45, "getFeatures"));
-
- eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(45,
- (short) 0x01, getFeatureResponseMsg()));
-
- executeNow();
-
- Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING,
- connectionConductor.getConductorState());
- Assert.assertEquals((short) 0x01, connectionConductor.getVersion()
- .shortValue());
- }
-
- /**
- * Test of handshake, covering version negotiation and features.
- * Controller sends first helloMessage with default version
- * and switch negotiates following versions: 0x05, 0x03, 0x01
- *
- * @throws Exception
- */
- @Test
- public void testHandshake2SwitchStarts() throws Exception {
- connectionConductor.setBitmapNegotiationEnable(false);
- eventPlan.add(0, EventFactory.createConnectionReadyCallback(connectionConductor));
- eventPlan.add(0,
- EventFactory.createDefaultWaitForRpcEvent(21, "helloReply"));
- eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L,
- (short) 0x05, new HelloMessageBuilder()));
- eventPlan.add(0, EventFactory.createDefaultNotificationEvent(43L,
- (short) 0x03, new HelloMessageBuilder()));
- eventPlan.add(0,
- EventFactory.createDefaultWaitForRpcEvent(44, "helloReply"));
- eventPlan.add(0, EventFactory.createDefaultNotificationEvent(44L,
- (short) 0x01, new HelloMessageBuilder()));
- eventPlan.add(0,
- EventFactory.createDefaultWaitForRpcEvent(45, "getFeatures"));
-
- eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(45,
- (short) 0x01, getFeatureResponseMsg()));
-
- executeNow();
-
- Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING,
- connectionConductor.getConductorState());
- Assert.assertEquals((short) 0x01, connectionConductor.getVersion()
- .shortValue());
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onFlowRemovedMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage)}
- * .
- *
- * @throws InterruptedException
- */
- @Test
- public void testOnFlowRemovedMessage() throws InterruptedException {
- FlowRemovedMessageService objFms = new FlowRemovedMessageService();
- controller.addMessageTranslator(FlowRemovedMessage.class, 4, objFms);
-
- simulateV13PostHandshakeState(connectionConductor);
- objFms.resetLatch(2);
-
- // Now send Flow Removed messages
- FlowRemovedMessageBuilder builder1 = new FlowRemovedMessageBuilder();
- builder1.setVersion((short) 4);
- builder1.setXid(1L);
- connectionConductor.onFlowRemovedMessage(builder1.build());
- LOG.debug("about to wait for popListener");
- builder1.setXid(2L);
- connectionConductor.onFlowRemovedMessage(builder1.build());
-
- flushMessageProcessing();
- Assert.assertTrue(objFms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS));
- Assert.assertEquals(2, flowremovedMessageCounter);
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onMultipartReplyMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage)}
- * .
- */
- @Test
- public void testOnMultipartReplyMessage() {
- // fail("Not yet implemented");
- // TODO:: add test
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onPacketInMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage)}
- * .
- *
- * @throws InterruptedException
- */
- @Test
- public void testOnPacketInMessage() throws InterruptedException {
- PacketInMessageService objPms = new PacketInMessageService();
- controller.addMessageTranslator(PacketInMessage.class, 4, objPms);
-
- simulateV13PostHandshakeState(connectionConductor);
-
- // Now send PacketIn
- PacketInMessageBuilder builder1 = new PacketInMessageBuilder();
- builder1.setVersion((short) 4);
- builder1.setBufferId((long) 1);
- connectionConductor.onPacketInMessage(builder1.build());
- builder1.setBufferId((long) 2);
- connectionConductor.onPacketInMessage(builder1.build());
-
- flushMessageProcessing();
- Assert.assertTrue(objPms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS));
- Assert.assertEquals(2, packetinMessageCounter);
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onPortStatusMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage)}
- * .
- *
- * @throws InterruptedException
- */
- @Test
- public void testOnPortStatusMessage() throws InterruptedException {
- PortStatusMessageService objPSms = new PortStatusMessageService();
- controller.addMessageTranslator(PortStatusMessage.class, 4, objPSms);
-
- simulateV13PostHandshakeState(connectionConductor);
-
- // Send Port Status messages
- PortStatusMessageBuilder builder1 = new PortStatusMessageBuilder();
- builder1.setVersion((short) 4);
- PortFeatures features = new PortFeatures(true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false);
- builder1.setPortNo(90L).setReason(PortReason.OFPPRADD).setCurrentFeatures(features);
- objPSms.resetLatch(3);
- LOG.debug("sending port message");
- connectionConductor.onPortStatusMessage(builder1.build());
- builder1.setPortNo(90L).setReason(PortReason.OFPPRMODIFY).setCurrentFeatures(features);
- connectionConductor.onPortStatusMessage(builder1.build());
- builder1.setPortNo(90L).setReason(PortReason.OFPPRDELETE).setCurrentFeatures(features);
- connectionConductor.onPortStatusMessage(builder1.build());
-
- flushMessageProcessing();
- Assert.assertTrue(objPSms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS));
- Assert.assertEquals(1, portstatusModifyMessageCounter);
- Assert.assertEquals(1, portstatusAddMessageCounter);
- Assert.assertEquals(1, portstatusDeleteMessageCounter);
- }
-
- private void flushMessageProcessing() throws InterruptedException {
- // make sure that harvester sleeps deeply
- Thread.sleep(maxProcessingTimeout);
- // flushing messages
- queueProcessor.getHarvesterHandle().ping();
- }
-
- /**
- * @throws InterruptedException
- */
- private void executeLater() throws InterruptedException {
- execute(false);
- }
-
- /**
- * @throws InterruptedException
- */
- private void executeNow() throws InterruptedException {
- execute(true);
- connectionConductor.getHsPool().shutdown();
- }
-
- /**
- * @throws InterruptedException
- */
- private void execute(final boolean join) throws InterruptedException {
- libSimulation = new Thread(adapter, "junit-adapter");
- libSimulation.start();
- if (join) {
- libSimulation.join();
- }
- }
-
- private static GetFeaturesOutputBuilder getFeatureResponseMsg() {
- GetFeaturesOutputBuilder getFeaturesOutputBuilder = new GetFeaturesOutputBuilder();
- getFeaturesOutputBuilder.setDatapathId(new BigInteger("102030405060"));
- getFeaturesOutputBuilder.setAuxiliaryId((short) 0);
- getFeaturesOutputBuilder.setBuffers(4L);
- getFeaturesOutputBuilder.setReserved(0L);
- getFeaturesOutputBuilder.setTables((short) 2);
- getFeaturesOutputBuilder.setCapabilities(createCapabilities(84));
-
- return getFeaturesOutputBuilder;
- }
-
- /**
- * @return
- */
- private static Capabilities createCapabilities(final long input) {
- final Boolean FLOW_STATS = (input & (1 << 0)) != 0;
- final Boolean TABLE_STATS = (input & (1 << 1)) != 0;
- final Boolean PORT_STATS = (input & (1 << 2)) != 0;
- final Boolean GROUP_STATS = (input & (1 << 3)) != 0;
- final Boolean IP_REASM = (input & (1 << 5)) != 0;
- final Boolean QUEUE_STATS = (input & (1 << 6)) != 0;
- final Boolean PORT_BLOCKED = (input & (1 << 8)) != 0;
- Capabilities capabilities = new Capabilities(FLOW_STATS, GROUP_STATS, IP_REASM,
- PORT_BLOCKED, PORT_STATS, QUEUE_STATS, TABLE_STATS);
- return capabilities;
- }
-
- public abstract class ProcessingLatchService {
- private CountDownLatch processingLatch = new CountDownLatch(0);
-
- public void resetLatch(int passAmount) {
- processingLatch = new CountDownLatch(passAmount);
- }
-
- protected void countDown() {
- processingLatch.countDown();
- }
-
- public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
- return processingLatch.await(timeout, unit);
- }
- }
-
- public class ExperimenterMessageService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
- @Override
- public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) {
- LOG.debug("Received a packet in Experimenter Service");
- ConnectionConductorImplTest.this.incrExperimenterMessageCounter();
- return null;
- }
- }
-
- public class PacketInMessageService extends ProcessingLatchService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
- @Override
- public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) {
- LOG.debug("Received a packet in PacketIn Service");
- ConnectionConductorImplTest.this.incrPacketinMessageCounter();
- countDown();
- return null;
- }
- }
-
- public class FlowRemovedMessageService extends ProcessingLatchService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
- @Override
- public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) {
- LOG.debug("Received a packet in FlowRemoved Service");
- ConnectionConductorImplTest.this.incrFlowremovedMessageCounter();
- countDown();
- return null;
- }
- }
-
- public class PortStatusMessageService extends ProcessingLatchService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
- @Override
- public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) {
- LOG.debug("Received a packet in PortStatus Service");
- if ((((PortStatusMessage) msg).getReason().equals(PortReason.OFPPRADD))) {
- ConnectionConductorImplTest.this.incrPortstatusAddMessageCounter();
- } else if (((PortStatusMessage) msg).getReason().equals(PortReason.OFPPRDELETE)) {
- ConnectionConductorImplTest.this.incrPortstatusDeleteMessageCounter();
- } else if (((PortStatusMessage) msg).getReason().equals(PortReason.OFPPRMODIFY)) {
- ConnectionConductorImplTest.this.incrPortstatusModifyMessageCounter();
- }
- countDown();
- return null;
- }
- }
-
- public class ErrorMessageService extends ProcessingLatchService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
- @Override
- public List<DataObject> translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) {
- LOG.debug("Received a packet in Experimenter Service");
- ConnectionConductorImplTest.this.incrErrorMessageCounter();
- countDown();
- return null;
- }
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onExperimenterMessage(ExperimenterMessage)}
- * .
- *
- * @throws InterruptedException
- */
- @Test
- public void testOnErrorMessage() throws InterruptedException {
- simulateV13PostHandshakeState(connectionConductor);
- final int messageAmount = 2;
-
- objErms.resetLatch(messageAmount);
- ErrorMessageBuilder builder1 = new ErrorMessageBuilder();
- builder1.setVersion((short) 4);
- builder1.setCode(100);
- connectionConductor.onErrorMessage(builder1.build());
- builder1.setCode(200);
- connectionConductor.onErrorMessage(builder1.build());
-
- flushMessageProcessing();
- Assert.assertTrue(objErms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS));
- Assert.assertEquals(messageAmount, errorMessageCounter);
- }
-
- /**
- * @return listener mapping for:
- * <ul>
- * <li>experimenter</li>
- * <li>error</li>
- * </ul>
- */
- private Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> assembleTranslatorMapping() {
- Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping = new HashMap<>();
- TranslatorKey tKey;
-
- IMDMessageTranslator<OfHeader, List<DataObject>> objEms = new ExperimenterMessageService();
- Collection<IMDMessageTranslator<OfHeader, List<DataObject>>> existingValues = new ArrayList<>();
- existingValues.add(objEms);
- tKey = new TranslatorKey(4, ExperimenterMessage.class.getName());
- translatorMapping.put(tKey, existingValues);
- objErms = new ErrorMessageService();
- existingValues.add(objErms);
- tKey = new TranslatorKey(4, ErrorMessage.class.getName());
- translatorMapping.put(tKey, existingValues);
- return translatorMapping;
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#processPortStatusMsg(PortStatus)}
- * <br><br>
- * Tests for getting features from port status message by port version
- * <ul>
- * <li>features are malformed - one of them is null</li>
- * <li>mismatch between port version and port features</li>
- * <li>mismatch between port version and port features</li>
- * <li>non-existing port version</li>
- * <li>port version OF 1.0</li>
- * <li>port version OF 1.3</li>
- * </ul>
- */
- @Test
- public void testProcessPortStatusMsg() {
- simulateV13PostHandshakeState(connectionConductor);
-
- long portNumber = 90L;
- long portNumberV10 = 91L;
- PortStatusMessage msg;
-
- PortStatusMessageBuilder builder = new PortStatusMessageBuilder();
- PortFeatures features = new PortFeatures(true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false);
- PortFeatures featuresMal = new PortFeatures(true, false, false, false, null, false, false, false, false, false, false, false, false, false, false, false);
- PortFeaturesV10 featuresV10 = new PortFeaturesV10(true, false, false, false, false, false, false, false, false, false, false, false);
-
- //Malformed features
- builder.setVersion((short) 1).setPortNo(portNumber).setReason(PortReason.OFPPRADD).setCurrentFeatures(featuresMal);
- connectionConductor.processPortStatusMsg(builder.build());
- Assert.assertTrue(connectionConductor.getSessionContext().getPortsBandwidth().isEmpty());
- Assert.assertTrue(connectionConductor.getSessionContext().getPhysicalPorts().isEmpty());
-
- //Version-features mismatch
- builder.setCurrentFeatures(features);
- connectionConductor.processPortStatusMsg(builder.build());
- Assert.assertTrue(connectionConductor.getSessionContext().getPortsBandwidth().isEmpty());
- Assert.assertTrue(connectionConductor.getSessionContext().getPhysicalPorts().isEmpty());
-
- //Non existing version
- builder.setVersion((short) 0);
- connectionConductor.processPortStatusMsg(builder.build());
- Assert.assertTrue(connectionConductor.getSessionContext().getPortsBandwidth().isEmpty());
- Assert.assertTrue(connectionConductor.getSessionContext().getPhysicalPorts().isEmpty());
-
- //Version OF 1.3
- builder.setVersion((short) 4);
- msg = builder.build();
- connectionConductor.processPortStatusMsg(builder.build());
- Assert.assertTrue(connectionConductor.getSessionContext().getPortBandwidth(portNumber));
- Assert.assertEquals(connectionConductor.getSessionContext().getPhysicalPort(portNumber), msg);
-
- //Version OF 1.0
- builder.setVersion((short) 1).setPortNo(portNumberV10).setCurrentFeatures(null).setCurrentFeaturesV10(featuresV10);
- msg = builder.build();
- connectionConductor.processPortStatusMsg(builder.build());
- Assert.assertTrue(connectionConductor.getSessionContext().getPortBandwidth(portNumberV10));
- Assert.assertEquals(connectionConductor.getSessionContext().getPhysicalPort(portNumberV10), msg);
- }
-
-
- @Test
- public void testHandshakeFailOperations(){
- connectionConductor.onHandshakeFailure();
- connectionConductor.checkState(ConnectionConductor.CONDUCTOR_STATE.RIP);
- }
- private static void simulateV13PostHandshakeState(final ConnectionConductorImpl conductor) {
- GetFeaturesOutputBuilder featureOutput = getFeatureResponseMsg();
- conductor.postHandshakeBasic(featureOutput.build(), OFConstants.OFP_VERSION_1_3);
- LOG.debug("simulating post handshake event done");
- }
-}
package org.opendaylight.openflowplugin.openflow.md.core;
-import static org.mockito.Mockito.when;
import junit.framework.TestCase;
-import org.junit.Before;
import org.junit.Test;
-import org.mockito.Mock;
import org.opendaylight.openflowplugin.api.ConnectionException;
import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF;
public class ErrorHandlerSimpleImplTest extends TestCase {
ErrorHandler errorHandler = new ErrorHandlerSimpleImpl();
- @Mock
- SessionContext sessionContext;
-
- @Mock
- SwitchSessionKeyOF switchSessionKeyOF;
-
- @Before
- public void setup() {
- when(sessionContext.getSessionKey()).thenReturn(switchSessionKeyOF);
- when(switchSessionKeyOF.getId()).thenReturn(new byte[0]);
- }
-
@Test
public void testHandleException() throws Exception {
ConnectionException connectionException = new ConnectionException("Exception for testing purpose only.");
- errorHandler.handleException(connectionException, sessionContext);
+ errorHandler.handleException(connectionException);
Exception someException = new Exception("Exception for testing purpose only.");
- errorHandler.handleException(someException, sessionContext);
+ errorHandler.handleException(someException);
}
}
\ No newline at end of file
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler;
import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeListener;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.HelloElementType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
@Before
public void setUp() {
handshakeManager = new HandshakeManagerImpl(adapter, OFConstants.OFP_VERSION_1_3,
- ConnectionConductor.VERSION_ORDER);
+ OFConstants.VERSION_ORDER);
handshakeManager.setErrorHandler(errorHandler);
handshakeManager.setHandshakeListener(handshakeListener);
handshakeManager.setUseVersionBitmap(false);
// logging errors if occurred
ArgumentCaptor<Throwable> errorCaptor = ArgumentCaptor.forClass(Throwable.class);
Mockito.verify(errorHandler, Mockito.atMost(1)).handleException(
- errorCaptor.capture(), Matchers.any(SessionContext.class));
+ errorCaptor.capture());
for (Throwable problem : errorCaptor.getAllValues()) {
LOG.warn(problem.getMessage(), problem);
}
Mockito.verify(errorHandler, Mockito.times(expectedErrors)).handleException(
- Matchers.any(Throwable.class), Matchers.any(SessionContext.class));
+ Matchers.any(Throwable.class));
}
/**
+++ /dev/null
-/**
- * Copyright (c) 2013 IBM 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.openflowplugin.openflow.md.core;
-
-import java.util.List;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketIn;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MDControllerTest {
- protected static final Logger LOG = LoggerFactory
- .getLogger(ConnectionConductorImplTest.class);
-
- protected MDController controller;
-
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
- controller = new MDController(convertorManager);
- controller.init();
- }
-
- /**
- * @throws java.lang.Exception
- */
- @After
- public void tearDown() throws Exception {
- controller = null;
- }
-
- @Test
- public void testAddMessageListeners() {
- //clean translators
- controller.getMessageTranslators().clear();
-
- // Empty map
- int size = controller.getMessageTranslators().size();
- Assert.assertEquals(0, size);
- // Add one
- IMDMessageTranslator<OfHeader, List<DataObject>> objDps = new DataPacketService() ;
- controller.addMessageTranslator(PacketIn.class, 4, objDps);
- size = controller.getMessageTranslators().size();
- Assert.assertEquals(1, size);
- // Remove one
- controller.removeMessageTranslator(PacketIn.class, 4, objDps);
- size = controller.getMessageTranslators().size();
- Assert.assertEquals(0, size);
- // Add two and remove One
- IMDMessageTranslator objFps = new FlowProgrammerService();
- controller.addMessageTranslator(PacketIn.class, 4, objDps);
- controller.addMessageTranslator(FlowRemoved.class, 4, objFps);
- controller.removeMessageTranslator(FlowRemoved.class, 4, objFps);
- size = controller.getMessageTranslators().size();
- Assert.assertEquals(1, size);
- // Add one more and remove both
- controller.addMessageTranslator(FlowRemoved.class, 4, objFps);
- controller.removeMessageTranslator(PacketIn.class, 4, objDps);
- controller.removeMessageTranslator(FlowRemoved.class, 4, objFps);
- size = controller.getMessageTranslators().size();
- Assert.assertEquals(0, size);
- // Add multiple listeners to messageTypes
- controller.addMessageTranslator(PacketIn.class, 4, objDps);
- controller.addMessageTranslator(PacketIn.class, 4, objFps); // Duplicate value entry
- controller.addMessageTranslator(FlowRemoved.class, 4, objFps);
- size = controller.getMessageTranslators().size();
- Assert.assertEquals(2, size);
- // Remove one of the multiple listener, still size remains same
- controller.removeMessageTranslator(PacketIn.class, 4, objFps);
- size = controller.getMessageTranslators().size();
- Assert.assertEquals(2, size);
- }
-
- private class DataPacketService implements IMDMessageTranslator<OfHeader, List<DataObject>> {
- @Override
- public List<DataObject> translate(SwitchConnectionDistinguisher cookie, SessionContext sw, OfHeader msg) {
- LOG.debug("Received a packet in DataPacket Service");
- return null;
- }
- }
-
- private class FlowProgrammerService implements IMDMessageTranslator<OfHeader, DataObject> {
- @Override
- public DataObject translate(SwitchConnectionDistinguisher cookie, SessionContext sw, OfHeader msg) {
- LOG.debug("Received a packet in Flow Programmer Service");
- return null;
- }
- }
-
-
-
-}
import org.junit.Assert;
import org.junit.Test;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
+import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.HelloElementType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.hello.Elements;
public void testCreateHelloInputWoElements() {
short highestVersion = (short) 0x04;
long xid = 42L;
-
+
HelloInput helloMsg = MessageFactory.createHelloInput(highestVersion, xid);
Assert.assertEquals(highestVersion, helloMsg.getVersion().shortValue());
Assert.assertEquals(xid, helloMsg.getXid().longValue());
long xid = 42L;
Boolean[] expectedVersionBitmap = new Boolean[]{
false, true, false, false, true};
-
- HelloInput helloMsg = MessageFactory.createHelloInput(highestVersion, xid,
- ConnectionConductor.VERSION_ORDER);
+
+ HelloInput helloMsg = MessageFactory.createHelloInput(highestVersion, xid, OFConstants.VERSION_ORDER);
Assert.assertEquals(highestVersion, helloMsg.getVersion().shortValue());
Assert.assertEquals(xid, helloMsg.getXid().longValue());
Assert.assertEquals(1, helloMsg.getElements().size());
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core;\r
-\r
-import org.junit.Assert;\r
-import org.junit.Test;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessageBuilder;\r
-\r
-/**\r
- * @author michal.polkorab\r
- *\r
- */\r
-public class NotificationQueueWrapperTest {\r
-\r
- /**\r
- * Test NotificationQueueWrapper creation\r
- */\r
- @Test(expected=IllegalArgumentException.class)\r
- public void test() {\r
- NotificationQueueWrapper queueWrapper = new NotificationQueueWrapper(null, null);\r
- }\r
-\r
- /**\r
- * Test NotificationQueueWrapper creation\r
- */\r
- @Test(expected=IllegalArgumentException.class)\r
- public void test2() {\r
- EchoRequestMessageBuilder echoBuilder = new EchoRequestMessageBuilder();\r
- NotificationQueueWrapper queueWrapper = new NotificationQueueWrapper(echoBuilder.build(), null);\r
- }\r
-\r
- /**\r
- * Test NotificationQueueWrapper creation\r
- */\r
- @Test\r
- public void test3() {\r
- EchoRequestMessageBuilder echoBuilder = new EchoRequestMessageBuilder();\r
- NotificationQueueWrapper queueWrapper = new NotificationQueueWrapper(echoBuilder.build(),\r
- (short) EncodeConstants.OF13_VERSION_ID);\r
-\r
- Assert.assertEquals("Wrong implemented interface", "org.opendaylight.openflowplugin.api.openflow.md"\r
- + ".core.NotificationQueueWrapper", queueWrapper.getImplementedInterface().getName());\r
- Assert.assertEquals("Wrong version", 4, queueWrapper.getVersion().intValue());\r
- Assert.assertEquals("Wrong notification", "org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol"\r
- + ".rev130731.EchoRequestMessage", queueWrapper.getNotification().getImplementedInterface().getName());\r
- Assert.assertEquals("Wrong xid", -1, queueWrapper.getXid().longValue());\r
- queueWrapper.setXid(12345L);\r
- Assert.assertEquals("Wrong xid", 12345, queueWrapper.getXid().intValue());\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core;
-
-import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author mirehak
- * @param <T> resulting type
- *
- */
-public class PopListenerCountingImpl<T> implements PopListener<T> {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(PopListenerCountingImpl.class);
- private int count = 0;
-
- @Override
- public synchronized void onPop(T processedMessage) {
- LOG.debug("message popped: {}", processedMessage);
- count += 1;
- notify();
- }
-
- /**
- * @return the count
- */
- public int getCount() {
- return count;
- }
-
-}
+++ /dev/null
-/*
- * 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.openflowplugin.openflow.md.core;
-
-import static org.junit.Assert.assertNotNull;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-
-/**
- * Created by Martin Bobak mbobak@cisco.com on 8/29/14.
- */
-@RunWith(MockitoJUnitRunner.class)
-public class SwitchConnectionHandlerImplTest {
-
-
- @Mock
- private ErrorHandler errorHandler;
- @Mock
- private MessageSpy<DataContainer> messageSpy;
- @Mock
- private ConnectionAdapter connectionAdapter;
-
- /**
- * Test method for SwitchConnectionHandlerImpl initialization.
- */
- @Test
- public void basicInitializationTest() {
- SwitchConnectionHandlerImpl switchConnectionHandler = new SwitchConnectionHandlerImpl();
- assertNotNull(switchConnectionHandler);
- switchConnectionHandler.setMessageSpy(messageSpy);
- switchConnectionHandler.setErrorHandler(errorHandler);
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Stack;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import org.opendaylight.controller.sal.common.util.RpcErrors;
-import org.opendaylight.controller.sal.common.util.Rpcs;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
-import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler;
-import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
-import org.opendaylight.openflowjava.protocol.api.extensibility.AlienMessageListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEventBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
-import org.opendaylight.yangtools.yang.binding.Notification;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
-import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author mirehak
- */
-public class ConnectionAdapterStackImpl implements ConnectionAdapter, Runnable {
-
- /** notify and rpc-response thread start default delay in [ms] */
- public static final int JOB_DELAY = 50;
-
- protected static final Logger LOG = LoggerFactory
- .getLogger(ConnectionAdapterStackImpl.class);
-
- protected Stack<? extends SwitchTestEvent> eventPlan;
- protected OpenflowProtocolListener ofListener;
- protected SystemNotificationsListener systemListener;
-
- protected Map<Long, SettableFuture<?>> rpcResults = new HashMap<>();
- protected boolean planTouched = false;
-
- private long proceedTimeout;
-
- protected List<Exception> occuredExceptions = new ArrayList<>();
-
- private ConnectionReadyListener connectionReadyListener;
-
- private int planItemCounter;
-
- private boolean autoRead = true;
- private final ExecutorService pool;
- private boolean packetInFiltering;
-
-
- /**
- * default ctor
- */
- public ConnectionAdapterStackImpl() {
- pool = Executors.newSingleThreadExecutor();
- }
-
- @Override
- public synchronized Future<RpcResult<BarrierOutput>> barrier(
- final BarrierInput arg0) {
- checkRpcAndNext(arg0, "barrier");
- SettableFuture<RpcResult<BarrierOutput>> result = createAndRegisterRpcResult(arg0);
- return result;
- }
-
- @Override
- public synchronized Future<RpcResult<EchoOutput>> echo(final EchoInput arg0) {
- checkRpcAndNext(arg0, "echo");
- Future<RpcResult<EchoOutput>> result = createAndRegisterRpcResult(arg0);
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> echoReply(final EchoReplyInput arg0) {
- checkRpcAndNext(arg0, "echoReply");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> experimenter(final ExperimenterInput arg0) {
- checkRpcAndNext(arg0, "experimenter");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> flowMod(final FlowModInput arg0) {
- checkRpcAndNext(arg0, "flowMod");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public synchronized Future<RpcResult<GetAsyncOutput>> getAsync(
- final GetAsyncInput arg0) {
- checkRpcAndNext(arg0, "echo");
- Future<RpcResult<GetAsyncOutput>> result = createAndRegisterRpcResult(arg0);
- return result;
- }
-
- @Override
- public synchronized Future<RpcResult<GetConfigOutput>> getConfig(
- final GetConfigInput arg0) {
- checkRpcAndNext(arg0, "echo");
- Future<RpcResult<GetConfigOutput>> result = createAndRegisterRpcResult(arg0);
- return result;
- }
-
- @Override
- public synchronized Future<RpcResult<GetFeaturesOutput>> getFeatures(
- final GetFeaturesInput arg0) {
- checkRpcAndNext(arg0, "getFeatures");
- Future<RpcResult<GetFeaturesOutput>> result = createAndRegisterRpcResult(arg0);
- return result;
- }
-
- @Override
- public synchronized Future<RpcResult<GetQueueConfigOutput>> getQueueConfig(
- final GetQueueConfigInput arg0) {
- checkRpcAndNext(arg0, "echo");
- Future<RpcResult<GetQueueConfigOutput>> result = createAndRegisterRpcResult(arg0);
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> groupMod(final GroupModInput arg0) {
- checkRpcAndNext(arg0, "groupMod");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> hello(final HelloInput arg0) {
- checkRpcAndNext(arg0, "helloReply");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> meterMod(final MeterModInput arg0) {
- checkRpcAndNext(arg0, "meterMod");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> packetOut(final PacketOutInput arg0) {
- checkRpcAndNext(arg0, "packetOut");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> portMod(final PortModInput arg0) {
- checkRpcAndNext(arg0, "portMod");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public synchronized Future<RpcResult<RoleRequestOutput>> roleRequest(
- final RoleRequestInput arg0) {
- checkRpcAndNext(arg0, "echo");
- Future<RpcResult<RoleRequestOutput>> result = createAndRegisterRpcResult(arg0);
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> setAsync(final SetAsyncInput arg0) {
- checkRpcAndNext(arg0, "setAsync");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> setConfig(final SetConfigInput arg0) {
- checkRpcAndNext(arg0, "setConfig");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public Future<RpcResult<Void>> tableMod(final TableModInput arg0) {
- checkRpcAndNext(arg0, "tableMod");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public Future<Boolean> disconnect() {
- LOG.debug("adapter is told to disconnect");
- DisconnectEventBuilder disconnectEventBuilder = new DisconnectEventBuilder();
- disconnectEventBuilder.setInfo("disconnected by plugin");
- systemListener.onDisconnectEvent(disconnectEventBuilder.build());
- return null;
- }
-
- @Override
- public boolean isAlive() {
- // TODO make dynamic
- return true;
- }
-
- @Override
- public void setMessageListener(final OpenflowProtocolListener ofListener) {
- this.ofListener = ofListener;
- }
-
- @Override
- public void checkListeners() {
- if (ofListener == null || systemListener == null
- || connectionReadyListener == null) {
- occuredExceptions
- .add(new IllegalStateException("missing listeners"));
- }
- }
-
- @Override
- public void setSystemListener(final SystemNotificationsListener systemListener) {
- this.systemListener = systemListener;
- }
-
- @Override
- public void setAlienMessageListener(final AlienMessageListener alienMessageListener) {
-
- }
-
- /**
- * @param rpcInput
- * rpc call parameter
- * @param rpcName
- * rpc yang name
- */
- private boolean checkRpc(final OfHeader rpcInput, final String rpcName) {
- String msg = null;
- boolean finished = true;
-
- if (eventPlan.isEmpty()) {
- throw new IllegalStateException("eventPlan already depleted");
- }
-
- LOG.debug("checking rpc: name={}, ver={}, xid={}", rpcName,
- rpcInput.getVersion(), rpcInput.getXid());
- if (!(eventPlan.peek() instanceof SwitchTestWaitForRpcEvent)
- && !(eventPlan.peek() instanceof SwitchTestWaitForAllEvent)) {
- if (eventPlan.peek() instanceof SwitchTestNotificationEvent) {
- SwitchTestNotificationEvent notifEvent = (SwitchTestNotificationEvent) (eventPlan
- .peek());
- msg = "expected [notification: "
- + notifEvent.getPlannedNotification() + "], got ["
- + rpcInput.getClass().getSimpleName() + "]";
- } else if (eventPlan.peek() instanceof SwitchTestRcpResponseEvent) {
- SwitchTestRcpResponseEvent rpcEvent = (SwitchTestRcpResponseEvent) (eventPlan
- .peek());
- msg = "expected [rpc: " + rpcEvent.getPlannedRpcResponse()
- + "], got [" + rpcInput.getClass().getSimpleName()
- + "]";
- }
- } else {
- if (eventPlan.peek() instanceof SwitchTestWaitForAllEvent) {
- SwitchTestWaitForAllEvent switchTestWaitForAll = (SwitchTestWaitForAllEvent) eventPlan
- .peek();
- Set<SwitchTestWaitForRpcEvent> eventBag = switchTestWaitForAll
- .getWaitEventBag();
- List<String> msgLot = new ArrayList<>();
-
- if (eventBag == null || eventBag.isEmpty()) {
- msg = "no wait events in bag";
- } else {
- finished = false;
- for (SwitchTestWaitForRpcEvent switchTestWaitForRpc : eventBag) {
- String msgPart = checkSingleRpcContent(rpcInput,
- rpcName, switchTestWaitForRpc);
-
- if (msgPart != null) {
- msgLot.add(msgPart);
- } else {
- LOG.debug("wait event matched: {}", rpcName);
- eventBag.remove(switchTestWaitForRpc);
- if (eventBag.isEmpty()) {
- finished = true;
- }
- msgLot.clear();
- break;
- }
- }
- }
-
- if (!msgLot.isEmpty()) {
- msg = Joiner.on(" | ").join(msgLot);
- }
- } else if (eventPlan.peek() instanceof SwitchTestWaitForRpcEvent) {
- SwitchTestWaitForRpcEvent switchTestRpcEvent = (SwitchTestWaitForRpcEvent) eventPlan
- .peek();
- msg = checkSingleRpcContent(rpcInput, rpcName,
- switchTestRpcEvent);
- }
- }
-
- if (msg != null) {
- LOG.debug("rpc check .. FAILED: " + msg);
- occuredExceptions.add(new IllegalArgumentException("step:"
- + planItemCounter + " | " + msg));
- } else {
- LOG.debug("rpc check .. OK");
- }
- return finished;
- }
-
- /**
- * @param rpcInput
- * @param rpcName
- * @param switchTestWaitForRpc
- * @return
- */
- private static String checkSingleRpcContent(final OfHeader rpcInput,
- final String rpcName, final SwitchTestWaitForRpcEvent switchTestWaitForRpc) {
- String failureMsg = null;
- if (!rpcName.equals(switchTestWaitForRpc.getRpcName())) {
- failureMsg = "expected rpc name ["
- + switchTestWaitForRpc.getRpcName() + "], got [" + rpcName
- + "]";
- } else if (!rpcInput.getXid().equals(switchTestWaitForRpc.getXid())) {
- failureMsg = "expected " + rpcName + ".xid ["
- + switchTestWaitForRpc.getXid() + "], got ["
- + rpcInput.getXid() + "]";
- }
-
- return failureMsg;
- }
-
- /**
- * @param rpcInput
- * rpc call parameter
- * @param rpcName
- * rpc yang name
- */
- private synchronized void checkRpcAndNext(final OfHeader rpcInput, final String rpcName) {
- boolean finished = checkRpc(rpcInput, rpcName);
- if (finished) {
- next();
- }
- }
-
- /**
- * discard current event, execute next, if possible
- */
- private void next() {
- LOG.debug("<---> STEPPING TO NEXT event in plan (leaving [{}] {})",
- planItemCounter, eventPlan.peek());
- eventPlan.pop();
- planItemCounter++;
- planTouched = true;
- try {
- Thread.sleep(JOB_DELAY);
- } catch (InterruptedException e) {
- LOG.error(e.getMessage(), e);
- }
- notify();
- }
-
- /**
- * start or continue processing plan
- */
- private synchronized void proceed() {
- boolean processed = false;
- LOG.debug("proceeding plan item[{}]: {}", planItemCounter,
- eventPlan.peek());
- if (eventPlan.peek() instanceof SwitchTestNotificationEvent) {
- SwitchTestNotificationEvent notification = (SwitchTestNotificationEvent) eventPlan
- .peek();
- processNotification(notification);
- processed = true;
- } else if (eventPlan.peek() instanceof SwitchTestRcpResponseEvent) {
- SwitchTestRcpResponseEvent rpcResponse = (SwitchTestRcpResponseEvent) eventPlan
- .peek();
- processRpcResponse(rpcResponse);
- processed = true;
- } else if (eventPlan.peek() instanceof SwitchTestCallbackEvent) {
- SwitchTestCallbackEvent callbackEvent = (SwitchTestCallbackEvent) eventPlan
- .peek();
- try {
- callbackEvent.getCallback().call();
- } catch (Exception e) {
- LOG.error(e.getMessage(), e);
- occuredExceptions.add(e);
- }
- processed = true;
- }
-
- if (processed) {
- next();
- } else {
- try {
- LOG.debug("now WAITING for OF_LISTENER to act ..");
- wait(proceedTimeout);
- } catch (InterruptedException e) {
- LOG.error(e.getMessage(), e);
- }
- }
- }
-
- @Override
- public void run() {
- LOG.debug("|---> evenPlan STARTING ..");
- planItemCounter = 0;
- while (!eventPlan.isEmpty()) {
- planTouched = false;
- proceed();
- if (!planTouched) {
- occuredExceptions
- .add(new IllegalStateException(
- "eventPlan STALLED, planItemCounter="
- + planItemCounter));
- break;
- }
- }
-
- try {
- Thread.sleep(JOB_DELAY);
- } catch (InterruptedException e) {
- LOG.error(e.getMessage(), e);
- }
- LOG.debug("<---| eventPlan DONE");
- }
-
- /**
- * @param notificationEvent
- */
- private synchronized void processNotification(
- final SwitchTestNotificationEvent notificationEvent) {
-
- Notification notification = notificationEvent.getPlannedNotification();
- LOG.debug("notificating OF_LISTENER: "
- + notification.getClass().getSimpleName());
-
- // system events
- if (notification instanceof DisconnectEvent) {
- systemListener.onDisconnectEvent((DisconnectEvent) notification);
- }
- // of notifications
- else if (notification instanceof EchoRequestMessage) {
- ofListener.onEchoRequestMessage((EchoRequestMessage) notification);
- } else if (notification instanceof ErrorMessage) {
- ofListener.onErrorMessage((ErrorMessage) notification);
- } else if (notification instanceof ExperimenterMessage) {
- ofListener
- .onExperimenterMessage((ExperimenterMessage) notification);
- } else if (notification instanceof FlowRemovedMessage) {
- ofListener.onFlowRemovedMessage((FlowRemovedMessage) notification);
- } else if (notification instanceof HelloMessage) {
- ofListener.onHelloMessage((HelloMessage) notification);
- } else if (notification instanceof MultipartReplyMessage) {
- ofListener
- .onMultipartReplyMessage((MultipartReplyMessage) notification);
- } else if (notification instanceof PacketInMessage) {
- ofListener.onPacketInMessage((PacketInMessage) notification);
- } else if (notification instanceof PortStatusMessage) {
- ofListener.onPortStatusMessage((PortStatusMessage) notification);
- }
- // default
- else {
- occuredExceptions.add(new IllegalStateException("step:"
- + planItemCounter + " | "
- + "message listening not supported for type: "
- + notification.getClass()));
- }
-
- LOG.debug("notification [" + notification.getClass().getSimpleName()
- + "] .. done");
- }
-
- /**
- * @param rpcResponse
- */
- private synchronized void processRpcResponse(
- final SwitchTestRcpResponseEvent rpcResponse) {
- OfHeader plannedRpcResponseValue = rpcResponse.getPlannedRpcResponse();
- LOG.debug("rpc-responding to OF_LISTENER: {}", rpcResponse.getXid());
-
- @SuppressWarnings("unchecked")
- final SettableFuture<RpcResult<?>> response = (SettableFuture<RpcResult<?>>) rpcResults
- .get(rpcResponse.getXid());
-
- if (response != null) {
- boolean successful = plannedRpcResponseValue != null;
- Collection<RpcError> errors;
- if (successful) {
- errors = Collections.emptyList();
- } else {
- errors = Lists.newArrayList(RpcErrors.getRpcError("unit",
- "unit", "not requested", ErrorSeverity.ERROR,
- "planned response to RPC.id = " + rpcResponse.getXid(),
- ErrorType.RPC, new Exception(
- "rpc response failed (planned behavior)")));
- }
-
- final RpcResult<?> result = Rpcs.getRpcResult(successful,
- plannedRpcResponseValue, errors);
- setFutureViaPool(response, result);
- } else {
- String msg = "RpcResponse not expected: xid="
- + rpcResponse.getXid() + ", "
- + plannedRpcResponseValue.getClass().getSimpleName();
- LOG.error(msg);
- occuredExceptions.add(new IllegalStateException("step:"
- + planItemCounter + " | " + msg));
- }
-
- LOG.debug("rpc [" + rpcResponse.getXid() + "] .. done");
- }
-
- private void setFutureViaPool(final SettableFuture<RpcResult<?>> response, final RpcResult<?> result) {
- pool.execute(new Runnable() {
- @Override
- public void run() {
- response.set(result);
- }
- });
- }
-
- /**
- * @param arg0
- * rpc call content
- * @return rpc future result
- */
- private <IN extends OfHeader, OUT extends OfHeader> SettableFuture<RpcResult<OUT>> createAndRegisterRpcResult(
- final IN arg0) {
- SettableFuture<RpcResult<OUT>> result = SettableFuture.create();
- rpcResults.put(arg0.getXid(), result);
- return result;
- }
-
- /**
- * @return rpc future result
- */
- private static ListenableFuture<RpcResult<Void>> createOneWayRpcResult() {
- return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
- }
-
- /**
- * @param eventPlan
- * the eventPlan to set
- */
- public void setEventPlan(final Stack<? extends SwitchTestEvent> eventPlan) {
- this.eventPlan = eventPlan;
- }
-
- /**
- * @param proceedTimeout
- * max timeout for processing one planned event (in [ms])
- */
- public void setProceedTimeout(final long proceedTimeout) {
- this.proceedTimeout = proceedTimeout;
- }
-
- /**
- * @return the occuredExceptions
- */
- public List<Exception> getOccuredExceptions() {
- return occuredExceptions;
- }
-
- @Override
- public void fireConnectionReadyNotification() {
- connectionReadyListener.onConnectionReady();
- }
-
- @Override
- public void setConnectionReadyListener(
- final ConnectionReadyListener connectionReadyListener) {
- this.connectionReadyListener = connectionReadyListener;
- }
-
- @Override
- public Future<RpcResult<Void>> multipartRequest(final MultipartRequestInput arg0) {
- checkRpcAndNext(arg0, "multipartRequestInput");
- ListenableFuture<RpcResult<Void>> result = createOneWayRpcResult();
- return result;
- }
-
- @Override
- public InetSocketAddress getRemoteAddress() {
- return InetSocketAddress.createUnresolved("unittest-odl.example.org", 4242);
- }
-
- @Override
- public boolean isAutoRead() {
- return autoRead;
- }
-
- @Override
- public <T extends OutboundQueueHandler> OutboundQueueHandlerRegistration<T> registerOutboundQueueHandler(final T t, final int i, final long l) {
- return null;
- }
-
- @Override
- public void setAutoRead(final boolean autoRead) {
- this.autoRead = autoRead;
- }
-
- @Override
- public void setPacketInFiltering(final boolean packetInFiltering) {
- this.packetInFiltering = packetInFiltering;
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.concurrent.Callable;
-
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.Notification;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author mirehak
- */
-public abstract class EventFactory {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(EventFactory.class);
-
- /** default protocol version */
- public static final Short DEFAULT_VERSION = 4;
-
- /**
- * @param xid
- * transaction id
- * @param version
- * version id
- * @param builder
- * message builder instance
- * @return default notification event
- */
- public static SwitchTestNotificationEvent createDefaultNotificationEvent(
- long xid, short version, Object builder) {
- SwitchTestNotificationEventImpl event = new SwitchTestNotificationEventImpl();
- Notification notification = build(setupHeader(xid, version, builder));
- event.setNotification(notification);
- return event;
- }
-
- /**
- * @param xid
- * transaction id
- * @param version
- * version id
- * @param builder
- * rpc response builder instance
- * @return default notification event
- */
- public static SwitchTestRcpResponseEvent createDefaultRpcResponseEvent(
- long xid, short version, Object builder) {
- SwitchTestRcpResponseEventImpl event = new SwitchTestRcpResponseEventImpl();
- OfHeader rpcResponse = build(setupHeader(xid, version, builder));
- event.setResponse(rpcResponse);
- event.setXid(xid);
- return event;
- }
-
- /**
- * @param setupHeader
- * @return
- */
- @SuppressWarnings("unchecked")
- private static <E> E build(Object builder) {
- E notification = null;
- try {
- Class<?> builderClazz = builder.getClass();
- notification = (E) builderClazz.getMethod("build", new Class[0])
- .invoke(builder, new Object[0]);
- } catch (Exception e) {
- LOG.error(e.getMessage(), e);
- }
- return notification;
- }
-
- /**
- * @param xid
- * transaction id
- * @param rpcName
- * name of rpc method
- * @return default notification event
- */
- public static SwitchTestWaitForRpcEvent createDefaultWaitForRpcEvent(
- long xid, String rpcName) {
- SwitchTestWaitForRpcEventImpl event = new SwitchTestWaitForRpcEventImpl();
- event.setRpcName(rpcName);
- event.setXid(xid);
- return event;
- }
-
- /**
- * @param events
- * @return wait for all wrapper
- */
- public static SwitchTestWaitForAllEvent createDefaultWaitForAllEvent(
- SwitchTestWaitForRpcEvent... events) {
- SwitchTestWaitForAllEventImpl eventBag = new SwitchTestWaitForAllEventImpl();
- HashSet<SwitchTestWaitForRpcEvent> eventsSet = new HashSet<>(Arrays.asList(events));
- eventBag.setEventBag(eventsSet);
- return eventBag;
- }
-
- /**
- * @param xid
- * @param version
- * @param builder
- * @return original builder
- */
- public static <E> E setupHeader(long xid, short version, E builder) {
- try {
- Class<?> builderClazz = builder.getClass();
- builderClazz.getMethod("setXid", Long.class).invoke(builder, xid);
- builderClazz.getMethod("setVersion", Short.class).invoke(builder,
- version);
- } catch (Exception e) {
- LOG.error(e.getMessage(), e);
- }
-
- return builder;
- }
-
- /**
- * use {@link #DEFAULT_VERSION}
- * @param xid
- * @param builder
- * @return original builder
- */
- public static <E> E setupHeader(long xid, E builder) {
- return setupHeader(xid, DEFAULT_VERSION, builder);
- }
-
- /**
- * @param connectionConductor
- * @return scenario callback
- */
- public static SwitchTestCallbackEventImpl createConnectionReadyCallback(
- final ConnectionReadyListener connectionConductor) {
- SwitchTestCallbackEventImpl connectionReadyCallback = new SwitchTestCallbackEventImpl();
- connectionReadyCallback.setCallable(new Callable<Void>() {
- @Override
- public Void call() throws Exception {
- connectionConductor.onConnectionReady();
- return null;
- }
- });
- return connectionReadyCallback;
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-import java.util.concurrent.Callable;
-
-/**
- * @author mirehak
- */
-public interface SwitchTestCallbackEvent extends SwitchTestEvent {
-
- /**
- * @return callback to be executed
- */
- public Callable<Void> getCallback();
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-import java.util.concurrent.Callable;
-
-/**
- * @author mirehak
- *
- */
-public class SwitchTestCallbackEventImpl implements SwitchTestCallbackEvent {
-
- private Callable<Void> callable;
-
- /**
- * @param callable the callable to set
- */
- public void setCallable(Callable<Void> callable) {
- this.callable = callable;
- }
-
- @Override
- public Callable<Void> getCallback() {
- return callable;
- }
-
- @Override
- public String toString() {
- String callableDesc = null;
- if (callable != null) {
- callableDesc = "Callable<Void>:"+System.identityHashCode(callable);
- }
- return "SwitchTestCallbackEventImpl [" + callableDesc + "]";
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-/**
- * @author mirehak
- */
-public interface SwitchTestEvent {
- // nothing, unifying iface
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-import org.opendaylight.yangtools.yang.binding.Notification;
-
-/**
- * @author mirehak
- */
-public interface SwitchTestNotificationEvent extends SwitchTestEvent {
-
- /**
- * @return next switch notification/rpc response
- */
- Notification getPlannedNotification();
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yangtools.yang.binding.Notification;
-
-/**
- * @author mirehak
- */
-public class SwitchTestNotificationEventImpl implements
- SwitchTestNotificationEvent {
-
- private Notification notification;
-
- /**
- * @param notification
- * the notification to set
- */
- public void setNotification(Notification notification) {
- this.notification = notification;
- }
-
- @Override
- public Notification getPlannedNotification() {
- return notification;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("SwitchTestNotificationEventImpl [notification=");
- if (notification instanceof OfHeader) {
- OfHeader header = (OfHeader) notification;
- sb.append("version:").append(header.getVersion()).append(';')
- .append("xid:").append(header.getXid()).append(';')
- .append("type:").append(header.getClass().getSimpleName());
- } else {
- sb.append(notification.toString());
- }
- sb.append(']');
- return sb.toString();
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-
-/**
- * @author mirehak
- */
-public interface SwitchTestRcpResponseEvent extends SwitchTestEvent {
-
- /**
- * @return switch notification/rpc response
- */
- public OfHeader getPlannedRpcResponse();
-
- /**
- * @return response transaction id
- */
- public long getXid();
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-
-/**
- * @author mirehak
- */
-public class SwitchTestRcpResponseEventImpl implements
- SwitchTestRcpResponseEvent {
-
- private OfHeader response;
- private long xid;
-
- /**
- * @param response
- * the response to set
- */
- public void setResponse(OfHeader response) {
- this.response = response;
- }
-
- @Override
- public OfHeader getPlannedRpcResponse() {
- return response;
- }
-
- @Override
- public long getXid() {
- return xid;
- }
-
- /**
- * @param xid
- * the xid to set
- */
- public void setXid(long xid) {
- this.xid = xid;
- }
-
- @Override
- public String toString() {
- return "SwitchTestRcpResponseEventImpl [response=" + response.getClass().getSimpleName()
- + ", xid=" + xid + "]";
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-import java.util.Set;
-
-/**
- * @author mirehak
- */
-public interface SwitchTestWaitForAllEvent extends SwitchTestEvent {
-
- /**
- * @return set of wait events
- */
- public Set<SwitchTestWaitForRpcEvent> getWaitEventBag();
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-/**
- * @author mirehak
- *
- */
-public class SwitchTestWaitForAllEventImpl implements SwitchTestWaitForAllEvent {
-
- private Set<SwitchTestWaitForRpcEvent> eventBag;
-
- /**
- * @param eventBag the eventBag to set
- */
- public void setEventBag(Set<SwitchTestWaitForRpcEvent> eventBag) {
- this.eventBag = eventBag;
- }
-
- @Override
- public Set<SwitchTestWaitForRpcEvent> getWaitEventBag() {
- return eventBag;
- }
-
- @Override
- public String toString() {
- List<String> rpcNames = null;
- if (eventBag != null) {
- rpcNames = new ArrayList<>();
- for (SwitchTestWaitForRpcEvent waitEvent : eventBag) {
- rpcNames.add(waitEvent.getRpcName()+"["+waitEvent.getXid()+"]");
- }
- }
- return "SwitchTestWaitForAllEventImpl "+rpcNames;
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-/**
- * @author mirehak
- */
-public interface SwitchTestWaitForRpcEvent extends SwitchTestEvent {
-
- /**
- * @return expected name of RPC
- */
- public String getRpcName();
-
- /**
- * @return expected transaction ID
- */
- public long getXid();
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.plan;
-
-/**
- * @author mirehak
- */
-public class SwitchTestWaitForRpcEventImpl implements SwitchTestWaitForRpcEvent {
-
- private String rpcName;
- private long xid;
-
- @Override
- public String getRpcName() {
- return rpcName;
- }
-
- @Override
- public long getXid() {
- return xid;
- }
-
- /**
- * @param rpcName
- * the rpcName to set
- */
- public void setRpcName(String rpcName) {
- this.rpcName = rpcName;
- }
-
- /**
- * @param xid
- * the xid to set
- */
- public void setXid(long xid) {
- this.xid = xid;
- }
-
- @Override
- public String toString() {
- return "SwitchTestWaitForRpcEventImpl [rpcName=" + rpcName + ", xid=" + xid
- + "]";
- }
-}
+++ /dev/null
-/*
- * 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.openflowplugin.openflow.md.core.sal;
-
-import com.google.common.util.concurrent.ListeningExecutorService;
-import java.math.BigInteger;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.ArrayBlockingQueue;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Matchers;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF;
-import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder;
-import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Created by Martin Bobak mbobak@cisco.com on 9/22/14.
- */
-@RunWith(MockitoJUnitRunner.class)
-public class ConcurrentSalRegistrationManagerTest {
-
-
- /** registration related action must end within this amount of seconds */
- private static final int REGISTRATION_ACTION_TIMEOUT = 5;
- protected SalRegistrationManager registrationManager;
- protected static final Logger LOG = LoggerFactory.getLogger(ConcurrentSalRegistrationManagerTest.class);
- protected static final SwitchSessionKeyOF SWITCH_SESSION_KEY_OF = new SwitchSessionKeyOF();
-
- private static final long THREAD_SLEEP_MILLIS = 100;
- private static final String DELAYED_THREAD = "DELAYED_THREAD";
- private static final String NO_DELAY_THREAD = "NO_DELAY_THREAD";
-
- private ThreadPoolCollectingExecutor taskExecutor;
-
- @Mock
- protected SessionContext context;
- @Mock
- private ConnectionConductor connectionConductor;
- @Mock
- private ListeningExecutorService rpcPool;
- @Mock
- private NotificationProviderService notificationProviderService;
- @Mock
- private RpcProviderRegistry rpcProviderRegistry;
- @Mock
- private DataBroker dataBroker;
- @Mock
- private NotificationEnqueuer notificationEnqueuer;
- @Mock
- private ConnectionAdapter connectionAdapter;
-
- private GetFeaturesOutput features;
-
- /**
- * prepare surrounding objects
- */
- @Before
- public void setUp() {
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
- registrationManager = new SalRegistrationManager(convertorManager);
- SWITCH_SESSION_KEY_OF.setDatapathId(BigInteger.ONE);
- Mockito.when(context.getNotificationEnqueuer()).thenReturn(notificationEnqueuer);
-
- // features mockery
- features = new GetFeaturesOutputBuilder()
- .setVersion(OFConstants.OFP_VERSION_1_3)
- .setDatapathId(BigInteger.valueOf(42))
- .setCapabilities(new Capabilities(true, true, true, true, true, true, true))
- .build();
- Mockito.when(context.getFeatures()).thenReturn(features);
-
- Mockito.when(context.getPrimaryConductor()).thenReturn(connectionConductor);
- Mockito.when(context.getSessionKey()).thenReturn(SWITCH_SESSION_KEY_OF);
- Mockito.when(connectionConductor.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
-
- // provider context - registration responder
- Mockito.when(rpcProviderRegistry.addRoutedRpcImplementation(Matchers.<Class<RpcService>>any(), Matchers.any(RpcService.class)))
- .then(new Answer<RoutedRpcRegistration<?>>() {
- @Override
- public RoutedRpcRegistration<?> answer(InvocationOnMock invocation) {
- if (Thread.currentThread().getName().equals(DELAYED_THREAD)) {
- try {
- LOG.info(String.format("Will wait for %d millis", THREAD_SLEEP_MILLIS/10));
- Thread.sleep(THREAD_SLEEP_MILLIS);
- } catch (InterruptedException e) {
- LOG.error("delaying of worker thread [{}] failed.", Thread.currentThread().getName(), e);
- }
- }
-
- Object[] args = invocation.getArguments();
- RoutedRpcRegistration<RpcService> registration = Mockito.mock(RoutedRpcRegistration.class);
- Mockito.when(registration.getInstance()).thenReturn((RpcService) args[1]);
-
- return registration;
- }
- });
-
- Mockito.when(connectionConductor.getConnectionAdapter()).thenReturn(connectionAdapter);
- Mockito.when(connectionAdapter.getRemoteAddress()).thenReturn(new InetSocketAddress("10.1.2.3", 4242));
-
- taskExecutor = new ThreadPoolCollectingExecutor(
- 2, 2, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(2), "junit");
-
- registrationManager.setRpcProviderRegistry(rpcProviderRegistry);
- registrationManager.setDataService(dataBroker);
- registrationManager.setPublishService(notificationProviderService);
- registrationManager.init();
- OFSessionUtil.getSessionManager().setRpcPool(rpcPool);
- }
-
- /**
- * clean up
- * @throws InterruptedException
- */
- @After
- public void tearDown() throws InterruptedException {
- taskExecutor.shutdown();
- taskExecutor.awaitTermination(1, TimeUnit.SECONDS);
- if (!taskExecutor.isTerminated()) {
- taskExecutor.shutdownNow();
- }
- LOG.info("All tasks have finished.");
-
- LOG.info("amount of scheduled threads: {}, exited threads: {}, failed threads: {}",
- taskExecutor.getTaskCount(), taskExecutor.getThreadExitCounter(), taskExecutor.getFailLogbook().size());
- for (String exitStatus : taskExecutor.getFailLogbook()) {
- LOG.debug(exitStatus);
- }
-
- OFSessionUtil.releaseSessionManager();
- Assert.assertTrue("there should not be any failed threads in the pool", taskExecutor.getFailLogbook().isEmpty());
- Assert.assertTrue("there should not be any living thread in the pool", taskExecutor.getActiveCount() == 0);
- }
-
- /**
- * Test method which verifies that session could not be invalidated while in creation.
- * @throws InterruptedException
- * @throws TimeoutException
- * @throws ExecutionException
- */
- @Test
- public void testConcurrentRemoveSessionContext() throws InterruptedException, ExecutionException, TimeoutException {
- // run registrations
- Callable<Void> delayedThread = new Callable<Void>() {
- @Override
- public Void call() {
- LOG.info("Delayed session adding thread started.");
- Thread.currentThread().setName(DELAYED_THREAD);
- OFSessionUtil.getSessionManager().addSessionContext(SWITCH_SESSION_KEY_OF, context);
- LOG.info("Delayed session adding thread finished.");
- return null;
- }
- };
-
- Callable<Void> noDelayThread = new Callable<Void>() {
- @Override
- public Void call() {
- LOG.info("Session removing thread started.");
- Thread.currentThread().setName(NO_DELAY_THREAD);
- OFSessionUtil.getSessionManager().invalidateSessionContext(SWITCH_SESSION_KEY_OF);
- LOG.info("Session removing thread finished.");
- return null;
- }
- };
-
- Future<Void> addSessionResult = taskExecutor.submit(delayedThread);
- Future<Void> removeSessionResult = taskExecutor.submit(noDelayThread);
-
- addSessionResult.get(REGISTRATION_ACTION_TIMEOUT, TimeUnit.SECONDS);
- removeSessionResult.get(REGISTRATION_ACTION_TIMEOUT, TimeUnit.SECONDS);
- }
-
- private static class ThreadPoolCollectingExecutor extends ThreadPoolLoggingExecutor {
-
- private List<String> failLogbook;
- private int threadExitCounter = 0;
-
- /**
- * @param corePoolSize
- * @param maximumPoolSize
- * @param keepAliveTime
- * @param unit
- * @param workQueue
- * @param poolName
- */
- public ThreadPoolCollectingExecutor(int corePoolSize,
- int maximumPoolSize, long keepAliveTime, TimeUnit unit,
- BlockingQueue<Runnable> workQueue, String poolName) {
- super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, poolName);
-
- failLogbook = Collections.synchronizedList(new ArrayList<String>());
- }
-
- @Override
- protected void afterExecute(Runnable r, Throwable t) {
- super.afterExecute(r, t);
- threadExitCounter ++;
-
- if (t != null) {
- failLogbook.add("job ["+r+"] exited with throwable:" + t.getMessage());
- }
- }
-
- /**
- * @return the chronicles
- */
- public List<String> getFailLogbook() {
- return failLogbook;
- }
-
- /**
- * @return the threadExitCounter
- */
- public int getThreadExitCounter() {
- return threadExitCounter;
- }
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.sal;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.MoreExecutors;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Executors;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Matchers;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowHashIdMapping;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlowBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortConfig;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortNumberUni;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.PortBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.PortKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.queue.rev130925.QueueId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowModFlags;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.group.update.UpdatedGroupBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.meter.update.UpdatedMeterBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetSourceBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetTypeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.port.update.UpdatedPortBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.table.update.UpdatedTable;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.table.update.UpdatedTableBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableConfig;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.ApplySetfieldBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.table.features.TablePropertiesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.table.features.table.properties.TableFeatureProperties;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.table.features.table.properties.TableFeaturePropertiesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.table.features.table.properties.TableFeaturePropertiesKey;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-
-/**
- * simple NPE smoke test
- */
-@RunWith(MockitoJUnitRunner.class)
-public class ModelDrivenSwitchImplTest {
-
- private ModelDrivenSwitchImpl mdSwitchOF10;
- private ModelDrivenSwitchImpl mdSwitchOF13;
-
- @Mock
- private SessionContext context;
- @Mock
- private ConnectionConductor conductor;
- @Mock
- private IMessageDispatchService messageDispatchService;
- @Mock
- private GetFeaturesOutput features;
- @Mock
- private MessageSpy<DataContainer> messageSpy;
- @Mock
- private DataBroker dataBroker;
- @Mock
- private ReadWriteTransaction rwTx;
- @Mock
- private EntityOwnershipService entityOwnershipService;
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- Mockito.when(context.getPrimaryConductor()).thenReturn(conductor);
- Mockito.when(context.getMessageDispatchService()).thenReturn(messageDispatchService);
- Mockito.when(conductor.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_0)
- .thenReturn(OFConstants.OFP_VERSION_1_3);
- Mockito.when(context.getFeatures()).thenReturn(features);
- Mockito.when(features.getDatapathId()).thenReturn(BigInteger.valueOf(1));
-
-
- OFSessionUtil.getSessionManager().setRpcPool(MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)));
- OFSessionUtil.getSessionManager().setMessageSpy(messageSpy);
- OFSessionUtil.getSessionManager().setDataBroker(dataBroker);
-
- CheckedFuture<Optional<FlowHashIdMapping>, ReadFailedException> dummyReadFuture
- = Futures.<Optional<FlowHashIdMapping>,ReadFailedException>immediateCheckedFuture(Optional.<FlowHashIdMapping>absent());
- Mockito.when(rwTx.read(Matchers.<LogicalDatastoreType>any(), Matchers.<InstanceIdentifier<FlowHashIdMapping>>any())).thenReturn(dummyReadFuture);
- Mockito.when(dataBroker.newReadWriteTransaction()).thenReturn(rwTx);
-
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
- mdSwitchOF10 = new ModelDrivenSwitchImpl(null, null, context, convertorManager);
- mdSwitchOF13 = new ModelDrivenSwitchImpl(null, null, context, convertorManager);
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#addFlow(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testAddFlow() throws InterruptedException, ExecutionException {
- UpdateFlowOutputBuilder updateFlowOutput = new UpdateFlowOutputBuilder();
- updateFlowOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<UpdateFlowOutput> result = RpcResultBuilder.success(updateFlowOutput.build()).build();
- Mockito.when(
- messageDispatchService.flowMod(Matchers.any(FlowModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- AddFlowInputBuilder input = new AddFlowInputBuilder();
- input.setMatch(createMatch());
-
- Mockito.when(features.getVersion()).thenReturn((short)1);
- mdSwitchOF10.addFlow(input.build()).get();
- Mockito.when(features.getVersion()).thenReturn((short)4);
- mdSwitchOF13.addFlow(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).flowMod(
- Matchers.any(FlowModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#removeFlow(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testRemoveFlow() throws InterruptedException, ExecutionException {
- UpdateFlowOutputBuilder updateFlowOutput = new UpdateFlowOutputBuilder();
- updateFlowOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<UpdateFlowOutput> result = RpcResultBuilder.success(updateFlowOutput.build()).build();
- Mockito.when(
- messageDispatchService.flowMod(Matchers.any(FlowModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- RemoveFlowInputBuilder input = new RemoveFlowInputBuilder();
- input.setMatch(createMatch());
-
- Mockito.when(features.getVersion()).thenReturn((short)1);
- mdSwitchOF10.removeFlow(input.build()).get();
- Mockito.when(features.getVersion()).thenReturn((short)4);
- mdSwitchOF13.removeFlow(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).flowMod(
- Matchers.any(FlowModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
-
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#updateFlow(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testUpdateFlow() throws InterruptedException, ExecutionException {
- UpdateFlowOutputBuilder updateFlowOutput = new UpdateFlowOutputBuilder();
- updateFlowOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<UpdateFlowOutput> result = RpcResultBuilder.success(updateFlowOutput.build()).build();
- Mockito.when(
- messageDispatchService.flowMod(Matchers.any(FlowModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- UpdateFlowInputBuilder input = new UpdateFlowInputBuilder();
- UpdatedFlowBuilder updatedFlow = new UpdatedFlowBuilder();
- updatedFlow.setBarrier(false);
- updatedFlow.setMatch(createMatch());
- updatedFlow.setPriority(65);
- updatedFlow.setFlags(new FlowModFlags(true, false, true, false, true));
- input.setUpdatedFlow(updatedFlow.build());
- OriginalFlowBuilder originalFlowBuilder = new OriginalFlowBuilder();
- originalFlowBuilder.setMatch(createMatch());
- originalFlowBuilder.setPriority(65);
- originalFlowBuilder.setFlags(new FlowModFlags(true, false, true, false, true));
- input.setOriginalFlow(originalFlowBuilder.build());
- KeyedInstanceIdentifier<Flow, FlowKey> dummyIdentifier = InstanceIdentifier.create(Nodes.class)
- .child(Node.class, new NodeKey(new NodeId("openflow:1")))
- .augmentation(FlowCapableNode.class)
- .child(Table.class, new TableKey((short)0))
- .child(Flow.class, new FlowKey(new FlowId("1")));
- input.setFlowRef(new FlowRef(dummyIdentifier));
-
- Mockito.when(features.getVersion()).thenReturn((short)1);
- mdSwitchOF10.updateFlow(input.build()).get();
- Mockito.when(features.getVersion()).thenReturn((short)4);
- mdSwitchOF13.updateFlow(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).flowMod(
- Matchers.any(FlowModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * addGroup(org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.
- * AddGroupInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testAddGroup() throws InterruptedException, ExecutionException {
- UpdateGroupOutputBuilder updateGroupOutput = new UpdateGroupOutputBuilder();
- updateGroupOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<UpdateGroupOutput> result = RpcResultBuilder.success(updateGroupOutput.build()).build();
- Mockito.when(
- messageDispatchService.groupMod(Matchers.any(GroupModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- AddGroupInputBuilder input = new AddGroupInputBuilder();
- input.setGroupType(org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes.GroupFf);
- input.setGroupId(new GroupId(789L));
-
- mdSwitchOF10.addGroup(input.build()).get();
- mdSwitchOF13.addGroup(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).groupMod(
- Matchers.any(GroupModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * updateGroup(org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.
- * UpdateGroupInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testUpdateGroup() throws InterruptedException, ExecutionException {
- UpdateGroupOutputBuilder updateGroupOutput = new UpdateGroupOutputBuilder();
- updateGroupOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<UpdateGroupOutput> result = RpcResultBuilder.success(updateGroupOutput.build()).build();
- Mockito.when(
- messageDispatchService.groupMod(Matchers.any(GroupModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- UpdateGroupInputBuilder input = new UpdateGroupInputBuilder();
- UpdatedGroupBuilder updatedGroupBuilder = new UpdatedGroupBuilder();
- updatedGroupBuilder.setGroupId(new GroupId(789L));
- updatedGroupBuilder.setGroupType(org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes.GroupFf);
- input.setUpdatedGroup(updatedGroupBuilder.build());
-
- mdSwitchOF10.updateGroup(input.build()).get();
- mdSwitchOF13.updateGroup(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).groupMod(
- Matchers.any(GroupModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * removeGroup(org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.
- * RemoveGroupInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testRemoveGroup() throws InterruptedException, ExecutionException {
- UpdateGroupOutputBuilder updateGroupOutput = new UpdateGroupOutputBuilder();
- updateGroupOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<UpdateGroupOutput> result = RpcResultBuilder.success(updateGroupOutput.build()).build();
- Mockito.when(
- messageDispatchService.groupMod(Matchers.any(GroupModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- RemoveGroupInputBuilder input = new RemoveGroupInputBuilder();
- input.setGroupId(new GroupId(789L));
- input.setGroupType(org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes.GroupFf);
-
- mdSwitchOF10.removeGroup(input.build()).get();
- mdSwitchOF13.removeGroup(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).groupMod(
- Matchers.any(GroupModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * addMeter(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.
- * AddMeterInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testAddMeter() throws InterruptedException, ExecutionException {
- UpdateMeterOutputBuilder updateMeterOutput = new UpdateMeterOutputBuilder();
- updateMeterOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<UpdateMeterOutput> result = RpcResultBuilder.success(updateMeterOutput.build()).build();
- Mockito.when(
- messageDispatchService.meterMod(Matchers.any(MeterModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- AddMeterInputBuilder input = new AddMeterInputBuilder();
- input.setMeterId(new MeterId(78L));
-
- mdSwitchOF10.addMeter(input.build()).get();
- mdSwitchOF13.addMeter(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).meterMod(
- Matchers.any(MeterModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * updateMeter(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.
- * UpdateMeterInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testUpdtateMeter() throws InterruptedException, ExecutionException {
- UpdateMeterOutputBuilder updateMeterOutput = new UpdateMeterOutputBuilder();
- updateMeterOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<UpdateMeterOutput> result = RpcResultBuilder.success(updateMeterOutput.build()).build();
- Mockito.when(
- messageDispatchService.meterMod(Matchers.any(MeterModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- UpdateMeterInputBuilder input = new UpdateMeterInputBuilder();
- UpdatedMeterBuilder updatedMeterBuilder = new UpdatedMeterBuilder();
- updatedMeterBuilder.setMeterId(new MeterId(89L));
- updatedMeterBuilder.setBarrier(false);
- input.setUpdatedMeter(updatedMeterBuilder.build());
-
- mdSwitchOF10.updateMeter(input.build()).get();
- mdSwitchOF13.updateMeter(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).meterMod(
- Matchers.any(MeterModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * removeMeter(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.
- * RemoveMeterInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testRemoveMeter() throws InterruptedException, ExecutionException {
- UpdateMeterOutputBuilder updateMeterOutput = new UpdateMeterOutputBuilder();
- updateMeterOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<UpdateMeterOutput> result = RpcResultBuilder.success(updateMeterOutput.build()).build();
- Mockito.when(
- messageDispatchService.meterMod(Matchers.any(MeterModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- RemoveMeterInputBuilder input = new RemoveMeterInputBuilder();
- input.setMeterId(new MeterId(89L));
-
- mdSwitchOF10.removeMeter(input.build()).get();
- mdSwitchOF13.removeMeter(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).meterMod(
- Matchers.any(MeterModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAllGroupStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.
- * GetAllGroupStatisticsInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetAllGroupStatistics() throws InterruptedException, ExecutionException {
- GetAllGroupStatisticsOutputBuilder getAllGroupStatistcsOutput = new GetAllGroupStatisticsOutputBuilder();
- getAllGroupStatistcsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetAllGroupStatisticsInputBuilder input = new GetAllGroupStatisticsInputBuilder();
-
- mdSwitchOF10.getAllGroupStatistics(input.build()).get();
- mdSwitchOF13.getAllGroupStatistics(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getGroupDescription(org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.
- * GetGroupDescriptionInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetGroupDescription() throws InterruptedException, ExecutionException {
- GetGroupDescriptionOutputBuilder getGroupDescOutput = new GetGroupDescriptionOutputBuilder();
- getGroupDescOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetGroupDescriptionInputBuilder input = new GetGroupDescriptionInputBuilder();
-
- mdSwitchOF10.getGroupDescription(input.build()).get();
- mdSwitchOF13.getGroupDescription(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getGroupFeatures(org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.
- * GetGroupFeaturesInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetGroupFeatures() throws InterruptedException, ExecutionException {
- GetGroupFeaturesOutputBuilder getGroupFeaturesOutput = new GetGroupFeaturesOutputBuilder();
- getGroupFeaturesOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetGroupFeaturesInputBuilder input = new GetGroupFeaturesInputBuilder();
-
- mdSwitchOF10.getGroupFeatures(input.build()).get();
- mdSwitchOF13.getGroupFeatures(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getGroupStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.
- * GetGroupStatisticsInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- //TODO GetGroupStatistics why NPE?
- @Test
- public void testGetGroupStatistics() throws InterruptedException, ExecutionException {
- GetGroupStatisticsOutputBuilder getGroupStatsOutput = new GetGroupStatisticsOutputBuilder();
- getGroupStatsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetGroupStatisticsInputBuilder input = new GetGroupStatisticsInputBuilder();
- input.setGroupId(new GroupId(42L));
-
- mdSwitchOF10.getGroupStatistics(input.build()).get();
- mdSwitchOF13.getGroupStatistics(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAllMeterConfigStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.
- * GetAllMeterConfigStatisticsInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetAllMeterConfigStatistics() throws InterruptedException, ExecutionException {
- GetAllMeterConfigStatisticsOutputBuilder getAllMeterConfigStatsOutput =
- new GetAllMeterConfigStatisticsOutputBuilder();
- getAllMeterConfigStatsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetAllMeterConfigStatisticsInputBuilder input = new GetAllMeterConfigStatisticsInputBuilder();
-
- mdSwitchOF10.getAllMeterConfigStatistics(input.build()).get();
- mdSwitchOF13.getAllMeterConfigStatistics(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAllMeterStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.
- * GetAllMeterStatisticsInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetAllMeterStatistics() throws InterruptedException, ExecutionException {
- GetAllMeterStatisticsOutputBuilder getAllMeterStatisticsOutput =
- new GetAllMeterStatisticsOutputBuilder();
- getAllMeterStatisticsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetAllMeterStatisticsInputBuilder input = new GetAllMeterStatisticsInputBuilder();
-
- mdSwitchOF10.getAllMeterStatistics(input.build()).get();
- mdSwitchOF13.getAllMeterStatistics(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getMeterFeatures(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.
- * GetMeterFeaturesInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetMeterFeatures() throws InterruptedException, ExecutionException {
- GetMeterFeaturesOutputBuilder getMeterFeaturesOutput =
- new GetMeterFeaturesOutputBuilder();
- getMeterFeaturesOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetMeterFeaturesInputBuilder input = new GetMeterFeaturesInputBuilder();
-
- mdSwitchOF10.getMeterFeatures(input.build()).get();
- mdSwitchOF13.getMeterFeatures(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getMeterStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.
- * GetMeterStatisticsInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetMeterStatistics() throws InterruptedException, ExecutionException {
- GetMeterStatisticsOutputBuilder getMeterStatsOutput = new GetMeterStatisticsOutputBuilder();
- getMeterStatsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetMeterStatisticsInputBuilder input = new GetMeterStatisticsInputBuilder();
- input.setMeterId(new MeterId(42L));
-
- mdSwitchOF10.getMeterStatistics(input.build()).get();
- mdSwitchOF13.getMeterStatistics(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAllNodeConnectorsStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.
- * GetAllNodeConnectorsStatisticsInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetAllNodeConnectorsStatistics() throws InterruptedException, ExecutionException {
- GetAllNodeConnectorsStatisticsOutputBuilder getAllNodeConnectorsStatsOutput =
- new GetAllNodeConnectorsStatisticsOutputBuilder();
- getAllNodeConnectorsStatsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();;
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetAllNodeConnectorsStatisticsInputBuilder input = new GetAllNodeConnectorsStatisticsInputBuilder();
-
- mdSwitchOF10.getAllNodeConnectorsStatistics(input.build()).get();
- mdSwitchOF13.getAllNodeConnectorsStatistics(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getNodeConnectorStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.
- * GetNodeConnectorStatisticsInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetNodeConnectorStatistics() throws InterruptedException, ExecutionException {
- GetNodeConnectorStatisticsOutputBuilder getNodeConnectorStatsOutput =
- new GetNodeConnectorStatisticsOutputBuilder();
- getNodeConnectorStatsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetNodeConnectorStatisticsInputBuilder input = new GetNodeConnectorStatisticsInputBuilder();
- input.setNodeConnectorId(new NodeConnectorId("openflow:12:8"));
-
- Mockito.when(features.getVersion()).thenReturn((short)1);
- mdSwitchOF10.getNodeConnectorStatistics(input.build()).get();
- Mockito.when(features.getVersion()).thenReturn((short)4);
- mdSwitchOF13.getNodeConnectorStatistics(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * updatePort(org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.
- * UpdatePortInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testUpdatePort() throws InterruptedException, ExecutionException {
- UpdatePortOutputBuilder updatePortOutput = new UpdatePortOutputBuilder();
- updatePortOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<UpdatePortOutput> result = RpcResultBuilder.success(updatePortOutput.build()).build();
- Mockito.when(
- messageDispatchService.portMod(Matchers.any(PortModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- UpdatePortInputBuilder input = new UpdatePortInputBuilder();
-
- PortBuilder portBuilder = new PortBuilder();
- List<Port> ports = new ArrayList<Port>();
- ports.add(createPort());
- portBuilder.setPort(ports);
- UpdatedPortBuilder updatedPortBuilder = new UpdatedPortBuilder();
- updatedPortBuilder.setPort(portBuilder.build());
- input.setUpdatedPort(updatedPortBuilder.build());
-
- mdSwitchOF10.updatePort(input.build()).get();
- mdSwitchOF13.updatePort(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).portMod(
- Matchers.any(PortModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- private static Port createPort() {
- org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.PortBuilder port =
- new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.PortBuilder();
-
- port.setPortName("TestingPort01");
- port.setMask(new PortConfig(true, true, true, true));
- port.setConfiguration(new PortConfig(true, true, true, true));
- port.setAdvertisedFeatures(new PortFeatures(true, true, true, true,
- false, false, false, false,
- true, true, true, true,
- false, false, false, false));
- port.setPortNumber(new PortNumberUni(42L));
- port.setHardwareAddress(new MacAddress("01:23:45:67:89:ab"));
- port.setBarrier(true);
- port.setContainerName("TestContainer");
- port.setPortModOrder(25L);
- port.setKey(new PortKey(25L));
- return port.build();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * updateTable(org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.
- * UpdateTableInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testUpdateTable() throws InterruptedException, ExecutionException {
- UpdateTableOutputBuilder updateTableOutput = new UpdateTableOutputBuilder();
- updateTableOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- UpdateTableInputBuilder input = new UpdateTableInputBuilder();
- input.setUpdatedTable(createUpdateTable());
-
- mdSwitchOF10.updateTable(input.build()).get();
- mdSwitchOF13.updateTable(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- private static UpdatedTable createUpdateTable() {
- UpdatedTableBuilder updatedTableBuilder = new UpdatedTableBuilder();
- TableFeaturesBuilder tableFeaturesBuilder = new TableFeaturesBuilder();
- tableFeaturesBuilder.setConfig(new TableConfig(true));
- tableFeaturesBuilder.setKey(new TableFeaturesKey((short) 42));
- tableFeaturesBuilder.setMaxEntries(42L);
- tableFeaturesBuilder.setMetadataMatch(BigInteger.valueOf(42424242));
- tableFeaturesBuilder.setMetadataWrite(BigInteger.valueOf(42424242));
- tableFeaturesBuilder.setName("testTableFeatures");
- tableFeaturesBuilder.setTableId((short) 41);
-
- TablePropertiesBuilder tablePropertiesBuilder = new TablePropertiesBuilder();
- TableFeaturePropertiesBuilder tableFeaturePropertiesBuilder = new TableFeaturePropertiesBuilder();
- tableFeaturePropertiesBuilder.setKey(new TableFeaturePropertiesKey(45));
- tableFeaturePropertiesBuilder.setOrder(44);
- tableFeaturePropertiesBuilder.setTableFeaturePropType(new ApplySetfieldBuilder().build());
- List<TableFeatureProperties> tableFeatureProperties = new ArrayList<TableFeatureProperties>();
- tableFeatureProperties.add(tableFeaturePropertiesBuilder.build());
- tablePropertiesBuilder.setTableFeatureProperties(tableFeatureProperties);
-
- tableFeaturesBuilder.setTableProperties(tablePropertiesBuilder.build());
- List<TableFeatures> tableFeatures = new ArrayList<TableFeatures>();
- tableFeatures.add(tableFeaturesBuilder.build());
- updatedTableBuilder.setTableFeatures(tableFeatures);
- return updatedTableBuilder.build();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAllFlowStatisticsFromFlowTable(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.
- * GetAllFlowStatisticsFromFlowTableInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetAllFlowStatisticsFromFlowTable() throws InterruptedException, ExecutionException {
- GetAllFlowStatisticsFromFlowTableOutputBuilder allFlowStatisticsFromFlowTableOutput =
- new GetAllFlowStatisticsFromFlowTableOutputBuilder();
- allFlowStatisticsFromFlowTableOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetAllFlowStatisticsFromFlowTableInputBuilder input = new GetAllFlowStatisticsFromFlowTableInputBuilder();
- input.setTableId(new org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId((short) 42));
-
- mdSwitchOF10.getAllFlowStatisticsFromFlowTable(input.build()).get();
- mdSwitchOF13.getAllFlowStatisticsFromFlowTable(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAllFlowStatisticsFromFlowTable(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.
- * GetAllFlowStatisticsFromFlowTableInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetAllFlowsStatisticsFromAllFlowTables() throws InterruptedException, ExecutionException {
- GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder allFlowStatisticsFromAllFlowTablesOutput =
- new GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder();
- allFlowStatisticsFromAllFlowTablesOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetAllFlowsStatisticsFromAllFlowTablesInputBuilder input =
- new GetAllFlowsStatisticsFromAllFlowTablesInputBuilder();
-
- mdSwitchOF10.getAllFlowsStatisticsFromAllFlowTables(input.build()).get();
- mdSwitchOF13.getAllFlowsStatisticsFromAllFlowTables(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAllFlowStatisticsFromFlowTable(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.
- * GetAllFlowStatisticsFromFlowTableInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetFlowStatisticsFromFlowTables() throws InterruptedException, ExecutionException {
- GetFlowStatisticsFromFlowTableOutputBuilder flowStatisticsFromFlowTablesOutput =
- new GetFlowStatisticsFromFlowTableOutputBuilder();
- flowStatisticsFromFlowTablesOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetFlowStatisticsFromFlowTableInputBuilder input =
- new GetFlowStatisticsFromFlowTableInputBuilder();
- input.setMatch(createMatch());
-
- mdSwitchOF10.getFlowStatisticsFromFlowTable(input.build()).get();
- mdSwitchOF13.getFlowStatisticsFromFlowTable(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- private static Match createMatch() {
- MatchBuilder matchBuilder = new MatchBuilder();
- EthernetMatchBuilder ethernetMatchBuilder = new EthernetMatchBuilder();
- EthernetDestinationBuilder ethernetDestinationBuilder = new EthernetDestinationBuilder();
- ethernetDestinationBuilder.setAddress(new MacAddress("01:23:45:67:89:ab"));
- ethernetDestinationBuilder.setMask(new MacAddress("01:23:45:67:89:ab"));
- ethernetMatchBuilder.setEthernetDestination(ethernetDestinationBuilder.build());
- EthernetSourceBuilder ethernetSourceBuilder = new EthernetSourceBuilder();
- ethernetSourceBuilder.setAddress(new MacAddress("01:23:45:67:89:ab"));
- ethernetSourceBuilder.setMask(new MacAddress("01:23:45:67:89:ab"));
- ethernetMatchBuilder.setEthernetSource(ethernetSourceBuilder.build());
- ethernetMatchBuilder.setEthernetType(new EthernetTypeBuilder().setType(new EtherType(42L)).build());
- matchBuilder.setEthernetMatch(ethernetMatchBuilder.build());
- return matchBuilder.build();
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAggregateFlowStatisticsFromFlowTableForAllFlows(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.
- * GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetAggregateFlowStatisticsFromFlowTableForAllFlows() throws InterruptedException,
- ExecutionException {
- GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder aggregateFlowStatisticsOutput =
- new GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder();
- aggregateFlowStatisticsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetAggregateFlowStatisticsFromFlowTableForAllFlowsInputBuilder input =
- new GetAggregateFlowStatisticsFromFlowTableForAllFlowsInputBuilder();
- input.setTableId(new org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId((short) 42));
-
- mdSwitchOF10.getAggregateFlowStatisticsFromFlowTableForAllFlows(input.build()).get();
- mdSwitchOF13.getAggregateFlowStatisticsFromFlowTableForAllFlows(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAggregateFlowStatisticsFromFlowTableForGivenMatch(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.
- * GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetAggregateFlowStatisticsFromFlowTableForGivenMatch() throws InterruptedException,
- ExecutionException {
- GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder aggregateFlowStatisticsForMatchOutput =
- new GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder();
- aggregateFlowStatisticsForMatchOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetAggregateFlowStatisticsFromFlowTableForGivenMatchInputBuilder input =
- new GetAggregateFlowStatisticsFromFlowTableForGivenMatchInputBuilder();
- input.setMatch(createMatch());
- input.setCookie(new FlowCookie(BigInteger.valueOf(123456)));
- input.setCookieMask(new FlowCookie(BigInteger.valueOf(123456)));
- input.setOutGroup(44L);
- input.setOutPort(BigInteger.valueOf(12563));
-
- mdSwitchOF10.getAggregateFlowStatisticsFromFlowTableForGivenMatch(input.build()).get();
- mdSwitchOF13.getAggregateFlowStatisticsFromFlowTableForGivenMatch(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getFlowTablesStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.
- * GetFlowTablesStatisticsInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetFlowTablesStatistics() throws InterruptedException, ExecutionException {
- GetFlowTablesStatisticsOutputBuilder flowTableStatisticsOutput =
- new GetFlowTablesStatisticsOutputBuilder();
- flowTableStatisticsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetFlowTablesStatisticsInputBuilder input = new GetFlowTablesStatisticsInputBuilder();
-
- mdSwitchOF10.getFlowTablesStatistics(input.build()).get();
- mdSwitchOF13.getFlowTablesStatistics(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAllQueuesStatisticsFromAllPorts(org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.
- * GetAllQueuesStatisticsFromAllPortsInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetAllQueuesStatisticsFromAllPorts() throws InterruptedException, ExecutionException {
- GetAllQueuesStatisticsFromAllPortsOutputBuilder allQueuesStatisticsAllPortsOutput =
- new GetAllQueuesStatisticsFromAllPortsOutputBuilder();
- allQueuesStatisticsAllPortsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetAllQueuesStatisticsFromAllPortsInputBuilder input =
- new GetAllQueuesStatisticsFromAllPortsInputBuilder();
-
- mdSwitchOF10.getAllQueuesStatisticsFromAllPorts(input.build()).get();
- mdSwitchOF13.getAllQueuesStatisticsFromAllPorts(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getAllQueuesStatisticsFromGivenPort(org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.
- * GetAllQueuesStatisticsFromGivenPortInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetAllQueuesStatisticsFromGivenPort() throws InterruptedException, ExecutionException {
- GetAllQueuesStatisticsFromGivenPortOutputBuilder allQueuesStatisticsGivenPortsOutput =
- new GetAllQueuesStatisticsFromGivenPortOutputBuilder();
- allQueuesStatisticsGivenPortsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetAllQueuesStatisticsFromGivenPortInputBuilder input =
- new GetAllQueuesStatisticsFromGivenPortInputBuilder();
- input.setNodeConnectorId(new NodeConnectorId("openflow:12:8"));
-
- Mockito.when(features.getVersion()).thenReturn((short)1);
- mdSwitchOF10.getAllQueuesStatisticsFromGivenPort(input.build()).get();
- Mockito.when(features.getVersion()).thenReturn((short)4);
- mdSwitchOF13.getAllQueuesStatisticsFromGivenPort(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#
- * getQueueStatisticsFromGivenPort(org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.
- * GetQueueStatisticsFromGivenPortInput)}
- * .
- * @throws ExecutionException
- * @throws InterruptedException
- */
- @Test
- public void testGetQueueStatisticsFromGivenPort() throws InterruptedException, ExecutionException {
- GetQueueStatisticsFromGivenPortOutputBuilder queuesStatisticsGivenPortOutput =
- new GetQueueStatisticsFromGivenPortOutputBuilder();
- queuesStatisticsGivenPortOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42)));
- RpcResult<Void> result = RpcResultBuilder.success((Void)null).build();
- Mockito.when(
- messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- GetQueueStatisticsFromGivenPortInputBuilder input =
- new GetQueueStatisticsFromGivenPortInputBuilder();
- input.setNodeConnectorId(new NodeConnectorId("openflow:12:8"));
- input.setQueueId(new QueueId(55L));
-
- Mockito.when(features.getVersion()).thenReturn((short)1);
- mdSwitchOF10.getQueueStatisticsFromGivenPort(input.build()).get();
- Mockito.when(features.getVersion()).thenReturn((short)4);
- mdSwitchOF13.getQueueStatisticsFromGivenPort(input.build()).get();
- Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest(
- Matchers.any(MultipartRequestInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class));
- }
-}
+++ /dev/null
-/*
- * 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.openflowplugin.openflow.md.core.sal;
-
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.when;
-
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import java.util.Collection;
-import java.util.concurrent.Callable;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.sal.NotificationComposer;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-
-@RunWith(MockitoJUnitRunner.class)
-public class OFRpcTaskUtilTest {
-
- @Mock
- private OFRpcTaskContext taskContext;
- @Mock
- private SwitchConnectionDistinguisher connectionDistinguisher;
- @Mock
- private SessionContext sessionContext;
- @Mock
- private IMessageDispatchService messageDispatchService;
- @Mock
- private GetFeaturesOutput featuresOutput;
- @Mock
- private ListenableFuture<RpcResult<BarrierOutput>> resultListenableFuture;
- @Mock
- private ListenableFuture<RpcResult<UpdateFlowOutput>> updateFlowRpcResultListenableFuture;
- @Mock
- private NotificationProviderService notificationProviderService;
- @Mock
- private NotificationComposer<?> notificationComposer;
- @Mock
- ListeningExecutorService executorService;
- private ConvertorManager convertorManager;
-
-
- @Before
- public void setUp() {
- convertorManager = ConvertorManagerFactory.createDefaultManager();
- when(taskContext.getSession()).thenReturn(sessionContext);
- when(taskContext.getMessageService()).thenReturn(messageDispatchService);
- when(sessionContext.getNextXid()).thenReturn(new Long(10));
- when(sessionContext.getFeatures()).thenReturn(featuresOutput);
- when(featuresOutput.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
- when(messageDispatchService.barrier(Mockito.any(BarrierInput.class), Mockito.any(SwitchConnectionDistinguisher.class))).thenReturn(resultListenableFuture);
- when(taskContext.getRpcPool()).thenReturn(executorService);
- when(executorService.submit(Mockito.<Callable<RpcResult<UpdateFlowOutput>>> any())).thenReturn(updateFlowRpcResultListenableFuture);
- }
-
-
- @Test
- public void testManageBarrier() throws Exception {
- final Collection<RpcError> rpcErrors = OFRpcTaskUtil.manageBarrier(taskContext, true, connectionDistinguisher);
- assertNotNull(rpcErrors);
- }
-
- @Test
- public void testHookFutureNotification() throws Exception {
- final AddFlowInputBuilder flowInputBuilder = new AddFlowInputBuilder();
- final OFRpcTask<AddFlowInput, RpcResult<UpdateFlowOutput>> addFlowInputRpcResultOFRpcTask = OFRpcTaskFactory.createAddFlowTask(taskContext, flowInputBuilder.build(), connectionDistinguisher, convertorManager);
- OFRpcTaskUtil.hookFutureNotification(addFlowInputRpcResultOFRpcTask, updateFlowRpcResultListenableFuture, notificationProviderService, notificationComposer);
- }
-
- @Test
- public void testChainFutureBarrier() throws Exception {
- final AddFlowInputBuilder flowInputBuilder = new AddFlowInputBuilder();
- flowInputBuilder.setBarrier(true);
- final OFRpcTask<AddFlowInput, RpcResult<UpdateFlowOutput>> addFlowInputRpcResultOFRpcTask = OFRpcTaskFactory.createAddFlowTask(taskContext, flowInputBuilder.build(), connectionDistinguisher, convertorManager);
- OFRpcTaskUtil.chainFutureBarrier(addFlowInputRpcResultOFRpcTask, updateFlowRpcResultListenableFuture);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.sal;\r
-\r
-\r
-import com.google.common.util.concurrent.Futures;
-import java.util.ArrayList;\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.mockito.Mock;\r
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;\r
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.openflowjava.protocol.spi.connection.SwitchConnectionProvider;\r
-\r
-/**\r
- * @author michal.polkorab\r
- *\r
- */\r
-public class OpenflowPluginProviderTest {\r
-\r
- @Mock
- DataBroker dataBroker;
- @Mock
- NotificationProviderService notificationProviderService;
- @Mock
- RpcProviderRegistry rpcProviderRegistry;
- @Mock
- SwitchConnectionProvider switchProvider;
-\r
- OpenflowPluginProvider provider = new OpenflowPluginProvider();\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- MockitoAnnotations.initMocks(this);\r
- provider = new OpenflowPluginProvider();\r
- }\r
-\r
- /**\r
- * Test {@link OpenflowPluginProvider#initialization()}\r
- */\r
- @Test\r
- public void testInitialization() {\r
- Mockito.when(switchProvider.startup()).thenReturn(Futures.immediateFuture(Boolean.TRUE));
- ArrayList<SwitchConnectionProvider> switchProviders = new ArrayList<>();\r
- switchProviders.add(switchProvider);\r
- provider.setSwitchConnectionProviders(switchProviders);\r
- provider.setDataBroker(dataBroker);
- provider.setNotificationService(notificationProviderService);
- provider.setRpcRegistry(rpcProviderRegistry);
- provider.initialization();\r
-\r
- Assert.assertNotNull("Wrong message count dumper", provider.getMessageCountDumper());\r
- Assert.assertNotNull("Wrong extension converter registrator", provider.getExtensionConverterRegistrator());\r
- Assert.assertNotNull("Wrong data broker", provider.getDataBroker());
- Assert.assertNotNull("Wrong notification service", provider.getNotificationService());
- Assert.assertNotNull("Wrong rpc registry", provider.getRpcRegistry());
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/*
- * 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.openflowplugin.openflow.md.core.sal;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import java.math.BigInteger;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Matchers;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.AbstractModelDrivenSwitchRegistration;
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitch;
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF;
-import org.opendaylight.openflowplugin.openflow.md.core.role.OfEntityManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
-import org.opendaylight.openflowplugin.openflow.md.core.session.SessionContextOFImpl;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-
-/**
- * Created by Martin Bobak mbobak@cisco.com on 8/26/14.
- */
-@RunWith(MockitoJUnitRunner.class)
-public class SalRegistrationManagerTest {
-
-
- private static final BigInteger dataPathId = BigInteger.ONE;
-
- private SalRegistrationManager salRegistrationManager;
-
- private SessionContextOFImpl context;
- @Mock
- private ConnectionConductor conductor;
- @Mock
- private IMessageDispatchService messageDispatchService;
- @Mock
- private GetFeaturesOutput features;
- @Mock
- private BindingAwareBroker.ProviderContext providerContext;
- @Mock
- private NotificationEnqueuer notificationEnqueuer;
- @Mock
- private ListeningExecutorService rpcPool;
- @Mock
- private NotificationProviderService notificationProviderService;
- @Mock
- private RpcProviderRegistry rpcProviderRegistry;
- @Mock
- private DataBroker dataBroker;
- @Mock
- private EntityOwnershipService entityOwnershipService;
-
- @Mock
- private ModelDrivenSwitchImpl ofSwitch;
-
- private ModelDrivenSwitch mdSwitchOF13;
-
- ModelDrivenSwitchRegistration registration;
-
- @Before
- public void setUp() {
- OFSessionUtil.getSessionManager().setRpcPool(rpcPool);
- Mockito.when(conductor.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_0)
- .thenReturn(OFConstants.OFP_VERSION_1_3);
- context = new SessionContextOFImpl();
- context.setPrimaryConductor(conductor);
- Mockito.when(features.getDatapathId()).thenReturn(BigInteger.valueOf(1));
- Mockito.when(features.getVersion()).thenReturn((short) 1);
- context.setFeatures(features);
- context.setNotificationEnqueuer(notificationEnqueuer);
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
-
- OfEntityManager entManager = new OfEntityManager(entityOwnershipService,getConfig());
- mdSwitchOF13 = new ModelDrivenSwitchImpl(null, null, context, convertorManager);
- registration = new AbstractModelDrivenSwitchRegistration(mdSwitchOF13) {
- @Override
- protected void removeRegistration() {
- // no-op
- }
- };
- context.setProviderRegistration(registration);
-
- UpdateFlowOutputBuilder updateFlowOutput = new UpdateFlowOutputBuilder();
- RpcResult<UpdateFlowOutput> result = RpcResultBuilder.success(updateFlowOutput.build()).build();
-
- Mockito.when(
- messageDispatchService.flowMod(Matchers.any(FlowModInput.class),
- Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result));
-
- salRegistrationManager = new SalRegistrationManager(convertorManager);
- salRegistrationManager.setPublishService(notificationProviderService);
- salRegistrationManager.setDataService(dataBroker);
- salRegistrationManager.setRpcProviderRegistry(rpcProviderRegistry);
- salRegistrationManager.setOfEntityManager(entManager);
-
- salRegistrationManager.init();
-
- }
-
- /**
- * free sesion manager
- */
- @After
- public void tearDown() {
- OFSessionUtil.releaseSessionManager();
- }
-
- /**
- * Test for {@link org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager#identifierFromDatapathId(java.math.BigInteger)}
- */
- @Test
- public void testIdentifierFromDatapathId() {
- InstanceIdentifier<Node> node = SalRegistrationManager.identifierFromDatapathId(dataPathId);
- assertNotNull(node);
- assertEquals("NodeKey [_id=Uri [_value=openflow:1]]", ((KeyedInstanceIdentifier<?, ?>) node).getKey().toString());
- }
-
- /**
- * Test for {@link org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager#nodeKeyFromDatapathId(java.math.BigInteger)}
- */
- @Test
- public void testNodeKeyFromDatapathId() {
- NodeKey nodeKey = SalRegistrationManager.nodeKeyFromDatapathId(dataPathId);
- assertNotNull(nodeKey);
- assertEquals("openflow:1", nodeKey.getId().getValue());
- }
-
- /**
- * Test for {@link org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager#nodeIdFromDatapathId(java.math.BigInteger)}
- */
- @Test
- public void testNodeIdFromDatapathId() {
- NodeId nodeId = SalRegistrationManager.nodeIdFromDatapathId(dataPathId);
- assertNotNull(nodeId);
- assertEquals("openflow:1", nodeId.getValue());
- }
-
- /**
- * Test for {@link SalRegistrationManager#getSessionManager()}
- */
- @Test
- public void testGetSessionManager() {
- assertNotNull(salRegistrationManager.getPublishService());
- }
-
-
- /**
- * Test for {@link org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager#onSessionRemoved(org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext)}
- */
- @Test
- public void testOnSessionRemoved() {
-// assertNotNull(context.getProviderRegistration());
-// salRegistrationManager.onSessionAdded(null,context);
-// salRegistrationManager.onSessionRemoved(context);
-// assertNull(context.getProviderRegistration());
- }
-
- /**
- * Test for {@link org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager#onSessionAdded(org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF, org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext)}
- */
- public void testOnAdded() {
- SwitchSessionKeyOF switchSessionKeyOF = new SwitchSessionKeyOF();
- salRegistrationManager.onSessionAdded(switchSessionKeyOF, context);
- }
-
- public OpenflowPluginConfig getConfig(){
- OpenflowPluginConfig.OpenflowPluginConfigBuilder cfgBuilder =
- new OpenflowPluginConfig.OpenflowPluginConfigBuilder();
- cfgBuilder.setSkipTableFeatures(true);
- return cfgBuilder.build();
-
- }
-}
-
--- /dev/null
+/**
+ * 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.openflowplugin.openflow.md.core.session;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterManager;
+import org.opendaylight.openflowplugin.extension.api.core.session.ExtensionSessionManager;
+
+/**
+ * test of {@link ExtensionSessionManagerImpl}
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class ExtensionSessionManagerImplTest {
+
+ @Mock
+ private ExtensionConverterManager extensionConverterManager;
+
+ private ExtensionSessionManager sm;
+
+
+ /**
+ * prepare session manager
+ */
+ @Before
+ public void setUp() {
+ sm = ExtensionSessionManagerImpl.getInstance();
+ }
+
+ @Test
+ public void setExtensionConverterProvider() {
+ sm.setExtensionConverterProvider(extensionConverterManager);
+ assertEquals(extensionConverterManager, sm.getExtensionConverterProvider());
+ }
+
+}
+++ /dev/null
-/**
- * Copyright (c) 2013 IBM 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.openflowplugin.openflow.md.core.session;
-
-import java.math.BigInteger;
-import java.net.InetSocketAddress;
-import java.util.HashMap;
-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.Future;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
-import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler;
-import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
-import org.opendaylight.openflowjava.protocol.api.extensibility.AlienMessageListener;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-
-/**
- * test for {@link MessageDispatchServiceImpl}
- */
-public class MessageDispatchServiceImplTest {
-
- MockSessionContext session;
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- session = new MockSessionContext(0);
-
- }
-
- /**
- * Test barrier message for null cookie
- *
- * @throws Exception
- */
- @Test
- public void testBarrierMessageForPrimary() throws Exception {
- MockConnectionConductor conductor = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey();
- BarrierInputBuilder barrierMsg = new BarrierInputBuilder();
- session.getMessageDispatchService().barrier(barrierMsg.build(), cookie);
- Assert.assertEquals(MessageType.BARRIER, session.getPrimaryConductor()
- .getMessageType());
- }
-
- /**
- * Test experimenter message for null cookie
- */
- @Test
- public void testExperimenter() {
- MockConnectionConductor conductor = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey();
- ExperimenterInputBuilder experimenterInputBuilder = new ExperimenterInputBuilder();
- session.getMessageDispatchService().experimenter(
- experimenterInputBuilder.build(), cookie);
- Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor()
- .getMessageType());
- }
-
- /**
- * Test get async input with null cookie
- */
- @Test
- public void testGetAsync() {
- MockConnectionConductor conductor = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey();
- GetAsyncInputBuilder getAsyncInputBuilder = new GetAsyncInputBuilder();
- session.getMessageDispatchService().getAsync(
- getAsyncInputBuilder.build(), cookie);
- Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor()
- .getMessageType());
- }
-
- /**
- * Test get async output with null cookie
- */
- @Test
- public void testGetConfig() {
- MockConnectionConductor conductor = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey();
- GetConfigInputBuilder getConfigInputBuilder = new GetConfigInputBuilder();
- session.getMessageDispatchService().getConfig(
- getConfigInputBuilder.build(), cookie);
- Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor()
- .getMessageType());
- }
-
- /**
- * Test get features with null cookie
- */
- @Test
- public void testGetFeatures() {
- MockConnectionConductor conductor = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey();
- GetFeaturesInputBuilder getFeaturesInputBuilder = new GetFeaturesInputBuilder();
- session.getMessageDispatchService().getFeatures(
- getFeaturesInputBuilder.build(), cookie);
- Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor()
- .getMessageType());
- }
-
- /**
- * Test get queue config with null cookie
- */
- @Test
- public void testGetQueueConfig() {
- MockConnectionConductor conductor = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey();
- GetQueueConfigInputBuilder getQueueConfigInputBuilder = new GetQueueConfigInputBuilder();
- session.getMessageDispatchService().getQueueConfig(
- getQueueConfigInputBuilder.build(), cookie);
- Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor()
- .getMessageType());
- }
-
- /**
- * Test multipart request with null cookie
- */
- @Test
- public void testGetMultipart() {
- MockConnectionConductor conductor = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey();
- MultipartRequestInputBuilder multipartRequestInputBuilder = new MultipartRequestInputBuilder();
- session.getMessageDispatchService().multipartRequest(
- multipartRequestInputBuilder.build(), cookie);
- Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor()
- .getMessageType());
- }
-
- /**
- * Test role request with null cookie
- */
- @Test
- public void testRoleRequest() {
- MockConnectionConductor conductor = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey();
- RoleRequestInputBuilder roleRequestInputBuilder = new RoleRequestInputBuilder();
- session.getMessageDispatchService().roleRequest(
- roleRequestInputBuilder.build(), cookie);
- Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor()
- .getMessageType());
- }
-
- /**
- * Test table mod with null cookie
- */
- @Test
- public void testTableMod() {
- MockConnectionConductor conductor = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey();
- TableModInputBuilder tableModInputBuilder = new TableModInputBuilder();
- session.getMessageDispatchService().tableMod(
- tableModInputBuilder.build(), cookie);
- Assert.assertEquals(MessageType.TABLEMOD, session.getPrimaryConductor()
- .getMessageType());
- }
-
- /**
- * Test packet out message for primary connection
- *
- * @throws Exception
- */
- @Test
- public void testPacketOutMessageForPrimary() throws Exception {
- session.getMessageDispatchService().packetOut(null, null);
- Assert.assertEquals(MessageType.PACKETOUT, session
- .getPrimaryConductor().getMessageType());
- }
-
- /**
- * Test packet out message for auxiliary connection
- *
- * @throws Exception
- */
- @Test
- public void testPacketOutMessageForAuxiliary() throws Exception {
- MockConnectionConductor conductor = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey();
- session.addAuxiliaryConductor(cookie, conductor);
- session.getMessageDispatchService().packetOut(null, cookie);
- Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor()
- .getMessageType());
- conductor = (MockConnectionConductor) session
- .getAuxiliaryConductor(cookie);
- Assert.assertEquals(MessageType.PACKETOUT, conductor.getMessageType());
- }
-
- /**
- * Test packet out message when multiple auxiliary connection exist
- *
- * @throws Exception
- */
- @Test
- public void testPacketOutMessageForMultipleAuxiliary() throws Exception {
- MockConnectionConductor conductor1 = new MockConnectionConductor(1);
- SwitchConnectionDistinguisher cookie1 = conductor1.getAuxiliaryKey();
- session.addAuxiliaryConductor(cookie1, conductor1);
- MockConnectionConductor conductor2 = new MockConnectionConductor(2);
- SwitchConnectionDistinguisher cookie2 = conductor2.getAuxiliaryKey();
- session.addAuxiliaryConductor(cookie2, conductor2);
- MockConnectionConductor conductor3 = new MockConnectionConductor(3);
- SwitchConnectionDistinguisher cookie3 = conductor3.getAuxiliaryKey();
- session.addAuxiliaryConductor(cookie3, conductor3);
- PacketOutInputBuilder builder = new PacketOutInputBuilder();
- // send message
- session.getMessageDispatchService().packetOut(builder.build(), cookie2);
-
- Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor()
- .getMessageType());
-
- conductor3 = (MockConnectionConductor) session
- .getAuxiliaryConductor(cookie3);
- Assert.assertEquals(MessageType.NONE, conductor3.getMessageType());
-
- conductor2 = (MockConnectionConductor) session
- .getAuxiliaryConductor(cookie2);
- Assert.assertEquals(MessageType.PACKETOUT, conductor2.getMessageType());
-
- conductor1 = (MockConnectionConductor) session
- .getAuxiliaryConductor(cookie1);
- Assert.assertEquals(MessageType.NONE, conductor1.getMessageType());
-
- }
-
- /**
- * Test for invalid session
- *
- * @throws Exception
- */
- @Test
- public void testInvalidSession() throws Exception {
- session.setValid(false);
- Future<RpcResult<Void>> resultFuture = session
- .getMessageDispatchService().packetOut(null, null);
- if (resultFuture.isDone()) {
- RpcResult<Void> rpcResult = resultFuture.get();
- Assert.assertTrue(!rpcResult.getErrors().isEmpty());
-
- Iterator<RpcError> it = rpcResult.getErrors().iterator();
- RpcError rpcError = it.next();
-
- Assert.assertTrue(rpcError.getApplicationTag().equals(
- OFConstants.APPLICATION_TAG));
- Assert.assertTrue(rpcError.getTag().equals(
- OFConstants.ERROR_TAG_TIMEOUT));
- Assert.assertTrue(rpcError.getErrorType().equals(
- RpcError.ErrorType.TRANSPORT));
- }
- }
-
-}
-
-class MockSessionContext implements SessionContext {
- private MockConnectionConductor conductor;
- private Map<SwitchConnectionDistinguisher, ConnectionConductor> map;
- private IMessageDispatchService messageService;
- private boolean isValid = true;
- private ModelDrivenSwitchRegistration registration;
- private int seed;
- private SwitchSessionKeyOF sessionKey;
-
- MockSessionContext(int conductorNum) {
- conductor = new MockConnectionConductor(conductorNum);
- map = new HashMap<>();
- messageService = new MessageDispatchServiceImpl(this);
- sessionKey = new SwitchSessionKeyOF();
- sessionKey.setDatapathId(new BigInteger("0"));
- }
-
- @Override
- public MockConnectionConductor getPrimaryConductor() {
- // TODO Auto-generated method stub
- return conductor;
- }
-
- @Override
- public GetFeaturesOutput getFeatures() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public ConnectionConductor getAuxiliaryConductor(
- SwitchConnectionDistinguisher auxiliaryKey) {
-
- return map.get(auxiliaryKey);
- }
-
- @Override
- public Set<Entry<SwitchConnectionDistinguisher, ConnectionConductor>> getAuxiliaryConductors() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void addAuxiliaryConductor(
- SwitchConnectionDistinguisher auxiliaryKey,
- ConnectionConductor conductorArg) {
- map.put(auxiliaryKey, conductorArg);
- }
-
- @Override
- public ConnectionConductor removeAuxiliaryConductor(
- SwitchConnectionDistinguisher connectionCookie) {
- return map.remove(connectionCookie);
- }
-
- @Override
- public boolean isValid() {
- // TODO Auto-generated method stub
- return isValid;
- }
-
- @Override
- public void setValid(boolean valid) {
- isValid = valid;
- }
-
- @Override
- public SwitchSessionKeyOF getSessionKey() {
- return sessionKey;
- }
-
- @Override
- public IMessageDispatchService getMessageDispatchService() {
- // TODO Auto-generated method stub
- return messageService;
- }
-
- @Override
- public Long getNextXid() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Map<Long, PortGrouping> getPhysicalPorts() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Set<Long> getPorts() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public PortGrouping getPhysicalPort(Long portNumber) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Boolean getPortBandwidth(Long portNumber) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean isPortEnabled(long portNumber) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public boolean isPortEnabled(PortGrouping port) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public List<PortGrouping> getEnabledPorts() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Map<Long, Boolean> getPortsBandwidth() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public ModelDrivenSwitchRegistration getProviderRegistration() {
- return registration;
- }
-
- @Override
- public void setProviderRegistration(ModelDrivenSwitchRegistration registration) {
- this.registration = registration;
- }
-
- @Override
- public int getSeed() {
- return seed;
- }
-
- /**
- * @param seed
- * the seed to set
- */
- public void setSeed(int seed) {
- this.seed = seed;
- }
-
- @Override
- public NotificationEnqueuer getNotificationEnqueuer() {
- return conductor;
- }
-
- @Override
- public ControllerRole getRoleOnDevice() {
- return null;
- }
-
- @Override
- public void setRoleOnDevice(ControllerRole roleOnDevice) {
- // NOOP
- }
-}
-
-class MockConnectionConductor implements ConnectionConductor,
- NotificationEnqueuer {
-
- private int conductorNum;
- private MockConnectionAdapter adapter;
-
- public MockConnectionConductor(int conductorNumber) {
- conductorNum = conductorNumber;
- adapter = new MockConnectionAdapter();
- }
-
- @Override
- public void init() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public Short getVersion() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public CONDUCTOR_STATE getConductorState() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void setConductorState(CONDUCTOR_STATE conductorState) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public Future<Boolean> disconnect() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void setSessionContext(SessionContext context) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void setConnectionCookie(SwitchConnectionDistinguisher auxiliaryKey) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public SessionContext getSessionContext() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public SwitchConnectionDistinguisher getAuxiliaryKey() {
- if (0 != conductorNum) {
- SwitchConnectionCookieOFImpl key = new SwitchConnectionCookieOFImpl();
- key.setAuxiliaryId((short) conductorNum);
- key.init(42);
- return key;
- }
- return null;
- }
-
- @Override
- public ConnectionAdapter getConnectionAdapter() {
- // TODO Auto-generated method stub
- return adapter;
- }
-
- public MessageType getMessageType() {
- return adapter.getMessageType();
- }
-
- @Override
- public void setQueueProcessor(
- QueueProcessor<OfHeader, DataObject> queueKeeper) {
- // NOOP
- }
-
- @Override
- public void setErrorHandler(ErrorHandler errorHandler) {
- // NOOP
- }
-
- @Override
- public void setId(int conductorId) {
- // NOOP
- }
-
- @Override
- public void enqueueNotification(NotificationQueueWrapper notification) {
- // NOOP
- }
-}
-
-enum MessageType {
- NONE, BARRIER, FLOWMOD, TABLEMOD, PACKETOUT;
-}
-
-class MockConnectionAdapter implements ConnectionAdapter {
-
- private MessageType messageType;
- private ConnectionReadyListener connectionReadyListener;
- private boolean packetInFiltering;
-
- public MockConnectionAdapter() {
- setMessageType(MessageType.NONE);
- }
-
- @Override
- public Future<RpcResult<BarrierOutput>> barrier(BarrierInput input) {
- setMessageType(MessageType.BARRIER);
- return null;
- }
-
- @Override
- public Future<RpcResult<EchoOutput>> echo(EchoInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> echoReply(EchoReplyInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> experimenter(ExperimenterInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> flowMod(FlowModInput input) {
- setMessageType(MessageType.FLOWMOD);
- return null;
- }
-
- @Override
- public Future<RpcResult<GetAsyncOutput>> getAsync(GetAsyncInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<GetConfigOutput>> getConfig(GetConfigInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<GetFeaturesOutput>> getFeatures(
- GetFeaturesInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<GetQueueConfigOutput>> getQueueConfig(
- GetQueueConfigInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> groupMod(GroupModInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> hello(HelloInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> meterMod(MeterModInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> packetOut(PacketOutInput input) {
- setMessageType(MessageType.PACKETOUT);
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> portMod(PortModInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<RoleRequestOutput>> roleRequest(
- RoleRequestInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> setAsync(SetAsyncInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> setConfig(SetConfigInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Future<RpcResult<Void>> tableMod(TableModInput input) {
- setMessageType(MessageType.TABLEMOD);
- return null;
- }
-
- @Override
- public Future<Boolean> disconnect() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean isAlive() {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void setMessageListener(OpenflowProtocolListener messageListener) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void setSystemListener(SystemNotificationsListener systemListener) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void setAlienMessageListener(AlienMessageListener alienMessageListener) {
-
- }
-
- @Override
- public void checkListeners() {
- // TODO Auto-generated method stub
-
- }
-
- /**
- * @return the messageType
- */
- public MessageType getMessageType() {
- return messageType;
- }
-
- /**
- * @param messageType
- * the messageType to set
- */
- public void setMessageType(MessageType messageType) {
- this.messageType = messageType;
- }
-
- @Override
- public void fireConnectionReadyNotification() {
- connectionReadyListener.onConnectionReady();
- }
-
- @Override
- public void setConnectionReadyListener(
- ConnectionReadyListener connectionReadyListener) {
- this.connectionReadyListener = connectionReadyListener;
- }
-
- @Override
- public Future<RpcResult<Void>> multipartRequest(MultipartRequestInput input) {
- // TODO Auto-generated method stub
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter
- * #getRemoteAddress()
- */
- @Override
- public InetSocketAddress getRemoteAddress() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean isAutoRead() {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public <T extends OutboundQueueHandler> OutboundQueueHandlerRegistration<T> registerOutboundQueueHandler(final T t, final int i, final long l) {
- return null;
- }
-
- @Override
- public void setAutoRead(boolean arg0) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void setPacketInFiltering(boolean packetInFiltering) {
- this.packetInFiltering = packetInFiltering;
- }
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.core.session;
-
-import com.google.common.util.concurrent.Futures;
-import java.math.BigInteger;
-import java.util.Collections;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Matchers;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-
-/**
- *
- */
-@RunWith(MockitoJUnitRunner.class)
-public class OFRoleManagerTest {
-
- @Mock
- private SessionManager sessionManager;
- @Mock
- private SessionContext session;
- @Mock
- private GetFeaturesOutput features;
- @Mock
- private ConnectionConductor primaryConductor;
- @Mock
- private ConnectionAdapter connectionAdapter;
-
- private OFRoleManager manager;
- private RoleRequestOutput roleRequestOutput;
- private BarrierOutput barrierOutput;
- private BigInteger generationId = BigInteger.TEN;
-
- /**
- * prepare values
- */
- @Before
- public void setUp() {
- Mockito.when(session.getFeatures()).thenReturn(features);
- Mockito.when(features.getVersion()).thenReturn(Short.valueOf((short) 42));
- Mockito.when(session.getNextXid()).thenReturn(84L);
- Mockito.when(session.getPrimaryConductor()).thenReturn(primaryConductor);
- Mockito.when(primaryConductor.getConnectionAdapter()).thenReturn(connectionAdapter);
- roleRequestOutput = new RoleRequestOutputBuilder()
- .setGenerationId(generationId)
- .setRole(ControllerRole.OFPCRROLESLAVE)
- .setVersion((short) 42)
- .setXid(21L)
- .build();
- barrierOutput = new BarrierOutputBuilder()
- .setVersion((short) 42)
- .setXid(1L)
- .build();
-
- manager = new OFRoleManager(sessionManager);
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager#manageRoleChange(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}.
- * <br/>
- * session lot is empty is invalid
- */
- @Test
- public void testManageRoleChangeFail1() {
- manager.manageRoleChange(OfpRole.BECOMESLAVE);
- Mockito.verify(connectionAdapter, Mockito.never()).roleRequest(Matchers.any(RoleRequestInput.class));
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager#manageRoleChange(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}.
- * <br/>
- * available session is invalid
- */
- @Test
- public void testManageRoleChangeFail2() {
- Mockito.when(sessionManager.getAllSessions()).thenReturn(Collections.singleton(session));
- manager.manageRoleChange(OfpRole.BECOMESLAVE);
- Mockito.verify(connectionAdapter, Mockito.never()).roleRequest(Matchers.any(RoleRequestInput.class));
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager#manageRoleChange(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}.
- * <br/>
- * device bound to valid session is not answering
- */
- @Test
- public void testManageRoleChangeFail3() {
- Mockito.when(session.isValid()).thenReturn(true);
- Mockito.when(sessionManager.getAllSessions()).thenReturn(Collections.singleton(session));
-// manager.manageRoleChange(OfpRole.BECOMESLAVE);
-// Mockito.verify(connectionAdapter, Mockito.times(1)).roleRequest(Matchers.any(RoleRequestInput.class));
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager#manageRoleChange(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}.
- */
- @Test
- public void testManageRoleChangeOK() {
- Mockito.when(session.isValid()).thenReturn(true);
- Mockito.when(sessionManager.getAllSessions()).thenReturn(Collections.singleton(session));
- Mockito.when(connectionAdapter.roleRequest(Matchers.any(RoleRequestInput.class)))
- .thenReturn(Futures.immediateFuture(RpcResultBuilder.success(roleRequestOutput).build()));
- Mockito.when(connectionAdapter.barrier(Matchers.any(BarrierInput.class)))
- .thenReturn(Futures.immediateFuture(RpcResultBuilder.success(barrierOutput).build()));
-
- //manager.manageRoleChange(OfpRole.BECOMESLAVE);
-
- ArgumentCaptor<RoleRequestInput> roleRequestCaptor = ArgumentCaptor.forClass(RoleRequestInput.class);
- //Mockito.verify(connectionAdapter, Mockito.times(2)).roleRequest(roleRequestCaptor.capture());
-
-// List<RoleRequestInput> values = roleRequestCaptor.getAllValues();
-// Assert.assertEquals(ControllerRole.OFPCRROLENOCHANGE, values.get(0).getRole());
-// Assert.assertEquals(0L, values.get(0).getGenerationId().longValue());
-// Assert.assertEquals(ControllerRole.OFPCRROLESLAVE, values.get(1).getRole());
-// Assert.assertEquals(11L, values.get(1).getGenerationId().longValue());
- }
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.session;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeaturesV10;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessageBuilder;
-/**
- * @author jsebin
- */
-public class PortFeaturesUtilTest {
-
- private PortStatusMessageBuilder portStatusMessageBuilder;
- private PortFeaturesUtil portUtil;
-
-
- /**
- * initialization of {@link org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessageBuilder.PortStatusMessageBuilder}
- * and {@link PortFeaturesUtil}
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- portStatusMessageBuilder = new PortStatusMessageBuilder();
- portUtil = PortFeaturesUtil.getInstance();
- }
-
- /**
- * @throws Exception
- */
- @After
- public void tearDown() throws Exception {
- portStatusMessageBuilder = null;
- portUtil = null;
- }
-
- /**
- * Test method for
- * {@link PortFeaturesUtil#getPortBandwidth()} for OF 1.0 version
- * and features
- * .
- */
- @Test
- public void testFeaturesV10() {
- PortFeaturesV10 features = new PortFeaturesV10(true, true, true, false, true, false, true, true, true, false, true, false);
- portStatusMessageBuilder.setReason(PortReason.OFPPRMODIFY).setVersion((short) 1).setCurrentFeaturesV10(features);
-
- Assert.assertNotNull(portUtil.getPortBandwidth(portStatusMessageBuilder.build()));
- }
-
- /**
- * Test method for
- * {@link PortFeaturesUtil#getPortBandwidth()} for OF 1.3 version
- * and features
- * .
- */
- @Test
- public void testFeaturesV13() {
- PortFeatures features = new PortFeatures(true, true, true, false, true, false, true, true, true, false, true, false, false, true, false, false);
- portStatusMessageBuilder.setReason(PortReason.OFPPRMODIFY).setVersion((short) 4).setCurrentFeatures(features);
-
- Assert.assertNotNull(portUtil.getPortBandwidth(portStatusMessageBuilder.build()));
- }
-
- /**
- * Test method for
- * {@link PortFeaturesUtil#getPortBandwidth()} for malformed features
- * - at least one feature is null
- * .
- */
- @Test
- public void testFeaturesMalformed() {
- PortFeaturesV10 features = new PortFeaturesV10(true, true, true, true, true, true, false, false, false, false, true, null);
- portStatusMessageBuilder.setReason(PortReason.OFPPRMODIFY).setVersion((short) 1).setCurrentFeaturesV10(features);
-
- Assert.assertNull(portUtil.getPortBandwidth(portStatusMessageBuilder.build()));
- }
-
- /**
- * Test method for
- * {@link PortFeaturesUtil#getPortBandwidth()} for mismatch between
- * port version and port features
- * .
- */
- @Test
- public void testFeaturesVersionMismatch() {
- PortFeatures features = new PortFeatures(true, true, true, false, true, false, true, true, true, false, true, false, false, true, false, false);
- portStatusMessageBuilder.setReason(PortReason.OFPPRMODIFY).setVersion((short) 1).setCurrentFeatures(features);
-
- Assert.assertNull(portUtil.getPortBandwidth(portStatusMessageBuilder.build()));
- }
-
- /**
- * Test method for
- * {@link PortFeaturesUtil#getPortBandwidth()} for nonexisting port version
- * .
- */
- @Test
- public void testFeaturesNonexistingVersion() {
- PortFeatures features = new PortFeatures(true, true, true, false, true, false, true, true, true, false, true, false, false, true, false, false);
- portStatusMessageBuilder.setReason(PortReason.OFPPRMODIFY).setVersion((short) 0).setCurrentFeatures(features);
-
- Assert.assertNull(portUtil.getPortBandwidth(portStatusMessageBuilder.build()));
- }
-
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.core.session;
-
-import static org.mockito.Matchers.any;
-
-import com.google.common.util.concurrent.ListeningExecutorService;
-import java.math.BigInteger;
-import java.net.InetSocketAddress;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Matchers;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF;
-import org.opendaylight.openflowplugin.openflow.md.core.role.OfEntityManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder;
-import org.opendaylight.yangtools.yang.binding.RpcService;
-
-/**
- * test of {@link SessionManagerOFImpl}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class SessionManagerOFImplTest {
-
- private SessionManager sm;
- private SwitchSessionKeyOF sessionKey;
- @Mock
- private SessionContext context;
- @Mock
- private ConnectionConductor primaryConductor;
- @Mock
- private ListeningExecutorService rpcPool;
- @Mock
- private NotificationProviderService notificationProviderService;
- @Mock
- private RpcProviderRegistry rpcProviderRegistry;
- @Mock
- private NotificationEnqueuer notificationEnqueuer;
- @Mock
- private ConnectionAdapter connectionAdapter;
- @Mock
- private DataBroker dataService;
-
- @Mock
- private OfEntityManager entManager;
-
- @Mock
- private ModelDrivenSwitchImpl ofSwitch;
-
-
- /**
- * prepare session manager
- */
- @Before
- public void setUp() {
- // context
- Mockito.when(context.getPrimaryConductor()).thenReturn(primaryConductor);
- Mockito.when(context.getNotificationEnqueuer()).thenReturn(notificationEnqueuer);
-
- // provider context - registration responder
- Mockito.when(rpcProviderRegistry.addRoutedRpcImplementation(Matchers.<Class<RpcService>> any(), any(RpcService.class)))
- .then(new Answer<RoutedRpcRegistration<?>>() {
- @Override
- public RoutedRpcRegistration<?> answer(final InvocationOnMock invocation) {
- final Object[] args = invocation.getArguments();
- final RoutedRpcRegistration<RpcService> registration = Mockito.mock(RoutedRpcRegistration.class);
- Mockito.when(registration.getInstance()).thenReturn((RpcService) args[1]);
- return registration;
- }
- });
-
- // session listener - prepare registration and notification mockery
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
- final SalRegistrationManager sessionListener = new SalRegistrationManager(convertorManager);
- sessionListener.setPublishService(notificationProviderService);
- sessionListener.setRpcProviderRegistry(rpcProviderRegistry);
- sessionListener.setDataService(dataService);
- sessionListener.setOfEntityManager(entManager);
-
- // session manager (mimic SalRegistrationManager.onSessionInitiated())
- sm = SessionManagerOFImpl.getInstance();
- sm.setRpcPool(rpcPool);
- sm.registerSessionListener(sessionListener);
- sm.setNotificationProviderService(notificationProviderService);
-
- // session key - switch id
- sessionKey = new SwitchSessionKeyOF();
- sessionKey.setDatapathId(BigInteger.valueOf(42));
- }
-
- /**
- * free session manager
- */
- @After
- public void tearDown() {
- SessionManagerOFImpl.releaseInstance();
- sessionKey = null;
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.session.SessionManagerOFImpl#addSessionContext(SwitchSessionKeyOF, SessionContext)}.
- */
- @Test
- public void testAddSessionContext() {
- // prepare mocks and values
- final GetFeaturesOutputBuilder featuresBld = new GetFeaturesOutputBuilder().setDatapathId(BigInteger.valueOf(42));
- featuresBld.setVersion((short) 123);
- Mockito.when(context.getFeatures()).thenReturn(featuresBld.build());
- Mockito.when(primaryConductor.getConnectionAdapter()).thenReturn(connectionAdapter);
- Mockito.when(connectionAdapter.getRemoteAddress()).thenReturn(new InetSocketAddress("10.1.2.3", 4242));
-
- //test target
- sm.addSessionContext(sessionKey, context);
-
- //capture
- //ArgumentCaptor<NotificationQueueWrapper> notifCaptor = ArgumentCaptor.forClass(NotificationQueueWrapper.class);
- //Mockito.verify(notificationEnqueuer).enqueueNotification(notifCaptor.capture());
- //check
- //Notification notification = notifCaptor.getValue().getNotification();
- //Assert.assertEquals(NodeUpdated.class, notification.getImplementedInterface());
- //FlowCapableNodeUpdated fcNodeUpdate = ((NodeUpdated) notification).getAugmentation(FlowCapableNodeUpdated.class);
-
- //Assert.assertNotNull(fcNodeUpdate);
- //Assert.assertEquals("10.1.2.3", fcNodeUpdate.getIpAddress().getIpv4Address().getValue());
- }
-
-}
+++ /dev/null
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.openflowplugin.openflow.md.core.session;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author mirehak
- */
-public class SwitchConnectionCookieOFImplTest {
-
- private static final Logger LOG = LoggerFactory
- .getLogger(SwitchConnectionCookieOFImplTest.class);
-
- private SwitchConnectionCookieOFImpl switchConnectionKey;
-
- private int seed;
-
- /**
- * @throws java.lang.Exception
- */
- @Before
- public void setUp() throws Exception {
- seed = 4242;
- switchConnectionKey = createSwitchSessionKey((short) 42);
- }
-
- /**
- * @param datapathId
- * @return
- */
- private static SwitchConnectionCookieOFImpl createSwitchSessionKey(short auxiliary) {
- SwitchConnectionCookieOFImpl key = new SwitchConnectionCookieOFImpl();
- key.setAuxiliaryId(auxiliary);
- return key;
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl#getId()}
- * .
- */
- @Test
- public void testGetId() {
- switchConnectionKey.init(seed);
- LOG.debug("testKey.id: " + Long.toHexString(switchConnectionKey.getCookie()));
- long expected = 710033450L;
- Assert.assertEquals(expected, switchConnectionKey.getCookie());
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl#initUUID()}
- * .
- */
- @Test
- public void testInitId1() {
- try {
- switchConnectionKey.setAuxiliaryId((short) 0);
- switchConnectionKey.init(seed);
- Assert.fail("init should fail with no datapathId");
- } catch (Exception e) {
- // expected
- }
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl#equals(Object)}
- * ,
- * {@link org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl#hashCode()}
- * .
- */
- @Test
- public void testHashAndEquals() {
- // insert equal keys
- SwitchConnectionCookieOFImpl key1 = createSwitchSessionKey((short) 42);
- key1.init(seed);
-
- SwitchConnectionCookieOFImpl key2 = createSwitchSessionKey((short) 42);
- key2.init(seed);
-
- SwitchConnectionCookieOFImpl key3 = createSwitchSessionKey((short) 43);
- key3.init(seed);
- SwitchConnectionCookieOFImpl key4 = createSwitchSessionKey((short) 21);
- key4.init(seed);
-
- Map<SwitchConnectionDistinguisher, Integer> keyLot = new HashMap<>();
- keyLot.put(key1, System.identityHashCode(key1));
- Assert.assertEquals(1, keyLot.size());
- keyLot.put(key2, System.identityHashCode(key2));
- Assert.assertEquals(1, keyLot.size());
- keyLot.put(key3, System.identityHashCode(key3));
- Assert.assertEquals(2, keyLot.size());
- keyLot.put(key4, System.identityHashCode(key4));
- Assert.assertEquals(3, keyLot.size());
-
- // lookup using inited key
- Assert.assertEquals(System.identityHashCode(key2), keyLot.get(key1)
- .intValue());
- Assert.assertEquals(System.identityHashCode(key2), keyLot.get(key2)
- .intValue());
- Assert.assertEquals(System.identityHashCode(key3), keyLot.get(key3)
- .intValue());
- Assert.assertEquals(System.identityHashCode(key4), keyLot.get(key4)
- .intValue());
-
- // lookup using not inited key
- SwitchConnectionCookieOFImpl keyWithoutInit = createSwitchSessionKey((short) 42);
- Assert.assertNull(keyLot.get(keyWithoutInit));
-
- // creating brand new key and lookup
- SwitchConnectionCookieOFImpl keyWithInit = createSwitchSessionKey((short) 43);
- keyWithInit.init(seed);
- Assert.assertEquals(System.identityHashCode(key3),
- keyLot.get(keyWithInit).intValue());
-
- // lookup with key containing encoded part only
- LOG.debug("key3.id: " + Long.toHexString(key3.getCookie()));
- SwitchConnectionCookieOFImpl keyWithoutDPID = new SwitchConnectionCookieOFImpl(734546075L);
- Assert.assertEquals(System.identityHashCode(key3),
- keyLot.get(keyWithoutDPID).intValue());
- }
-
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.core.translator;
-
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Method;
-import java.math.BigInteger;
-import java.util.List;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.BaseNodeErrorNotification;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessageBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- *
- */
-public class ErrorTranslatorTest {
-
- private final ErrorTranslator errorTranslator = new ErrorTranslator();
- private final ErrorMessageBuilder builder = new ErrorMessageBuilder();;
- private static final BigInteger DATAPATH_ID = BigInteger.valueOf(0x7777L);
- private static Logger LOG = LoggerFactory
- .getLogger(ErrorTranslatorTest.class);
-
- @Mock
- SwitchConnectionDistinguisher cookie;
- @Mock
- SessionContext sc;
- @Mock
- GetFeaturesOutput features;
-
- /**
- * startup method
- */
- @Before
- public void setUp() {
- builder.setCode(21);
- builder.setXid(42L);
- builder.setData(new byte[]{42});
-
- MockitoAnnotations.initMocks(this);
- when(sc.getFeatures()).thenReturn(features);
- when(features.getDatapathId()).thenReturn(DATAPATH_ID);
- }
-
-
- @Test
- public void testTranslate() {
- builder.setType(1);
- List<DataObject> data = errorTranslator.translate(cookie, sc, builder.build());
- assertNotNull(data);
- Assert.assertEquals(1, data.size());
- DataObject obj = data.get(0);
- Assert.assertTrue(obj instanceof BaseNodeErrorNotification);
- BaseNodeErrorNotification nodeError = (BaseNodeErrorNotification)obj;
- NodeRef expectedNode = new NodeRef(
- InventoryDataServiceUtil.identifierFromDatapathId(DATAPATH_ID));
- Assert.assertEquals(expectedNode, nodeError.getNode());
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorTranslator#getGranularNodeErrors(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType, NodeRef)}.
- *
- * @throws Exception
- */
- @Test
- public void testGetGranularNodeErrors() throws Exception {
- BigInteger dpid = BigInteger.valueOf(0x1122334455667788L);
- NodeRef node = new NodeRef(
- InventoryDataServiceUtil.identifierFromDatapathId(dpid));
- for (ErrorType eType : ErrorType.values()) {
- builder.setType(eType.getIntValue());
- ErrorMessage errorMessage = errorTranslator.getGranularNodeErrors(builder.build(), eType, node);
- LOG.debug("translating errorMessage of type {}", eType);
- assertNotNull("translated error is null", errorMessage);
- Assert.assertEquals(21, errorMessage.getCode().intValue());
- Assert.assertEquals(eType, errorMessage.getType());
- Method getNode = errorMessage.getClass().getMethod("getNode");
- getNode.setAccessible(true);
- Assert.assertEquals(node, getNode.invoke(errorMessage));
- Method getXid = errorMessage.getClass().getMethod("getTransactionId", new Class[0]);
- getXid.setAccessible(true);
- TransactionId xid = (TransactionId) getXid.invoke(errorMessage, new Object[0]);
- Assert.assertEquals(42L, xid.getValue().longValue());
- assertNotNull("data is null", errorMessage.getData());
- }
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorTranslator#decodeErrorType(int)}.
- */
- @Test
- public void testDecodeErrorType() {
- for (ErrorType eType : ErrorType.values()) {
- ErrorType result = errorTranslator.decodeErrorType(eType.getIntValue());
- Assert.assertEquals(eType, result);
- }
- }
-
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.core.translator;
-
-import java.lang.reflect.Method;
-import java.math.BigInteger;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessageBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- *
- */
-public class ErrorTranslatorV10Test {
-
- private ErrorV10Translator errorTranslator;
- private static Logger LOG = LoggerFactory
- .getLogger(ErrorTranslatorV10Test.class);
-
- /**
- * startup method
- */
- @Before
- public void setUp() {
- errorTranslator = new ErrorV10Translator();
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorTranslator#getGranularNodeErrors(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType, NodeRef)}.
- * @throws Exception
- */
- @Test
- public void testGetGranularNodeErrors() throws Exception {
- BigInteger dpid = BigInteger.valueOf(0x1122334455L);
- NodeRef node = new NodeRef(
- InventoryDataServiceUtil.identifierFromDatapathId(dpid));
- for (ErrorType eType : ErrorType.values()) {
- ErrorMessageBuilder builder = new ErrorMessageBuilder();
- builder.setType(eType.getIntValue());
- builder.setCode(21);
- builder.setXid(42L);
- builder.setData(new byte[]{42});
-
- ErrorMessage errorMessage = errorTranslator.getGranularNodeErrors(builder.build(), eType, node);
- LOG.debug("translating errorMessage of type {}", eType);
- Assert.assertNotNull("translated error is null", errorMessage);
- Assert.assertEquals(21, errorMessage.getCode().intValue());
- Assert.assertEquals(eType, errorMessage.getType());
- Method getNode = errorMessage.getClass().getMethod("getNode");
- getNode.setAccessible(true);
- Assert.assertEquals(node, getNode.invoke(errorMessage));
- Method getXid = errorMessage.getClass().getMethod("getTransactionId", new Class[0]);
- getXid.setAccessible(true);
- TransactionId xid = (TransactionId) getXid.invoke(errorMessage, new Object[0]);
- Assert.assertEquals(42L, xid.getValue().longValue());
- Assert.assertNotNull("data is null", errorMessage.getData());
- }
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorTranslator#decodeErrorType(int)}.
- */
- @Test
- public void testDecodeErrorType() {
- for (ErrorType eType : ErrorType.values()) {
- ErrorType result = errorTranslator.decodeErrorType(eType.getIntValue());
- int expectedType = -1;
- switch (eType.getIntValue()) {
- case 3:
- expectedType = 5;
- break;
- case 4:
- expectedType = 7;
- break;
- case 5:
- expectedType = 9;
- break;
- default:
- expectedType = eType.getIntValue();
- }
-
- Assert.assertEquals(expectedType, result.getIntValue());
- }
- }
-}
+++ /dev/null
-/*
- * 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.openflowplugin.openflow.md.core.translator;
-
-import static org.mockito.Mockito.when;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import junit.framework.TestCase;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ActionTypeV10;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.CapabilitiesV10;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortConfig;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortState;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPort;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPortBuilder;
-import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-
-@RunWith(MockitoJUnitRunner.class)
-public class FeaturesV10ToNodeConnectorUpdatedTranslatorTest extends TestCase {
-
- private static final FeaturesV10ToNodeConnectorUpdatedTranslator FEATURES_V_10_TO_NODE_CONNECTOR_UPDATED_TRANSLATOR = new FeaturesV10ToNodeConnectorUpdatedTranslator();
- private static final PortFeatures PORT_FEATURES = new PortFeatures(true, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false);
-
- @Mock
- SwitchConnectionDistinguisher switchConnectionDistinguisher;
- private static final PortConfig PORT_CONFIG = new PortConfig(true, false, false, false);
- @Mock
- SessionContext sessionContext;
- @Mock
- GetFeaturesOutput featuresOutput;
-
- @Test
- /**
- * Test method for basic functionality of {@link FeaturesV10ToNodeConnectorUpdatedTranslator#translate(org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher, org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext, org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader)}
- */
- public void testTranslate() throws Exception {
-
- when(sessionContext.getFeatures()).thenReturn(featuresOutput);
- when(featuresOutput.getDatapathId()).thenReturn(BigInteger.valueOf(42));
- List<DataObject> data = FEATURES_V_10_TO_NODE_CONNECTOR_UPDATED_TRANSLATOR.translate(switchConnectionDistinguisher, sessionContext, new MockOfHeader());
- assertNotNull(data);
- assertEquals(10, data.size());
- }
-
- private final class MockOfHeader implements OfHeader, GetFeaturesOutput {
-
- @Override
- public Short getVersion() {
- return OFConstants.OFP_VERSION_1_3;
- }
-
- @Override
- public Long getXid() {
- return new Long(1);
- }
-
- @Override
- public Class<? extends DataContainer> getImplementedInterface() {
- return GetFeaturesOutput.class;
- }
-
- @Override
- public <E extends Augmentation<GetFeaturesOutput>> E getAugmentation(final Class<E> eClass) {
- return null;
- }
-
- @Override
- public BigInteger getDatapathId() {
- return null;
- }
-
- @Override
- public Long getBuffers() {
- return null;
- }
-
- @Override
- public Short getTables() {
- return null;
- }
-
- @Override
- public Short getAuxiliaryId() {
- return null;
- }
-
- @Override
- public Capabilities getCapabilities() {
- return null;
- }
-
- @Override
- public Long getReserved() {
- return null;
- }
-
- @Override
- public CapabilitiesV10 getCapabilitiesV10() {
- return null;
- }
-
- @Override
- public ActionTypeV10 getActionsV10() {
- return null;
- }
-
- @Override
- public List<PhyPort> getPhyPort() {
- List<PhyPort> phyPorts = new ArrayList<>();
- for (int i = 0; i < 10; i++) {
- PhyPortBuilder phyPortBuilder = new PhyPortBuilder();
- phyPortBuilder.setAdvertisedFeatures(PORT_FEATURES);
- phyPortBuilder.setConfig(PORT_CONFIG);
- phyPortBuilder.setCurrentFeatures(PORT_FEATURES);
- phyPortBuilder.setPeerFeatures(PORT_FEATURES);
- phyPortBuilder.setState(PortState.getDefaultInstance("live"));
- phyPortBuilder.setSupportedFeatures(PORT_FEATURES);
- phyPortBuilder.setPortNo(new Long(42));
- phyPorts.add(phyPortBuilder.build());
- }
- return phyPorts;
- }
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*
- * 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.openflowplugin.openflow.md.core.translator;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.when;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.List;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
-import org.opendaylight.openflowplugin.openflow.md.core.extension.ExtensionConverterManagerImpl;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
-import org.opendaylight.openflowplugin.openflow.md.core.session.SessionManagerOFImpl;
-import org.opendaylight.openflowplugin.openflow.md.util.ByteUtil;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Dscp;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6FlowLabel;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.mod.removed.Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ProtocolMatchFields;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4Match;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.IpMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Tunnel;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatch;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.EtherType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Ipv6ExthdrFlags;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpOp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpSha;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpSpa;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpTha;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpTpa;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthSrc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv4Code;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv4Type;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv6Code;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv6Type;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.InPhyPort;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.InPort;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpProto;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv4Dst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv4Src;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Dst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Exthdr;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Flabel;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdSll;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdTarget;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdTll;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Src;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Metadata;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsBos;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsLabel;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.PbbIsid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.SctpDst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TcpDst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TunnelId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.UdpDst;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.UdpSrc;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.VlanPcp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntryBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpOpCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpShaCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpSpaCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpThaCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpTpaCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthDstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthSrcCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthTypeCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv4CodeCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv4TypeCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv6CodeCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv6TypeCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.InPhyPortCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.InPortCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpDscpCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpEcnCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpProtoCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv4DstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv4SrcCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6DstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6ExthdrCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6FlabelCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdSllCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdTargetCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdTllCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6SrcCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MetadataCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsBosCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsLabelCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsTcCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.PbbIsidCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.SctpDstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.SctpSrcCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TcpDstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TcpSrcCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TunnelIdCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.UdpDstCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.UdpSrcCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.VlanPcpCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.VlanVidCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.arp.op._case.ArpOpBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.arp.sha._case.ArpShaBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.arp.spa._case.ArpSpaBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.arp.tha._case.ArpThaBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.arp.tpa._case.ArpTpaBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.eth.dst._case.EthDstBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.eth.src._case.EthSrcBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.eth.type._case.EthTypeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.icmpv4.code._case.Icmpv4CodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.icmpv4.type._case.Icmpv4TypeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.icmpv6.code._case.Icmpv6CodeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.icmpv6.type._case.Icmpv6TypeBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.in.phy.port._case.InPhyPortBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.in.port._case.InPortBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ip.dscp._case.IpDscpBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ip.ecn._case.IpEcnBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ip.proto._case.IpProtoBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv4.dst._case.Ipv4DstBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv4.src._case.Ipv4SrcBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.dst._case.Ipv6DstBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.exthdr._case.Ipv6ExthdrBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.flabel._case.Ipv6FlabelBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.nd.sll._case.Ipv6NdSllBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.nd.target._case.Ipv6NdTargetBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.nd.tll._case.Ipv6NdTllBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.src._case.Ipv6SrcBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.mpls.bos._case.MplsBosBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.mpls.label._case.MplsLabelBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.mpls.tc._case.MplsTcBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.pbb.isid._case.PbbIsidBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.sctp.dst._case.SctpDstBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.sctp.src._case.SctpSrcBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.tcp.dst._case.TcpDstBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.tcp.src._case.TcpSrcBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.tunnel.id._case.TunnelIdBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.udp.dst._case.UdpDstBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.udp.src._case.UdpSrcBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.vlan.pcp._case.VlanPcpBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.vlan.vid._case.VlanVidBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-
-@RunWith(MockitoJUnitRunner.class)
-public class FlowRemovedTranslatorTest {
-
- private FlowRemovedTranslator flowRemovedTranslator;
- private static final BigInteger DATA_PATH_ID = BigInteger.valueOf(42);
- public static final Ipv6Address IPV_6_ADDRESS = new Ipv6Address("2001:0DB8:AC10:FE01:0000:0000:0000:0000");
- private static final byte[] IPV_6_ADDRESS_MASK = ByteUtil.unsignedIntToBytes(new Long(64));
- private static final Ipv4Address IPV_4_ADDRESS = new Ipv4Address("10.0.0.1");
- private static final byte[] IPV_4_ADDRESS_MASK = ByteUtil.unsignedIntToBytes(new Long(8));
-
- @Mock
- SwitchConnectionDistinguisher switchConnectionDistinguisher;
-
- @Mock
- SessionContext sessionContext;
-
- @Mock
- FlowRemovedMessage msg;
-
- @Mock
- ConnectionConductor connectionConductor;
-
- @Mock
- GetFeaturesOutput featuresOutput;
-
- private static final MacAddress MAC_ADDRESS = new MacAddress("00:01:02:03:04:05");
-
-
- private static List<MatchEntry> fieldClassesAndAugmentations = new ArrayList<>();
-
-
- private static void setupClassAndAugmentationMap() {
-
-
- MatchEntryBuilder matchEntryBuilder = new MatchEntryBuilder();
- InPortBuilder portBuilder = new InPortBuilder();
- portBuilder.setPortNumber(new PortNumber((long) 42));
- InPortCaseBuilder inPortCaseBuilder = new InPortCaseBuilder();
- inPortCaseBuilder.setInPort(portBuilder.build());
- matchEntryBuilder.setMatchEntryValue(inPortCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(InPort.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- InPhyPortBuilder inPhyPortBuilder = new InPhyPortBuilder();
- PortNumber portNumber = new PortNumber((long) 42);
- inPhyPortBuilder.setPortNumber(portNumber);
- InPhyPortCaseBuilder inPhyPortCaseBuilder = new InPhyPortCaseBuilder();
- inPhyPortCaseBuilder.setInPhyPort(inPhyPortBuilder.build());
- matchEntryBuilder.setMatchEntryValue(inPhyPortCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(InPhyPort.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- MetadataCaseBuilder metadataCaseBuilder = new MetadataCaseBuilder();
- org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.metadata._case.MetadataBuilder metadataBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.metadata._case.MetadataBuilder();
- metadataBuilder.setMetadata(new byte[0]);
- metadataBuilder.setMask(new byte[0]);
- metadataCaseBuilder.setMetadata(metadataBuilder.build());
- matchEntryBuilder.setMatchEntryValue(metadataCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Metadata.class);
- matchEntryBuilder.setHasMask(false);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
-
- EthTypeBuilder ethTypeBuilder = new EthTypeBuilder();
- ethTypeBuilder.setEthType(new EtherType(6));
- EthTypeCaseBuilder ethTypeCaseBuilder = new EthTypeCaseBuilder();
- ethTypeCaseBuilder.setEthType(ethTypeBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ethTypeCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(EthType.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- VlanVidBuilder vlanVidBuilder = new VlanVidBuilder();
- vlanVidBuilder.setCfiBit(true);
- vlanVidBuilder.setVlanVid(42);
- VlanVidCaseBuilder vlanVidCaseBuilder = new VlanVidCaseBuilder();
- vlanVidCaseBuilder.setVlanVid(vlanVidBuilder.build());
- matchEntryBuilder.setMatchEntryValue(vlanVidCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.VlanVid.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- VlanPcpBuilder vlanPcpBuilder = new VlanPcpBuilder();
- vlanPcpBuilder.setVlanPcp((short) 7);
- VlanPcpCaseBuilder vlanPcpCaseBuilder = new VlanPcpCaseBuilder();
- vlanPcpCaseBuilder.setVlanPcp(vlanPcpBuilder.build());
- matchEntryBuilder.setMatchEntryValue(vlanPcpCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(VlanPcp.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- IpDscpBuilder ipDscpBuilder = new IpDscpBuilder();
- ipDscpBuilder.setDscp(new Dscp((short) 10));
- IpDscpCaseBuilder ipDscpCaseBuilder = new IpDscpCaseBuilder();
- ipDscpCaseBuilder.setIpDscp(ipDscpBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipDscpCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpDscp.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- IpEcnBuilder ipEcnBuilder = new IpEcnBuilder();
- ipEcnBuilder.setEcn((short) 10);
- IpEcnCaseBuilder ipEcnCaseBuilder = new IpEcnCaseBuilder();
- ipEcnCaseBuilder.setIpEcn(ipEcnBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipEcnCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpEcn.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- IpProtoBuilder ipProtoBuilder = new IpProtoBuilder();
- ipProtoBuilder.setProtocolNumber(OFConstants.OFP_VERSION_1_3);
- IpProtoCaseBuilder ipProtoCaseBuilder = new IpProtoCaseBuilder();
- ipProtoCaseBuilder.setIpProto(ipProtoBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipProtoCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(IpProto.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- TcpSrcBuilder tcpSrcBuilder = new TcpSrcBuilder();
- org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber port = new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber(43);
- tcpSrcBuilder.setPort(port);
- TcpSrcCaseBuilder tcpSrcCaseBuilder = new TcpSrcCaseBuilder();
- tcpSrcCaseBuilder.setTcpSrc(tcpSrcBuilder.build());
- matchEntryBuilder.setMatchEntryValue(tcpSrcCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TcpSrc.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- TcpDstBuilder tcpDstBuilder = new TcpDstBuilder();
- tcpDstBuilder.setPort(port);
- TcpDstCaseBuilder tcpDstCaseBuilder = new TcpDstCaseBuilder();
- tcpDstCaseBuilder.setTcpDst(tcpDstBuilder.build());
- matchEntryBuilder.setMatchEntryValue(tcpDstCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(TcpDst.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- UdpSrcBuilder udpSrcBuilder = new UdpSrcBuilder();
- udpSrcBuilder.setPort(port);
- UdpSrcCaseBuilder udpSrcCaseBuilder = new UdpSrcCaseBuilder();
- udpSrcCaseBuilder.setUdpSrc(udpSrcBuilder.build());
- matchEntryBuilder.setMatchEntryValue(udpSrcCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(UdpSrc.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- UdpDstBuilder udpDstBuilder = new UdpDstBuilder();
- udpDstBuilder.setPort(port);
- UdpDstCaseBuilder udpDstCaseBuilder = new UdpDstCaseBuilder();
- udpDstCaseBuilder.setUdpDst(udpDstBuilder.build());
- matchEntryBuilder.setMatchEntryValue(udpDstCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(UdpDst.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- SctpSrcBuilder sctpSrcBuilder = new SctpSrcBuilder();
- sctpSrcBuilder.setPort(port);
- SctpSrcCaseBuilder sctpSrcCaseBuilder = new SctpSrcCaseBuilder();
- sctpSrcCaseBuilder.setSctpSrc(sctpSrcBuilder.build());
- matchEntryBuilder.setMatchEntryValue(sctpSrcCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.SctpSrc.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- SctpDstBuilder sctpDstBuilder = new SctpDstBuilder();
- sctpDstBuilder.setPort(port);
- SctpDstCaseBuilder sctpDstCaseBuilder = new SctpDstCaseBuilder();
- sctpDstCaseBuilder.setSctpDst(sctpDstBuilder.build());
- matchEntryBuilder.setMatchEntryValue(sctpDstCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(SctpDst.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Icmpv4TypeBuilder icmpv4TypeBuilder = new Icmpv4TypeBuilder();
- icmpv4TypeBuilder.setIcmpv4Type((short) 10);
- Icmpv4TypeCaseBuilder icmpv4TypeCaseBuilder = new Icmpv4TypeCaseBuilder();
- icmpv4TypeCaseBuilder.setIcmpv4Type(icmpv4TypeBuilder.build());
- matchEntryBuilder.setMatchEntryValue(icmpv4TypeCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Icmpv4Type.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Icmpv4CodeBuilder icmpv4CodeBuilder = new Icmpv4CodeBuilder();
- icmpv4CodeBuilder.setIcmpv4Code((short) 10);
- Icmpv4CodeCaseBuilder icmpv4CodeCaseBuilder = new Icmpv4CodeCaseBuilder();
- icmpv4CodeCaseBuilder.setIcmpv4Code(icmpv4CodeBuilder.build());
- matchEntryBuilder.setMatchEntryValue(icmpv4CodeCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Icmpv4Code.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Icmpv6TypeBuilder icmpv6TypeBuilder = new Icmpv6TypeBuilder();
- icmpv6TypeBuilder.setIcmpv6Type((short) 10);
- Icmpv6TypeCaseBuilder icmpv6TypeCaseBuilder = new Icmpv6TypeCaseBuilder();
- icmpv6TypeCaseBuilder.setIcmpv6Type(icmpv6TypeBuilder.build());
- matchEntryBuilder.setMatchEntryValue(icmpv6TypeCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Icmpv6Type.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Icmpv6CodeBuilder icmpv6CodeBuilder = new Icmpv6CodeBuilder();
- icmpv6CodeBuilder.setIcmpv6Code((short) 10);
- Icmpv6CodeCaseBuilder icmpv6CodeCaseBuilder = new Icmpv6CodeCaseBuilder();
- icmpv6CodeCaseBuilder.setIcmpv6Code(icmpv6CodeBuilder.build());
- matchEntryBuilder.setMatchEntryValue(icmpv6CodeCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Icmpv6Code.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- ArpOpBuilder arpOpBuilder = new ArpOpBuilder();
- arpOpBuilder.setOpCode(42);
- ArpOpCaseBuilder arpOpCaseBuilder = new ArpOpCaseBuilder();
- arpOpCaseBuilder.setArpOp(arpOpBuilder.build());
- matchEntryBuilder.setMatchEntryValue(arpOpCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(ArpOp.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- ArpShaBuilder arpShaBuilder = new ArpShaBuilder();
- arpShaBuilder.setMacAddress(MAC_ADDRESS);
- ArpShaCaseBuilder arpShaCaseBuilder = new ArpShaCaseBuilder();
- arpShaCaseBuilder.setArpSha(arpShaBuilder.build());
- matchEntryBuilder.setMatchEntryValue(arpShaCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(ArpSha.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- ArpThaBuilder arpThaBuilder = new ArpThaBuilder();
- arpThaBuilder.setMacAddress(MAC_ADDRESS);
- ArpThaCaseBuilder arpThaCaseBuilder = new ArpThaCaseBuilder();
- arpThaCaseBuilder.setArpTha(arpThaBuilder.build());
- matchEntryBuilder.setMatchEntryValue(arpThaCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(ArpTha.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- EthDstBuilder ethDstBuilder = new EthDstBuilder();
- ethDstBuilder.setMacAddress(MAC_ADDRESS);
- EthDstCaseBuilder ethDstCaseBuilder = new EthDstCaseBuilder();
- ethDstCaseBuilder.setEthDst(ethDstBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ethDstCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthDst.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- EthSrcBuilder ethSrcBuilder = new EthSrcBuilder();
- ethSrcBuilder.setMacAddress(MAC_ADDRESS);
- EthSrcCaseBuilder ethSrcCaseBuilder = new EthSrcCaseBuilder();
- ethSrcCaseBuilder.setEthSrc(ethSrcBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ethSrcCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(EthSrc.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
-
- Ipv6FlabelBuilder ipv6FlabelBuilder = new Ipv6FlabelBuilder();
- ipv6FlabelBuilder.setIpv6Flabel(new Ipv6FlowLabel((long) 42));
- Ipv6FlabelCaseBuilder ipv6FlabelCaseBuilder = new Ipv6FlabelCaseBuilder();
- ipv6FlabelCaseBuilder.setIpv6Flabel(ipv6FlabelBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipv6FlabelCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Ipv6Flabel.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Ipv6NdTargetBuilder ipv6NdTargetBuilder = new Ipv6NdTargetBuilder();
- ipv6NdTargetBuilder.setIpv6Address(IPV_6_ADDRESS);
- Ipv6NdTargetCaseBuilder ipv6NdTargetCaseBuilder = new Ipv6NdTargetCaseBuilder();
- ipv6NdTargetCaseBuilder.setIpv6NdTarget(ipv6NdTargetBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipv6NdTargetCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Ipv6NdTarget.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Ipv6NdSllBuilder ipv6NdSllBuilder = new Ipv6NdSllBuilder();
- ipv6NdSllBuilder.setMacAddress(MAC_ADDRESS);
- Ipv6NdSllCaseBuilder ipv6NdSllCaseBuilder = new Ipv6NdSllCaseBuilder();
- ipv6NdSllCaseBuilder.setIpv6NdSll(ipv6NdSllBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipv6NdSllCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Ipv6NdSll.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Ipv6NdTllBuilder ipv6NdTllBuilder = new Ipv6NdTllBuilder();
- ipv6NdTllBuilder.setMacAddress(MAC_ADDRESS);
- Ipv6NdTllCaseBuilder ipv6NdTllCaseBuilder = new Ipv6NdTllCaseBuilder();
- ipv6NdTllCaseBuilder.setIpv6NdTll(ipv6NdTllBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipv6NdTllCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Ipv6NdTll.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Ipv6ExthdrBuilder ipv6ExthdrBuilder = new Ipv6ExthdrBuilder();
- Ipv6ExthdrFlags ipv6ExthdrFlags = new Ipv6ExthdrFlags(true, true, true, true, true, true, true, true, true);
- ipv6ExthdrBuilder.setPseudoField(ipv6ExthdrFlags);
- ipv6ExthdrBuilder.setMask(IPV_6_ADDRESS_MASK);
- Ipv6ExthdrCaseBuilder ipv6ExthdrCaseBuilder = new Ipv6ExthdrCaseBuilder();
- ipv6ExthdrCaseBuilder.setIpv6Exthdr(ipv6ExthdrBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipv6ExthdrCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Ipv6Exthdr.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- MplsLabelBuilder mplsLabelBuilder = new MplsLabelBuilder();
- mplsLabelBuilder.setMplsLabel((long) 42);
- MplsLabelCaseBuilder mplsLabelCaseBuilder = new MplsLabelCaseBuilder();
- mplsLabelCaseBuilder.setMplsLabel(mplsLabelBuilder.build());
- matchEntryBuilder.setMatchEntryValue(mplsLabelCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(MplsLabel.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- MplsTcBuilder mplsTcBuilder = new MplsTcBuilder();
- mplsTcBuilder.setTc((short) 0);
- MplsTcCaseBuilder mplsTcCaseBuilder = new MplsTcCaseBuilder();
- mplsTcCaseBuilder.setMplsTc(mplsTcBuilder.build());
- matchEntryBuilder.setMatchEntryValue(mplsTcCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsTc.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- MplsBosBuilder mplsBosBuilder = new MplsBosBuilder();
- mplsBosBuilder.setBos(false);
- MplsBosCaseBuilder mplsBosCaseBuilder = new MplsBosCaseBuilder();
- mplsBosCaseBuilder.setMplsBos(mplsBosBuilder.build());
- matchEntryBuilder.setMatchEntryValue(mplsBosCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(MplsBos.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- PbbIsidBuilder pbbIsidBuilder = new PbbIsidBuilder();
- pbbIsidBuilder.setIsid((long) 42);
- PbbIsidCaseBuilder pbbIsidCaseBuilder = new PbbIsidCaseBuilder();
- pbbIsidCaseBuilder.setPbbIsid(pbbIsidBuilder.build());
- matchEntryBuilder.setMatchEntryValue(pbbIsidCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(PbbIsid.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- TunnelIdBuilder tunnelIdBuilder = new TunnelIdBuilder();
- tunnelIdBuilder.setMask(new byte[0]);
- tunnelIdBuilder.setTunnelId(new byte[42]);
- TunnelIdCaseBuilder tunnelIdCaseBuilder = new TunnelIdCaseBuilder();
- tunnelIdCaseBuilder.setTunnelId(tunnelIdBuilder.build());
- matchEntryBuilder.setMatchEntryValue(tunnelIdCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(TunnelId.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- ArpTpaBuilder arpTpaBuilder = new ArpTpaBuilder();
- arpTpaBuilder.setIpv4Address(IPV_4_ADDRESS);
- arpTpaBuilder.setMask(new byte[0]);
- ArpTpaCaseBuilder arpTpaCaseBuilder = new ArpTpaCaseBuilder();
- arpTpaCaseBuilder.setArpTpa(arpTpaBuilder.build());
- matchEntryBuilder.setMatchEntryValue(arpTpaCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(ArpTpa.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- ArpSpaBuilder arpSpaBuilder = new ArpSpaBuilder();
- arpSpaBuilder.setMask(new byte[0]);
- arpSpaBuilder.setIpv4Address(IPV_4_ADDRESS);
- ArpSpaCaseBuilder arpSpaCaseBuilder = new ArpSpaCaseBuilder();
- arpSpaCaseBuilder.setArpSpa(arpSpaBuilder.build());
- matchEntryBuilder.setMatchEntryValue(arpSpaCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(ArpSpa.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Ipv4SrcBuilder ipv4SrcBuilder = new Ipv4SrcBuilder();
- ipv4SrcBuilder.setIpv4Address(IPV_4_ADDRESS);
- ipv4SrcBuilder.setMask(IPV_4_ADDRESS_MASK);
- Ipv4SrcCaseBuilder ipv4SrcCaseBuilder = new Ipv4SrcCaseBuilder();
- ipv4SrcCaseBuilder.setIpv4Src(ipv4SrcBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipv4SrcCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Ipv4Src.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Ipv4DstBuilder ipv4DstBuilder = new Ipv4DstBuilder();
- ipv4DstBuilder.setIpv4Address(IPV_4_ADDRESS);
- ipv4DstBuilder.setMask(IPV_4_ADDRESS_MASK);
- Ipv4DstCaseBuilder ipv4DstCaseBuilder = new Ipv4DstCaseBuilder();
- ipv4DstCaseBuilder.setIpv4Dst(ipv4DstBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipv4DstCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Ipv4Dst.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
-
- Ipv6SrcBuilder ipv6SrcBuilder = new Ipv6SrcBuilder();
- ipv6SrcBuilder.setIpv6Address(IPV_6_ADDRESS);
- ipv6SrcBuilder.setMask(IPV_6_ADDRESS_MASK);
- Ipv6SrcCaseBuilder ipv6SrcCaseBuilder = new Ipv6SrcCaseBuilder();
- ipv6SrcCaseBuilder.setIpv6Src(ipv6SrcBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipv6SrcCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Ipv6Src.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
-
- Ipv6DstBuilder ipv6DstBuilder = new Ipv6DstBuilder();
- ipv6DstBuilder.setIpv6Address(IPV_6_ADDRESS);
- ipv6DstBuilder.setMask(IPV_6_ADDRESS_MASK);
- Ipv6DstCaseBuilder ipv6DstCaseBuilder = new Ipv6DstCaseBuilder();
- ipv6DstCaseBuilder.setIpv6Dst(ipv6DstBuilder.build());
- matchEntryBuilder.setMatchEntryValue(ipv6DstCaseBuilder.build());
- matchEntryBuilder.setOxmMatchField(Ipv6Dst.class);
- fieldClassesAndAugmentations.add(matchEntryBuilder.build());
- }
-
-
- @Before
- public void setup() {
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
- flowRemovedTranslator = new FlowRemovedTranslator(convertorManager);
- when(sessionContext.getPrimaryConductor()).thenReturn(connectionConductor);
- when(connectionConductor.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
- when(sessionContext.getFeatures()).thenReturn(featuresOutput);
- when(featuresOutput.getDatapathId()).thenReturn(DATA_PATH_ID);
- ExtensionConverterManagerImpl extensionConverterProvider = new ExtensionConverterManagerImpl();
- //extensionConverterProvider.registerMatchConvertor()
- SessionManagerOFImpl.getInstance().setExtensionConverterProvider(extensionConverterProvider);
- }
-
- @Test
- public void testTranslate() throws Exception {
- List<DataObject> dataObjectList = flowRemovedTranslator.translate(switchConnectionDistinguisher, sessionContext, msg);
- assertNotNull(dataObjectList);
- }
-
- @Test
- public void testFromMatch() throws Exception {
- setupClassAndAugmentationMap();
- org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder matchBuilder = new MatchBuilder();
- matchBuilder.setMatchEntry(fieldClassesAndAugmentations);
- Match match = flowRemovedTranslator.fromMatch(matchBuilder.build(), DATA_PATH_ID, OpenflowVersion.OF13);
- assertNotNull(match);
- assertEthernetMatch(match.getEthernetMatch());
- assertIcmpV4Match(match.getIcmpv4Match());
-
- assertEquals("openflow:42:42", match.getInPhyPort().getValue());
- assertEquals("openflow:42:42", match.getInPort().getValue());
- assertIpMatch(match.getIpMatch());
-
- assertNotNull(match.getLayer3Match());
- assertNotNull(match.getLayer4Match());
-
- assertProtocolMatchFields(match.getProtocolMatchFields());
-
- assertMetada(match.getMetadata());
-
- assertTunnelMatch(match.getTunnel());
-
- assertVlanMatch(match.getVlanMatch());
- }
-
- private static void assertTunnelMatch(final Tunnel tunnel) {
- assertEquals(0, tunnel.getTunnelId().intValue());
- }
-
- private static void assertVlanMatch(final VlanMatch vlanMatch) {
- assertEquals(true, vlanMatch.getVlanId().isVlanIdPresent());
- assertEquals(new Integer(42), vlanMatch.getVlanId().getVlanId().getValue());
-
- assertEquals((short) 7, vlanMatch.getVlanPcp().getValue().shortValue());
- }
-
- private static void assertMetada(final org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Metadata metadata) {
- assertEquals(0, metadata.getMetadata().intValue());
- }
-
- private static void assertProtocolMatchFields(final ProtocolMatchFields protocolMatchFields) {
- assertEquals((short) 0, protocolMatchFields.getMplsBos().shortValue());
- assertEquals(42, protocolMatchFields.getMplsLabel().longValue());
- assertEquals((short) 0, protocolMatchFields.getMplsTc().shortValue());
- assertEquals(42, protocolMatchFields.getPbb().getPbbIsid().longValue());
- }
-
- private static void assertIpMatch(final IpMatch ipMatch) {
- assertEquals(10, ipMatch.getIpDscp().getValue().longValue());
- assertEquals(10, ipMatch.getIpEcn().shortValue());
- assertEquals(4, ipMatch.getIpProtocol().shortValue());
- }
-
- private static void assertIcmpV4Match(final Icmpv4Match icmpv4Match) {
- assertEquals(10, icmpv4Match.getIcmpv4Code().longValue());
- assertEquals(10, icmpv4Match.getIcmpv4Type().longValue());
- }
-
- private static void assertEthernetMatch(final EthernetMatch ethernetMatch) {
- assertEquals(MAC_ADDRESS, ethernetMatch.getEthernetDestination().getAddress());
- assertEquals(MAC_ADDRESS, ethernetMatch.getEthernetSource().getAddress());
- assertEquals(new Long(6), ethernetMatch.getEthernetType().getType().getValue());
- }
-
-}
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.translator;\r
-\r
-import static org.mockito.Mockito.when;\r
-\r
-import java.math.BigInteger;\r
-import java.util.List;\r
-\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.mockito.Mock;\r
-import org.mockito.MockitoAnnotations;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyDescCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.desc._case.MultipartReplyDescBuilder;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-\r
-/**\r
- * @author michal.polkorab\r
- *\r
- */\r
-public class MultiPartMessageDescToNodeUpdatedTranslatorTest {\r
-\r
- @Mock SwitchConnectionDistinguisher cookie;\r
- @Mock SessionContext sc;\r
- @Mock GetFeaturesOutput features;\r
-\r
- MultiPartMessageDescToNodeUpdatedTranslator translator = new MultiPartMessageDescToNodeUpdatedTranslator();\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- MockitoAnnotations.initMocks(this);\r
- when(sc.getFeatures()).thenReturn(features);\r
- when(features.getDatapathId()).thenReturn(new BigInteger("42"));\r
- }\r
-\r
- /**\r
- * Test {@link MultiPartMessageDescToNodeUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with wrong inputs\r
- */\r
- @Test\r
- public void testWrongInputs() {\r
- HelloMessageBuilder helloBuilder = new HelloMessageBuilder();\r
- HelloMessage helloMessage = helloBuilder.build();\r
- List<DataObject> list = translator.translate(cookie, sc, helloMessage);\r
- Assert.assertEquals("Wrong output", 0, list.size());\r
- \r
- MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder();\r
- builder.setType(MultipartType.OFPMPFLOW);\r
- MultipartReplyMessage message = builder.build();\r
- list = translator.translate(cookie, sc, message);\r
- Assert.assertEquals("Wrong output", 0, list.size());\r
- }\r
-\r
- /**\r
- * Test {@link MultiPartMessageDescToNodeUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with correct input\r
- */\r
- @Test\r
- public void testCorrectInput() {\r
- MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder();\r
- builder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- builder.setXid(12345L);\r
- builder.setType(MultipartType.OFPMPDESC);\r
- builder.setFlags(new MultipartRequestFlags(false));\r
- \r
- MultipartReplyDescCaseBuilder caseBuilder = new MultipartReplyDescCaseBuilder();\r
- MultipartReplyDescBuilder descBuilder = new MultipartReplyDescBuilder();\r
- descBuilder.setMfrDesc("Collaboration ltd.");\r
- descBuilder.setHwDesc("Simple switch");\r
- descBuilder.setSwDesc("Best software ever inside");\r
- descBuilder.setSerialNum("123456789");\r
- descBuilder.setDpDesc("0000000000000001");\r
- caseBuilder.setMultipartReplyDesc(descBuilder.build());\r
- builder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = builder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
- Assert.assertEquals("Wrong output", 1, list.size());\r
- NodeUpdated nodeUpdated = (NodeUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", nodeUpdated.getId().getValue());\r
- FlowCapableNodeUpdated flowCapable = nodeUpdated.getAugmentation(FlowCapableNodeUpdated.class);\r
- Assert.assertEquals("Wrong manufacturer", "Collaboration ltd.", flowCapable.getManufacturer());\r
- Assert.assertEquals("Wrong hardware", "Simple switch", flowCapable.getHardware());\r
- Assert.assertEquals("Wrong software", "Best software ever inside", flowCapable.getSoftware());\r
- Assert.assertEquals("Wrong serial number", "123456789", flowCapable.getSerialNumber());\r
- Assert.assertEquals("Wrong datapath description", "0000000000000001", flowCapable.getDescription());\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.translator;\r
-\r
-import static org.mockito.Mockito.when;\r
-\r
-import java.math.BigInteger;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.mockito.Mock;\r
-import org.mockito.MockitoAnnotations;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;\r
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortConfig;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeatures;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortState;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortDescCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.MultipartReplyPortDescBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.multipart.reply.port.desc.Ports;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.multipart.reply.port.desc.PortsBuilder;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-\r
-/**\r
- * @author michal.polkorab\r
- *\r
- */\r
-public class MultiPartReplyPortToNodeConnectorUpdatedTranslatorTest {\r
-\r
- @Mock SwitchConnectionDistinguisher cookie;\r
- @Mock SessionContext sc;\r
- @Mock GetFeaturesOutput features;\r
-\r
- MultiPartReplyPortToNodeConnectorUpdatedTranslator translator = new MultiPartReplyPortToNodeConnectorUpdatedTranslator();\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- MockitoAnnotations.initMocks(this);\r
- when(sc.getFeatures()).thenReturn(features);\r
- when(features.getDatapathId()).thenReturn(new BigInteger("42"));\r
- }\r
-\r
- /**\r
- * Test {@link MultiPartReplyPortToNodeConnectorUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with wrong inputs\r
- */\r
- @Test\r
- public void testWrongInputs() {\r
- HelloMessageBuilder helloBuilder = new HelloMessageBuilder();\r
- HelloMessage helloMessage = helloBuilder.build();\r
- List<DataObject> list = translator.translate(cookie, sc, helloMessage);\r
- Assert.assertEquals("Wrong output", 0, list.size());\r
- \r
- MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder();\r
- builder.setType(MultipartType.OFPMPFLOW);\r
- MultipartReplyMessage message = builder.build();\r
- list = translator.translate(cookie, sc, message);\r
- Assert.assertEquals("Wrong output", 0, list.size());\r
- }\r
-\r
- /**\r
- * Test {@link MultiPartReplyPortToNodeConnectorUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with correct input (no ports)\r
- */\r
- @Test\r
- public void testEmptyPortDescWithCorrectInput() {\r
- MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder();\r
- builder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- builder.setXid(12345L);\r
- builder.setType(MultipartType.OFPMPPORTDESC);\r
- builder.setFlags(new MultipartRequestFlags(false));\r
- \r
- MultipartReplyPortDescCaseBuilder caseBuilder = new MultipartReplyPortDescCaseBuilder();\r
- MultipartReplyPortDescBuilder descBuilder = new MultipartReplyPortDescBuilder();\r
- List<Ports> ports = new ArrayList<>();\r
- descBuilder.setPorts(ports);\r
- caseBuilder.setMultipartReplyPortDesc(descBuilder.build());\r
- builder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = builder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
- Assert.assertEquals("Wrong output", 0, list.size());\r
- }\r
-\r
- /**\r
- * Test {@link MultiPartReplyPortToNodeConnectorUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with correct input\r
- */\r
- @Test\r
- public void testPortDescWithCorrectInput() {\r
- MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder();\r
- builder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- builder.setXid(12345L);\r
- builder.setType(MultipartType.OFPMPPORTDESC);\r
- builder.setFlags(new MultipartRequestFlags(false));\r
- \r
- MultipartReplyPortDescCaseBuilder caseBuilder = new MultipartReplyPortDescCaseBuilder();\r
- MultipartReplyPortDescBuilder descBuilder = new MultipartReplyPortDescBuilder();\r
- List<Ports> ports = new ArrayList<>();\r
- PortsBuilder portBuilder = new PortsBuilder();\r
- portBuilder.setPortNo(5L);\r
- portBuilder.setHwAddr(new MacAddress("06:07:08:09:0A:0B"));\r
- portBuilder.setName("MultipartPortDesc port");\r
- portBuilder.setConfig(new PortConfig(true, false, true, false));\r
- portBuilder.setState(new PortState(true, false, true));\r
- portBuilder.setCurrentFeatures(new PortFeatures(false, true, false, true,\r
- false, true, false, true, false, true, false, true, false, true, false, true));\r
- portBuilder.setAdvertisedFeatures(new PortFeatures(true, false, true, false, true,\r
- false, true, false, true, false, true, false, true, false, true, false));\r
- portBuilder.setSupportedFeatures(new PortFeatures(false, false, false, false, false,\r
- false, false, false, false, false, false, false, false, false, false, false));\r
- portBuilder.setPeerFeatures(new PortFeatures(true, true, true, true, true,\r
- true, true, true, true, true, true, true, true, true, true, true));\r
- portBuilder.setCurrSpeed(12L);\r
- portBuilder.setMaxSpeed(13L);\r
- ports.add(portBuilder.build());\r
- portBuilder = new PortsBuilder();\r
- portBuilder.setPortNo(50L);\r
- portBuilder.setHwAddr(new MacAddress("05:06:07:08:09:0A"));\r
- portBuilder.setName("MultipartPortDesc port");\r
- portBuilder.setConfig(new PortConfig(false, true, false, true));\r
- portBuilder.setState(new PortState(false, true, false));\r
- portBuilder.setCurrentFeatures(null);\r
- portBuilder.setAdvertisedFeatures(null);\r
- portBuilder.setSupportedFeatures(null);\r
- portBuilder.setPeerFeatures(null);\r
- portBuilder.setCurrSpeed(120L);\r
- portBuilder.setMaxSpeed(130L);\r
- ports.add(portBuilder.build());\r
- descBuilder.setPorts(ports);\r
- caseBuilder.setMultipartReplyPortDesc(descBuilder.build());\r
- builder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = builder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
- Assert.assertEquals("Wrong output", 2, list.size());\r
- NodeConnectorUpdated nodeUpdated = (NodeConnectorUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42:5", nodeUpdated.getId().getValue());\r
- FlowCapableNodeConnectorUpdated flowCapable = nodeUpdated.getAugmentation(FlowCapableNodeConnectorUpdated.class);\r
- Assert.assertEquals("Wrong port number", 5, flowCapable.getPortNumber().getUint32().intValue());\r
- Assert.assertEquals("Wrong hardware address", new MacAddress("06:07:08:09:0A:0B"), flowCapable.getHardwareAddress());\r
- Assert.assertEquals("Wrong name", "MultipartPortDesc port", flowCapable.getName());\r
- Assert.assertEquals("Wrong config", true, flowCapable.getConfiguration().isNOFWD());\r
- Assert.assertEquals("Wrong config", false, flowCapable.getConfiguration().isNOPACKETIN());\r
- Assert.assertEquals("Wrong config", true, flowCapable.getConfiguration().isNORECV());\r
- Assert.assertEquals("Wrong config", false, flowCapable.getConfiguration().isPORTDOWN());\r
- Assert.assertEquals("Wrong state", true, flowCapable.getState().isBlocked());\r
- Assert.assertEquals("Wrong state", false, flowCapable.getState().isLinkDown());\r
- Assert.assertEquals("Wrong state", true, flowCapable.getState().isLive());\r
- Assert.assertEquals("Wrong current features", new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port\r
- .rev130925.PortFeatures(false, true, false, true, false, true, false, false, true, false, true, false,\r
- true, true, false, true), flowCapable.getCurrentFeature());\r
- Assert.assertEquals("Wrong advertised features", new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port\r
- .rev130925.PortFeatures(true, false, true, false, true, false, true, true, false, true, false, true,\r
- false, false, true, false), flowCapable.getAdvertisedFeatures());\r
- Assert.assertEquals("Wrong supported features", new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port\r
- .rev130925.PortFeatures(false, false, false, false, false, false, false, false, false, false, false, false,\r
- false, false, false, false), flowCapable.getSupported());\r
- Assert.assertEquals("Wrong peer features", new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port\r
- .rev130925.PortFeatures(true, true, true, true, true, true, true, true, true, true, true, true,\r
- true, true, true, true), flowCapable.getPeerFeatures());\r
- Assert.assertEquals("Wrong current speed", 12, flowCapable.getCurrentSpeed().intValue());\r
- Assert.assertEquals("Wrong max speed", 13, flowCapable.getMaximumSpeed().intValue());\r
- nodeUpdated = (NodeConnectorUpdated) list.get(1);\r
- Assert.assertEquals("Wrong node-id", "openflow:42:50", nodeUpdated.getId().getValue());\r
- flowCapable = nodeUpdated.getAugmentation(FlowCapableNodeConnectorUpdated.class);\r
- Assert.assertEquals("Wrong port number", 50, flowCapable.getPortNumber().getUint32().intValue());\r
- Assert.assertEquals("Wrong hardware address", new MacAddress("05:06:07:08:09:0A"), flowCapable.getHardwareAddress());\r
- Assert.assertEquals("Wrong name", "MultipartPortDesc port", flowCapable.getName());\r
- Assert.assertEquals("Wrong config", false, flowCapable.getConfiguration().isNOFWD());\r
- Assert.assertEquals("Wrong config", true, flowCapable.getConfiguration().isNOPACKETIN());\r
- Assert.assertEquals("Wrong config", false, flowCapable.getConfiguration().isNORECV());\r
- Assert.assertEquals("Wrong config", true, flowCapable.getConfiguration().isPORTDOWN());\r
- Assert.assertEquals("Wrong state", false, flowCapable.getState().isBlocked());\r
- Assert.assertEquals("Wrong state", true, flowCapable.getState().isLinkDown());\r
- Assert.assertEquals("Wrong state", false, flowCapable.getState().isLive());\r
- Assert.assertEquals("Wrong current features", null, flowCapable.getCurrentFeature());\r
- Assert.assertEquals("Wrong advertised features", null, flowCapable.getAdvertisedFeatures());\r
- Assert.assertEquals("Wrong supported features", null, flowCapable.getSupported());\r
- Assert.assertEquals("Wrong peer features", null, flowCapable.getPeerFeatures());\r
- Assert.assertEquals("Wrong current speed", 120, flowCapable.getCurrentSpeed().intValue());\r
- Assert.assertEquals("Wrong max speed", 130, flowCapable.getMaximumSpeed().intValue());\r
- }\r
-}\r
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.translator;\r
-\r
-import static org.mockito.Mockito.when;\r
-\r
-import java.math.BigInteger;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mock;\r
-import org.mockito.runners.MockitoJUnitRunner;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.OFConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.augments.rev150225.NextTableRelatedTableFeatureProperty;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.augments.rev150225.NextTableRelatedTableFeaturePropertyBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.augments.rev150225.table.features.properties.container.table.feature.properties.NextTableIds;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.augments.rev150225.table.features.properties.container.table.feature.properties.NextTableIdsBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.TableConfig;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.TableFeaturesPropType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableFeaturesCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeaturesBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.multipart.reply.table.features.TableFeatures;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.multipart.reply.table.features.TableFeaturesBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.table.features.properties.grouping.TableFeatureProperties;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.table.features.properties.grouping.TableFeaturePropertiesBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.TableUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.NextTable;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-\r
-/**\r
- * @author michal.polkorab\r
- *\r
- */\r
-@RunWith(MockitoJUnitRunner.class)\r
-public class MultipartReplyTableFeaturesToTableUpdatedTranslatorTest {\r
-\r
- @Mock SwitchConnectionDistinguisher cookie;\r
- @Mock SessionContext sc;\r
- @Mock GetFeaturesOutput features;\r
- @Mock ConnectionConductor conductor;\r
-\r
- MultipartReplyTableFeaturesToTableUpdatedTranslator translator;\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();\r
- translator = new MultipartReplyTableFeaturesToTableUpdatedTranslator(convertorManager);\r
- when(sc.getPrimaryConductor()).thenReturn(conductor);\r
- when(sc.getFeatures()).thenReturn(features);\r
- when(conductor.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);\r
- when(features.getDatapathId()).thenReturn(new BigInteger("42"));\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTableFeaturesToTableUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with wrong inputs\r
- */\r
- @Test\r
- public void testWrongInputs() {\r
- HelloMessageBuilder helloBuilder = new HelloMessageBuilder();\r
- HelloMessage helloMessage = helloBuilder.build();\r
- List<DataObject> list = translator.translate(cookie, sc, helloMessage);\r
- Assert.assertEquals("Wrong output", 0, list.size());\r
- \r
- MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder();\r
- builder.setType(MultipartType.OFPMPFLOW);\r
- MultipartReplyMessage message = builder.build();\r
- list = translator.translate(cookie, sc, message);\r
- Assert.assertEquals("Wrong output", 0, list.size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTableFeaturesToTableUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with correct inputs (no table features)\r
- */\r
- @Test\r
- public void testEmptyTableFeaturesWithCorrectInput() {\r
- MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder();\r
- builder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- builder.setXid(12345L);\r
- builder.setType(MultipartType.OFPMPTABLEFEATURES);\r
- builder.setFlags(new MultipartRequestFlags(false));\r
- \r
- MultipartReplyTableFeaturesCaseBuilder caseBuilder = new MultipartReplyTableFeaturesCaseBuilder();\r
- MultipartReplyTableFeaturesBuilder featuresBuilder = new MultipartReplyTableFeaturesBuilder();\r
- List<TableFeatures> features = new ArrayList<>();\r
- featuresBuilder.setTableFeatures(features);\r
- caseBuilder.setMultipartReplyTableFeatures(featuresBuilder.build());\r
- builder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = builder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
- Assert.assertEquals("Wrong output", 1, list.size());\r
- TableUpdated tableUpdated = (TableUpdated) list.get(0);\r
- Assert.assertEquals("Wrong table features size", 0, tableUpdated.getTableFeatures().size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTableFeaturesToTableUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with correct inputs\r
- */\r
- @Test\r
- public void testTableFeaturesWithCorrectInput() {\r
- MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder();\r
- builder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- builder.setXid(12345L);\r
- builder.setType(MultipartType.OFPMPTABLEFEATURES);\r
- builder.setFlags(new MultipartRequestFlags(false));\r
- \r
- MultipartReplyTableFeaturesCaseBuilder caseBuilder = new MultipartReplyTableFeaturesCaseBuilder();\r
- MultipartReplyTableFeaturesBuilder featuresBuilder = new MultipartReplyTableFeaturesBuilder();\r
- List<TableFeatures> features = new ArrayList<>();\r
- \r
- TableFeaturesBuilder tableFeatBuilder = new TableFeaturesBuilder();\r
- tableFeatBuilder.setTableId((short) 2);\r
- tableFeatBuilder.setName("Fastest table in the world");\r
- byte[] metadataMatch = new byte[]{0, 1, 2, 3, 4, 5, 6, 7};\r
- tableFeatBuilder.setMetadataMatch(metadataMatch);\r
- byte[] metadataWrite = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};\r
- tableFeatBuilder.setMetadataWrite(metadataWrite);\r
- tableFeatBuilder.setConfig(new TableConfig(false));\r
- tableFeatBuilder.setMaxEntries(10L);\r
- List<TableFeatureProperties> properties = new ArrayList<>();\r
- TableFeaturePropertiesBuilder propBuilder = new TableFeaturePropertiesBuilder();\r
- propBuilder.setType(TableFeaturesPropType.OFPTFPTNEXTTABLES);\r
- NextTableRelatedTableFeaturePropertyBuilder tableBuilder = new NextTableRelatedTableFeaturePropertyBuilder();\r
- List<NextTableIds> tableIds = new ArrayList<>();\r
- NextTableIdsBuilder nextTableIdsBuilder = new NextTableIdsBuilder();\r
- nextTableIdsBuilder.setTableId((short) 9);\r
- tableIds.add(nextTableIdsBuilder.build());\r
- nextTableIdsBuilder = new NextTableIdsBuilder();\r
- nextTableIdsBuilder.setTableId((short) 10);\r
- tableIds.add(nextTableIdsBuilder.build());\r
- nextTableIdsBuilder = new NextTableIdsBuilder();\r
- nextTableIdsBuilder.setTableId((short) 11);\r
- tableIds.add(nextTableIdsBuilder.build());\r
- tableBuilder.setNextTableIds(tableIds);\r
- propBuilder.addAugmentation(NextTableRelatedTableFeatureProperty.class, tableBuilder.build());\r
- properties.add(propBuilder.build());\r
- tableFeatBuilder.setTableFeatureProperties(properties);\r
- features.add(tableFeatBuilder.build());\r
- featuresBuilder.setTableFeatures(features);\r
- caseBuilder.setMultipartReplyTableFeatures(featuresBuilder.build());\r
- builder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = builder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
- Assert.assertEquals("Wrong output", 1, list.size());\r
- TableUpdated tableUpdated = (TableUpdated) list.get(0);\r
- Assert.assertEquals("Wrong table features size", 1, tableUpdated.getTableFeatures().size());\r
- org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features\r
- .TableFeatures feature = tableUpdated.getTableFeatures().get(0);\r
- Assert.assertEquals("Wrong table-id", 2, feature.getTableId().intValue());\r
- Assert.assertEquals("Wrong table name", "Fastest table in the world", feature.getName());\r
- Assert.assertEquals("Wrong metadata match", new BigInteger(metadataMatch), feature.getMetadataMatch());\r
- Assert.assertEquals("Wrong metadata write", new BigInteger(metadataWrite), feature.getMetadataWrite());\r
- Assert.assertEquals("Wrong config", false, feature.getConfig().isDEPRECATEDMASK());\r
- Assert.assertEquals("Wrong max entries", 10, feature.getMaxEntries().intValue());\r
- Assert.assertEquals("Wrong properties size", 1, feature.getTableProperties().getTableFeatureProperties().size());\r
- org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.table.features.table.properties\r
- .TableFeatureProperties property = feature.getTableProperties().getTableFeatureProperties().get(0);\r
- Assert.assertEquals("Wrong property type", "org.opendaylight.yang.gen.v1.urn.opendaylight.table.types"\r
- + ".rev131026.table.feature.prop.type.table.feature.prop.type.NextTable",\r
- property.getTableFeaturePropType().getImplementedInterface().getName());\r
- NextTable nextTableProperty = (NextTable) property.getTableFeaturePropType();\r
- Assert.assertEquals("Wrong next tables size", 3, nextTableProperty.getTables().getTableIds().size());\r
- Assert.assertEquals("Wrong next tables size", 9, nextTableProperty.getTables().getTableIds().get(0).intValue());\r
- Assert.assertEquals("Wrong next tables size", 10, nextTableProperty.getTables().getTableIds().get(1).intValue());\r
- Assert.assertEquals("Wrong next tables size", 11, nextTableProperty.getTables().getTableIds().get(2).intValue());\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.translator;\r
-\r
-import static org.mockito.Mockito.when;\r
-\r
-import java.math.BigInteger;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mock;\r
-import org.mockito.MockitoAnnotations;\r
-import org.mockito.runners.MockitoJUnitRunner;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterConfigStatsUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterStatisticsUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.config.stats.reply.MeterConfigStats;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.meter.band.headers.MeterBandHeader;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterBandType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterId;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.meter.band.header.meter.band.MeterBandDropCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.meter.band.header.meter.band.MeterBandDscpRemarkCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.meter.band.header.meter.band.meter.band.drop._case.MeterBandDropBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.meter.band.header.meter.band.meter.band.dscp.remark._case.MeterBandDscpRemarkBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterConfigCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.MultipartReplyMeterBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.multipart.reply.meter.MeterStats;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.multipart.reply.meter.MeterStatsBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.multipart.reply.meter.meter.stats.MeterBandStats;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.multipart.reply.meter.meter.stats.MeterBandStatsBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.MultipartReplyMeterConfigBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.multipart.reply.meter.config.MeterConfig;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.multipart.reply.meter.config.MeterConfigBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.multipart.reply.meter.config.meter.config.Bands;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.multipart.reply.meter.config.meter.config.BandsBuilder;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-\r
-/**\r
- * @author michal.polkorab\r
- */\r
-@RunWith(MockitoJUnitRunner.class)\r
-public class MultipartReplyTranslatorFifthTest {\r
-\r
- @Mock\r
- SwitchConnectionDistinguisher cookie;\r
- @Mock\r
- SessionContext sc;\r
- @Mock\r
- ConnectionConductor conductor;\r
- @Mock\r
- GetFeaturesOutput features;\r
-\r
- MultipartReplyTranslator translator;\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();\r
- translator = new MultipartReplyTranslator(convertorManager);\r
- MockitoAnnotations.initMocks(this);\r
- when(sc.getPrimaryConductor()).thenReturn(conductor);\r
- when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);\r
- when(sc.getFeatures()).thenReturn(features);\r
- when(features.getDatapathId()).thenReturn(new BigInteger("42"));\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with empty meter stats\r
- */\r
- @Test\r
- public void testEmptyMeterStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPMETER);\r
-\r
- MultipartReplyMeterCaseBuilder caseBuilder = new MultipartReplyMeterCaseBuilder();\r
- MultipartReplyMeterBuilder meterBuilder = new MultipartReplyMeterBuilder();\r
- List<MeterStats> meterStats = new ArrayList<>();\r
- meterBuilder.setMeterStats(meterStats);\r
- caseBuilder.setMultipartReplyMeter(meterBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- MeterStatisticsUpdated statUpdate = (MeterStatisticsUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong meter stats size", 0, statUpdate.getMeterStats().size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with meter stats\r
- */\r
- @Test\r
- public void testMeterStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPMETER);\r
-\r
- MultipartReplyMeterCaseBuilder caseBuilder = new MultipartReplyMeterCaseBuilder();\r
- MultipartReplyMeterBuilder meterBuilder = new MultipartReplyMeterBuilder();\r
- List<MeterStats> meterStats = new ArrayList<>();\r
- MeterStatsBuilder builder = new MeterStatsBuilder();\r
- builder.setMeterId(new MeterId(15L));\r
- builder.setFlowCount(16L);\r
- builder.setPacketInCount(new BigInteger("17"));\r
- builder.setByteInCount(new BigInteger("18"));\r
- builder.setDurationSec(19L);\r
- builder.setDurationNsec(20L);\r
- List<MeterBandStats> meterBands = new ArrayList<>();\r
- MeterBandStatsBuilder meterStatsBuilder = new MeterBandStatsBuilder();\r
- meterStatsBuilder.setPacketBandCount(new BigInteger("21"));\r
- meterStatsBuilder.setByteBandCount(new BigInteger("22"));\r
- meterBands.add(meterStatsBuilder.build());\r
- meterStatsBuilder = new MeterBandStatsBuilder();\r
- meterStatsBuilder.setPacketBandCount(new BigInteger("23"));\r
- meterStatsBuilder.setByteBandCount(new BigInteger("24"));\r
- meterBands.add(meterStatsBuilder.build());\r
- builder.setMeterBandStats(meterBands);\r
- meterStats.add(builder.build());\r
- builder = new MeterStatsBuilder();\r
- builder.setMeterId(new MeterId(150L));\r
- builder.setFlowCount(160L);\r
- builder.setPacketInCount(new BigInteger("170"));\r
- builder.setByteInCount(new BigInteger("180"));\r
- builder.setDurationSec(190L);\r
- builder.setDurationNsec(200L);\r
- meterBands = new ArrayList<>();\r
- builder.setMeterBandStats(meterBands);\r
- meterStats.add(builder.build());\r
- meterBuilder.setMeterStats(meterStats);\r
- caseBuilder.setMultipartReplyMeter(meterBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- MeterStatisticsUpdated statUpdate = (MeterStatisticsUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong group stats size", 2, statUpdate.getMeterStats().size());\r
- org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply\r
- .MeterStats stat = statUpdate.getMeterStats().get(0);\r
- Assert.assertEquals("Wrong meter-id", 15, stat.getMeterId().getValue().intValue());\r
- Assert.assertEquals("Wrong flow count", 16, stat.getFlowCount().getValue().intValue());\r
- Assert.assertEquals("Wrong packet in count", 17, stat.getPacketInCount().getValue().intValue());\r
- Assert.assertEquals("Wrong byte in count", 18, stat.getByteInCount().getValue().intValue());\r
- Assert.assertEquals("Wrong duration sec", 19, stat.getDuration().getSecond().getValue().intValue());\r
- Assert.assertEquals("Wrong duration n sec", 20, stat.getDuration().getNanosecond().getValue().intValue());\r
- Assert.assertEquals("Wrong meter band stats size", 2, stat.getMeterBandStats().getBandStat().size());\r
- Assert.assertEquals("Wrong band id", 0, stat.getMeterBandStats().getBandStat().get(0)\r
- .getBandId().getValue().intValue());\r
- Assert.assertEquals("Wrong packet band count", 21, stat.getMeterBandStats().getBandStat().get(0)\r
- .getPacketBandCount().getValue().intValue());\r
- Assert.assertEquals("Wrong byte band count", 22, stat.getMeterBandStats().getBandStat().get(0)\r
- .getByteBandCount().getValue().intValue());\r
- Assert.assertEquals("Wrong band id", 1, stat.getMeterBandStats().getBandStat().get(1)\r
- .getBandId().getValue().intValue());\r
- Assert.assertEquals("Wrong packet band count", 23, stat.getMeterBandStats().getBandStat().get(1)\r
- .getPacketBandCount().getValue().intValue());\r
- Assert.assertEquals("Wrong byte band count", 24, stat.getMeterBandStats().getBandStat().get(1)\r
- .getByteBandCount().getValue().intValue());\r
- stat = statUpdate.getMeterStats().get(1);\r
- Assert.assertEquals("Wrong meter-id", 150, stat.getMeterId().getValue().intValue());\r
- Assert.assertEquals("Wrong flow count", 160, stat.getFlowCount().getValue().intValue());\r
- Assert.assertEquals("Wrong packet in count", 170, stat.getPacketInCount().getValue().intValue());\r
- Assert.assertEquals("Wrong byte in count", 180, stat.getByteInCount().getValue().intValue());\r
- Assert.assertEquals("Wrong duration sec", 190, stat.getDuration().getSecond().getValue().intValue());\r
- Assert.assertEquals("Wrong duration n sec", 200, stat.getDuration().getNanosecond().getValue().intValue());\r
- Assert.assertEquals("Wrong meter band stats size", 0, stat.getMeterBandStats().getBandStat().size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with empty meter config stats\r
- */\r
- @Test\r
- public void testEmptyMeterConfigStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPMETERCONFIG);\r
-\r
- MultipartReplyMeterConfigCaseBuilder caseBuilder = new MultipartReplyMeterConfigCaseBuilder();\r
- MultipartReplyMeterConfigBuilder meterBuilder = new MultipartReplyMeterConfigBuilder();\r
- List<MeterConfig> meterStats = new ArrayList<>();\r
- meterBuilder.setMeterConfig(meterStats);\r
- caseBuilder.setMultipartReplyMeterConfig(meterBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- MeterConfigStatsUpdated statUpdate = (MeterConfigStatsUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong meter config stats size", 0, statUpdate.getMeterConfigStats().size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with meter config stats\r
- */\r
- @Test\r
- public void testMeterConfigStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPMETERCONFIG);\r
-\r
- MultipartReplyMeterConfigCaseBuilder caseBuilder = new MultipartReplyMeterConfigCaseBuilder();\r
- MultipartReplyMeterConfigBuilder meterBuilder = new MultipartReplyMeterConfigBuilder();\r
- List<MeterConfig> meterStats = new ArrayList<>();\r
- MeterConfigBuilder builder = new MeterConfigBuilder();\r
- builder.setFlags(new MeterFlags(false, true, false, true));\r
- builder.setMeterId(new MeterId(20L));\r
- List<Bands> bands = new ArrayList<>();\r
- BandsBuilder bandBuilder = new BandsBuilder();\r
- MeterBandDropCaseBuilder dropCaseBuilder = new MeterBandDropCaseBuilder();\r
- MeterBandDropBuilder dropBuilder = new MeterBandDropBuilder();\r
- dropBuilder.setType(MeterBandType.OFPMBTDROP);\r
- dropBuilder.setRate(21L);\r
- dropBuilder.setBurstSize(22L);\r
- dropCaseBuilder.setMeterBandDrop(dropBuilder.build());\r
- bandBuilder.setMeterBand(dropCaseBuilder.build());\r
- bands.add(bandBuilder.build());\r
- bandBuilder = new BandsBuilder();\r
- MeterBandDscpRemarkCaseBuilder dscpCaseBuilder = new MeterBandDscpRemarkCaseBuilder();\r
- MeterBandDscpRemarkBuilder dscpBuilder = new MeterBandDscpRemarkBuilder();\r
- dscpBuilder.setType(MeterBandType.OFPMBTDSCPREMARK);\r
- dscpBuilder.setRate(23L);\r
- dscpBuilder.setBurstSize(24L);\r
- dscpBuilder.setPrecLevel((short) 25);\r
- dscpCaseBuilder.setMeterBandDscpRemark(dscpBuilder.build());\r
- bandBuilder.setMeterBand(dscpCaseBuilder.build());\r
- bands.add(bandBuilder.build());\r
- builder.setBands(bands);\r
- meterStats.add(builder.build());\r
- builder = new MeterConfigBuilder();\r
- builder.setFlags(new MeterFlags(true, false, true, false));\r
- builder.setMeterId(new MeterId(26L));\r
- bands = new ArrayList<>();\r
- builder.setBands(bands);\r
- meterStats.add(builder.build());\r
- meterBuilder.setMeterConfig(meterStats);\r
- caseBuilder.setMultipartReplyMeterConfig(meterBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- MeterConfigStatsUpdated statUpdate = (MeterConfigStatsUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong meter config stats size", 2, statUpdate.getMeterConfigStats().size());\r
- MeterConfigStats stat = statUpdate.getMeterConfigStats().get(0);\r
- Assert.assertEquals("Wrong flag", false, stat.getFlags().isMeterBurst());\r
- Assert.assertEquals("Wrong flag", false, stat.getFlags().isMeterPktps());\r
- Assert.assertEquals("Wrong flag", true, stat.getFlags().isMeterKbps());\r
- Assert.assertEquals("Wrong flag", true, stat.getFlags().isMeterStats());\r
- Assert.assertEquals("Wrong meter-id", 20, stat.getMeterId().getValue().intValue());\r
- Assert.assertEquals("Wrong bands size", 2, stat.getMeterBandHeaders().getMeterBandHeader().size());\r
- MeterBandHeader header = stat.getMeterBandHeaders().getMeterBandHeader().get(0);\r
- Assert.assertEquals("Wrong band type", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter"\r
- + ".types.rev130918.band.type.band.type.Drop", header.getBandType().getImplementedInterface().getName());\r
- Assert.assertEquals("Wrong band rate", 21, header.getBandRate().intValue());\r
- Assert.assertEquals("Wrong band burst size", 22, header.getBandBurstSize().intValue());\r
- Assert.assertEquals("Wrong flag", true, header.getMeterBandTypes().getFlags().isOfpmbtDrop());\r
- Assert.assertEquals("Wrong flag", false, header.getMeterBandTypes().getFlags().isOfpmbtDscpRemark());\r
- Assert.assertEquals("Wrong flag", false, header.getMeterBandTypes().getFlags().isOfpmbtExperimenter());\r
- header = stat.getMeterBandHeaders().getMeterBandHeader().get(1);\r
- Assert.assertEquals("Wrong band type", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter"\r
- + ".types.rev130918.band.type.band.type.DscpRemark", header.getBandType().getImplementedInterface().getName());\r
- Assert.assertEquals("Wrong band rate", 23, header.getBandRate().intValue());\r
- Assert.assertEquals("Wrong band burst size", 24, header.getBandBurstSize().intValue());\r
- Assert.assertEquals("Wrong flag", false, header.getMeterBandTypes().getFlags().isOfpmbtDrop());\r
- Assert.assertEquals("Wrong flag", true, header.getMeterBandTypes().getFlags().isOfpmbtDscpRemark());\r
- Assert.assertEquals("Wrong flag", false, header.getMeterBandTypes().getFlags().isOfpmbtExperimenter());\r
- stat = statUpdate.getMeterConfigStats().get(1);\r
- Assert.assertEquals("Wrong flag", true, stat.getFlags().isMeterBurst());\r
- Assert.assertEquals("Wrong flag", true, stat.getFlags().isMeterPktps());\r
- Assert.assertEquals("Wrong flag", false, stat.getFlags().isMeterKbps());\r
- Assert.assertEquals("Wrong flag", false, stat.getFlags().isMeterStats());\r
- Assert.assertEquals("Wrong meter-id", 26, stat.getMeterId().getValue().intValue());\r
- Assert.assertEquals("Wrong bands size", 0, stat.getMeterBandHeaders().getMeterBandHeader().size());\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.translator;\r
-\r
-import static org.mockito.Mockito.when;\r
-\r
-import java.math.BigInteger;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mock;\r
-import org.mockito.runners.MockitoJUnitRunner;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdate;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.and.statistics.map.list.FlowAndStatisticsMapList;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.instruction.rev130731.instructions.grouping.Instruction;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.FlowModFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.OxmMatchType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyFlowCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.MultipartReplyFlowBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.multipart.reply.flow.FlowStats;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.multipart.reply.flow.FlowStatsBuilder;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-\r
-/**\r
- * @author michal.polkorab\r
- *\r
- */\r
-@RunWith(MockitoJUnitRunner.class)\r
-public class MultipartReplyTranslatorFirstTest {\r
-\r
- @Mock SwitchConnectionDistinguisher cookie;\r
- @Mock SessionContext sc;\r
- @Mock ConnectionConductor conductor;\r
- @Mock GetFeaturesOutput features;\r
-\r
- MultipartReplyTranslator translator;\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();\r
- translator = new MultipartReplyTranslator(convertorManager);\r
- when(sc.getPrimaryConductor()).thenReturn(conductor);\r
- when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);\r
- when(sc.getFeatures()).thenReturn(features);\r
- when(features.getDatapathId()).thenReturn(new BigInteger("42"));\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with null and incorrect message\r
- */\r
- @Test\r
- public void test() {\r
- List<DataObject> list = translator.translate(cookie, sc, null);\r
-\r
- Assert.assertEquals("Wrong list size", 0, list.size());\r
- HelloMessageBuilder helloBuilder = new HelloMessageBuilder();\r
- list = translator.translate(cookie, sc, helloBuilder.build());\r
- Assert.assertEquals("Wrong list size", 0, list.size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with experimenter MultipartReply message\r
- */\r
- @Test\r
- public void testExperimenterCase() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPEXPERIMENTER);\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 0, list.size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with empty flow stats\r
- */\r
- @Test\r
- public void testEmptyFlowCase() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPFLOW);\r
- \r
- MultipartReplyFlowCaseBuilder caseBuilder = new MultipartReplyFlowCaseBuilder();\r
- MultipartReplyFlowBuilder flowBuilder = new MultipartReplyFlowBuilder();\r
- List<FlowStats> flowStats = new ArrayList<>();\r
- flowBuilder.setFlowStats(flowStats);\r
- caseBuilder.setMultipartReplyFlow(flowBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- FlowsStatisticsUpdate flowUpdate = (FlowsStatisticsUpdate) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", flowUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, flowUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, flowUpdate.getTransactionId().getValue().intValue());\r
- List<FlowAndStatisticsMapList> mapList = flowUpdate.getFlowAndStatisticsMapList();\r
- Assert.assertEquals("Wrong flow stats size", 0, mapList.size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with experimenter MultipartReply message\r
- */\r
- @Test\r
- public void testFlowCase() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPFLOW);\r
- \r
- MultipartReplyFlowCaseBuilder caseBuilder = new MultipartReplyFlowCaseBuilder();\r
- MultipartReplyFlowBuilder flowBuilder = new MultipartReplyFlowBuilder();\r
- List<FlowStats> flowStats = new ArrayList<>();\r
- FlowStatsBuilder statsBuilder = new FlowStatsBuilder();\r
- statsBuilder.setTableId((short) 1);\r
- statsBuilder.setDurationSec(2L);\r
- statsBuilder.setDurationNsec(3L);\r
- statsBuilder.setPriority(4);\r
- statsBuilder.setIdleTimeout(5);\r
- statsBuilder.setHardTimeout(6);\r
- FlowModFlags flags = new FlowModFlags(true, false, true, false, true);\r
- statsBuilder.setFlags(flags);\r
- statsBuilder.setCookie(new BigInteger("7"));\r
- statsBuilder.setPacketCount(new BigInteger("8"));\r
- statsBuilder.setByteCount(new BigInteger("9"));\r
- MatchBuilder matchBuilder = new MatchBuilder();\r
- matchBuilder.setType(OxmMatchType.class);\r
- matchBuilder.setMatchEntry(new ArrayList<MatchEntry>());\r
- statsBuilder.setMatch(matchBuilder.build());\r
- statsBuilder.setInstruction(new ArrayList<Instruction>());\r
- flowStats.add(statsBuilder.build());\r
- statsBuilder = new FlowStatsBuilder();\r
- statsBuilder.setTableId((short) 10);\r
- statsBuilder.setDurationSec(20L);\r
- statsBuilder.setDurationNsec(30L);\r
- statsBuilder.setPriority(40);\r
- statsBuilder.setIdleTimeout(50);\r
- statsBuilder.setHardTimeout(60);\r
- flags = new FlowModFlags(false, true, false, true, false);\r
- statsBuilder.setFlags(flags);\r
- statsBuilder.setCookie(new BigInteger("70"));\r
- statsBuilder.setPacketCount(new BigInteger("80"));\r
- statsBuilder.setByteCount(new BigInteger("90"));\r
- matchBuilder = new MatchBuilder();\r
- matchBuilder.setType(OxmMatchType.class);\r
- matchBuilder.setMatchEntry(new ArrayList<MatchEntry>());\r
- statsBuilder.setMatch(matchBuilder.build());\r
- statsBuilder.setInstruction(new ArrayList<Instruction>());\r
- flowStats.add(statsBuilder.build());\r
- flowBuilder.setFlowStats(flowStats);\r
- caseBuilder.setMultipartReplyFlow(flowBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- FlowsStatisticsUpdate flowUpdate = (FlowsStatisticsUpdate) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", flowUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, flowUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, flowUpdate.getTransactionId().getValue().intValue());\r
- List<FlowAndStatisticsMapList> mapList = flowUpdate.getFlowAndStatisticsMapList();\r
- Assert.assertEquals("Wrong flow stats size", 2, mapList.size());\r
- FlowAndStatisticsMapList stat = mapList.get(0);\r
- Assert.assertEquals("Wrong table-id", 1, stat.getTableId().intValue());\r
- Assert.assertEquals("Wrong duration sec", 2, stat.getDuration().getSecond().getValue().intValue());\r
- Assert.assertEquals("Wrong duration n sec", 3, stat.getDuration().getNanosecond().getValue().intValue());\r
- Assert.assertEquals("Wrong priority", 4, stat.getPriority().intValue());\r
- Assert.assertEquals("Wrong idle-timeout", 5, stat.getIdleTimeout().intValue());\r
- Assert.assertEquals("Wrong hard-timeout", 6, stat.getHardTimeout().intValue());\r
- org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowModFlags expectedFlags = \r
- new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026\r
- .FlowModFlags(!flags.isOFPFFCHECKOVERLAP(), !flags.isOFPFFNOBYTCOUNTS(), !flags.isOFPFFNOPKTCOUNTS(),\r
- !flags.isOFPFFRESETCOUNTS(), !flags.isOFPFFSENDFLOWREM());\r
- Assert.assertEquals("Wrong flags", expectedFlags, stat.getFlags());\r
- Assert.assertEquals("Wrong cookie", 7, stat.getCookie().getValue().intValue());\r
- Assert.assertEquals("Wrong packet count", 8, stat.getPacketCount().getValue().intValue());\r
- Assert.assertEquals("Wrong byte count", 9, stat.getByteCount().getValue().intValue());\r
- org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder emptyMatchBuilder = \r
- new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder();\r
- Match emptyMatch = emptyMatchBuilder.build();\r
- Assert.assertEquals("Wrong match", emptyMatch, stat.getMatch());\r
- Assert.assertEquals("Wrong instructions", 0, stat.getInstructions().getInstruction().size());\r
- stat = mapList.get(1);\r
- Assert.assertEquals("Wrong table-id", 10, stat.getTableId().intValue());\r
- Assert.assertEquals("Wrong duration sec", 20, stat.getDuration().getSecond().getValue().intValue());\r
- Assert.assertEquals("Wrong duration n sec", 30, stat.getDuration().getNanosecond().getValue().intValue());\r
- Assert.assertEquals("Wrong priority", 40, stat.getPriority().intValue());\r
- Assert.assertEquals("Wrong idle-timeout", 50, stat.getIdleTimeout().intValue());\r
- Assert.assertEquals("Wrong hard-timeout", 60, stat.getHardTimeout().intValue());\r
- expectedFlags = new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026\r
- .FlowModFlags(flags.isOFPFFCHECKOVERLAP(), flags.isOFPFFNOBYTCOUNTS(), flags.isOFPFFNOPKTCOUNTS(),\r
- flags.isOFPFFRESETCOUNTS(), flags.isOFPFFSENDFLOWREM());\r
- Assert.assertEquals("Wrong flags", expectedFlags, stat.getFlags());\r
- Assert.assertEquals("Wrong cookie", 70, stat.getCookie().getValue().intValue());\r
- Assert.assertEquals("Wrong packet count", 80, stat.getPacketCount().getValue().intValue());\r
- Assert.assertEquals("Wrong byte count", 90, stat.getByteCount().getValue().intValue());\r
- Assert.assertEquals("Wrong match", emptyMatch, stat.getMatch());\r
- Assert.assertEquals("Wrong instructions", 0, stat.getInstructions().getInstruction().size());\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.translator;\r
-\r
-import static org.mockito.Mockito.when;\r
-\r
-import java.math.BigInteger;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mock;\r
-import org.mockito.runners.MockitoJUnitRunner;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupDescStatsUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupStatisticsUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.desc.stats.reply.GroupDescStats;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.action.rev150203.action.grouping.action.choice.DecMplsTtlCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.action.rev150203.action.grouping.action.choice.PopPbbCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.action.rev150203.actions.grouping.Action;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.action.rev150203.actions.grouping.ActionBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.GroupId;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.GroupType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortNumber;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.buckets.grouping.BucketsList;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.buckets.grouping.BucketsListBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupDescCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.MultipartReplyGroupBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.multipart.reply.group.GroupStats;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.multipart.reply.group.GroupStatsBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.multipart.reply.group.group.stats.BucketStats;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.multipart.reply.group.group.stats.BucketStatsBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.desc._case.MultipartReplyGroupDescBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.desc._case.multipart.reply.group.desc.GroupDesc;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.desc._case.multipart.reply.group.desc.GroupDescBuilder;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-\r
-/**\r
- * @author michal.polkorab\r
- *\r
- */\r
-@RunWith(MockitoJUnitRunner.class)\r
-public class MultipartReplyTranslatorFourthTest {\r
-\r
- @Mock SwitchConnectionDistinguisher cookie;\r
- @Mock SessionContext sc;\r
- @Mock ConnectionConductor conductor;\r
- @Mock GetFeaturesOutput features;\r
-\r
- MultipartReplyTranslator translator;\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();\r
- translator = new MultipartReplyTranslator(convertorManager);\r
- when(sc.getPrimaryConductor()).thenReturn(conductor);\r
- when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);\r
- when(sc.getFeatures()).thenReturn(features);\r
- when(features.getDatapathId()).thenReturn(new BigInteger("42"));\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with empty group stats\r
- */\r
- @Test\r
- public void testEmptyGroupStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPGROUP);\r
-\r
- MultipartReplyGroupCaseBuilder caseBuilder = new MultipartReplyGroupCaseBuilder();\r
- MultipartReplyGroupBuilder groupBuilder = new MultipartReplyGroupBuilder();\r
- List<GroupStats> groupStats = new ArrayList<>();\r
- groupBuilder.setGroupStats(groupStats);\r
- caseBuilder.setMultipartReplyGroup(groupBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- GroupStatisticsUpdated statUpdate = (GroupStatisticsUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong group stats size", 0, statUpdate.getGroupStats().size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with group stats\r
- */\r
- @Test\r
- public void testGroupStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPGROUP);\r
-\r
- MultipartReplyGroupCaseBuilder caseBuilder = new MultipartReplyGroupCaseBuilder();\r
- MultipartReplyGroupBuilder groupBuilder = new MultipartReplyGroupBuilder();\r
- List<GroupStats> groupStats = new ArrayList<>();\r
- GroupStatsBuilder builder = new GroupStatsBuilder();\r
- builder.setGroupId(new GroupId(55L));\r
- builder.setRefCount(56L);\r
- builder.setPacketCount(new BigInteger("57"));\r
- builder.setByteCount(new BigInteger("58"));\r
- builder.setDurationSec(59L);\r
- builder.setDurationNsec(60L);\r
- List<BucketStats> bucketStats = new ArrayList<>();\r
- BucketStatsBuilder bucketBuilder = new BucketStatsBuilder();\r
- bucketBuilder.setByteCount(new BigInteger("61"));\r
- bucketBuilder.setPacketCount(new BigInteger("62"));\r
- bucketStats.add(bucketBuilder.build());\r
- bucketBuilder = new BucketStatsBuilder();\r
- bucketBuilder.setByteCount(new BigInteger("63"));\r
- bucketBuilder.setPacketCount(new BigInteger("64"));\r
- bucketStats.add(bucketBuilder.build());\r
- builder.setBucketStats(bucketStats);\r
- groupStats.add(builder.build());\r
- builder = new GroupStatsBuilder();\r
- builder.setGroupId(new GroupId(550L));\r
- builder.setRefCount(560L);\r
- builder.setPacketCount(new BigInteger("570"));\r
- builder.setByteCount(new BigInteger("580"));\r
- builder.setDurationSec(590L);\r
- builder.setDurationNsec(600L);\r
- bucketStats = new ArrayList<>();\r
- builder.setBucketStats(bucketStats);\r
- groupStats.add(builder.build());\r
- groupBuilder.setGroupStats(groupStats);\r
- caseBuilder.setMultipartReplyGroup(groupBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- GroupStatisticsUpdated statUpdate = (GroupStatisticsUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong group stats size", 2, statUpdate.getGroupStats().size());\r
- org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.statistics.reply\r
- .GroupStats stat = statUpdate.getGroupStats().get(0);\r
- Assert.assertEquals("Wrong group-id", 55, stat.getGroupId().getValue().intValue());\r
- Assert.assertEquals("Wrong ref count", 56, stat.getRefCount().getValue().intValue());\r
- Assert.assertEquals("Wrong packet count", 57, stat.getPacketCount().getValue().intValue());\r
- Assert.assertEquals("Wrong byte count", 58, stat.getByteCount().getValue().intValue());\r
- Assert.assertEquals("Wrong duration sec", 59, stat.getDuration().getSecond().getValue().intValue());\r
- Assert.assertEquals("Wrong duration n sec", 60, stat.getDuration().getNanosecond().getValue().intValue());\r
- Assert.assertEquals("Wrong bucket stats size", 2, stat.getBuckets().getBucketCounter().size());\r
- Assert.assertEquals("Wrong bucket-id", 0, stat.getBuckets().getBucketCounter().get(0).getBucketId().getValue().intValue());\r
- Assert.assertEquals("Wrong byte count", 61, stat.getBuckets().getBucketCounter().get(0).getByteCount().getValue().intValue());\r
- Assert.assertEquals("Wrong packet count", 62, stat.getBuckets().getBucketCounter().get(0).getPacketCount().getValue().intValue());\r
- Assert.assertEquals("Wrong bucket-id", 1, stat.getBuckets().getBucketCounter().get(1).getBucketId().getValue().intValue());\r
- Assert.assertEquals("Wrong byte count", 63, stat.getBuckets().getBucketCounter().get(1).getByteCount().getValue().intValue());\r
- Assert.assertEquals("Wrong packet count", 64, stat.getBuckets().getBucketCounter().get(1).getPacketCount().getValue().intValue());\r
- stat = statUpdate.getGroupStats().get(1);\r
- Assert.assertEquals("Wrong group-id", 550, stat.getGroupId().getValue().intValue());\r
- Assert.assertEquals("Wrong ref count", 560, stat.getRefCount().getValue().intValue());\r
- Assert.assertEquals("Wrong packet count", 570, stat.getPacketCount().getValue().intValue());\r
- Assert.assertEquals("Wrong byte count", 580, stat.getByteCount().getValue().intValue());\r
- Assert.assertEquals("Wrong duration sec", 590, stat.getDuration().getSecond().getValue().intValue());\r
- Assert.assertEquals("Wrong duration n sec", 600, stat.getDuration().getNanosecond().getValue().intValue());\r
- Assert.assertEquals("Wrong bucket stats size", 0, stat.getBuckets().getBucketCounter().size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with empty group desc stats\r
- */\r
- @Test\r
- public void testEmptyGroupDescStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPGROUPDESC);\r
-\r
- MultipartReplyGroupDescCaseBuilder caseBuilder = new MultipartReplyGroupDescCaseBuilder();\r
- MultipartReplyGroupDescBuilder groupBuilder = new MultipartReplyGroupDescBuilder();\r
- List<GroupDesc> groupStats = new ArrayList<>();\r
- groupBuilder.setGroupDesc(groupStats);\r
- caseBuilder.setMultipartReplyGroupDesc(groupBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- GroupDescStatsUpdated statUpdate = (GroupDescStatsUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong group stats size", 0, statUpdate.getGroupDescStats().size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with group desc stats\r
- */\r
- @Test\r
- public void testGroupDescStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPGROUPDESC);\r
-\r
- MultipartReplyGroupDescCaseBuilder caseBuilder = new MultipartReplyGroupDescCaseBuilder();\r
- MultipartReplyGroupDescBuilder groupBuilder = new MultipartReplyGroupDescBuilder();\r
- List<GroupDesc> groupStats = new ArrayList<>();\r
-\r
- GroupDescBuilder builder = new GroupDescBuilder();\r
- builder.setType(GroupType.OFPGTALL);\r
- builder.setGroupId(new GroupId(1L));\r
- List<BucketsList> buckets = new ArrayList<>();\r
- BucketsListBuilder bucketBuilder = new BucketsListBuilder();\r
- bucketBuilder.setWeight(28);\r
- bucketBuilder.setWatchPort(new PortNumber(56L));\r
- bucketBuilder.setWatchGroup(112L);\r
-\r
- List<Action> actions = new ArrayList<>();\r
- ActionBuilder actionBuilder = new ActionBuilder();\r
- DecMplsTtlCaseBuilder decMplsTtlCaseBuilder = new DecMplsTtlCaseBuilder();\r
- actionBuilder.setActionChoice(decMplsTtlCaseBuilder.build());\r
- actions.add(actionBuilder.build());\r
-\r
- actionBuilder = new ActionBuilder();\r
- PopPbbCaseBuilder popPbbCaseBuilder = new PopPbbCaseBuilder();\r
- actionBuilder.setActionChoice(popPbbCaseBuilder.build());\r
- actions.add(actionBuilder.build());\r
-\r
- bucketBuilder.setAction(actions);\r
- buckets.add(bucketBuilder.build());\r
- bucketBuilder = new BucketsListBuilder();\r
- bucketBuilder.setWeight(280);\r
- bucketBuilder.setWatchPort(new PortNumber(560L));\r
- bucketBuilder.setWatchGroup(1120L);\r
- actions = new ArrayList<>();\r
- bucketBuilder.setAction(actions);\r
- buckets.add(bucketBuilder.build());\r
- builder.setBucketsList(buckets);\r
- groupStats.add(builder.build());\r
- groupBuilder.setGroupDesc(groupStats);\r
- caseBuilder.setMultipartReplyGroupDesc(groupBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- GroupDescStatsUpdated statUpdate = (GroupDescStatsUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong group stats size", 1, statUpdate.getGroupDescStats().size());\r
- GroupDescStats stat = statUpdate.getGroupDescStats().get(0);\r
- Assert.assertEquals("Wrong group-id", 1, stat.getGroupId().getValue().intValue());\r
- Assert.assertEquals("Wrong group type", GroupTypes.GroupAll, stat.getGroupType());\r
- Assert.assertEquals("Wrong buckets size", 2, stat.getBuckets().getBucket().size());\r
- Bucket bucket = stat.getBuckets().getBucket().get(0);\r
- Assert.assertEquals("Wrong weight size", 28, bucket.getWeight().intValue());\r
- Assert.assertEquals("Wrong watch port size", 56, bucket.getWatchPort().intValue());\r
- Assert.assertEquals("Wrong watch group size", 112, bucket.getWatchGroup().intValue());\r
- Assert.assertEquals("Wrong actions size", 2, bucket.getAction().size());\r
- Assert.assertEquals("Wrong action type", "org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112"\r
- + ".action.action.DecMplsTtlCase", bucket.getAction().get(0).getAction().getImplementedInterface().getName());\r
- Assert.assertEquals("Wrong action type", "org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112"\r
- + ".action.action.PopPbbActionCase", bucket.getAction().get(1).getAction().getImplementedInterface().getName());\r
- bucket = stat.getBuckets().getBucket().get(1);\r
- Assert.assertEquals("Wrong weight size", 280, bucket.getWeight().intValue());\r
- Assert.assertEquals("Wrong watch port size", 560, bucket.getWatchPort().intValue());\r
- Assert.assertEquals("Wrong watch group size", 1120, bucket.getWatchGroup().intValue());\r
- Assert.assertEquals("Wrong actions size", 0, bucket.getAction().size());\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.translator;\r
-\r
-import static org.mockito.Mockito.when;\r
-\r
-import java.math.BigInteger;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mock;\r
-import org.mockito.runners.MockitoJUnitRunner;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.AggregateFlowStatisticsUpdate;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupFeaturesUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterFeaturesUpdated;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ActionType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.GroupCapabilities;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.GroupTypes;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterBandTypeBitmap;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyAggregateCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupFeaturesCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterFeaturesCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.aggregate._case.MultipartReplyAggregateBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.features._case.MultipartReplyGroupFeaturesBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.features._case.MultipartReplyMeterFeaturesBuilder;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-\r
-/**\r
- * @author michal.polkorab\r
- *\r
- */\r
-@RunWith(MockitoJUnitRunner.class)\r
-public class MultipartReplyTranslatorSecondTest {\r
-\r
- @Mock SwitchConnectionDistinguisher cookie;\r
- @Mock SessionContext sc;\r
- @Mock ConnectionConductor conductor;\r
- @Mock GetFeaturesOutput features;\r
-\r
- MultipartReplyTranslator translator;\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();\r
- translator = new MultipartReplyTranslator(convertorManager);\r
- when(sc.getPrimaryConductor()).thenReturn(conductor);\r
- when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);\r
- when(sc.getFeatures()).thenReturn(features);\r
- when(features.getDatapathId()).thenReturn(new BigInteger("42"));\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with aggregate stat\r
- */\r
- @Test\r
- public void testAggregateCase() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPAGGREGATE);\r
- \r
- MultipartReplyAggregateCaseBuilder caseBuilder = new MultipartReplyAggregateCaseBuilder();\r
- MultipartReplyAggregateBuilder aggBuilder = new MultipartReplyAggregateBuilder();\r
- aggBuilder.setByteCount(new BigInteger("52"));\r
- aggBuilder.setFlowCount(6587L);\r
- aggBuilder.setPacketCount(new BigInteger("25"));\r
- caseBuilder.setMultipartReplyAggregate(aggBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- AggregateFlowStatisticsUpdate aggUpdate = (AggregateFlowStatisticsUpdate) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", aggUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, aggUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, aggUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong byte count", 52, aggUpdate.getByteCount().getValue().intValue());\r
- Assert.assertEquals("Wrong packet count", 25, aggUpdate.getPacketCount().getValue().intValue());\r
- Assert.assertEquals("Wrong flow count", 6587, aggUpdate.getFlowCount().getValue().intValue());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with group features stat\r
- */\r
- @Test\r
- public void testGroupFeaturesCase() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPGROUPFEATURES);\r
- \r
- MultipartReplyGroupFeaturesCaseBuilder caseBuilder = new MultipartReplyGroupFeaturesCaseBuilder();\r
- MultipartReplyGroupFeaturesBuilder featBuilder = new MultipartReplyGroupFeaturesBuilder();\r
- featBuilder.setTypes(new GroupTypes(true, false, true, false));\r
- featBuilder.setCapabilities(new GroupCapabilities(false, true, false, true));\r
- List<Long> maxGroups = new ArrayList<>();\r
- maxGroups.add(1L);\r
- maxGroups.add(2L);\r
- maxGroups.add(3L);\r
- maxGroups.add(4L);\r
- featBuilder.setMaxGroups(maxGroups);\r
- List<ActionType> actionTypes = new ArrayList<>();\r
- ActionType actionType1 = new ActionType(true, false, true, false, false, false, true,\r
- false, true, false, true, false, true, false, true, false, true);\r
- actionTypes.add(actionType1);\r
- ActionType actionType2 = new ActionType(false, true, false, true, false, true, false,\r
- true, false, true, false, true, false, true, false, true, false);\r
- actionTypes.add(actionType2);\r
- ActionType actionType3 = new ActionType(false, false, false, false, false, false, false,\r
- true, true, true, true, true, true, true, true, true, true);\r
- actionTypes.add(actionType3);\r
- ActionType actionType4 = new ActionType(true, true, true, true, true, true, true,\r
- false, false, false, false, false, false, false, false, false, false);\r
- actionTypes.add(actionType4);\r
- featBuilder.setActionsBitmap(actionTypes);\r
- caseBuilder.setMultipartReplyGroupFeatures(featBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- GroupFeaturesUpdated groupUpdate = (GroupFeaturesUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", groupUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, groupUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, groupUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong group types size", 2, groupUpdate.getGroupTypesSupported().size());\r
- Assert.assertEquals("Wrong group type", "org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupAll",\r
- groupUpdate.getGroupTypesSupported().get(0).getName());\r
- Assert.assertEquals("Wrong group type", "org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupIndirect",\r
- groupUpdate.getGroupTypesSupported().get(1).getName());\r
- Assert.assertEquals("Wrong group capabilities size", 2, groupUpdate.getGroupCapabilitiesSupported().size());\r
- Assert.assertEquals("Wrong group capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.ChainingChecks",\r
- groupUpdate.getGroupCapabilitiesSupported().get(0).getName());\r
- Assert.assertEquals("Wrong group capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.SelectWeight",\r
- groupUpdate.getGroupCapabilitiesSupported().get(1).getName());\r
- Assert.assertEquals("Wrong max groups", maxGroups, groupUpdate.getMaxGroups());\r
- Assert.assertEquals("Wrong actions bitmap", 137072641, groupUpdate.getActions().get(0).longValue());\r
- Assert.assertEquals("Wrong actions bitmap", 131336192, groupUpdate.getActions().get(1).longValue());\r
- Assert.assertEquals("Wrong actions bitmap", 247365632, groupUpdate.getActions().get(2).longValue());\r
- Assert.assertEquals("Wrong actions bitmap", 21043201, groupUpdate.getActions().get(3).longValue());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with meter features stat\r
- */\r
- @Test\r
- public void testMeterFeaturesCase() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPMETERFEATURES);\r
- \r
- MultipartReplyMeterFeaturesCaseBuilder caseBuilder = new MultipartReplyMeterFeaturesCaseBuilder();\r
- MultipartReplyMeterFeaturesBuilder featBuilder = new MultipartReplyMeterFeaturesBuilder();\r
- featBuilder.setMaxMeter(1L);\r
- featBuilder.setBandTypes(new MeterBandTypeBitmap(true, true));\r
- featBuilder.setCapabilities(new MeterFlags(true, true, true, true));\r
- featBuilder.setMaxBands((short) 2);\r
- featBuilder.setMaxColor((short) 3);\r
- caseBuilder.setMultipartReplyMeterFeatures(featBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- MeterFeaturesUpdated megterUpdate = (MeterFeaturesUpdated) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", megterUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, megterUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, megterUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong max meter", 1, megterUpdate.getMaxMeter().getValue().intValue());\r
- Assert.assertEquals("Wrong max bands", 2, megterUpdate.getMaxBands().intValue());\r
- Assert.assertEquals("Wrong max color", 3, megterUpdate.getMaxColor().intValue());\r
- Assert.assertEquals("Wrong capabilities size", 4, megterUpdate.getMeterCapabilitiesSupported().size());\r
- Assert.assertEquals("Wrong capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918"\r
- + ".MeterBurst", megterUpdate.getMeterCapabilitiesSupported().get(0).getName());\r
- Assert.assertEquals("Wrong capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918"\r
- + ".MeterKbps", megterUpdate.getMeterCapabilitiesSupported().get(1).getName());\r
- Assert.assertEquals("Wrong capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918"\r
- + ".MeterPktps", megterUpdate.getMeterCapabilitiesSupported().get(2).getName());\r
- Assert.assertEquals("Wrong capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918"\r
- + ".MeterStats", megterUpdate.getMeterCapabilitiesSupported().get(3).getName());\r
- Assert.assertEquals("Wrong band types size", 2, megterUpdate.getMeterBandSupported().size());\r
- Assert.assertEquals("Wrong band type", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBandDrop",\r
- megterUpdate.getMeterBandSupported().get(0).getName());\r
- Assert.assertEquals("Wrong band type", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBandDscpRemark",\r
- megterUpdate.getMeterBandSupported().get(1).getName());\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.translator;\r
-\r
-import static org.mockito.Mockito.when;\r
-\r
-import java.math.BigInteger;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mock;\r
-import org.mockito.runners.MockitoJUnitRunner;\r
-import org.opendaylight.openflowjava.protocol.api.util.BinContent;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;\r
-import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsUpdate;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.and.statistics.map.FlowTableAndStatisticsMap;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortNumberValues;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortStatsCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyQueueCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableCaseBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.stats._case.MultipartReplyPortStatsBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.stats._case.multipart.reply.port.stats.PortStats;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.stats._case.multipart.reply.port.stats.PortStatsBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.queue._case.MultipartReplyQueueBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.queue._case.multipart.reply.queue.QueueStats;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.queue._case.multipart.reply.queue.QueueStatsBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table._case.MultipartReplyTableBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table._case.multipart.reply.table.TableStats;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table._case.multipart.reply.table.TableStatsBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdate;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMap;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.QueueStatisticsUpdate;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMap;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-\r
-/**\r
- * @author michal.polkorab\r
- *\r
- */\r
-@RunWith(MockitoJUnitRunner.class)\r
-public class MultipartReplyTranslatorThirdTest {\r
-\r
- @Mock SwitchConnectionDistinguisher cookie;\r
- @Mock SessionContext sc;\r
- @Mock ConnectionConductor conductor;\r
- @Mock GetFeaturesOutput features;\r
-\r
- MultipartReplyTranslator translator;\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();\r
- translator = new MultipartReplyTranslator(convertorManager);\r
- when(sc.getPrimaryConductor()).thenReturn(conductor);\r
- when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);\r
- when(sc.getFeatures()).thenReturn(features);\r
- when(features.getDatapathId()).thenReturn(new BigInteger("42"));\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with empty port stats\r
- */\r
- @Test\r
- public void testEmptyPortStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPPORTSTATS);\r
- \r
- MultipartReplyPortStatsCaseBuilder caseBuilder = new MultipartReplyPortStatsCaseBuilder();\r
- MultipartReplyPortStatsBuilder statsBuilder = new MultipartReplyPortStatsBuilder();\r
- List<PortStats> portStats = new ArrayList<>();\r
- statsBuilder.setPortStats(portStats);\r
- caseBuilder.setMultipartReplyPortStats(statsBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- NodeConnectorStatisticsUpdate statUpdate = (NodeConnectorStatisticsUpdate) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong port stats size", 0, statUpdate.getNodeConnectorStatisticsAndPortNumberMap().size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with port stats\r
- */\r
- @Test\r
- public void testPortStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPPORTSTATS);\r
- \r
- MultipartReplyPortStatsCaseBuilder caseBuilder = new MultipartReplyPortStatsCaseBuilder();\r
- MultipartReplyPortStatsBuilder statsBuilder = new MultipartReplyPortStatsBuilder();\r
- List<PortStats> portStats = new ArrayList<>();\r
- PortStatsBuilder builder = new PortStatsBuilder();\r
- builder.setPortNo(1L);\r
- builder.setRxPackets(new BigInteger("2"));\r
- builder.setTxPackets(new BigInteger("3"));\r
- builder.setRxBytes(new BigInteger("4"));\r
- builder.setTxBytes(new BigInteger("5"));\r
- builder.setRxDropped(new BigInteger("6"));\r
- builder.setTxDropped(new BigInteger("7"));\r
- builder.setRxErrors(new BigInteger("8"));\r
- builder.setTxErrors(new BigInteger("9"));\r
- builder.setRxFrameErr(new BigInteger("10"));\r
- builder.setRxOverErr(new BigInteger("11"));\r
- builder.setRxCrcErr(new BigInteger("12"));\r
- builder.setCollisions(new BigInteger("13"));\r
- builder.setDurationSec(14L);\r
- builder.setDurationNsec(15L);\r
- portStats.add(builder.build());\r
- builder = new PortStatsBuilder();\r
- builder.setPortNo(BinContent.intToUnsignedLong(PortNumberValues.CONTROLLER.getIntValue()));\r
- builder.setRxPackets(new BigInteger("20"));\r
- builder.setTxPackets(new BigInteger("30"));\r
- builder.setRxBytes(new BigInteger("40"));\r
- builder.setTxBytes(new BigInteger("50"));\r
- builder.setRxDropped(new BigInteger("60"));\r
- builder.setTxDropped(new BigInteger("70"));\r
- builder.setRxErrors(new BigInteger("80"));\r
- builder.setTxErrors(new BigInteger("90"));\r
- builder.setRxFrameErr(new BigInteger("100"));\r
- builder.setRxOverErr(new BigInteger("110"));\r
- builder.setRxCrcErr(new BigInteger("120"));\r
- builder.setCollisions(new BigInteger("130"));\r
- portStats.add(builder.build());\r
- statsBuilder.setPortStats(portStats);\r
- caseBuilder.setMultipartReplyPortStats(statsBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- NodeConnectorStatisticsUpdate statUpdate = (NodeConnectorStatisticsUpdate) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong port stats size", 2, statUpdate.getNodeConnectorStatisticsAndPortNumberMap().size());\r
- NodeConnectorStatisticsAndPortNumberMap stat = statUpdate.getNodeConnectorStatisticsAndPortNumberMap().get(0);\r
- Assert.assertEquals("Wrong port number", "openflow:42:1", stat.getNodeConnectorId().getValue());\r
- Assert.assertEquals("Wrong rx packets", 2, stat.getPackets().getReceived().intValue());\r
- Assert.assertEquals("Wrong tx packets", 3, stat.getPackets().getTransmitted().intValue());\r
- Assert.assertEquals("Wrong rx bytes", 4, stat.getBytes().getReceived().intValue());\r
- Assert.assertEquals("Wrong tx bytes", 5, stat.getBytes().getTransmitted().intValue());\r
- Assert.assertEquals("Wrong rx dropped", 6, stat.getReceiveDrops().intValue());\r
- Assert.assertEquals("Wrong tx dropped", 7, stat.getTransmitDrops().intValue());\r
- Assert.assertEquals("Wrong rx errors", 8, stat.getReceiveErrors().intValue());\r
- Assert.assertEquals("Wrong tx errors", 9, stat.getTransmitErrors().intValue());\r
- Assert.assertEquals("Wrong rx frame error", 10, stat.getReceiveFrameError().intValue());\r
- Assert.assertEquals("Wrong rx over error", 11, stat.getReceiveOverRunError().intValue());\r
- Assert.assertEquals("Wrong rx crc error", 12, stat.getReceiveCrcError().intValue());\r
- Assert.assertEquals("Wrong collision count", 13, stat.getCollisionCount().intValue());\r
- Assert.assertEquals("Wrong duration sec", 14, stat.getDuration().getSecond().getValue().intValue());\r
- Assert.assertEquals("Wrong duration n sec", 15, stat.getDuration().getNanosecond().getValue().intValue());\r
- stat = statUpdate.getNodeConnectorStatisticsAndPortNumberMap().get(1);\r
- Assert.assertEquals("Wrong port number", "openflow:42:CONTROLLER", stat.getNodeConnectorId().getValue());\r
- Assert.assertEquals("Wrong rx packets", 20, stat.getPackets().getReceived().intValue());\r
- Assert.assertEquals("Wrong tx packets", 30, stat.getPackets().getTransmitted().intValue());\r
- Assert.assertEquals("Wrong rx bytes", 40, stat.getBytes().getReceived().intValue());\r
- Assert.assertEquals("Wrong tx bytes", 50, stat.getBytes().getTransmitted().intValue());\r
- Assert.assertEquals("Wrong rx dropped", 60, stat.getReceiveDrops().intValue());\r
- Assert.assertEquals("Wrong tx dropped", 70, stat.getTransmitDrops().intValue());\r
- Assert.assertEquals("Wrong rx errors", 80, stat.getReceiveErrors().intValue());\r
- Assert.assertEquals("Wrong tx errors", 90, stat.getTransmitErrors().intValue());\r
- Assert.assertEquals("Wrong rx frame error", 100, stat.getReceiveFrameError().intValue());\r
- Assert.assertEquals("Wrong rx over error", 110, stat.getReceiveOverRunError().intValue());\r
- Assert.assertEquals("Wrong rx crc error", 120, stat.getReceiveCrcError().intValue());\r
- Assert.assertEquals("Wrong collision count", 130, stat.getCollisionCount().intValue());\r
- Assert.assertEquals("Wrong duration sec", null, stat.getDuration().getSecond());\r
- Assert.assertEquals("Wrong duration n sec", null, stat.getDuration().getNanosecond());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with empty table stats\r
- */\r
- @Test\r
- public void testEmptyTableStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPTABLE);\r
- \r
- MultipartReplyTableCaseBuilder caseBuilder = new MultipartReplyTableCaseBuilder();\r
- MultipartReplyTableBuilder statsBuilder = new MultipartReplyTableBuilder();\r
- List<TableStats> tableStats = new ArrayList<>();\r
- statsBuilder.setTableStats(tableStats);\r
- caseBuilder.setMultipartReplyTable(statsBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- FlowTableStatisticsUpdate statUpdate = (FlowTableStatisticsUpdate) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong table stats size", 0, statUpdate.getFlowTableAndStatisticsMap().size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with table stats\r
- */\r
- @Test\r
- public void testTableStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPTABLE);\r
- \r
- MultipartReplyTableCaseBuilder caseBuilder = new MultipartReplyTableCaseBuilder();\r
- MultipartReplyTableBuilder statsBuilder = new MultipartReplyTableBuilder();\r
- List<TableStats> tableStats = new ArrayList<>();\r
- TableStatsBuilder builder = new TableStatsBuilder();\r
- builder.setTableId((short) 1);\r
- builder.setActiveCount(2L);\r
- builder.setLookupCount(new BigInteger("3"));\r
- builder.setMatchedCount(new BigInteger("4"));\r
- tableStats.add(builder.build());\r
- builder = new TableStatsBuilder();\r
- builder.setTableId((short) 10);\r
- builder.setActiveCount(20L);\r
- builder.setLookupCount(new BigInteger("30"));\r
- builder.setMatchedCount(new BigInteger("40"));\r
- tableStats.add(builder.build());\r
- statsBuilder.setTableStats(tableStats);\r
- caseBuilder.setMultipartReplyTable(statsBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- FlowTableStatisticsUpdate statUpdate = (FlowTableStatisticsUpdate) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong table stats size", 2, statUpdate.getFlowTableAndStatisticsMap().size());\r
- FlowTableAndStatisticsMap stat = statUpdate.getFlowTableAndStatisticsMap().get(0);\r
- Assert.assertEquals("Wrong table-id", 1, stat.getTableId().getValue().intValue());\r
- Assert.assertEquals("Wrong active count", 2, stat.getActiveFlows().getValue().intValue());\r
- Assert.assertEquals("Wrong lookup count", 3, stat.getPacketsLookedUp().getValue().intValue());\r
- Assert.assertEquals("Wrong matched count", 4, stat.getPacketsMatched().getValue().intValue());\r
- stat = statUpdate.getFlowTableAndStatisticsMap().get(1);\r
- Assert.assertEquals("Wrong table-id", 10, stat.getTableId().getValue().intValue());\r
- Assert.assertEquals("Wrong active count", 20, stat.getActiveFlows().getValue().intValue());\r
- Assert.assertEquals("Wrong lookup count", 30, stat.getPacketsLookedUp().getValue().intValue());\r
- Assert.assertEquals("Wrong matched count", 40, stat.getPacketsMatched().getValue().intValue());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with empty queue stats\r
- */\r
- @Test\r
- public void testEmptyQueueStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPQUEUE);\r
- \r
- MultipartReplyQueueCaseBuilder caseBuilder = new MultipartReplyQueueCaseBuilder();\r
- MultipartReplyQueueBuilder statsBuilder = new MultipartReplyQueueBuilder();\r
- List<QueueStats> queueStats = new ArrayList<>();\r
- statsBuilder.setQueueStats(queueStats);\r
- caseBuilder.setMultipartReplyQueue(statsBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- QueueStatisticsUpdate statUpdate = (QueueStatisticsUpdate) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong queue stats size", 0, statUpdate.getQueueIdAndStatisticsMap().size());\r
- }\r
-\r
- /**\r
- * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * with queue stats\r
- */\r
- @Test\r
- public void testQueueStats() {\r
- MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder();\r
- mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- mpBuilder.setXid(123L);\r
- mpBuilder.setFlags(new MultipartRequestFlags(false));\r
- mpBuilder.setType(MultipartType.OFPMPQUEUE);\r
- \r
- MultipartReplyQueueCaseBuilder caseBuilder = new MultipartReplyQueueCaseBuilder();\r
- MultipartReplyQueueBuilder statsBuilder = new MultipartReplyQueueBuilder();\r
- List<QueueStats> queueStats = new ArrayList<>();\r
- QueueStatsBuilder builder = new QueueStatsBuilder();\r
- builder.setPortNo(BinContent.intToUnsignedLong(PortNumberValues.FLOOD.getIntValue()));\r
- builder.setQueueId(2L);\r
- builder.setTxPackets(new BigInteger("3"));\r
- builder.setTxBytes(new BigInteger("4"));\r
- builder.setTxErrors(new BigInteger("5"));\r
- builder.setDurationSec(6L);\r
- builder.setDurationNsec(7L);\r
- queueStats.add(builder.build());\r
- builder = new QueueStatsBuilder();\r
- builder.setPortNo(BinContent.intToUnsignedLong(PortNumberValues.INPORT.getIntValue()));\r
- builder.setQueueId(20L);\r
- builder.setTxPackets(new BigInteger("30"));\r
- builder.setTxBytes(new BigInteger("40"));\r
- builder.setTxErrors(new BigInteger("50"));\r
- builder.setDurationSec(60L);\r
- builder.setDurationNsec(70L);\r
- queueStats.add(builder.build());\r
- statsBuilder.setQueueStats(queueStats);\r
- caseBuilder.setMultipartReplyQueue(statsBuilder.build());\r
- mpBuilder.setMultipartReplyBody(caseBuilder.build());\r
- MultipartReplyMessage message = mpBuilder.build();\r
- \r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- QueueStatisticsUpdate statUpdate = (QueueStatisticsUpdate) list.get(0);\r
- Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue());\r
- Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies());\r
- Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue());\r
- Assert.assertEquals("Wrong queue stats size", 2, statUpdate.getQueueIdAndStatisticsMap().size());\r
- QueueIdAndStatisticsMap stat = statUpdate.getQueueIdAndStatisticsMap().get(0);\r
- Assert.assertEquals("Wrong port number", "openflow:42:FLOOD", stat.getNodeConnectorId().getValue());\r
- Assert.assertEquals("Wrong queue-id", 2, stat.getQueueId().getValue().intValue());\r
- Assert.assertEquals("Wrong tx packets", 3, stat.getTransmittedPackets().getValue().intValue());\r
- Assert.assertEquals("Wrong tx bytes", 4, stat.getTransmittedBytes().getValue().intValue());\r
- Assert.assertEquals("Wrong tx errors", 5, stat.getTransmissionErrors().getValue().intValue());\r
- Assert.assertEquals("Wrong duration sec", 6, stat.getDuration().getSecond().getValue().intValue());\r
- Assert.assertEquals("Wrong duration n sec", 7, stat.getDuration().getNanosecond().getValue().intValue());\r
- stat = statUpdate.getQueueIdAndStatisticsMap().get(1);\r
- Assert.assertEquals("Wrong port number", "openflow:42:IN_PORT", stat.getNodeConnectorId().getValue());\r
- Assert.assertEquals("Wrong queue-id", 20, stat.getQueueId().getValue().intValue());\r
- Assert.assertEquals("Wrong tx packets", 30, stat.getTransmittedPackets().getValue().intValue());\r
- Assert.assertEquals("Wrong tx bytes", 40, stat.getTransmittedBytes().getValue().intValue());\r
- Assert.assertEquals("Wrong tx errors", 50, stat.getTransmissionErrors().getValue().intValue());\r
- Assert.assertEquals("Wrong duration sec", 60, stat.getDuration().getSecond().getValue().intValue());\r
- Assert.assertEquals("Wrong duration n sec", 70, stat.getDuration().getNanosecond().getValue().intValue());\r
- }\r
-}
\ No newline at end of file
+++ /dev/null
-/*\r
- * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.translator;\r
-\r
-import java.math.BigInteger;\r
-import java.util.List;\r
-\r
-import static org.mockito.Mockito.when;\r
-\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.mockito.Mock;\r
-import org.mockito.MockitoAnnotations;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-\r
-/**\r
- * @author michal.polkorab\r
- *\r
- */\r
-public class NotificationPlainTranslatorTest {\r
-\r
- @Mock SwitchConnectionDistinguisher cookie;\r
- @Mock SessionContext sc;\r
- @Mock GetFeaturesOutput features;\r
-\r
- NotificationPlainTranslator translator = new NotificationPlainTranslator();\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- MockitoAnnotations.initMocks(this);\r
- }\r
-\r
- /**\r
- * Tests {@link NotificationPlainTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- */\r
- @Test\r
- public void testIncorrectInput() {\r
- HelloMessageBuilder helloBuilder = new HelloMessageBuilder();\r
- HelloMessage message = helloBuilder.build();\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, message);\r
-\r
- Assert.assertEquals("Wrong list size", 0, list.size());\r
- }\r
-\r
- /**\r
- * Tests {@link NotificationPlainTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- */\r
- @Test\r
- public void test() {\r
- when(sc.getFeatures()).thenReturn(features);\r
- when(features.getDatapathId()).thenReturn(new BigInteger("64"));\r
- HelloMessageBuilder helloBuilder = new HelloMessageBuilder();\r
- helloBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);\r
- helloBuilder.setXid(42L);\r
- HelloMessage message = helloBuilder.build();\r
- NotificationQueueWrapper wrapper = new NotificationQueueWrapper(message, message.getVersion());\r
-\r
- List<DataObject> list = translator.translate(cookie, sc, wrapper);\r
-\r
- Assert.assertEquals("Wrong list size", 1, list.size());\r
- HelloMessage hello = (HelloMessage) list.get(0);\r
- Assert.assertEquals("Wrong output", 4, hello.getVersion().intValue());\r
- Assert.assertEquals("Wrong output", 42, hello.getXid().intValue());\r
- }\r
-}\r
+++ /dev/null
-/**\r
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.openflow.md.core.translator;\r
-\r
-import static org.mockito.Mockito.when;\r
-\r
-import java.io.IOException;\r
-import java.math.BigInteger;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.Collections;\r
-import java.util.HashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-import org.junit.Assert;\r
-import org.junit.Before;\r
-import org.junit.Test;\r
-import org.junit.runner.RunWith;\r
-import org.mockito.Mock;\r
-import org.mockito.runners.MockitoJUnitRunner;\r
-import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;\r
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;\r
-import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;\r
-import org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl;\r
-import org.opendaylight.openflowplugin.openflow.md.core.session.SessionContextOFImpl;\r
-import org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl;\r
-import org.opendaylight.openflowplugin.openflow.md.queue.QueueProcessorLightImpl;\r
-import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PacketInReason;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessageBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceivedBuilder;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.SendToController;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-\r
-/**\r
- * Created by Jakub Toth jatoth@cisco.com on 3/10/14.\r
- */\r
-@RunWith(MockitoJUnitRunner.class)\r
-public class PacketInV10TranslatorTest {\r
- private static final Logger LOG = LoggerFactory\r
- .getLogger(PacketInV10TranslatorTest.class);\r
-\r
- @Mock\r
- private SessionContext sc;\r
- @Mock\r
- private ConnectionConductorImpl conductor;\r
- @Mock\r
- private GetFeaturesOutput features;\r
-\r
- private SwitchConnectionDistinguisher cookie;\r
- private byte[] data;\r
-\r
- /**\r
- * Initializes mocks\r
- */\r
- @Before\r
- public void startUp() {\r
- when(sc.getPrimaryConductor()).thenReturn(conductor);\r
- when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF10_VERSION_ID);\r
- when(sc.getFeatures()).thenReturn(features);\r
- when(features.getDatapathId()).thenReturn(new BigInteger("42"));\r
-\r
- cookie = settingCookie();\r
- data = messageData();\r
- }\r
-\r
- /**\r
- * test\r
- * {@link PacketInV10Translator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * - all parameteres are null - translates packetIn from OF-API model to\r
- * MD-SAL model, supports OF-1.0\r
- */\r
- @Test\r
- public void testTranslateWithAllNullParam() {\r
- SwitchConnectionDistinguisher cookieNull = null;\r
- SessionContext sessionContext = null;\r
- OfHeader msg = null;\r
-\r
- PacketInV10Translator packetInV10Translator = new PacketInV10Translator();\r
-\r
- List<DataObject> salPacketIn = packetInV10Translator.translate(cookieNull,\r
- sessionContext, msg);\r
-\r
- Assert.assertEquals(true, salPacketIn.isEmpty());\r
-\r
- LOG.info("Test with all null parameters done.");\r
- }\r
-\r
- /**\r
- * test\r
- * {@link PacketInV10Translator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * - DPID is null- translates packetIn from OF-API model to MD-SAL model,\r
- * supports OF-1.0\r
- */\r
- @Test\r
- public void testTranslateDPIDNull() {\r
- SessionContext sessionContextOFImpl = new SessionContextOFImpl();\r
-\r
- PacketInMessage message = createPacketInMessage(data, null);\r
-\r
- PacketInV10Translator packetInV10Translator = new PacketInV10Translator();\r
-\r
- List<DataObject> salPacketIn = packetInV10Translator.translate(cookie,\r
- sessionContextOFImpl, message);\r
-\r
- Assert.assertEquals(true, salPacketIn.isEmpty());\r
- LOG.info("Test with null DPID parameter done.");\r
- }\r
-\r
- /**\r
- * test\r
- * {@link PacketInV10Translator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * - inPort is null- translates packetIn from OF-API model to MD-SAL model,\r
- * supports OF-1.0\r
- */\r
- @Test\r
- public void testTranslateInPortNull() {\r
- BigInteger datapathId = dataPathId();\r
-\r
- GetFeaturesOutputBuilder featuresBuilder = new GetFeaturesOutputBuilder();\r
- featuresBuilder.setDatapathId(datapathId);\r
-\r
- SessionContextOFImpl sessionContextOFImpl = new SessionContextOFImpl();\r
- sessionContextOFImpl.setFeatures(featuresBuilder.build());\r
-\r
- PacketInMessage message = createPacketInMessage(data, null);\r
-\r
- PacketInV10Translator packetInV10Translator = new PacketInV10Translator();\r
-\r
- List<DataObject> salPacketIn = packetInV10Translator.translate(cookie,\r
- sessionContextOFImpl, message);\r
-\r
- Assert.assertEquals(true, salPacketIn.isEmpty());\r
-\r
- LOG.info("Test with null inPort parameter done.");\r
- }\r
-\r
- /**\r
- * test\r
- * {@link PacketInV10Translator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)}\r
- * - translates packetIn from OF-API model to MD-SAL model, supports OF-1.0\r
- *\r
- * @throws IOException\r
- */\r
- @Test\r
- public void testTranslate() {\r
- BigInteger datapathId = dataPathId();\r
-\r
- PacketInMessage message = createPacketInMessage(data, 5);\r
-\r
- GetFeaturesOutput featuresOutput = createGetFeatureOutput(datapathId);\r
- initConnectionConductor(conductor, featuresOutput);\r
- SessionContextOFImpl sessionContextOFImpl = new SessionContextOFImpl();\r
- sessionContextOFImpl.setFeatures(featuresOutput);\r
- sessionContextOFImpl.setPrimaryConductor(conductor);\r
- PacketInV10Translator packetInV10Translator = new PacketInV10Translator();\r
- List<DataObject> salPacketIn = packetInV10Translator.translate(cookie,\r
- sessionContextOFImpl, message);\r
-\r
- Assert.assertEquals(Collections.singletonList(new PacketReceivedBuilder()\r
- .setIngress(InventoryDataServiceUtil.nodeConnectorRefFromDatapathIdPortno(datapathId, (long) message.getInPort(), OpenflowVersion.OF10))\r
- .setPacketInReason(SendToController.class)\r
- .setPayload(data)\r
- .build()).toString(), salPacketIn.toString());\r
-\r
- LOG.debug("Test translate done.");\r
- }\r
-\r
- /**\r
- * create datapathID\r
- *\r
- * @return BigInteger\r
- */\r
- private static BigInteger dataPathId() {\r
- byte[] datapathIdByte = new byte[EncodeConstants.SIZE_OF_LONG_IN_BYTES];\r
- for (int i = 0; i < datapathIdByte.length; i++) {\r
- datapathIdByte[i] = 1;\r
- }\r
- return new BigInteger(1, datapathIdByte);\r
- }\r
-\r
- /**\r
- * generate message from string to byte[]\r
- *\r
- * @return byte[]\r
- */\r
- private static byte[] messageData() {\r
- String string = new String("sendOutputMsg_TEST");\r
- return string.getBytes();\r
- }\r
-\r
- /**\r
- * create PacketInMessage with setting Version, InPort, Data, Reason\r
- *\r
- * @param data\r
- * @param port\r
- * @return PacketInMessage\r
- */\r
- private static PacketInMessage createPacketInMessage(final byte[] data,\r
- final java.lang.Integer port) {\r
- PacketInReason reason = PacketInReason.OFPRACTION;\r
- return new PacketInMessageBuilder()\r
- .setVersion((short) EncodeConstants.OF10_VERSION_ID)\r
- .setInPort(port).setData(data).setReason(reason).build();\r
-\r
- }\r
-\r
- /**\r
- * create cookie\r
- *\r
- * @return SwitchConnectionDistinguisher\r
- */\r
- private static SwitchConnectionDistinguisher settingCookie() {\r
- SwitchConnectionCookieOFImpl key = new SwitchConnectionCookieOFImpl();\r
- key.setAuxiliaryId((short) 1);\r
- key.init(42);\r
- return key;\r
- }\r
-\r
- /**\r
- * create GetFeatureOutput\r
- *\r
- * @param datapathId\r
- * @return GetFeaturesOutput\r
- */\r
- private static GetFeaturesOutput createGetFeatureOutput(final BigInteger datapathId) {\r
- return new GetFeaturesOutputBuilder().setDatapathId(datapathId)\r
- .setVersion((short) 0x01).build();\r
- }\r
-\r
- /**\r
- * init connectionConductor\r
- *\r
- * @param connectionConductor\r
- * @param featuresOutput\r
- */\r
- private static void initConnectionConductor(\r
- final ConnectionConductorImpl connectionConductor,\r
- final GetFeaturesOutput featuresOutput) {\r
- TranslatorKey paramK = new TranslatorKey(1, PacketInMessage.class.getSimpleName());\r
- Collection<IMDMessageTranslator<OfHeader, List<DataObject>>> coll = new ArrayList<>();\r
- coll.add(new PacketInV10Translator());\r
- Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping = new HashMap<>();\r
- translatorMapping.put(paramK, coll);\r
-\r
- QueueProcessorLightImpl queueProcessor = new QueueProcessorLightImpl();\r
- queueProcessor.setTranslatorMapping(translatorMapping);\r
- queueProcessor.init();\r
- connectionConductor.setQueueProcessor(queueProcessor);\r
- connectionConductor.init();\r
- connectionConductor\r
- .onHandshakeSuccessful(featuresOutput, (short) 0x01);\r
- }\r
-}\r
package org.opendaylight.openflowplugin.openflow.md.util;
import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.Futures;
+
import java.math.BigInteger;
-import java.util.List;
import org.junit.Assert;
-import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdatedBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdatedBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortNumberValuesV10;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
private static final long PORT_NO = PortNumberValuesV10.CONTROLLER.getIntValue();
private static final BigInteger PATH_ID = BigInteger.TEN;
- @Mock
- DataBroker dataBroker;
- @Mock
- ReadOnlyTransaction readOnlyTransaction;
- @Mock
- WriteTransaction writeTransaction;
- @Mock
- Nodes nodes;
- @Mock
- Node node;
-
-
- @Before
- public void setupEnvironment() {
- when(dataBroker.newReadOnlyTransaction()).thenReturn(readOnlyTransaction);
- when(readOnlyTransaction.read(Mockito.any(LogicalDatastoreType.class), Mockito.<InstanceIdentifier<Nodes>>any())).thenReturn(Futures.immediateCheckedFuture(Optional.of(nodes)));
-
- OFSessionUtil.getSessionManager().setDataBroker(dataBroker);
-
- }
-
- @Test
- /**
- * Primitive test method for {@link InventoryDataServiceUtil#putNodeConnector(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId, org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector)} ()}.
- */
- public void testPutNodeConnector(){
- when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
-
- NodeId nodeId = new NodeId("1");
- NodeConnectorBuilder nodeConnectorBuilder = new NodeConnectorBuilder();
- NodeConnectorId nodeConnectorId = new NodeConnectorId("1");
- nodeConnectorBuilder.setId(nodeConnectorId );
- nodeConnectorBuilder.setKey(new NodeConnectorKey(nodeConnectorId ));
- InventoryDataServiceUtil.putNodeConnector(nodeId, nodeConnectorBuilder.build());
- }
-
- /**
- * Primitive test method for {@link InventoryDataServiceUtil#readNode(org.opendaylight.yangtools.yang.binding.InstanceIdentifier)} ()}.
- */
- @Test
- public void testReadNode(){
- when(readOnlyTransaction.read(Mockito.any(LogicalDatastoreType.class), Mockito.<InstanceIdentifier<Node>>any())).thenReturn(Futures.immediateCheckedFuture(Optional.of(node)));
- InstanceIdentifier<Node> instanceId = InstanceIdentifier.create(Node.class);
- Node node = InventoryDataServiceUtil.readNode(instanceId);
- assertNotNull(node);
- }
- /**
- * Test method for {@link InventoryDataServiceUtil#checkForNodes()}.
- */
- @Test
- public void testCheckForNodes() {
- Nodes nodes = InventoryDataServiceUtil.checkForNodes();
- assertNotNull(nodes);
- }
-
- /**
- * Test method for {@link InventoryDataServiceUtil#readAllNodes()}.
- */
- @Test
- public void testReadAllNodes() {
- List<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> nodes = InventoryDataServiceUtil.readAllNodes();
- assertNotNull(nodes);
- }
-
/**
* Test method for {@link InventoryDataServiceUtil#nodeUpdatedBuilderFromDataPathId(BigInteger datapathId)}.
*/
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.util;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Queue;
-import java.util.concurrent.LinkedBlockingQueue;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesPriorityZipper;
-
-import com.google.common.collect.Lists;
-
-/**
- * test for {@link PollableQueuesPriorityZipper}
- */
-public class PollableQueuesPriorityZipperTest {
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesPriorityZipper#poll()}
- * .
- */
- @Test
- public void testPoll3() {
- Queue<String> l1 = new LinkedBlockingQueue<String>(Lists.newArrayList(
- "1", "2", "3"));
- Queue<String> l2 = new LinkedBlockingQueue<String>(Lists.newArrayList(
- "a", "b", "c", "d"));
- Queue<String> l3 = new LinkedBlockingQueue<String>(Lists.newArrayList(
- "A", "B"));
-
- PollableQueuesPriorityZipper<String> zipper = new PollableQueuesPriorityZipper<>();
- zipper.setPrioritizedSource(l1);
- zipper.addSource(l2);
- zipper.addSource(l3);
-
- String[] expected = new String[] { "1", "2", "3", "a", "A", "b", "B",
- "c", "d", null, "XXX" };
- List<String> result = new ArrayList<>();
- while (true) {
- String data = zipper.poll();
- result.add(data);
- if (data == null) {
- break;
- }
- }
- l1.offer("XXX");
- result.add(zipper.poll());
- Assert.assertArrayEquals(expected, result.toArray());
- }
-
- /**
- * Test method for
- * {@link org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesPriorityZipper#poll()}
- * .
- */
- @Test
- public void testPoll2() {
- Queue<String> l1 = new LinkedBlockingQueue<String>(Lists.newArrayList(
- "1", "2", "3"));
- Queue<String> l3 = new LinkedBlockingQueue<String>(Lists.newArrayList(
- "A", "B"));
-
- PollableQueuesPriorityZipper<String> zipper = new PollableQueuesPriorityZipper<>();
- zipper.setPrioritizedSource(l1);
- zipper.addSource(l3);
-
- String[] expected = new String[] { "1", "2", "3", "A", "B", null, "XXX" };
- List<String> result = new ArrayList<>();
- while (true) {
- String data = zipper.poll();
- result.add(data);
- if (data == null) {
- break;
- }
- }
- l1.offer("XXX");
- result.add(zipper.poll());
- Assert.assertArrayEquals(expected, result.toArray());
- }
-
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.util;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Queue;
-import java.util.concurrent.LinkedBlockingQueue;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesZipper;
-
-import com.google.common.collect.Lists;
-
-/**
- * test for {@link PollableQueuesZipper}
- */
-public class PollableQueuesZipperTest {
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesZipper#poll()}.
- */
- @Test
- public void testPoll() {
- Queue<String> l1 = new LinkedBlockingQueue<String>(Lists.newArrayList("1", "2", "3"));
- Queue<String> l2 = new LinkedBlockingQueue<String>(Lists.newArrayList("a", "b", "c", "d"));
- Queue<String> l3 = new LinkedBlockingQueue<String>(Lists.newArrayList("A", "B"));
-
- PollableQueuesZipper<String> zipper = new PollableQueuesZipper<>();
- zipper.addSource(l1);
- zipper.addSource(l2);
- zipper.addSource(l3);
-
- String[] expected = new String[] {
- "1", "a", "A", "2", "b", "B", "3", "c", "d", null, "XXX"
- };
- List<String> result = new ArrayList<>();
- while (true) {
- String data = zipper.poll();
- result.add(data);
- if (data == null) {
- break;
- }
- }
- l1.offer("XXX");
- result.add(zipper.poll());
- Assert.assertArrayEquals(expected, result.toArray());
- }
-
-}
+++ /dev/null
-/**
- * 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.openflowplugin.openflow.md.util;
-
-import java.math.BigInteger;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Matchers;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
-import org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager;
-import org.opendaylight.openflowplugin.openflow.md.core.session.RolePushException;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequest;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-
-import com.google.common.util.concurrent.Futures;
-
-/**
- * testing {@link RoleUtil}
- */
-@RunWith(MockitoJUnitRunner.class)
-public class RoleUtilTest {
-
- @Mock
- private SessionContext session;
- @Mock
- private GetFeaturesOutput features;
- @Mock
- private ConnectionConductor primaryConductor;
- @Mock
- private ConnectionAdapter connectionAdapter;
-
- private final BigInteger generationId = BigInteger.TEN;
- private RoleRequestOutput roleRequestOutput;
-
- /**
- * prepare values
- */
- @Before
- public void setUp() {
- Mockito.when(session.getFeatures()).thenReturn(features);
- Mockito.when(features.getVersion()).thenReturn(Short.valueOf((short) 42));
- Mockito.when(session.getNextXid()).thenReturn(84L);
- Mockito.when(session.getPrimaryConductor()).thenReturn(primaryConductor);
- Mockito.when(primaryConductor.getConnectionAdapter()).thenReturn(connectionAdapter);
- roleRequestOutput = new RoleRequestOutputBuilder()
- .setGenerationId(generationId)
- .setRole(ControllerRole.OFPCRROLESLAVE)
- .setVersion((short) 42)
- .setXid(21L)
- .build();
- Mockito.when(connectionAdapter.roleRequest(Matchers.any(RoleRequestInput.class)))
- .thenReturn(Futures.immediateFuture(RpcResultBuilder.success(roleRequestOutput).build()));
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#toOFJavaRole(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}.
- */
- @Test
- public void testToOFJavaRole() {
- Assert.assertEquals(ControllerRole.OFPCRROLEMASTER, RoleUtil.toOFJavaRole(OfpRole.BECOMEMASTER));
- Assert.assertEquals(ControllerRole.OFPCRROLESLAVE, RoleUtil.toOFJavaRole(OfpRole.BECOMESLAVE));
- Assert.assertEquals(ControllerRole.OFPCRROLENOCHANGE, RoleUtil.toOFJavaRole(OfpRole.NOCHANGE));
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#toOFJavaRole(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}.
- */
- @Test(expected = NullPointerException.class)
- public void testToOFJavaRoleNull() {
- RoleUtil.toOFJavaRole(null);
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#createRoleRequestInput(org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole, java.math.BigInteger)}.
- */
- @Test
- public void testCreateRuleRequestInput() {
- RoleRequestInput roleRequestInput = RoleUtil.createRoleRequestInput(session, OfpRole.BECOMEMASTER, generationId).build();
- Assert.assertEquals(generationId, roleRequestInput.getGenerationId());
- Assert.assertEquals(RoleRequestInput.class, roleRequestInput.getImplementedInterface());
- Assert.assertEquals(ControllerRole.OFPCRROLEMASTER, roleRequestInput.getRole());
- Assert.assertEquals(42, roleRequestInput.getVersion().intValue());
- Assert.assertEquals(84L, roleRequestInput.getXid().longValue());
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#sendRoleChangeRequest(org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole, java.math.BigInteger)}.
- * @throws Exception
- */
- @Test
- public void testSendRoleChangeRequest() throws Exception {
- Future<RpcResult<RoleRequestOutput>> roleRequestOutputFx = RoleUtil.sendRoleChangeRequest(session, OfpRole.BECOMEMASTER, generationId);
- Assert.assertNotNull(roleRequestOutputFx);
-
- ArgumentCaptor<RoleRequestInput> roleRequestCaptor = ArgumentCaptor.forClass(RoleRequestInput.class);
- Mockito.verify(connectionAdapter).roleRequest(roleRequestCaptor.capture());
-
- RoleRequest roleRequestInput = roleRequestCaptor.getValue();
- Assert.assertEquals(generationId, roleRequestInput.getGenerationId());
- Assert.assertEquals(RoleRequestInput.class, roleRequestInput.getImplementedInterface());
- Assert.assertEquals(ControllerRole.OFPCRROLEMASTER, roleRequestInput.getRole());
- Assert.assertEquals(42, roleRequestInput.getVersion().intValue());
- Assert.assertEquals(84L, roleRequestInput.getXid().longValue());
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#readGenerationIdFromDevice(org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext)}.
- * @throws Exception
- */
- @Test
- public void testReadGenerationIdFromDevice() throws Exception {
- BigInteger generationIdFromDevice = RoleUtil.readGenerationIdFromDevice(session).get();
- Assert.assertEquals(generationId, generationIdFromDevice);
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#getNextGenerationId(java.math.BigInteger)}.
- */
- @Test
- public void testGetNextGenerationId() {
- BigInteger[] src = new BigInteger[] {
- BigInteger.ZERO,
- BigInteger.ONE,
- OFRoleManager.MAX_GENERATION_ID.subtract(BigInteger.ONE),
- OFRoleManager.MAX_GENERATION_ID
- };
-
- BigInteger[] out = new BigInteger[] {
- BigInteger.ONE,
- BigInteger.valueOf(2L),
- OFRoleManager.MAX_GENERATION_ID,
- BigInteger.ZERO
- };
-
- for (int i = 0; i < src.length; i++) {
- BigInteger nextGenerationId = RoleUtil.getNextGenerationId(src[i]);
- Assert.assertEquals(out[i], nextGenerationId);
- }
- }
-
- /**
- * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#makeCheckedRuleRequestFxResult(com.google.common.util.concurrent.ListenableFuture)}.
- * @throws Exception
- */
- @Test
- public void testMakeCheckedRuleRequestFxResult() throws Exception {
- String message = "me sooo naughty!";
- try {
- RoleUtil.makeCheckedRuleRequestFxResult(Futures.<Boolean>immediateFailedFuture(new Exception(message))).checkedGet();
- } catch (Exception e) {
- Assert.assertEquals(RolePushException.class, e.getClass());
- Assert.assertEquals(ExecutionException.class, e.getCause().getClass());
- Assert.assertEquals(Exception.class, e.getCause().getCause().getClass());
- Assert.assertNull(e.getCause().getCause().getCause());
- Assert.assertEquals(message, e.getCause().getCause().getMessage());
- }
-
- try {
- RoleUtil.makeCheckedRuleRequestFxResult(Futures.<Boolean>immediateFailedFuture(new RolePushException(message))).checkedGet();
- } catch (Exception e) {
- Assert.assertEquals(RolePushException.class, e.getClass());
- Assert.assertNull(e.getCause());
- Assert.assertEquals(message, e.getMessage());
- }
-
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.openflowplugin.openflow.md.util;
-
-import java.util.Queue;
-import java.util.concurrent.ArrayBlockingQueue;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
-import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener;
-import org.opendaylight.openflowplugin.openflow.md.queue.WrapperQueueImpl;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@RunWith(MockitoJUnitRunner.class)
-public class WrapperQueueImplTest {
-
- protected static final Logger LOG = LoggerFactory
- .getLogger(WrapperQueueImplTest.class);
-
- @Mock
- private ConnectionConductor connectionConductor;
-
- @Mock
- private WaterMarkListener waterMarkListener;
-
- private WrapperQueueImpl<Integer> wrapperQueueImpl;
- private final int capacity = 100;
- private Queue<Integer> queueDefault;
- private int highWaterMark = 80;
- private int lowWaterMark = 65;
-
- /**
- * Setup before tests
- */
- @Before
- public void setUp() {
- queueDefault = new ArrayBlockingQueue<>(capacity);
-
- wrapperQueueImpl = new WrapperQueueImpl<>(capacity, queueDefault,
- waterMarkListener);
- }
-
- /**
- * Test for check if wrapper is not null
- */
- @Test
- public void testWrapperQueueImpl() {
- Assert.assertNotNull("Wrapper can not be null.", wrapperQueueImpl);
- }
-
- /**
- * Test for set setAutoRead on false on high water mark
- */
- @Test
- public void testReadOnHighWaterMark() {
-
- Assert.assertFalse("Wrapper must be not flooded at the start.",
- wrapperQueueImpl.isFlooded());
-
- push(79);
- Assert.assertFalse("Wrapper should not be flooded.",
- wrapperQueueImpl.isFlooded());
- Mockito.verify(waterMarkListener, Mockito.times(0)).onHighWaterMark();
-
- push(1);
- Assert.assertTrue("Wrapper should be flooded.",
- wrapperQueueImpl.isFlooded());
- Mockito.verify(waterMarkListener, Mockito.times(1)).onHighWaterMark();
-
- Assert.assertEquals(
- "Size of queue has to be equals to 80% of capacity of queue",
- highWaterMark, queueDefault.size());
- }
-
- /**
- *
- */
- private void push(int size) {
- for (int i = 0; i < size; i++) {
- try {
- wrapperQueueImpl.offer(i);
- } catch (Exception e) {
- LOG.error("Failed to offer item to queue.", e);
- }
- }
- }
-
- /**
- * Test for setAutoRead on true on low water mark
- */
- @Test
- public void testReadOnLowWaterMark() {
- Mockito.verify(waterMarkListener, Mockito.times(0)).onHighWaterMark();
- push(80);
- Assert.assertTrue("Wrapper should be flooded.",
- wrapperQueueImpl.isFlooded());
- Mockito.verify(waterMarkListener, Mockito.times(1)).onHighWaterMark();
-
- Assert.assertEquals(
- "Size of queue has to be equals to 80% of capacity of queue",
- highWaterMark, queueDefault.size());
-
- poll(14);
- Mockito.verify(waterMarkListener, Mockito.times(0)).onLowWaterMark();
- Assert.assertTrue("Wrapper should be still flooded.",
- wrapperQueueImpl.isFlooded());
-
- poll(1);
- Mockito.verify(waterMarkListener, Mockito.times(1)).onLowWaterMark();
-
- Assert.assertEquals(
- "Size of queue has to be equals to 65% on lowWaterMark.",
- lowWaterMark, queueDefault.size());
- Assert.assertFalse("Wrapped should be not flooded.",
- wrapperQueueImpl.isFlooded());
- }
-
- /**
- * Polling messages
- */
- private void poll(int size) {
-
- for (int i = 0; i < size; i++) {
- wrapperQueueImpl.poll();
- }
- }
-
- /**
- * Test for one cycle.
- */
- @Test
- public void testEndReadOnHWMStartOnLWM() {
-
- Assert.assertFalse("Wrapper should not be flooded",
- wrapperQueueImpl.isFlooded());
- Mockito.verify(waterMarkListener, Mockito.times(0)).onLowWaterMark();
- Mockito.verify(waterMarkListener, Mockito.times(0)).onHighWaterMark();
-
- push(81);
- Assert.assertTrue("Wrapper should be flooded",
- wrapperQueueImpl.isFlooded());
- Mockito.verify(waterMarkListener, Mockito.times(0)).onLowWaterMark();
- Mockito.verify(waterMarkListener, Mockito.times(1)).onHighWaterMark();
-
- poll(17);
- Assert.assertFalse("Wrapper should not be flooded",
- wrapperQueueImpl.isFlooded());
- Mockito.verify(waterMarkListener, Mockito.times(1)).onLowWaterMark();
- Mockito.verify(waterMarkListener, Mockito.times(1)).onHighWaterMark();
-
- push(18);
- Assert.assertTrue("Wrapper should be flooded",
- wrapperQueueImpl.isFlooded());
-
- Mockito.verify(waterMarkListener, Mockito.times(1)).onLowWaterMark();
- Mockito.verify(waterMarkListener, Mockito.times(2)).onHighWaterMark();
- }
-}
+++ /dev/null
-/*
- * 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.openflowplugin.statistics;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.List;
-import org.junit.Test;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.Action;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-
-/**
- * Created by Martin Bobak mbobak@cisco.com on 9/10/14.
- */
-public class MessageSpyCounterImplTest {
-
- private static final MessageSpyCounterImpl messageSpyCounter = new MessageSpyCounterImpl();
- private static final int EXPECTED_MSG_COUNT = 10;
-
- @Test
- public void testDumpMessageCounts() {
- DataContainer msg = new MockDataContainer();
- List<String> messageCounts = messageSpyCounter.dumpMessageCounts();
- assertEquals(EXPECTED_MSG_COUNT,messageCounts.size());
-
- assertEquals("FROM_SWITCH_ENQUEUED: no activity detected", messageCounts.get(0));
- messageSpyCounter.spyMessage(msg, MessageSpy.StatisticsGroup.FROM_SWITCH_ENQUEUED);
- messageCounts = messageSpyCounter.dumpMessageCounts();
- assertEquals("FROM_SWITCH_ENQUEUED: MSG[Action] -> +1 | 1", messageCounts.get(0));
-
- }
-
-
- private static class MockDataContainer implements DataContainer {
-
- @Override
- public Class<? extends DataContainer> getImplementedInterface() {
- return Action.class;
- }
- }
-}