Merge "Returning of future from request context - SalEchoService."
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / services / SalTableServiceImpl.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.services;
9
10 import com.google.common.base.Function;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.SettableFuture;
15 import java.math.BigInteger;
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.concurrent.Future;
19 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
20 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
21 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
22 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
23 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
24 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
25 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
26 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
27 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.TableFeaturesConvertor;
28 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.TableFeaturesReplyConvertor;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
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.MultipartReplyTableFeaturesCase;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeatures;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestTableFeaturesCaseBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.table.features._case.MultipartRequestTableFeaturesBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.table.features._case.multipart.request.table.features.TableFeatures;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.SalTableService;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableInput;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutput;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutputBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
54 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
55 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
56 import org.opendaylight.yangtools.yang.common.RpcError;
57 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
58 import org.opendaylight.yangtools.yang.common.RpcResult;
59 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
60 import org.slf4j.Logger;
61
62 public class SalTableServiceImpl extends CommonService implements SalTableService {
63
64     private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(SalTableServiceImpl.class);
65
66     public SalTableServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
67         super(requestContextStack, deviceContext);
68     }
69
70     @Override
71     public Future<RpcResult<UpdateTableOutput>> updateTable(final UpdateTableInput input) {
72         class FunctionImpl implements
73                 Function<RequestContext<List<MultipartReply>>, ListenableFuture<RpcResult<List<MultipartReply>>>> {
74
75             @Override
76             public ListenableFuture<RpcResult<List<MultipartReply>>> apply(final RequestContext<List<MultipartReply>> requestContext) {
77                 getMessageSpy().spyMessage(input.getImplementedInterface(),
78                         MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
79
80                 final SettableFuture<RpcResult<List<MultipartReply>>> result = SettableFuture.create();
81
82                 final MultipartRequestTableFeaturesCaseBuilder caseBuilder = new MultipartRequestTableFeaturesCaseBuilder();
83                 final MultipartRequestTableFeaturesBuilder requestBuilder = new MultipartRequestTableFeaturesBuilder();
84                 final List<TableFeatures> ofTableFeatureList = TableFeaturesConvertor.toTableFeaturesRequest(input
85                         .getUpdatedTable());
86                 requestBuilder.setTableFeatures(ofTableFeatureList);
87                 caseBuilder.setMultipartRequestTableFeatures(requestBuilder.build());
88
89                 // Set request body to main multipart request
90                 final Xid xid = requestContext.getXid();
91                 final MultipartRequestInputBuilder mprInput = createMultipartHeader(MultipartType.OFPMPTABLEFEATURES,
92                         xid.getValue());
93                 mprInput.setMultipartRequestBody(caseBuilder.build());
94                 final OutboundQueue outboundQueue = getDeviceContext().getPrimaryConnectionContext().getOutboundQueueProvider();
95
96                 final SettableFuture<RpcResult<List<MultipartReply>>> settableFuture = SettableFuture.create();
97                 final MultiMsgCollector multiMsgCollector = getDeviceContext().getMultiMsgCollector();
98                 multiMsgCollector.registerMultipartRequestContext(requestContext);
99
100                 final MultipartRequestInput multipartRequestInput = mprInput.build();
101                 outboundQueue.commitEntry(xid.getValue(), multipartRequestInput, new FutureCallback<OfHeader>() {
102                     @Override
103                     public void onSuccess(final OfHeader ofHeader) {
104                         if (ofHeader instanceof MultipartReply) {
105                             MultipartReply multipartReply = (MultipartReply) ofHeader;
106                             multiMsgCollector.addMultipartMsg(multipartReply);
107                         } else {
108                             if (null != ofHeader) {
109                                 LOG.info("Unexpected response type received {}.", ofHeader.getClass());
110                             } else {
111                                 LOG.info("Response received is null.");
112                             }
113                         }
114                         getMessageSpy().spyMessage(multipartRequestInput.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_SUCCESS);
115                         settableFuture.set(RpcResultBuilder.<List<MultipartReply>>success().build());
116                     }
117
118                     @Override
119                     public void onFailure(final Throwable throwable) {
120                         RpcResultBuilder<List<MultipartReply>> rpcResultBuilder = RpcResultBuilder.<List<MultipartReply>>failed().withError(RpcError.ErrorType.APPLICATION, throwable.getMessage(), throwable);
121                         RequestContextUtil.closeRequstContext(requestContext);
122                         multiMsgCollector.registerMultipartRequestContext(requestContext);
123                         getMessageSpy().spyMessage(multipartRequestInput.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.TO_SWITCH_SUBMIT_FAILURE);
124                         settableFuture.set(rpcResultBuilder.build());
125                     }
126                 });
127                 return settableFuture;
128             }
129         }
130
131         final ListenableFuture<RpcResult<List<MultipartReply>>> multipartFuture = handleServiceCall(new FunctionImpl());
132         final SettableFuture<RpcResult<UpdateTableOutput>> finalFuture = SettableFuture.create();
133
134         class CallBackImpl implements FutureCallback<RpcResult<List<MultipartReply>>> {
135             private final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(CallBackImpl.class);
136
137             @Override
138             public void onSuccess(final RpcResult<List<MultipartReply>> result) {
139
140                 if (result.isSuccessful()) {
141                     final List<MultipartReply> multipartReplies = result.getResult();
142                     if (multipartReplies.isEmpty()) {
143                         LOGGER.debug("Multipart reply to table features request shouldn't be empty list.");
144                         finalFuture.set(RpcResultBuilder.<UpdateTableOutput>failed()
145                                 .withError(ErrorType.RPC, "Multipart reply list is empty.").build());
146                     } else {
147                         final Long xid = multipartReplies.get(0).getXid();
148                         LOGGER.debug(
149                                 "OnSuccess, rpc result successful, multipart response for rpc update-table with xid {} obtained.",
150                                 xid);
151                         final UpdateTableOutputBuilder updateTableOutputBuilder = new UpdateTableOutputBuilder();
152                         updateTableOutputBuilder.setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
153                         finalFuture.set(RpcResultBuilder.success(updateTableOutputBuilder.build()).build());
154                         writeResponseToOperationalDatastore(multipartReplies);
155                     }
156                 } else {
157                     LOGGER.debug("OnSuccess, rpc result unsuccessful, multipart response for rpc update-table was unsuccessful.");
158                     finalFuture.set(RpcResultBuilder.<UpdateTableOutput>failed().withRpcErrors(result.getErrors())
159                             .build());
160                 }
161             }
162
163             @Override
164             public void onFailure(final Throwable t) {
165                 LOGGER.debug("Failure multipart response for table features request. Exception: {}", t);
166                 finalFuture.set(RpcResultBuilder.<UpdateTableOutput>failed()
167                         .withError(ErrorType.RPC, "Future error", t).build());
168             }
169
170             /**
171              * @param multipartReplies
172              */
173             private void writeResponseToOperationalDatastore(final List<MultipartReply> multipartReplies) {
174
175                 final List<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures> salTableFeatures = convertToSalTableFeatures(multipartReplies);
176
177                 final DeviceContext deviceContext = getDeviceContext();
178                 final NodeId nodeId = deviceContext.getPrimaryConnectionContext().getNodeId();
179                 final InstanceIdentifier<FlowCapableNode> flowCapableNodeII = InstanceIdentifier.create(Nodes.class)
180                         .child(Node.class, new NodeKey(nodeId)).augmentation(FlowCapableNode.class);
181                 for (org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures tableFeatureData : salTableFeatures) {
182                     final Short tableId = tableFeatureData.getTableId();
183                     KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures, TableFeaturesKey> tableFeaturesII = flowCapableNodeII
184                             .child(Table.class, new TableKey(tableId))
185                             .child(org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures.class,
186                                     new TableFeaturesKey(tableId));
187                     deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableFeaturesII,
188                             tableFeatureData);
189                 }
190
191             }
192
193             private List<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures> convertToSalTableFeatures(
194                     final List<MultipartReply> multipartReplies) {
195                 final List<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures> salTableFeaturesAll = new ArrayList<>();
196                 for (MultipartReply multipartReply : multipartReplies) {
197                     if (multipartReply.getType().equals(MultipartType.OFPMPTABLEFEATURES)) {
198                         MultipartReplyBody multipartReplyBody = multipartReply.getMultipartReplyBody();
199                         if (multipartReplyBody instanceof MultipartReplyTableFeaturesCase) {
200                             MultipartReplyTableFeaturesCase tableFeaturesCase = ((MultipartReplyTableFeaturesCase) multipartReplyBody);
201                             MultipartReplyTableFeatures salTableFeatures = tableFeaturesCase
202                                     .getMultipartReplyTableFeatures();
203                             List<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures> salTableFeaturesPartial = TableFeaturesReplyConvertor
204                                     .toTableFeaturesReply(salTableFeatures);
205                             salTableFeaturesAll.addAll(salTableFeaturesPartial);
206                             LOGGER.debug("TableFeature {} for xid {}.", salTableFeatures, multipartReply.getXid());
207                         }
208                     }
209                 }
210                 return salTableFeaturesAll;
211             }
212
213         }
214
215         Futures.addCallback(multipartFuture, new CallBackImpl());
216
217         return finalFuture;
218     }
219
220     private MultipartRequestInputBuilder createMultipartHeader(final MultipartType multipart, final Long xid) {
221         final MultipartRequestInputBuilder mprInput = new MultipartRequestInputBuilder();
222         mprInput.setType(multipart);
223         mprInput.setVersion(getVersion());
224         mprInput.setXid(xid);
225         mprInput.setFlags(new MultipartRequestFlags(false));
226         return mprInput;
227     }
228
229 }