Switch to MD-SAL APIs
[openflowplugin.git] / applications / forwardingrules-manager / src / main / java / org / opendaylight / openflowplugin / applications / frm / impl / GroupForwarder.java
1 /*
2  * Copyright (c) 2014, 2017 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.applications.frm.impl;
9
10 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getActiveBundle;
11 import static org.opendaylight.openflowplugin.applications.frm.util.FrmUtil.getNodeIdFromNodeIdentifier;
12
13 import com.google.common.util.concurrent.FluentFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.util.concurrent.Future;
19 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
20 import org.opendaylight.mdsal.binding.api.DataBroker;
21 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
22 import org.opendaylight.mdsal.binding.api.WriteTransaction;
23 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
24 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInput;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInputBuilder;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutput;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupInputBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupOutput;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupInput;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupInputBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.group.update.OriginalGroupBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.group.update.UpdatedGroupBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupRef;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
48 import org.opendaylight.yangtools.concepts.ListenerRegistration;
49 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
50 import org.opendaylight.yangtools.yang.common.RpcResult;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * GroupForwarder It implements
56  * {@link org.opendaylight.mdsal.binding.api.DataTreeChangeListener}
57  * for WildCardedPath to {@link Group} and ForwardingRulesCommiter interface for
58  * methods: add, update and remove {@link Group} processing for
59  * {@link org.opendaylight.mdsal.binding.api.DataTreeModification}.
60  */
61 public class GroupForwarder extends AbstractListeningCommiter<Group> {
62
63     private static final Logger LOG = LoggerFactory.getLogger(GroupForwarder.class);
64     private ListenerRegistration<GroupForwarder> listenerRegistration;
65     private final BundleGroupForwarder bundleGroupForwarder;
66
67     public GroupForwarder(final ForwardingRulesManager manager, final DataBroker db) {
68         super(manager, db);
69         this.bundleGroupForwarder = new BundleGroupForwarder(manager);
70     }
71
72     @SuppressWarnings("IllegalCatch")
73     @Override
74     public void registerListener() {
75         final DataTreeIdentifier<Group> treeId = DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION,
76                 getWildCardPath());
77
78         try {
79             listenerRegistration = dataBroker.registerDataTreeChangeListener(treeId, GroupForwarder.this);
80         } catch (final Exception e) {
81             LOG.warn("FRM Group DataTreeChange listener registration fail!");
82             LOG.debug("FRM Group DataTreeChange listener registration fail ..", e);
83             throw new IllegalStateException("GroupForwarder startup fail! System needs restart.", e);
84         }
85     }
86
87     @Override
88     public  void deregisterListener() {
89         close();
90     }
91
92     @Override
93     public void close() {
94         if (listenerRegistration != null) {
95             listenerRegistration.close();
96             listenerRegistration = null;
97         }
98     }
99
100     @Override
101     protected InstanceIdentifier<Group> getWildCardPath() {
102         return InstanceIdentifier.create(Nodes.class).child(Node.class).augmentation(FlowCapableNode.class)
103                 .child(Group.class);
104     }
105
106     @Override
107     public void remove(final InstanceIdentifier<Group> identifier, final Group removeDataObj,
108             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
109         BundleId bundleId = getActiveBundle(nodeIdent, provider);
110         if (bundleId != null) {
111             bundleGroupForwarder.remove(identifier, removeDataObj, nodeIdent, bundleId);
112         } else {
113             final Group group = removeDataObj;
114             final RemoveGroupInputBuilder builder = new RemoveGroupInputBuilder(group);
115             final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
116
117             builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
118             builder.setGroupRef(new GroupRef(identifier));
119             builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
120
121             final ListenableFuture<RpcResult<RemoveGroupOutput>> resultFuture =
122                     this.provider.getSalGroupService().removeGroup(builder.build());
123             Futures.addCallback(resultFuture,
124                     new RemoveGroupCallBack(removeDataObj.getGroupId().getValue(), nodeId),
125                     MoreExecutors.directExecutor());
126             JdkFutures.addErrorLogging(resultFuture, LOG, "removeGroup");
127         }
128     }
129
130     // TODO: Pull this into ForwardingRulesCommiter and override it here
131     @Override
132     public Future<RpcResult<RemoveGroupOutput>> removeWithResult(final InstanceIdentifier<Group> identifier,
133             final Group removeDataObj, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
134
135         final Group group = removeDataObj;
136         final RemoveGroupInputBuilder builder = new RemoveGroupInputBuilder(group);
137
138         builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
139         builder.setGroupRef(new GroupRef(identifier));
140         builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
141         return this.provider.getSalGroupService().removeGroup(builder.build());
142     }
143
144     @Override
145     public void update(final InstanceIdentifier<Group> identifier, final Group original, final Group update,
146             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
147         BundleId bundleId = getActiveBundle(nodeIdent, provider);
148         if (bundleId != null) {
149             bundleGroupForwarder.update(identifier, original, update, nodeIdent, bundleId);
150         } else {
151             final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
152             nodeConfigurator.enqueueJob(nodeId.getValue(), () -> {
153                 final Group originalGroup = original;
154                 final Group updatedGroup = update;
155                 final UpdateGroupInputBuilder builder = new UpdateGroupInputBuilder();
156                 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
157                 builder.setGroupRef(new GroupRef(identifier));
158                 builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
159                 builder.setUpdatedGroup(new UpdatedGroupBuilder(updatedGroup).build());
160                 builder.setOriginalGroup(new OriginalGroupBuilder(originalGroup).build());
161                 UpdateGroupInput updateGroupInput = builder.build();
162                 final ListenableFuture<RpcResult<UpdateGroupOutput>> resultFuture;
163                 resultFuture = this.provider.getSalGroupService().updateGroup(updateGroupInput);
164                 JdkFutures.addErrorLogging(resultFuture, LOG, "updateGroup");
165                 Futures.addCallback(resultFuture,
166                         new UpdateGroupCallBack(updateGroupInput.getOriginalGroup().getGroupId().getValue(), nodeId),
167                         MoreExecutors.directExecutor());
168                 return resultFuture;
169             });
170         }
171     }
172
173     @Override
174     public Future<? extends RpcResult<?>> add(final InstanceIdentifier<Group> identifier, final Group addDataObj,
175             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
176         BundleId bundleId = getActiveBundle(nodeIdent, provider);
177         if (bundleId != null) {
178             return bundleGroupForwarder.add(identifier, addDataObj, nodeIdent, bundleId);
179         } else {
180             final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
181             return nodeConfigurator
182                     .enqueueJob(nodeId.getValue(), () -> {
183                         final Group group = addDataObj;
184                         final AddGroupInputBuilder builder = new AddGroupInputBuilder(group);
185                         builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
186                         builder.setGroupRef(new GroupRef(identifier));
187                         builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
188                         AddGroupInput addGroupInput = builder.build();
189                         final ListenableFuture<RpcResult<AddGroupOutput>> resultFuture;
190                         resultFuture = this.provider.getSalGroupService().addGroup(addGroupInput);
191                         Futures.addCallback(resultFuture,
192                                 new AddGroupCallBack(addGroupInput.getGroupId().getValue(), nodeId),
193                                 MoreExecutors.directExecutor());
194                         return resultFuture;
195                     });
196         }
197     }
198
199     @Override
200     public void createStaleMarkEntity(InstanceIdentifier<Group> identifier, Group del,
201             InstanceIdentifier<FlowCapableNode> nodeIdent) {
202         LOG.debug("Creating Stale-Mark entry for the switch {} for Group {} ", nodeIdent.toString(), del.toString());
203         StaleGroup staleGroup = makeStaleGroup(identifier, del, nodeIdent);
204         persistStaleGroup(staleGroup, nodeIdent);
205
206     }
207
208     private StaleGroup makeStaleGroup(InstanceIdentifier<Group> identifier, Group del,
209             InstanceIdentifier<FlowCapableNode> nodeIdent) {
210         StaleGroupBuilder staleGroupBuilder = new StaleGroupBuilder(del);
211         return staleGroupBuilder.setGroupId(del.getGroupId()).build();
212     }
213
214     private void persistStaleGroup(StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
215         WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
216         writeTransaction.put(LogicalDatastoreType.CONFIGURATION, getStaleGroupInstanceIdentifier(staleGroup, nodeIdent),
217                 staleGroup, false);
218
219         FluentFuture<?> submitFuture = writeTransaction.commit();
220         handleStaleGroupResultFuture(submitFuture);
221     }
222
223     private void handleStaleGroupResultFuture(FluentFuture<?> submitFuture) {
224         submitFuture.addCallback(new FutureCallback<Object>() {
225             @Override
226             public void onSuccess(Object result) {
227                 LOG.debug("Stale Group creation success");
228             }
229
230             @Override
231             public void onFailure(Throwable throwable) {
232                 LOG.error("Stale Group creation failed {}", throwable);
233             }
234         }, MoreExecutors.directExecutor());
235
236     }
237
238     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.group
239         .types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
240             StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
241         return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
242     }
243
244     private final class AddGroupCallBack implements FutureCallback<RpcResult<AddGroupOutput>> {
245         private final Long groupId;
246         private final NodeId nodeId;
247
248         private AddGroupCallBack(final Long groupId, final NodeId nodeId) {
249             this.groupId = groupId;
250             this.nodeId = nodeId;
251         }
252
253         @Override
254         public void onSuccess(RpcResult<AddGroupOutput> result) {
255             if (result.isSuccessful()) {
256                 provider.getDevicesGroupRegistry().storeGroup(nodeId, groupId);
257                 LOG.debug("Group add with id {} finished without error for node {}", groupId, nodeId);
258             } else {
259                 LOG.debug("Group add with id {} failed for node {} with error {}", groupId, nodeId,
260                         result.getErrors());
261             }
262         }
263
264         @Override
265         public void onFailure(Throwable throwable) {
266             LOG.error("Service call for adding group {} failed for node with error {}", groupId, nodeId, throwable);
267         }
268     }
269
270     private final class UpdateGroupCallBack implements FutureCallback<RpcResult<UpdateGroupOutput>> {
271         private final Long groupId;
272         private final NodeId nodeId;
273
274         private UpdateGroupCallBack(final Long groupId, final NodeId nodeId) {
275             this.groupId = groupId;
276             this.nodeId = nodeId;
277         }
278
279         @Override
280         public void onSuccess(RpcResult<UpdateGroupOutput> result) {
281             if (result.isSuccessful()) {
282                 provider.getDevicesGroupRegistry().storeGroup(nodeId, groupId);
283                 LOG.debug("Group update with id {} finished without error for node {}", groupId, nodeId);
284             } else {
285                 LOG.debug("Group update with id {} failed for node {} with error {}", groupId, nodeId,
286                         result.getErrors().toString());
287             }
288         }
289
290         @Override
291         public void onFailure(Throwable throwable) {
292             LOG.error("Service call for updating group {} failed for node {} with", groupId, nodeId,
293                     throwable);
294         }
295     }
296
297     private final class RemoveGroupCallBack implements FutureCallback<RpcResult<RemoveGroupOutput>> {
298         private final Long groupId;
299         private final NodeId nodeId;
300
301         private RemoveGroupCallBack(final Long groupId, final NodeId nodeId) {
302             this.groupId = groupId;
303             this.nodeId = nodeId;
304         }
305
306         @Override
307         public void onSuccess(RpcResult<RemoveGroupOutput> result) {
308             if (result.isSuccessful()) {
309                 LOG.debug("Group remove with id {} finished without error for node {}", groupId, nodeId);
310                 provider.getDevicesGroupRegistry().removeGroup(nodeId, groupId);
311             } else {
312                 LOG.debug("Group remove with id {} failed for node {} with error {}", groupId, nodeId,
313                         result.getErrors().toString());
314             }
315         }
316
317         @Override
318         public void onFailure(Throwable throwable) {
319             LOG.error("Service call for removing group {} failed for node with error {}", groupId, nodeId, throwable);
320         }
321     }
322 }