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