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