Merge "Wiring message processing to deviceContext"
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / device / DeviceManagerImpl.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 javax.annotation.CheckForNull;
11 import javax.annotation.Nonnull;
12 import java.util.*;
13 import java.util.concurrent.Future;
14 import java.util.concurrent.TimeUnit;
15
16 import com.google.common.base.Preconditions;
17 import com.google.common.util.concurrent.*;
18 import io.netty.util.HashedWheelTimer;
19 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
22 import org.opendaylight.openflowplugin.api.openflow.device.*;
23 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceContextReadyHandler;
24 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
25 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcManager;
26 import org.opendaylight.openflowplugin.impl.common.MultipartRequestInputFactory;
27 import org.opendaylight.openflowplugin.impl.common.NodeStaticReplyTranslatorUtil;
28 import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
29 import org.opendaylight.openflowplugin.impl.rpc.RequestContextImpl;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupFeatures;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterFeatures;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.MultipartReplyBody;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyDescCase;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupFeaturesCase;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterFeaturesCase;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableFeaturesCase;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.desc._case.MultipartReplyDesc;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.features._case.MultipartReplyGroupFeatures;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.features._case.MultipartReplyMeterFeatures;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeatures;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
49 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
50 import org.opendaylight.yangtools.yang.common.RpcError;
51 import org.opendaylight.yangtools.yang.common.RpcResult;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  *
57  */
58 public class DeviceManagerImpl implements DeviceManager {
59
60     private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
61
62     private static final long TICK_DURATION = 500; // 0.5 sec.
63
64     private final RpcManager rpcManager;
65     private final DataBroker dataBroker;
66     private final HashedWheelTimer hashedWheelTimer;
67     private RequestContextStack dummyRequestContextStack;
68
69
70     public DeviceManagerImpl (@Nonnull final RpcManager rpcManager, @Nonnull final DataBroker dataBroker) {
71         this.rpcManager = Preconditions.checkNotNull(rpcManager);
72         this.dataBroker = Preconditions.checkNotNull(dataBroker);
73         hashedWheelTimer = new HashedWheelTimer(TICK_DURATION, TimeUnit.MILLISECONDS, 10);
74
75         dummyRequestContextStack = new RequestContextStack() {
76             @Override
77             public <T> void forgetRequestContext(RequestContext<T> requestContext) {
78                 //NOOP
79             }
80             @Override
81             public <T> SettableFuture<RpcResult<T>> storeOrFail(RequestContext<T> data) {
82                 return data.getFuture();
83             }
84             @Override
85             public <T> RequestContext<T> createRequestContext() {
86                 return new RequestContextImpl<>(this);
87             }
88         };
89     }
90
91     @Override
92     public void deviceConnected(@CheckForNull final ConnectionContext connectionContext) {
93         Preconditions.checkArgument(connectionContext != null);
94         final DeviceState deviceState = new DeviceStateImpl(connectionContext.getFeatures(), connectionContext.getNodeId());
95         final DeviceContextImpl deviceContext = new DeviceContextImpl(connectionContext, deviceState, dataBroker, hashedWheelTimer);
96         final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
97                 connectionContext.getConnectionAdapter(), deviceContext);
98         connectionContext.getConnectionAdapter().setMessageListener(messageListener);
99
100         final Xid nodeDescXid = deviceContext.getNextXid();
101         final ListenableFuture<Collection<MultipartReply>> replyDesc = getNodeStaticInfo(nodeDescXid, messageListener,
102                 MultipartType.OFPMPDESC, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
103
104         final Xid nodeMeterXid = deviceContext.getNextXid();
105         final ListenableFuture<Collection<MultipartReply>> replyMeterFeature = getNodeStaticInfo(nodeMeterXid, messageListener,
106                 MultipartType.OFPMPMETERFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
107
108         final Xid nodeGroupXid = deviceContext.getNextXid();
109         final ListenableFuture<Collection<MultipartReply>> replyGroupFeatures = getNodeStaticInfo(nodeGroupXid, messageListener,
110                 MultipartType.OFPMPGROUPFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
111
112         final Xid nodeTableXid = deviceContext.getNextXid();
113         final ListenableFuture<Collection<MultipartReply>> replyTableFeatures = getNodeStaticInfo(nodeTableXid, messageListener,
114                 MultipartType.OFPMPTABLEFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
115
116         final ListenableFuture<List<Collection<MultipartReply>>> deviceFeaturesFuture =
117                 Futures.allAsList(Arrays.asList(replyDesc, replyMeterFeature, replyGroupFeatures, replyTableFeatures));
118         Futures.addCallback(deviceFeaturesFuture, new FutureCallback<List<Collection<MultipartReply>>>() {
119             @Override
120             public void onSuccess(final List<Collection<MultipartReply>> result) {
121                 // FIXME : add statistics
122                 rpcManager.deviceConnected(deviceContext);
123                 deviceContext.submitTransaction();
124             }
125
126             @Override
127             public void onFailure(final Throwable t) {
128                 // FIXME : remove session
129             }
130         });
131     }
132
133     @Override
134     public void addRequestContextReadyHandler(final DeviceContextReadyHandler deviceContextReadyHandler) {
135         // TODO Auto-generated method stub
136     }
137
138     private ListenableFuture<Collection<MultipartReply>> getNodeStaticInfo(final Xid xid,
139             final MultiMsgCollector multiMsgCollector, final MultipartType type, final DeviceContext dContext,
140             final InstanceIdentifier<Node> nodeII, final short version) {
141         final ListenableFuture<Collection<MultipartReply>> future = multiMsgCollector.registerMultipartMsg(xid.getValue());
142
143         RequestContext<List<MultipartReply>> requestContext = dummyRequestContextStack.createRequestContext();
144         dContext.hookRequestCtx(xid, requestContext);
145         Futures.addCallback(requestContext.getFuture(), new FutureCallback<RpcResult<List<MultipartReply>>>() {
146             @Override
147             public void onSuccess(final RpcResult<List<MultipartReply>> rpcResult) {
148                 List<MultipartReply> result = rpcResult.getResult();
149                 if (result != null) {
150                     translateAndWriteReply(type, dContext, nodeII, result);
151                 } else {
152                     Iterator<RpcError> rpcErrorIterator = rpcResult.getErrors().iterator();
153                     while (rpcErrorIterator.hasNext()) {
154                         Throwable t = rpcErrorIterator.next().getCause();
155                         LOG.info("Failed to retrieve static node {} info: {}", type, t.getMessage());
156                         LOG.trace("Detailed error:", t);
157                     }
158                     if (MultipartType.OFPMPTABLE.equals(type)) {
159                         makeEmptyTables(dContext, nodeII, dContext.getPrimaryConnectionContext().getFeatures().getTables());
160                     }
161                 }
162             }
163
164             @Override
165             public void onFailure(final Throwable t) {
166                 LOG.info("Failed to retrieve static node {} info: {}", type, t.getMessage());
167             }
168         });
169
170         final Future<RpcResult<Void>> rpcFuture = dContext.getPrimaryConnectionContext().getConnectionAdapter()
171                 .multipartRequest(MultipartRequestInputFactory.makeMultipartRequestInput(xid.getValue(), version, type));
172         Futures.addCallback(JdkFutureAdapters.listenInPoolThread(rpcFuture), new FutureCallback<RpcResult<Void>>() {
173             @Override
174             public void onSuccess(final RpcResult<Void> result) {
175                 // NOOP
176             }
177             @Override
178             public void onFailure(final Throwable t) {
179                 future.cancel(true);
180             }
181         });
182         return future;
183     }
184
185     // FIXME : remove after ovs tableFeatures fix
186     private static void makeEmptyTables(final DeviceContext dContext, final InstanceIdentifier<Node> nodeII, final Short nrOfTables) {
187         for (int i = 0; i < nrOfTables; i++) {
188             final short tId = (short) i;
189             final InstanceIdentifier<Table> tableII = nodeII.augmentation(FlowCapableNode.class).child(Table.class, new TableKey(tId));
190             dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, new TableBuilder().setId(tId).build());
191         }
192     }
193
194     private static void translateAndWriteReply(final MultipartType type, final DeviceContext dContext,
195             final InstanceIdentifier<Node> nodeII, final Collection<MultipartReply> result) {
196         for (final MultipartReply reply : result) {
197             final MultipartReplyBody body = reply.getMultipartReplyBody();
198             switch (type) {
199             case OFPMPDESC:
200                 Preconditions.checkArgument(body instanceof MultipartReplyDescCase);
201                 final MultipartReplyDesc replyDesc = ((MultipartReplyDescCase) body).getMultipartReplyDesc();
202                 final FlowCapableNode fcNode = NodeStaticReplyTranslatorUtil.nodeDescTranslator(replyDesc);
203                 final InstanceIdentifier<FlowCapableNode> fNodeII = nodeII.augmentation(FlowCapableNode.class);
204                 dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, fNodeII, fcNode);
205                 break;
206
207             case OFPMPTABLEFEATURES:
208                 Preconditions.checkArgument(body instanceof MultipartReplyTableFeaturesCase);
209                 final MultipartReplyTableFeatures tableFeatures = ((MultipartReplyTableFeaturesCase) body).getMultipartReplyTableFeatures();
210                 final List<TableFeatures> tables = NodeStaticReplyTranslatorUtil.nodeTableFeatureTranslator(tableFeatures);
211                 for (final TableFeatures table : tables) {
212                     final Short tableId = table.getTableId();
213                     final InstanceIdentifier<Table> tableII = nodeII.augmentation(FlowCapableNode.class).child(Table.class, new TableKey(tableId));
214                     dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, new TableBuilder().setId(tableId).setTableFeatures(Collections.singletonList(table)).build());
215                 }
216                 break;
217
218             case OFPMPMETERFEATURES:
219                 Preconditions.checkArgument(body instanceof MultipartReplyMeterFeaturesCase);
220                 final MultipartReplyMeterFeatures meterFeatures = ((MultipartReplyMeterFeaturesCase) body).getMultipartReplyMeterFeatures();
221                 final NodeMeterFeatures mFeature = NodeStaticReplyTranslatorUtil.nodeMeterFeatureTranslator(meterFeatures);
222                 final InstanceIdentifier<NodeMeterFeatures> mFeatureII = nodeII.augmentation(NodeMeterFeatures.class);
223                 dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, mFeatureII, mFeature);
224                 break;
225
226             case OFPMPGROUPFEATURES:
227                 Preconditions.checkArgument(body instanceof MultipartReplyGroupFeaturesCase);
228                 final MultipartReplyGroupFeatures groupFeatures = ((MultipartReplyGroupFeaturesCase) body).getMultipartReplyGroupFeatures();
229                 final NodeGroupFeatures gFeature = NodeStaticReplyTranslatorUtil.nodeGroupFeatureTranslator(groupFeatures);
230                 final InstanceIdentifier<NodeGroupFeatures> gFeatureII = nodeII.augmentation(NodeGroupFeatures.class);
231                 dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, gFeatureII, gFeature);
232                 break;
233
234             default:
235                 throw new IllegalArgumentException("Unnexpected MultipartType " + type);
236             }
237         }
238     }
239 }