c19041aaeaac196cc7bc9d718422218d3681999f
[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.net.InetSocketAddress;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.TreeMap;
26 import java.util.concurrent.ArrayBlockingQueue;
27 import java.util.concurrent.BlockingQueue;
28 import java.util.concurrent.ExecutionException;
29 import javax.annotation.Nonnull;
30 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
31 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
32 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
33 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
34 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
35 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
36 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
37 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
38 import org.opendaylight.openflowplugin.api.openflow.connection.ThrottledNotificationsOfferer;
39 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
40 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
41 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
42 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
43 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
44 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
45 import org.opendaylight.openflowplugin.api.openflow.device.exception.DeviceDataException;
46 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceContextClosedHandler;
47 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceDisconnectedHandler;
48 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
49 import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
50 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
51 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
52 import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
53 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
54 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
55 import org.opendaylight.openflowplugin.impl.common.NodeStaticReplyTranslatorUtil;
56 import org.opendaylight.openflowplugin.impl.device.listener.MultiMsgCollectorImpl;
57 import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl;
58 import org.opendaylight.openflowplugin.impl.registry.group.DeviceGroupRegistryImpl;
59 import org.opendaylight.openflowplugin.impl.registry.meter.DeviceMeterRegistryImpl;
60 import org.opendaylight.openflowplugin.impl.services.RequestContextUtil;
61 import org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Error;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketIn;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsData;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsDataBuilder;
80 import org.opendaylight.yangtools.yang.binding.ChildOf;
81 import org.opendaylight.yangtools.yang.binding.DataObject;
82 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
83 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
84 import org.opendaylight.yangtools.yang.common.RpcError;
85 import org.opendaylight.yangtools.yang.common.RpcResult;
86 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
89
90 /**
91  *
92  */
93 public class DeviceContextImpl implements DeviceContext {
94
95     private static final Logger LOG = LoggerFactory.getLogger(DeviceContextImpl.class);
96     public static final String DEVICE_DISCONNECTED = "Device disconnected.";
97
98     private final ConnectionContext primaryConnectionContext;
99     private final DeviceState deviceState;
100     private final DataBroker dataBroker;
101     private final HashedWheelTimer hashedWheelTimer;
102     private final Map<Long, RequestContext> requests = new TreeMap<>();
103
104     private final Map<SwitchConnectionDistinguisher, ConnectionContext> auxiliaryConnectionContexts;
105     private final TransactionChainManager txChainManager;
106     private TranslatorLibrary translatorLibrary;
107     private final DeviceFlowRegistry deviceFlowRegistry;
108     private final DeviceGroupRegistry deviceGroupRegistry;
109     private final DeviceMeterRegistry deviceMeterRegistry;
110     private Timeout barrierTaskTimeout;
111     private NotificationService notificationService;
112     private final MessageSpy<Class<?>> messageSpy;
113     private DeviceDisconnectedHandler deviceDisconnectedHandler;
114     private final Collection<DeviceContextClosedHandler> closeHandlers = new HashSet<>();
115     private NotificationPublishService notificationPublishService;
116     private final ThrottledNotificationsOfferer throttledConnectionsHolder;
117     private final BlockingQueue<PacketReceived> bumperQueue;
118     private final OutboundQueue outboundQueueProvider;
119
120     @Override
121     public MultiMsgCollector getMultiMsgCollector() {
122         return multiMsgCollector;
123     }
124
125     @Override
126     public Long getReservedXid() {
127         return outboundQueueProvider.reserveEntry();
128     }
129
130     private final MultiMsgCollector multiMsgCollector = new MultiMsgCollectorImpl();
131
132
133     @VisibleForTesting
134     DeviceContextImpl(@Nonnull final ConnectionContext primaryConnectionContext,
135                       @Nonnull final DeviceState deviceState,
136                       @Nonnull final DataBroker dataBroker,
137                       @Nonnull final HashedWheelTimer hashedWheelTimer,
138                       @Nonnull final MessageSpy _messageSpy,
139                       @Nonnull final ThrottledNotificationsOfferer throttledConnectionsHolder) {
140         this.primaryConnectionContext = Preconditions.checkNotNull(primaryConnectionContext);
141         this.deviceState = Preconditions.checkNotNull(deviceState);
142         this.dataBroker = Preconditions.checkNotNull(dataBroker);
143         this.hashedWheelTimer = Preconditions.checkNotNull(hashedWheelTimer);
144         txChainManager = new TransactionChainManager(dataBroker, hashedWheelTimer, 500L, 500L);
145         auxiliaryConnectionContexts = new HashMap<>();
146         deviceFlowRegistry = new DeviceFlowRegistryImpl();
147         deviceGroupRegistry = new DeviceGroupRegistryImpl();
148         deviceMeterRegistry = new DeviceMeterRegistryImpl();
149         messageSpy = _messageSpy;
150         this.throttledConnectionsHolder = throttledConnectionsHolder;
151         bumperQueue = new ArrayBlockingQueue<>(5000);
152         multiMsgCollector.setDeviceReplyProcessor(this);
153         outboundQueueProvider = Preconditions.checkNotNull(primaryConnectionContext.getOutboundQueueProvider());
154     }
155
156     /**
157      * This method is called from {@link DeviceManagerImpl} only. So we could say "posthandshake process finish"
158      * and we are able to set a scheduler for an automatic transaction submitting by time (0,5sec).
159      */
160     void submitTransaction() {
161         txChainManager.enableSubmit();
162         txChainManager.submitTransaction();
163     }
164
165     @Override
166     public <M extends ChildOf<DataObject>> void onMessage(final M message, final RequestContext requestContext) {
167         // TODO Auto-generated method stub
168
169     }
170
171     @Override
172     public void addAuxiliaryConenctionContext(final ConnectionContext connectionContext) {
173         final SwitchConnectionDistinguisher connectionDistinguisher = createConnectionDistinguisher(connectionContext);
174         auxiliaryConnectionContexts.put(connectionDistinguisher, connectionContext);
175     }
176
177     private static SwitchConnectionDistinguisher createConnectionDistinguisher(final ConnectionContext connectionContext) {
178         return new SwitchConnectionCookieOFImpl(connectionContext.getFeatures().getAuxiliaryId());
179     }
180
181     @Override
182     public void removeAuxiliaryConenctionContext(final ConnectionContext connectionContext) {
183         // TODO Auto-generated method stub
184     }
185
186     @Override
187     public DeviceState getDeviceState() {
188         return deviceState;
189     }
190
191     @Override
192     public ReadTransaction getReadTransaction() {
193         return dataBroker.newReadOnlyTransaction();
194     }
195
196     @Override
197     public <T extends DataObject> void writeToTransaction(final LogicalDatastoreType store,
198                                                           final InstanceIdentifier<T> path, final T data) {
199         txChainManager.writeToTransaction(store, path, data);
200     }
201
202     @Override
203     public <T extends DataObject> void addDeleteToTxChain(final LogicalDatastoreType store, final InstanceIdentifier<T> path) {
204         txChainManager.addDeleteOperationTotTxChain(store, path);
205     }
206
207     @Override
208     public ConnectionContext getPrimaryConnectionContext() {
209         return primaryConnectionContext;
210     }
211
212     @Override
213     public ConnectionContext getAuxiliaryConnectiobContexts(final BigInteger cookie) {
214         return auxiliaryConnectionContexts.get(new SwitchConnectionCookieOFImpl(cookie.longValue()));
215     }
216
217     @Override
218     public RequestContext lookupRequest(final Xid xid) {
219         synchronized (requests) {
220             return requests.get(xid.getValue());
221         }
222     }
223
224     @Override
225     public int getNumberOfOutstandingRequests() {
226         synchronized (requests) {
227             return requests.size();
228         }
229     }
230
231     @Override
232     public void hookRequestCtx(final Xid xid, final RequestContext requestFutureContext) {
233         synchronized (requests) {
234             requests.put(xid.getValue(), requestFutureContext);
235         }
236     }
237
238     @Override
239     public RequestContext unhookRequestCtx(final Xid xid) {
240         synchronized (requests) {
241             return requests.remove(xid.getValue());
242         }
243     }
244
245     @Override
246     public DeviceFlowRegistry getDeviceFlowRegistry() {
247         return deviceFlowRegistry;
248     }
249
250     @Override
251     public DeviceGroupRegistry getDeviceGroupRegistry() {
252         return deviceGroupRegistry;
253     }
254
255     @Override
256     public DeviceMeterRegistry getDeviceMeterRegistry() {
257         return deviceMeterRegistry;
258     }
259
260     @Override
261     public void processReply(final OfHeader ofHeader) {
262         final RequestContext requestContext = requests.remove(ofHeader.getXid());
263         if (null != requestContext) {
264             RpcResult<OfHeader> rpcResult;
265             if (ofHeader instanceof Error) {
266                 //TODO : this is the point, where we can discover that add flow operation failed and where we should
267                 //TODO : remove this flow from deviceFlowRegistry
268                 final Error error = (Error) ofHeader;
269                 final String message = "Operation on device failed with xid " + ofHeader.getXid() + ".";
270                 rpcResult = RpcResultBuilder
271                         .<OfHeader>failed()
272                         .withError(RpcError.ErrorType.APPLICATION, message, new DeviceDataException(message, error))
273                         .build();
274                 messageSpy.spyMessage(ofHeader.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
275             } else {
276                 rpcResult = RpcResultBuilder
277                         .<OfHeader>success()
278                         .withResult(ofHeader)
279                         .build();
280                 messageSpy.spyMessage(ofHeader.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
281             }
282
283             requestContext.setResult(rpcResult);
284             try {
285                 requestContext.close();
286             } catch (final Exception e) {
287                 LOG.warn("Closing RequestContext failed: {}", e.getMessage());
288                 LOG.debug("Closing RequestContext failed.. ", e);
289             }
290         } else {
291             LOG.warn("Can't find request context registered for xid : {}. Type of reply: {}. From address: {}", ofHeader.getXid(), ofHeader.getClass().getName(),
292                     getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress());
293         }
294     }
295
296     @Override
297     public void processReply(final Xid xid, final List<MultipartReply> ofHeaderList) {
298         final RequestContext requestContext;
299         synchronized (requests) {
300             requestContext = requests.remove(xid.getValue());
301         }
302         if (null != requestContext) {
303             final RpcResult<List<MultipartReply>> rpcResult = RpcResultBuilder
304                     .<List<MultipartReply>>success()
305                     .withResult(ofHeaderList)
306                     .build();
307             requestContext.setResult(rpcResult);
308             for (final MultipartReply multipartReply : ofHeaderList) {
309                 messageSpy.spyMessage(multipartReply.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
310             }
311
312             unhookRequestCtx(xid);
313             try {
314                 requestContext.close();
315             } catch (final Exception e) {
316                 LOG.warn("Closing RequestContext failed: {}", e.getMessage());
317                 LOG.debug("Closing RequestContext failed.. ", e);
318             }
319         } else {
320             LOG.warn("Can't find request context registered for xid : {}. Type of reply: MULTIPART. From address: {}", xid.getValue(),
321                     getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress());
322         }
323     }
324
325     @Override
326     public void processException(final Xid xid, final DeviceDataException deviceDataException) {
327
328         LOG.trace("Processing exception for xid : {}", xid.getValue());
329
330         final RequestContext requestContext = requests.remove(xid.getValue());
331
332         if (null != requestContext) {
333             final RpcResult<List<OfHeader>> rpcResult = RpcResultBuilder
334                     .<List<OfHeader>>failed()
335                     .withError(RpcError.ErrorType.APPLICATION, String.format("Message processing failed : %s", deviceDataException.getError()), deviceDataException)
336                     .build();
337             requestContext.setResult(rpcResult);
338             messageSpy.spyMessage(deviceDataException.getClass(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
339             try {
340                 requestContext.close();
341             } catch (final Exception e) {
342                 LOG.warn("Closing RequestContext failed: ", e);
343                 LOG.debug("Closing RequestContext failed..", e);
344             }
345         } else {
346             LOG.warn("Can't find request context registered for xid : {}. Exception message {}",
347                     xid.getValue(), deviceDataException.getMessage());
348         }
349     }
350
351     @Override
352     public void processFlowRemovedMessage(final FlowRemoved flowRemoved) {
353         //TODO: will be defined later
354     }
355
356     @Override
357     public void processPortStatusMessage(final PortStatusMessage portStatus) {
358         messageSpy.spyMessage(portStatus.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
359         final TranslatorKey translatorKey = new TranslatorKey(portStatus.getVersion(), PortGrouping.class.getName());
360         final MessageTranslator<PortGrouping, FlowCapableNodeConnector> messageTranslator = translatorLibrary.lookupTranslator(translatorKey);
361         final FlowCapableNodeConnector flowCapableNodeConnector = messageTranslator.translate(portStatus, this, null);
362
363         final KeyedInstanceIdentifier<NodeConnector, NodeConnectorKey> iiToNodeConnector = provideIIToNodeConnector(portStatus.getPortNo(), portStatus.getVersion());
364         if (portStatus.getReason().equals(PortReason.OFPPRADD) || portStatus.getReason().equals(PortReason.OFPPRMODIFY)) {
365             // because of ADD status node connector has to be created
366             final NodeConnectorBuilder nConnectorBuilder = new NodeConnectorBuilder().setKey(iiToNodeConnector.getKey());
367             nConnectorBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class, new FlowCapableNodeConnectorStatisticsDataBuilder().build());
368             nConnectorBuilder.addAugmentation(FlowCapableNodeConnector.class, flowCapableNodeConnector);
369             writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector, nConnectorBuilder.build());
370         } else if (portStatus.getReason().equals(PortReason.OFPPRDELETE)) {
371             addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, iiToNodeConnector);
372         }
373     }
374
375     private KeyedInstanceIdentifier<NodeConnector, NodeConnectorKey> provideIIToNodeConnector(final long portNo, final short version) {
376         final InstanceIdentifier<Node> iiToNodes = deviceState.getNodeInstanceIdentifier();
377         final BigInteger dataPathId = deviceState.getFeatures().getDatapathId();
378         final NodeConnectorId nodeConnectorId = NodeStaticReplyTranslatorUtil.nodeConnectorId(dataPathId.toString(), portNo, version);
379         return iiToNodes.child(NodeConnector.class, new NodeConnectorKey(nodeConnectorId));
380     }
381
382     @Override
383     public void processPacketInMessage(final PacketInMessage packetInMessage) {
384         messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH);
385
386         final TranslatorKey translatorKey = new TranslatorKey(packetInMessage.getVersion(), PacketIn.class.getName());
387         final MessageTranslator<PacketInMessage, PacketReceived> messageTranslator = translatorLibrary.lookupTranslator(translatorKey);
388         final PacketReceived packetReceived = messageTranslator.translate(packetInMessage, this, null);
389
390         if (packetReceived != null) {
391             messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_TRANSLATE_OUT_SUCCESS);
392         } else {
393             messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_TRANSLATE_SRC_FAILURE);
394             return;
395         }
396
397         ListenableFuture<?> listenableFuture = notificationPublishService.offerNotification(packetReceived);
398         if (NotificationPublishService.REJECTED.equals(listenableFuture)) {
399             LOG.debug("notification offer rejected");
400             messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_NOTIFICATION_REJECTED);
401         } else if (listenableFuture.isDone()) {
402             Object x = null;
403             try {
404                 x = listenableFuture.get();
405                 messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
406             } catch (InterruptedException e) {
407                 LOG.debug("notification offer interrupted: {}", e.getMessage());
408                 LOG.trace("notification offer interrupted..", e);
409             } catch (ExecutionException e) {
410                 LOG.debug("notification offer failed: {}", e.getMessage());
411                 LOG.trace("notification offer failed..", e);
412             } finally {
413                 if (null == x) {
414                     messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_NOTIFICATION_REJECTED);
415                 }
416             }
417         } else {
418             messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
419         }
420     }
421
422     private void applyThrottling(final PacketReceived packetReceived, final ConnectionAdapter connectionAdapter) {
423         final InetSocketAddress remoteAddress = connectionAdapter.getRemoteAddress();
424         LOG.debug("Notification offer refused by notification service.");
425         messageSpy.spyMessage(packetReceived.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE);
426         connectionAdapter.setAutoRead(false);
427
428         LOG.debug("Throttling ingress for {}", remoteAddress);
429         final ListenableFuture<Void> queueDone;
430
431         // adding first notification
432         bumperQueue.offer(packetReceived);
433         synchronized (bumperQueue) {
434             queueDone = throttledConnectionsHolder.applyThrottlingOnConnection(bumperQueue);
435         }
436         Futures.addCallback(queueDone, new FutureCallback<Void>() {
437             @Override
438             public void onSuccess(final Void result) {
439                 LOG.debug("Un - throttling ingress for {}", remoteAddress);
440                 connectionAdapter.setAutoRead(true);
441             }
442
443             @Override
444             public void onFailure(final Throwable t) {
445                 LOG.warn("failed to offer queued notification for {}: {}", remoteAddress, t.getMessage());
446                 LOG.debug("failed to offer queued notification for {}.. ", remoteAddress, t);
447             }
448         });
449     }
450
451     @Override
452     public TranslatorLibrary oook() {
453         return translatorLibrary;
454     }
455
456     @Override
457     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
458         this.translatorLibrary = translatorLibrary;
459     }
460
461     @Override
462     public HashedWheelTimer getTimer() {
463         return hashedWheelTimer;
464     }
465
466     @Override
467     public void close() throws Exception {
468         deviceState.setValid(false);
469
470         LOG.trace("Removing node {} from operational DS.", getDeviceState().getNodeId());
471         addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, getDeviceState().getNodeInstanceIdentifier());
472
473         deviceGroupRegistry.close();
474         deviceFlowRegistry.close();
475         deviceMeterRegistry.close();
476
477         if (primaryConnectionContext.getConnectionAdapter().isAlive()) {
478             primaryConnectionContext.setConnectionState(ConnectionContext.CONNECTION_STATE.RIP);
479             primaryConnectionContext.getConnectionAdapter().disconnect();
480         }
481         for (final Map.Entry<Long, RequestContext> entry : requests.entrySet()) {
482             RequestContextUtil.closeRequestContextWithRpcError(entry.getValue(), DEVICE_DISCONNECTED);
483         }
484         for (final ConnectionContext connectionContext : auxiliaryConnectionContexts.values()) {
485             if (connectionContext.getConnectionAdapter().isAlive()) {
486                 connectionContext.getConnectionAdapter().disconnect();
487             }
488         }
489         for (final DeviceContextClosedHandler deviceContextClosedHandler : closeHandlers) {
490             deviceContextClosedHandler.onDeviceContextClosed(this);
491         }
492
493     }
494
495     @Override
496     public void onDeviceDisconnected(final ConnectionContext connectionContext) {
497         if (this.getPrimaryConnectionContext().equals(connectionContext)) {
498             try {
499                 close();
500             } catch (final Exception e) {
501                 LOG.trace("Error closing device context.");
502             }
503             if (null != deviceDisconnectedHandler) {
504                 deviceDisconnectedHandler.onDeviceDisconnected(connectionContext);
505             }
506         } else {
507             final SwitchConnectionDistinguisher connectionDistinguisher = createConnectionDistinguisher(connectionContext);
508             auxiliaryConnectionContexts.remove(connectionDistinguisher);
509         }
510     }
511
512     @Override
513     public RequestContext extractNextOutstandingMessage(final long barrierXid) {
514         RequestContext nextMessage = null;
515         synchronized (requests) {
516             final Iterator<Long> keyIterator = requests.keySet().iterator();
517             if (keyIterator.hasNext()) {
518                 final Long oldestXid = keyIterator.next();
519                 if (oldestXid < barrierXid) {
520                     nextMessage = requests.remove(oldestXid);
521                 }
522             }
523         }
524         return nextMessage;
525     }
526
527     @Override
528     public void setCurrentBarrierTimeout(final Timeout timeout) {
529         barrierTaskTimeout = timeout;
530     }
531
532     @Override
533     public Timeout getBarrierTaskTimeout() {
534         return barrierTaskTimeout;
535     }
536
537     @Override
538     public void setNotificationService(final NotificationService notificationServiceParam) {
539         notificationService = notificationServiceParam;
540     }
541
542     @Override
543     public void setNotificationPublishService(final NotificationPublishService notificationPublishService) {
544         this.notificationPublishService = notificationPublishService;
545     }
546
547     @Override
548     public MessageSpy getMessageSpy() {
549         return messageSpy;
550     }
551
552     @Override
553     public void setDeviceDisconnectedHandler(final DeviceDisconnectedHandler deviceDisconnectedHandler) {
554         this.deviceDisconnectedHandler = deviceDisconnectedHandler;
555     }
556
557     @Override
558     public void addDeviceContextClosedHandler(final DeviceContextClosedHandler deviceContextClosedHandler) {
559         this.closeHandlers.add(deviceContextClosedHandler);
560     }
561
562     @Override
563     public void startGatheringOperationsToOneTransaction() {
564         txChainManager.startGatheringOperationsToOneTransaction();
565     }
566
567     @Override
568     public void commitOperationsGatheredInOneTransaction() {
569         txChainManager.commitOperationsGatheredInOneTransaction();
570     }
571
572 }