AnyMessageTypeListener renamed to OpenflowMessageListenerFacade
[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 io.netty.util.TimerTask;
16 import java.math.BigInteger;
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.TimeUnit;
23 import java.util.concurrent.atomic.AtomicLong;
24 import javax.annotation.Nonnull;
25 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
26 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
29 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
30 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
31 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
32 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
33 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
34 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
35 import org.opendaylight.openflowplugin.api.openflow.device.exception.DeviceDataException;
36 import org.opendaylight.openflowplugin.api.openflow.device.listener.OpenflowMessageListenerFacade;
37 import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
38 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
39 import org.opendaylight.openflowplugin.impl.translator.PacketReceivedTranslator;
40 import org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Error;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableFeatures;
50 import org.opendaylight.yangtools.yang.binding.ChildOf;
51 import org.opendaylight.yangtools.yang.binding.DataObject;
52 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
53 import org.opendaylight.yangtools.yang.common.RpcError;
54 import org.opendaylight.yangtools.yang.common.RpcResult;
55 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  *
61  */
62 public class DeviceContextImpl implements DeviceContext {
63
64     private static final Logger LOG = LoggerFactory.getLogger(DeviceContextImpl.class);
65
66     private final ConnectionContext primaryConnectionContext;
67     private final DeviceState deviceState;
68     private final DataBroker dataBroker;
69     private final XidGenerator xidGenerator;
70     private final HashedWheelTimer hashedWheelTimer;
71     private Map<Long, RequestContext> requests = new TreeMap<>();
72
73     private final Map<SwitchConnectionDistinguisher, ConnectionContext> auxiliaryConnectionContexts;
74     private final TransactionChainManager txChainManager;
75     private TranslatorLibrary translatorLibrary;
76     private OpenflowMessageListenerFacade openflowMessageListenerFacade;
77
78     @VisibleForTesting
79     DeviceContextImpl(@Nonnull final ConnectionContext primaryConnectionContext,
80                       @Nonnull final DeviceState deviceState, @Nonnull final DataBroker dataBroker,
81                       @Nonnull final HashedWheelTimer hashedWheelTimer) {
82         this.primaryConnectionContext = Preconditions.checkNotNull(primaryConnectionContext);
83         this.deviceState = Preconditions.checkNotNull(deviceState);
84         this.dataBroker = Preconditions.checkNotNull(dataBroker);
85         this.hashedWheelTimer = Preconditions.checkNotNull(hashedWheelTimer);
86         xidGenerator = new XidGenerator();
87         txChainManager = new TransactionChainManager(dataBroker, 500L);
88         auxiliaryConnectionContexts = new HashMap<>();
89         requests = new HashMap<>();
90     }
91
92     /**
93      * This method is called from {@link DeviceManagerImpl} only. So we could say "posthandshake process finish"
94      * and we are able to set a scheduler for an automatic transaction submitting by time (0,5sec).
95      */
96     void submitTransaction() {
97         txChainManager.submitTransaction();
98         txChainManager.enableCounter();
99         hashedWheelTimer.newTimeout(new TimerTask() {
100             @Override
101             public void run(final Timeout timeout) throws Exception {
102                 submitTransaction();
103             }
104         }, 0, TimeUnit.MILLISECONDS);
105     }
106
107     @Override
108     public <M extends ChildOf<DataObject>> void onMessage(final M message, final RequestContext requestContext) {
109         // TODO Auto-generated method stub
110
111     }
112
113     @Override
114     public void addAuxiliaryConenctionContext(final ConnectionContext connectionContext) {
115         final SwitchConnectionDistinguisher connectionDistinguisher = new SwitchConnectionCookieOFImpl(connectionContext.getFeatures().getAuxiliaryId());
116         auxiliaryConnectionContexts.put(connectionDistinguisher, connectionContext);
117     }
118
119     @Override
120     public void removeAuxiliaryConenctionContext(final ConnectionContext connectionContext) {
121         // TODO Auto-generated method stub
122     }
123
124     @Override
125     public DeviceState getDeviceState() {
126         return deviceState;
127     }
128
129     @Override
130     public ReadTransaction getReadTransaction() {
131         return dataBroker.newReadOnlyTransaction();
132     }
133
134     @Override
135     public <T extends DataObject> void writeToTransaction(final LogicalDatastoreType store,
136                                                           final InstanceIdentifier<T> path, final T data) {
137         txChainManager.writeToTransaction(store, path, data);
138     }
139
140     @Override
141     public TableFeatures getCapabilities() {
142         // TODO Auto-generated method stub
143         return null;
144     }
145
146     @Override
147     public ConnectionContext getPrimaryConnectionContext() {
148         return primaryConnectionContext;
149     }
150
151     @Override
152     public ConnectionContext getAuxiliaryConnectiobContexts(final BigInteger cookie) {
153         return auxiliaryConnectionContexts.get(new SwitchConnectionCookieOFImpl(cookie.longValue()));
154     }
155
156     @Override
157     public Xid getNextXid() {
158         return xidGenerator.generate();
159     }
160
161     public Map<Long, RequestContext> getRequests() {
162         return requests;
163     }
164
165     @Override
166     public void hookRequestCtx(final Xid xid, final RequestContext requestFutureContext) {
167         // TODO Auto-generated method stub
168         requests.put(xid.getValue(), requestFutureContext);
169     }
170
171     @Override
172     public void attachOpenflowMessageListener(final OpenflowMessageListenerFacade openflowMessageListenerFacade) {
173         this.openflowMessageListenerFacade = openflowMessageListenerFacade;
174         primaryConnectionContext.getConnectionAdapter().setMessageListener(openflowMessageListenerFacade);
175     }
176
177     @Override
178     public OpenflowMessageListenerFacade getOpenflowMessageListenerFacade() {
179         return this.openflowMessageListenerFacade;
180     }
181
182     @Override
183     public void processReply(final OfHeader ofHeader) {
184         final RequestContext requestContext = getRequests().get(ofHeader.getXid());
185         if (null != requestContext) {
186             final SettableFuture replyFuture = requestContext.getFuture();
187             getRequests().remove(ofHeader.getXid());
188             RpcResult<OfHeader> rpcResult;
189             if (ofHeader instanceof Error) {
190                 final Error error = (Error) ofHeader;
191                 final String message = "Operation on device failed";
192                 rpcResult = RpcResultBuilder
193                         .<OfHeader>failed()
194                         .withError(RpcError.ErrorType.APPLICATION, message, new DeviceDataException(message, error))
195                         .build();
196             } else {
197                 rpcResult = RpcResultBuilder
198                         .<OfHeader>success()
199                         .withResult(ofHeader)
200                         .build();
201             }
202
203             replyFuture.set(rpcResult);
204             try {
205                 requestContext.close();
206             } catch (final Exception e) {
207                 LOG.error("Closing RequestContext failed: ", e);
208             }
209         } else {
210             LOG.error("Can't find request context registered for xid : {}", ofHeader.getXid());
211         }
212     }
213
214     @Override
215     public void processReply(final Xid xid, final List<MultipartReply> ofHeaderList) {
216         final RequestContext requestContext = getRequests().get(xid.getValue());
217         if (null != requestContext) {
218             final SettableFuture replyFuture = requestContext.getFuture();
219             getRequests().remove(xid.getValue());
220             final RpcResult<List<MultipartReply>> rpcResult = RpcResultBuilder
221                     .<List<MultipartReply>>success()
222                     .withResult(ofHeaderList)
223                     .build();
224             replyFuture.set(rpcResult);
225             try {
226                 requestContext.close();
227             } catch (final Exception e) {
228                 LOG.error("Closing RequestContext failed: ", e);
229             }
230         } else {
231             LOG.error("Can't find request context registered for xid : {}", xid.getValue());
232         }
233     }
234
235     @Override
236     public void processException(final Xid xid, final DeviceDataException deviceDataException) {
237
238         LOG.trace("Processing exception for xid : {}", xid.getValue());
239
240         final RequestContext requestContext = getRequests().get(xid.getValue());
241
242         if (null != requestContext) {
243             final SettableFuture replyFuture = requestContext.getFuture();
244             getRequests().remove(xid.getValue());
245             final RpcResult<List<OfHeader>> rpcResult = RpcResultBuilder
246                     .<List<OfHeader>>failed()
247                     .withError(RpcError.ErrorType.APPLICATION, String.format("Message processing failed : %s", deviceDataException.getError()), deviceDataException)
248                     .build();
249             replyFuture.set(rpcResult);
250             try {
251                 requestContext.close();
252             } catch (final Exception e) {
253                 LOG.error("Closing RequestContext failed: ", e);
254             }
255         } else {
256             LOG.error("Can't find request context registered for xid : {}", xid.getValue());
257         }
258     }
259
260     @Override
261     public void processFlowRemovedMessage(final FlowRemoved flowRemoved) {
262         //TODO: will be defined later
263     }
264
265     @Override
266     public void processPortStatusMessage(final PortStatusMessage portStatus) {
267         final TranslatorKey translatorKey = new TranslatorKey(portStatus.getVersion(), PortStatusMessage.class.getName());
268         final MessageTranslator<PortStatusMessage, FlowCapableNodeConnector> messageTranslator = translatorLibrary.lookupTranslator(translatorKey);
269         final FlowCapableNodeConnector nodeConnector = messageTranslator.translate(portStatus, this, null);
270         //TODO write into datastore
271     }
272
273     @Override
274     public void processPacketInMessage(final PacketInMessage packetInMessage) {
275         final TranslatorKey translatorKey = new TranslatorKey(packetInMessage.getVersion(), PacketReceivedTranslator.class.getName());
276         final MessageTranslator<PacketInMessage, PacketReceived> messageTranslator = translatorLibrary.lookupTranslator(translatorKey);
277         final PacketReceived packetReceived = messageTranslator.translate(packetInMessage, this, null);
278         //TODO publish to MD-SAL
279     }
280
281     @Override
282     public TranslatorLibrary oook() {
283         return translatorLibrary;
284     }
285
286     @Override
287     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
288         this.translatorLibrary = translatorLibrary;
289     }
290
291     @Override
292     public HashedWheelTimer getTimer() {
293         return this.hashedWheelTimer;
294     }
295
296
297     private class XidGenerator {
298
299         private final AtomicLong xid = new AtomicLong(0);
300
301         public Xid generate() {
302             return new Xid(xid.incrementAndGet());
303         }
304     }
305
306     @Override
307     public RequestContext extractNextOutstandingMessage(long barrierXid) {
308         RequestContext nextMessage = null;
309         Iterator<Long> keyIterator = requests.keySet().iterator();
310         if (keyIterator.hasNext()) {
311             Long oldestXid = keyIterator.next();
312             if (oldestXid < barrierXid) {
313                 nextMessage = requests.remove(oldestXid);
314             }
315         }
316         return nextMessage;
317     }
318 }