Use String(byte[], Charset)
[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.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.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.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).child(Node.class).augmentation(FlowCapableNode.class)
102                 .child(Group.class);
103     }
104
105     @Override
106     public void remove(final InstanceIdentifier<Group> identifier, final Group removeDataObj,
107             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
108         BundleId bundleId = getActiveBundle(nodeIdent, provider);
109         if (bundleId != null) {
110             provider.getBundleGroupListener().remove(identifier, removeDataObj, nodeIdent, bundleId);
111         } else {
112             final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
113             nodeConfigurator.enqueueJob(nodeId.getValue(), () -> {
114                 final Group group = removeDataObj;
115                 final RemoveGroupInputBuilder builder = new RemoveGroupInputBuilder(group);
116                 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
117                 builder.setGroupRef(new GroupRef(identifier));
118                 builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
119
120                 final ListenableFuture<RpcResult<RemoveGroupOutput>> resultFuture =
121                     this.provider.getSalGroupService().removeGroup(builder.build());
122                 Futures.addCallback(resultFuture,
123                     new RemoveGroupCallBack(removeDataObj.getGroupId().getValue(), nodeId),
124                     MoreExecutors.directExecutor());
125                 LoggingFutures.addErrorLogging(resultFuture, LOG, "removeGroup");
126                 return resultFuture;
127             });
128         }
129     }
130
131     // TODO: Pull this into ForwardingRulesCommiter and override it here
132     @Override
133     public Future<RpcResult<RemoveGroupOutput>> removeWithResult(final InstanceIdentifier<Group> identifier,
134             final Group removeDataObj, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
135
136         final Group group = removeDataObj;
137         final RemoveGroupInputBuilder builder = new RemoveGroupInputBuilder(group);
138
139         builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
140         builder.setGroupRef(new GroupRef(identifier));
141         builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
142         return this.provider.getSalGroupService().removeGroup(builder.build());
143     }
144
145     @Override
146     public void update(final InstanceIdentifier<Group> identifier, final Group original, final Group update,
147             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
148         BundleId bundleId = getActiveBundle(nodeIdent, provider);
149         if (bundleId != null) {
150             provider.getBundleGroupListener().update(identifier, original, update, nodeIdent, bundleId);
151         } else {
152             final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
153             nodeConfigurator.enqueueJob(nodeId.getValue(), () -> {
154                 final Group originalGroup = original;
155                 final Group updatedGroup = update;
156                 final UpdateGroupInputBuilder builder = new UpdateGroupInputBuilder();
157                 builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
158                 builder.setGroupRef(new GroupRef(identifier));
159                 builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
160                 builder.setUpdatedGroup(new UpdatedGroupBuilder(updatedGroup).build());
161                 builder.setOriginalGroup(new OriginalGroupBuilder(originalGroup).build());
162                 UpdateGroupInput updateGroupInput = builder.build();
163                 final ListenableFuture<RpcResult<UpdateGroupOutput>> resultFuture;
164                 resultFuture = this.provider.getSalGroupService().updateGroup(updateGroupInput);
165                 LoggingFutures.addErrorLogging(resultFuture, LOG, "updateGroup");
166                 Futures.addCallback(resultFuture,
167                         new UpdateGroupCallBack(updateGroupInput.getOriginalGroup().getGroupId().getValue(), nodeId),
168                         MoreExecutors.directExecutor());
169                 return resultFuture;
170             });
171         }
172     }
173
174     @Override
175     public Future<? extends RpcResult<?>> add(final InstanceIdentifier<Group> identifier, final Group addDataObj,
176             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
177         BundleId bundleId = getActiveBundle(nodeIdent, provider);
178         if (bundleId != null) {
179             return provider.getBundleGroupListener().add(identifier, addDataObj, nodeIdent, bundleId);
180         } else {
181             final NodeId nodeId = getNodeIdFromNodeIdentifier(nodeIdent);
182             return nodeConfigurator
183                     .enqueueJob(nodeId.getValue(), () -> {
184                         final Group group = addDataObj;
185                         final AddGroupInputBuilder builder = new AddGroupInputBuilder(group);
186                         builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
187                         builder.setGroupRef(new GroupRef(identifier));
188                         builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
189                         AddGroupInput addGroupInput = builder.build();
190                         final ListenableFuture<RpcResult<AddGroupOutput>> resultFuture;
191                         resultFuture = this.provider.getSalGroupService().addGroup(addGroupInput);
192                         Futures.addCallback(resultFuture,
193                                 new AddGroupCallBack(addGroupInput.getGroupId().getValue(), nodeId),
194                                 MoreExecutors.directExecutor());
195                         return resultFuture;
196                     });
197         }
198     }
199
200     @Override
201     public void createStaleMarkEntity(InstanceIdentifier<Group> identifier, Group del,
202             InstanceIdentifier<FlowCapableNode> nodeIdent) {
203         LOG.debug("Creating Stale-Mark entry for the switch {} for Group {} ", nodeIdent.toString(), del.toString());
204         StaleGroup staleGroup = makeStaleGroup(identifier, del, nodeIdent);
205         persistStaleGroup(staleGroup, nodeIdent);
206
207     }
208
209     private StaleGroup makeStaleGroup(InstanceIdentifier<Group> identifier, Group del,
210             InstanceIdentifier<FlowCapableNode> nodeIdent) {
211         StaleGroupBuilder staleGroupBuilder = new StaleGroupBuilder(del);
212         return staleGroupBuilder.setGroupId(del.getGroupId()).build();
213     }
214
215     private void persistStaleGroup(StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
216         WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
217         writeTransaction.put(LogicalDatastoreType.CONFIGURATION, getStaleGroupInstanceIdentifier(staleGroup, nodeIdent),
218                 staleGroup, false);
219
220         FluentFuture<?> submitFuture = writeTransaction.commit();
221         handleStaleGroupResultFuture(submitFuture);
222     }
223
224     private void handleStaleGroupResultFuture(FluentFuture<?> submitFuture) {
225         submitFuture.addCallback(new FutureCallback<Object>() {
226             @Override
227             public void onSuccess(Object result) {
228                 LOG.debug("Stale Group creation success");
229             }
230
231             @Override
232             public void onFailure(Throwable throwable) {
233                 LOG.error("Stale Group creation failed", throwable);
234             }
235         }, MoreExecutors.directExecutor());
236
237     }
238
239     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.group
240         .types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
241             StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
242         return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
243     }
244
245     private final class AddGroupCallBack implements FutureCallback<RpcResult<AddGroupOutput>> {
246         private final Uint32 groupId;
247         private final NodeId nodeId;
248
249         private AddGroupCallBack(final Uint32 groupId, final NodeId nodeId) {
250             this.groupId = groupId;
251             this.nodeId = nodeId;
252         }
253
254         @Override
255         public void onSuccess(RpcResult<AddGroupOutput> result) {
256             if (result.isSuccessful()) {
257                 provider.getDevicesGroupRegistry().storeGroup(nodeId, groupId);
258                 LOG.debug("Group add with id {} finished without error for node {}", groupId, nodeId);
259             } else {
260                 LOG.debug("Group add with id {} failed for node {} with error {}", groupId, nodeId,
261                         result.getErrors());
262             }
263         }
264
265         @Override
266         public void onFailure(Throwable throwable) {
267             LOG.error("Service call for adding group {} failed for node with error {}", groupId, nodeId, throwable);
268         }
269     }
270
271     private final class UpdateGroupCallBack implements FutureCallback<RpcResult<UpdateGroupOutput>> {
272         private final Uint32 groupId;
273         private final NodeId nodeId;
274
275         private UpdateGroupCallBack(final Uint32 groupId, final NodeId nodeId) {
276             this.groupId = groupId;
277             this.nodeId = nodeId;
278         }
279
280         @Override
281         public void onSuccess(RpcResult<UpdateGroupOutput> result) {
282             if (result.isSuccessful()) {
283                 provider.getDevicesGroupRegistry().storeGroup(nodeId, groupId);
284                 LOG.debug("Group update with id {} finished without error for node {}", groupId, nodeId);
285             } else {
286                 LOG.debug("Group update with id {} failed for node {} with error {}", groupId, nodeId,
287                         result.getErrors().toString());
288             }
289         }
290
291         @Override
292         public void onFailure(Throwable throwable) {
293             LOG.error("Service call for updating group {} failed for node {} with", groupId, nodeId,
294                     throwable);
295         }
296     }
297
298     private final class RemoveGroupCallBack implements FutureCallback<RpcResult<RemoveGroupOutput>> {
299         private final Uint32 groupId;
300         private final NodeId nodeId;
301
302         private RemoveGroupCallBack(final Uint32 groupId, final NodeId nodeId) {
303             this.groupId = groupId;
304             this.nodeId = nodeId;
305         }
306
307         @Override
308         public void onSuccess(RpcResult<RemoveGroupOutput> result) {
309             if (result.isSuccessful()) {
310                 LOG.debug("Group remove with id {} finished without error for node {}", groupId, nodeId);
311                 provider.getDevicesGroupRegistry().removeGroup(nodeId, groupId);
312             } else {
313                 LOG.debug("Group remove with id {} failed for node {} with error {}", groupId, nodeId,
314                         result.getErrors().toString());
315             }
316         }
317
318         @Override
319         public void onFailure(Throwable throwable) {
320             LOG.error("Service call for removing group {} failed for node with error {}", groupId, nodeId, throwable);
321         }
322     }
323 }