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