1decf7ee3db52bf50ee12fdbd92cbfe4a31e8e76
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / device / DeviceContextImpl.java
1 /**
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.openflowplugin.impl.device;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import io.netty.util.HashedWheelTimer;
16 import io.netty.util.Timeout;
17 import java.math.BigInteger;
18 import java.util.Collection;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.concurrent.ConcurrentHashMap;
24 import javax.annotation.Nonnull;
25 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
26 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
27 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
28 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
30 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
31 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
32 import org.opendaylight.openflowjava.protocol.api.keys.MessageTypeKey;
33 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
34 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
35 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
36 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
37 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
38 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
39 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
40 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
41 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceContextClosedHandler;
42 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
43 import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
44 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
45 import org.opendaylight.openflowplugin.api.openflow.registry.ItemLifeCycleRegistry;
46 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
47 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
48 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
49 import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
50 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
51 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleKeeper;
52 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
53 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
54 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
55 import org.opendaylight.openflowplugin.extension.api.ConvertorMessageFromOFJava;
56 import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
57 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
58 import org.opendaylight.openflowplugin.extension.api.exception.ConversionException;
59 import org.opendaylight.openflowplugin.extension.api.path.MessagePath;
60 import org.opendaylight.openflowplugin.impl.common.ItemLifeCycleSourceImpl;
61 import org.opendaylight.openflowplugin.impl.common.NodeStaticReplyTranslatorUtil;
62 import org.opendaylight.openflowplugin.impl.device.listener.MultiMsgCollectorImpl;
63 import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl;
64 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
65 import org.opendaylight.openflowplugin.impl.registry.group.DeviceGroupRegistryImpl;
66 import org.opendaylight.openflowplugin.impl.registry.meter.DeviceMeterRegistryImpl;
67 import org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.experimenter.message.service.rev151020.ExperimenterMessageFromDevBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Error;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketIn;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.experimenter.core.ExperimenterDataOfChoice;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.experimenter.types.rev151020.experimenter.core.message.ExperimenterMessageOfChoice;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsData;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsDataBuilder;
96 import org.opendaylight.yangtools.yang.binding.DataObject;
97 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
98 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
99 import org.slf4j.Logger;
100 import org.slf4j.LoggerFactory;
101
102 /**
103  *
104  */
105 public class DeviceContextImpl implements DeviceContext, ExtensionConverterProviderKeeper {
106
107     private static final Logger LOG = LoggerFactory.getLogger(DeviceContextImpl.class);
108
109     // TODO: drain factor should be parametrized
110     public static final float REJECTED_DRAIN_FACTOR = 0.25f;
111     // TODO: low water mark factor should be parametrized
112     private static final float LOW_WATERMARK_FACTOR = 0.75f;
113     // TODO: high water mark factor should be parametrized
114     private static final float HIGH_WATERMARK_FACTOR = 0.95f;
115
116     private final ConnectionContext primaryConnectionContext;
117     private final DeviceState deviceState;
118     private final DataBroker dataBroker;
119     private final HashedWheelTimer hashedWheelTimer;
120     private final Map<SwitchConnectionDistinguisher, ConnectionContext> auxiliaryConnectionContexts;
121     private final TransactionChainManager transactionChainManager;
122     private final DeviceFlowRegistry deviceFlowRegistry;
123     private final DeviceGroupRegistry deviceGroupRegistry;
124     private final DeviceMeterRegistry deviceMeterRegistry;
125     private final Collection<DeviceContextClosedHandler> closeHandlers = new HashSet<>();
126     private final PacketInRateLimiter packetInLimiter;
127     private final MessageSpy messageSpy;
128     private final ItemLifeCycleKeeper flowLifeCycleKeeper;
129     private NotificationPublishService notificationPublishService;
130     private NotificationService notificationService;
131     private final OutboundQueue outboundQueueProvider;
132     private Timeout barrierTaskTimeout;
133     private final MessageTranslator<PortGrouping, FlowCapableNodeConnector> portStatusTranslator;
134     private final MessageTranslator<PacketInMessage, PacketReceived> packetInTranslator;
135     private final MessageTranslator<FlowRemoved, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved> flowRemovedTranslator;
136     private final TranslatorLibrary translatorLibrary;
137     private Map<Long, NodeConnectorRef> nodeConnectorCache;
138     private ItemLifeCycleRegistry itemLifeCycleSourceRegistry;
139     private RpcContext rpcContext;
140     private ExtensionConverterProvider extensionConverterProvider;
141
142
143     @VisibleForTesting
144     DeviceContextImpl(@Nonnull final ConnectionContext primaryConnectionContext,
145                       @Nonnull final DeviceState deviceState,
146                       @Nonnull final DataBroker dataBroker,
147                       @Nonnull final HashedWheelTimer hashedWheelTimer,
148                       @Nonnull final MessageSpy _messageSpy,
149                       @Nonnull final OutboundQueueProvider outboundQueueProvider,
150                       @Nonnull final TranslatorLibrary translatorLibrary,
151                       @Nonnull final TransactionChainManager transactionChainManager) {
152         this.primaryConnectionContext = Preconditions.checkNotNull(primaryConnectionContext);
153         this.deviceState = Preconditions.checkNotNull(deviceState);
154         this.dataBroker = Preconditions.checkNotNull(dataBroker);
155         this.hashedWheelTimer = Preconditions.checkNotNull(hashedWheelTimer);
156         this.outboundQueueProvider = Preconditions.checkNotNull(outboundQueueProvider);
157         this.transactionChainManager = Preconditions.checkNotNull(transactionChainManager);
158         auxiliaryConnectionContexts = new HashMap<>();
159         deviceFlowRegistry = new DeviceFlowRegistryImpl();
160         deviceGroupRegistry = new DeviceGroupRegistryImpl();
161         deviceMeterRegistry = new DeviceMeterRegistryImpl();
162         messageSpy = _messageSpy;
163
164         packetInLimiter = new PacketInRateLimiter(primaryConnectionContext.getConnectionAdapter(),
165                 /*initial*/ 1000, /*initial*/2000, messageSpy, REJECTED_DRAIN_FACTOR);
166
167         this.translatorLibrary = translatorLibrary;
168         portStatusTranslator = translatorLibrary.lookupTranslator(
169                 new TranslatorKey(deviceState.getVersion(), PortGrouping.class.getName()));
170         packetInTranslator = translatorLibrary.lookupTranslator(
171                 new TranslatorKey(deviceState.getVersion(), PacketIn.class.getName()));
172         flowRemovedTranslator = translatorLibrary.lookupTranslator(
173                 new TranslatorKey(deviceState.getVersion(), FlowRemoved.class.getName()));
174
175
176         nodeConnectorCache = new ConcurrentHashMap<>();
177
178         itemLifeCycleSourceRegistry = new ItemLifeCycleRegistryImpl();
179         flowLifeCycleKeeper = new ItemLifeCycleSourceImpl();
180         itemLifeCycleSourceRegistry.registerLifeCycleSource(flowLifeCycleKeeper);
181     }
182
183     /**
184      * This method is called from {@link DeviceManagerImpl} only. So we could say "posthandshake process finish"
185      * and we are able to set a scheduler for an automatic transaction submitting by time (0,5sec).
186      */
187     void initialSubmitTransaction() {
188         transactionChainManager.initialSubmitWriteTransaction();
189     }
190
191     /**
192      * This method is called fron
193      */
194     void cancelTransaction() {
195         transactionChainManager.cancelWriteTransaction();
196     }
197
198     @Override
199     public Long getReservedXid() {
200         return outboundQueueProvider.reserveEntry();
201     }
202
203     @Override
204     public void addAuxiliaryConenctionContext(final ConnectionContext connectionContext) {
205         final SwitchConnectionDistinguisher connectionDistinguisher = createConnectionDistinguisher(connectionContext);
206         auxiliaryConnectionContexts.put(connectionDistinguisher, connectionContext);
207     }
208
209     private static SwitchConnectionDistinguisher createConnectionDistinguisher(final ConnectionContext connectionContext) {
210         return new SwitchConnectionCookieOFImpl(connectionContext.getFeatures().getAuxiliaryId());
211     }
212
213     @Override
214     public void removeAuxiliaryConenctionContext(final ConnectionContext connectionContext) {
215         // TODO Auto-generated method stub
216     }
217
218     @Override
219     public DeviceState getDeviceState() {
220         return deviceState;
221     }
222
223     @Override
224     public ReadTransaction getReadTransaction() {
225         return dataBroker.newReadOnlyTransaction();
226     }
227
228     @Override
229     public <T extends DataObject> void writeToTransaction(final LogicalDatastoreType store,
230                                                           final InstanceIdentifier<T> path, final T data) {
231         transactionChainManager.writeToTransaction(store, path, data);
232     }
233
234     @Override
235     public <T extends DataObject> void addDeleteToTxChain(final LogicalDatastoreType store, final InstanceIdentifier<T> path) {
236         transactionChainManager.addDeleteOperationTotTxChain(store, path);
237     }
238
239     @Override
240     public boolean submitTransaction() {
241         return transactionChainManager.submitWriteTransaction();
242     }
243
244     @Override
245     public ConnectionContext getPrimaryConnectionContext() {
246         return primaryConnectionContext;
247     }
248
249     @Override
250     public ConnectionContext getAuxiliaryConnectiobContexts(final BigInteger cookie) {
251         return auxiliaryConnectionContexts.get(new SwitchConnectionCookieOFImpl(cookie.longValue()));
252     }
253
254     @Override
255     public DeviceFlowRegistry getDeviceFlowRegistry() {
256         return deviceFlowRegistry;
257     }
258
259     @Override
260     public DeviceGroupRegistry getDeviceGroupRegistry() {
261         return deviceGroupRegistry;
262     }
263
264     @Override
265     public DeviceMeterRegistry getDeviceMeterRegistry() {
266         return deviceMeterRegistry;
267     }
268
269     @Override
270     public void processReply(final OfHeader ofHeader) {
271         if (ofHeader instanceof Error) {
272             messageSpy.spyMessage(ofHeader.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
273         } else {
274             messageSpy.spyMessage(ofHeader.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
275         }
276     }
277
278     @Override
279     public void processReply(final Xid xid, final List<MultipartReply> ofHeaderList) {
280         for (final MultipartReply multipartReply : ofHeaderList) {
281             messageSpy.spyMessage(multipartReply.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
282         }
283     }
284
285     @Override
286     public void processFlowRemovedMessage(final FlowRemoved flowRemoved) {
287         final ItemLifecycleListener itemLifecycleListener = flowLifeCycleKeeper.getItemLifecycleListener();
288         if (itemLifecycleListener != null) {
289             //1. translate to general flow (table, priority, match, cookie)
290             final org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved flowRemovedNotification =
291                     flowRemovedTranslator.translate(flowRemoved, this, null);
292             //2. create registry key
293             FlowRegistryKey flowRegKey = FlowRegistryKeyFactory.create(flowRemovedNotification);
294             //3. lookup flowId
295             final FlowDescriptor flowDescriptor = deviceFlowRegistry.retrieveIdForFlow(flowRegKey);
296             //4. if flowId present:
297             if (flowDescriptor != null) {
298                 // a) construct flow path
299                 KeyedInstanceIdentifier<Flow, FlowKey> flowPath = getDeviceState().getNodeInstanceIdentifier()
300                         .augmentation(FlowCapableNode.class)
301                         .child(Table.class, flowDescriptor.getTableKey())
302                         .child(Flow.class, new FlowKey(flowDescriptor.getFlowId()));
303                 // b) notify listener
304                 itemLifecycleListener.onRemoved(flowPath);
305             } else {
306                 LOG.debug("flow id not found: nodeId={} tableId={}, priority={}",
307                         getDeviceState().getNodeId(), flowRegKey.getTableId(), flowRemovedNotification.getPriority());
308             }
309         }
310     }
311
312     @Override
313     public void processPortStatusMessage(final PortStatusMessage portStatus) {
314         messageSpy.spyMessage(portStatus.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
315         final FlowCapableNodeConnector flowCapableNodeConnector = portStatusTranslator.translate(portStatus, this, null);
316
317         final KeyedInstanceIdentifier<NodeConnector, NodeConnectorKey> iiToNodeConnector = provideIIToNodeConnector(portStatus.getPortNo(), portStatus.getVersion());
318         if (portStatus.getReason().equals(PortReason.OFPPRADD) || portStatus.getReason().equals(PortReason.OFPPRMODIFY)) {
319             // because of ADD status node connector has to be created
320             final NodeConnectorBuilder nConnectorBuilder = new NodeConnectorBuilder().setKey(iiToNodeConnector.getKey());
321             nConnectorBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class, new FlowCapableNodeConnectorStatisticsDataBuilder().build());
322             nConnectorBuilder.addAugmentation(FlowCapableNodeConnector.class, flowCapableNodeConnector);
323             writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector, nConnectorBuilder.build());
324         } else if (portStatus.getReason().equals(PortReason.OFPPRDELETE)) {
325             addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector);
326         }
327         submitTransaction();
328     }
329
330     private KeyedInstanceIdentifier<NodeConnector, NodeConnectorKey> provideIIToNodeConnector(final long portNo, final short version) {
331         final InstanceIdentifier<Node> iiToNodes = deviceState.getNodeInstanceIdentifier();
332         final BigInteger dataPathId = deviceState.getFeatures().getDatapathId();
333         final NodeConnectorId nodeConnectorId = NodeStaticReplyTranslatorUtil.nodeConnectorId(dataPathId.toString(), portNo, version);
334         return iiToNodes.child(NodeConnector.class, new NodeConnectorKey(nodeConnectorId));
335     }
336
337     @Override
338     public void processPacketInMessage(final PacketInMessage packetInMessage) {
339         messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH);
340         final ConnectionAdapter connectionAdapter = getPrimaryConnectionContext().getConnectionAdapter();
341         final PacketReceived packetReceived = packetInTranslator.translate(packetInMessage, this, null);
342
343         if (packetReceived == null) {
344             LOG.debug("Received a null packet from switch {}", connectionAdapter.getRemoteAddress());
345             messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_TRANSLATE_SRC_FAILURE);
346             return;
347         } else {
348             messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_TRANSLATE_OUT_SUCCESS);
349         }
350
351         if (!packetInLimiter.acquirePermit()) {
352             LOG.debug("Packet limited");
353             // TODO: save packet into emergency slot if possible
354             messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PACKET_IN_LIMIT_REACHED_AND_DROPPED);
355             return;
356         }
357
358         final ListenableFuture<? extends Object> offerNotification = notificationPublishService.offerNotification(packetReceived);
359         if (NotificationPublishService.REJECTED.equals(offerNotification)) {
360             LOG.debug("notification offer rejected");
361             messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_NOTIFICATION_REJECTED);
362             packetInLimiter.drainLowWaterMark();
363             packetInLimiter.releasePermit();
364             return;
365         }
366
367         Futures.addCallback(offerNotification, new FutureCallback<Object>() {
368             @Override
369             public void onSuccess(final Object result) {
370                 messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
371                 packetInLimiter.releasePermit();
372             }
373
374             @Override
375             public void onFailure(final Throwable t) {
376                 messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_NOTIFICATION_REJECTED);
377                 LOG.debug("notification offer failed: {}", t.getMessage());
378                 LOG.trace("notification offer failed..", t);
379                 packetInLimiter.releasePermit();
380             }
381         });
382     }
383
384     @Override
385     public void processExperimenterMessage(ExperimenterMessage notification) {
386         // lookup converter
387         ExperimenterDataOfChoice vendorData = notification.getExperimenterDataOfChoice();
388         MessageTypeKey<? extends ExperimenterDataOfChoice> key = new MessageTypeKey<>(
389                 deviceState.getVersion(),
390                 (Class<? extends ExperimenterDataOfChoice>) vendorData.getImplementedInterface());
391         final ConvertorMessageFromOFJava<ExperimenterDataOfChoice, MessagePath> messageConverter = extensionConverterProvider.getMessageConverter(key);
392         if (messageConverter == null) {
393             LOG.warn("custom converter for {}[OF:{}] not found",
394                     notification.getExperimenterDataOfChoice().getImplementedInterface(),
395                     deviceState.getVersion());
396             return;
397         }
398         // build notification
399         final ExperimenterMessageOfChoice messageOfChoice;
400         try {
401             messageOfChoice = messageConverter.convert(vendorData, MessagePath.MESSAGE_NOTIFICATION);
402             final ExperimenterMessageFromDevBuilder experimenterMessageFromDevBld = new ExperimenterMessageFromDevBuilder()
403                 .setNode(new NodeRef(deviceState.getNodeInstanceIdentifier()))
404                     .setExperimenterMessageOfChoice(messageOfChoice);
405             // publish
406             notificationPublishService.offerNotification(experimenterMessageFromDevBld.build());
407         } catch (ConversionException e) {
408             LOG.warn("Conversion of experimenter notification failed", e);
409         }
410     }
411
412     @Override
413     public TranslatorLibrary oook() {
414         return translatorLibrary;
415     }
416
417     @Override
418     public HashedWheelTimer getTimer() {
419         return hashedWheelTimer;
420     }
421
422     @Override
423     public void close() {
424         LOG.debug("closing deviceContext: {}, nodeId:{}",
425                 getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress(),
426                 getDeviceState().getNodeId());
427
428         tearDown();
429
430         primaryConnectionContext.closeConnection(false);
431     }
432
433     private void tearDown() {
434         deviceState.setValid(false);
435
436         for (final ConnectionContext connectionContext : auxiliaryConnectionContexts.values()) {
437             connectionContext.closeConnection(false);
438         }
439
440         deviceGroupRegistry.close();
441         deviceFlowRegistry.close();
442         deviceMeterRegistry.close();
443
444         itemLifeCycleSourceRegistry.clear();
445
446
447         for (final DeviceContextClosedHandler deviceContextClosedHandler : closeHandlers) {
448             deviceContextClosedHandler.onDeviceContextClosed(this);
449         }
450
451         LOG.info("Closing transaction chain manager without cleaning inventory operational");
452         transactionChainManager.close();
453     }
454
455     @Override
456     public void onDeviceDisconnectedFromCluster() {
457         LOG.info("Removing device from operational and closing transaction Manager for device:{}", getDeviceState().getNodeId());
458         transactionChainManager.cleanupPostClosure();
459     }
460
461     @Override
462     public void onDeviceDisconnected(final ConnectionContext connectionContext) {
463         if (getPrimaryConnectionContext().equals(connectionContext)) {
464             try {
465                 tearDown();
466             } catch (final Exception e) {
467                 LOG.trace("Error closing device context.");
468             }
469         } else {
470             LOG.debug("auxiliary connection dropped: {}, nodeId:{}",
471                     connectionContext.getConnectionAdapter().getRemoteAddress(),
472                     getDeviceState().getNodeId());
473             final SwitchConnectionDistinguisher connectionDistinguisher = createConnectionDistinguisher(connectionContext);
474             auxiliaryConnectionContexts.remove(connectionDistinguisher);
475         }
476     }
477
478     @Override
479     public void setCurrentBarrierTimeout(final Timeout timeout) {
480         barrierTaskTimeout = timeout;
481     }
482
483     @Override
484     public Timeout getBarrierTaskTimeout() {
485         return barrierTaskTimeout;
486     }
487
488     @Override
489     public void setNotificationService(final NotificationService notificationServiceParam) {
490         notificationService = notificationServiceParam;
491     }
492
493     @Override
494     public void setNotificationPublishService(final NotificationPublishService notificationPublishService) {
495         this.notificationPublishService = notificationPublishService;
496     }
497
498     @Override
499     public MessageSpy getMessageSpy() {
500         return messageSpy;
501     }
502
503     @Override
504     public void addDeviceContextClosedHandler(final DeviceContextClosedHandler deviceContextClosedHandler) {
505         closeHandlers.add(deviceContextClosedHandler);
506     }
507
508     @Override
509     public void onPublished() {
510         primaryConnectionContext.getConnectionAdapter().setPacketInFiltering(false);
511         for (final ConnectionContext switchAuxConnectionContext : auxiliaryConnectionContexts.values()) {
512             switchAuxConnectionContext.getConnectionAdapter().setPacketInFiltering(false);
513         }
514     }
515
516     @Override
517     public MultiMsgCollector getMultiMsgCollector(final RequestContext<List<MultipartReply>> requestContext) {
518         return new MultiMsgCollectorImpl(this, requestContext);
519     }
520
521     @Override
522     public NodeConnectorRef lookupNodeConnectorRef(Long portNumber) {
523         return nodeConnectorCache.get(portNumber);
524     }
525
526     @Override
527     public void storeNodeConnectorRef(final Long portNumber, final NodeConnectorRef nodeConnectorRef) {
528         nodeConnectorCache.put(
529                 Preconditions.checkNotNull(portNumber),
530                 Preconditions.checkNotNull(nodeConnectorRef));
531     }
532
533     @Override
534     public void updatePacketInRateLimit(long upperBound) {
535         packetInLimiter.changeWaterMarks((int) (LOW_WATERMARK_FACTOR * upperBound), (int) (HIGH_WATERMARK_FACTOR * upperBound));
536     }
537
538     @Override
539     public ItemLifeCycleRegistry getItemLifeCycleSourceRegistry() {
540         return itemLifeCycleSourceRegistry;
541     }
542
543     @Override
544     public void setRpcContext(RpcContext rpcContext) {
545         this.rpcContext = rpcContext;
546     }
547
548     @Override
549     public RpcContext getRpcContext() {
550         return rpcContext;
551     }
552
553     @Override
554     public void setExtensionConverterProvider(ExtensionConverterProvider extensionConverterProvider) {
555         this.extensionConverterProvider = extensionConverterProvider;
556     }
557
558     @Override
559     public ExtensionConverterProvider getExtensionConverterProvider() {
560         return extensionConverterProvider;
561     }
562 }