NETVIRT-1536: Stale flows in ACL tables
[netvirt.git] / aclservice / impl / src / main / java / org / opendaylight / netvirt / aclservice / listeners / AclEventListener.java
1 /*
2  * Copyright (c) 2016 Ericsson India Global Services Pvt Ltd. 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.netvirt.aclservice.listeners;
9
10 import com.google.common.collect.ImmutableSet;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.Collections;
14 import java.util.HashSet;
15 import java.util.Iterator;
16 import java.util.List;
17 import java.util.Objects;
18 import java.util.Set;
19 import java.util.SortedSet;
20 import javax.annotation.Nonnull;
21 import javax.annotation.Nullable;
22 import javax.annotation.PostConstruct;
23 import javax.inject.Inject;
24 import javax.inject.Singleton;
25 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
29 import org.opendaylight.netvirt.aclservice.api.AclInterfaceCache;
30 import org.opendaylight.netvirt.aclservice.api.AclServiceManager;
31 import org.opendaylight.netvirt.aclservice.api.utils.AclInterface;
32 import org.opendaylight.netvirt.aclservice.utils.AclClusterUtil;
33 import org.opendaylight.netvirt.aclservice.utils.AclConstants;
34 import org.opendaylight.netvirt.aclservice.utils.AclDataUtil;
35 import org.opendaylight.netvirt.aclservice.utils.AclServiceUtils;
36 import org.opendaylight.serviceutils.srm.RecoverableListener;
37 import org.opendaylight.serviceutils.srm.ServiceRecoveryRegistry;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionBase;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionEgress;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionIngress;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
46 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 @Singleton
51 public class AclEventListener extends AsyncDataTreeChangeListenerBase<Acl, AclEventListener> implements
52         ClusteredDataTreeChangeListener<Acl>, RecoverableListener {
53
54     private static final Logger LOG = LoggerFactory.getLogger(AclEventListener.class);
55
56     private final AclServiceManager aclServiceManager;
57     private final AclClusterUtil aclClusterUtil;
58     private final DataBroker dataBroker;
59     private final AclDataUtil aclDataUtil;
60     private final AclServiceUtils aclServiceUtils;
61     private final AclInterfaceCache aclInterfaceCache;
62
63     @Inject
64     public AclEventListener(AclServiceManager aclServiceManager, AclClusterUtil aclClusterUtil, DataBroker dataBroker,
65             AclDataUtil aclDataUtil, AclServiceUtils aclServicUtils, AclInterfaceCache aclInterfaceCache,
66             ServiceRecoveryRegistry serviceRecoveryRegistry) {
67         super(Acl.class, AclEventListener.class);
68         this.aclServiceManager = aclServiceManager;
69         this.aclClusterUtil = aclClusterUtil;
70         this.dataBroker = dataBroker;
71         this.aclDataUtil = aclDataUtil;
72         this.aclServiceUtils = aclServicUtils;
73         this.aclInterfaceCache = aclInterfaceCache;
74         serviceRecoveryRegistry.addRecoverableListener(AclServiceUtils.getRecoverServiceRegistryKey(), this);
75     }
76
77     @Override
78     @PostConstruct
79     public void init() {
80         LOG.info("{} start", getClass().getSimpleName());
81         registerListener();
82     }
83
84     @Override
85     public void registerListener() {
86         registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker);
87     }
88
89     @Override
90     protected InstanceIdentifier<Acl> getWildCardPath() {
91         return InstanceIdentifier.create(AccessLists.class).child(Acl.class);
92     }
93
94     @Override
95     protected void remove(InstanceIdentifier<Acl> key, Acl acl) {
96         String aclName = acl.getAclName();
97         if (!AclServiceUtils.isOfAclInterest(acl)) {
98             LOG.trace("{} does not have SecurityRuleAttr augmentation", aclName);
99             return;
100         }
101
102         LOG.trace("On remove event, remove ACL: {}", acl);
103         this.aclDataUtil.removeAcl(aclName);
104         Integer aclTag = this.aclDataUtil.getAclTag(aclName);
105         if (aclTag != null) {
106             this.aclDataUtil.removeAclTag(aclName);
107             this.aclServiceUtils.releaseAclTag(aclName);
108         }
109         updateRemoteAclCache(acl.getAccessListEntries().getAce(), aclName, AclServiceManager.Action.REMOVE);
110     }
111
112     @Override
113     protected void update(InstanceIdentifier<Acl> key, Acl aclBefore, Acl aclAfter) {
114         if (!AclServiceUtils.isOfAclInterest(aclAfter) && !AclServiceUtils.isOfAclInterest(aclBefore)) {
115             LOG.trace("before {} and after {} does not have SecurityRuleAttr augmentation",
116                     aclBefore.getAclName(), aclAfter.getAclName());
117             return;
118         }
119         String aclName = aclAfter.getAclName();
120         Collection<AclInterface> interfacesBefore =
121                 ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
122         // Find and update added ace rules in acl
123         List<Ace> addedAceRules = getChangedAceList(aclAfter, aclBefore);
124
125         // Find and update deleted ace rules in acl
126         List<Ace> deletedAceRules = getDeletedAceList(aclAfter);
127
128         if (aclClusterUtil.isEntityOwner()) {
129             LOG.debug("On update event, remove Ace rules: {} for ACL: {}", deletedAceRules, aclName);
130             updateAceRules(interfacesBefore, aclName, deletedAceRules, AclServiceManager.Action.REMOVE);
131             if (null != deletedAceRules && !deletedAceRules.isEmpty()) {
132                 aclServiceUtils.deleteAcesFromConfigDS(aclName, deletedAceRules);
133             }
134         }
135         updateAclCaches(aclBefore, aclAfter, interfacesBefore);
136
137         if (aclClusterUtil.isEntityOwner()) {
138             LOG.debug("On update event, add Ace rules: {} for ACL: {}", addedAceRules, aclName);
139             updateAceRules(interfacesBefore, aclName, addedAceRules, AclServiceManager.Action.ADD);
140
141             aclServiceManager.notifyAcl(aclBefore, aclAfter, interfacesBefore, AclServiceManager.Action.UPDATE);
142         }
143     }
144
145     private void updateAceRules(Collection<AclInterface> interfaceList, String aclName, List<Ace> aceList,
146             AclServiceManager.Action action) {
147         if (null != aceList && !aceList.isEmpty()) {
148             LOG.trace("update ace rules - action: {} , ace rules: {}", action.name(), aceList);
149             for (AclInterface port : interfaceList) {
150                 for (Ace aceRule : aceList) {
151                     aclServiceManager.notifyAce(port, action, aclName, aceRule);
152                 }
153             }
154         }
155     }
156
157     @Override
158     protected void add(InstanceIdentifier<Acl> key, Acl acl) {
159         String aclName = acl.getAclName();
160         if (!AclServiceUtils.isOfAclInterest(acl)) {
161             LOG.trace("{} does not have SecurityRuleAttr augmentation", aclName);
162             return;
163         }
164
165         LOG.trace("On add event, add ACL: {}", acl);
166         this.aclDataUtil.addAcl(acl);
167
168         Integer aclTag = this.aclServiceUtils.allocateAclTag(aclName);
169         if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
170             this.aclDataUtil.addAclTag(aclName, aclTag);
171         }
172
173         updateRemoteAclCache(acl.getAccessListEntries().getAce(), aclName, AclServiceManager.Action.ADD);
174     }
175
176     /**
177      * Update remote acl cache.
178      *
179      * @param aceList the ace list
180      * @param aclName the acl name
181      * @param action the action
182      */
183     private void updateRemoteAclCache(@Nullable List<Ace> aceList, String aclName, AclServiceManager.Action action) {
184         if (null == aceList) {
185             return;
186         }
187         for (Ace ace : aceList) {
188             SecurityRuleAttr aceAttributes = ace.augmentation(SecurityRuleAttr.class);
189             if (AclServiceUtils.doesAceHaveRemoteGroupId(aceAttributes)) {
190                 if (action == AclServiceManager.Action.ADD) {
191                     aclDataUtil.addRemoteAclId(aceAttributes.getRemoteGroupId(), new Uuid(aclName),
192                             aceAttributes.getDirection());
193                 } else {
194                     aclDataUtil.removeRemoteAclId(aceAttributes.getRemoteGroupId(), new Uuid(aclName),
195                             aceAttributes.getDirection());
196                 }
197             }
198         }
199     }
200
201     private void updateAclCaches(Acl aclBefore, Acl aclAfter, Collection<AclInterface> aclInterfaces) {
202         String aclName = aclAfter.getAclName();
203         Integer aclTag = this.aclDataUtil.getAclTag(aclName);
204         if (aclTag == null) {
205             aclTag = this.aclServiceUtils.allocateAclTag(aclName);
206             if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
207                 this.aclDataUtil.addAclTag(aclName, aclTag);
208             }
209         }
210         this.aclDataUtil.addAcl(aclAfter);
211
212         updateAclCaches(aclBefore, aclAfter, aclInterfaces, DirectionEgress.class);
213         updateAclCaches(aclBefore, aclAfter, aclInterfaces, DirectionIngress.class);
214     }
215
216     private void updateAclCaches(Acl aclBefore, Acl aclAfter, Collection<AclInterface> aclInterfaces,
217             Class<? extends DirectionBase> direction) {
218         Uuid aclId = new Uuid(aclAfter.getAclName());
219         Set<Uuid> remoteAclsBefore = AclServiceUtils.getRemoteAclIdsByDirection(aclBefore, direction);
220         Set<Uuid> remoteAclsAfter = AclServiceUtils.getRemoteAclIdsByDirection(aclAfter, direction);
221
222         Set<Uuid> remoteAclsDeleted = new HashSet<>(remoteAclsBefore);
223         remoteAclsDeleted.removeAll(remoteAclsAfter);
224         for (Uuid remoteAcl : remoteAclsDeleted) {
225             aclDataUtil.removeRemoteAclId(remoteAcl, aclId, direction);
226         }
227
228         Set<Uuid> remoteAclsAdded = new HashSet<>(remoteAclsAfter);
229         remoteAclsAdded.removeAll(remoteAclsBefore);
230         for (Uuid remoteAcl : remoteAclsAdded) {
231             aclDataUtil.addRemoteAclId(remoteAcl, aclId, direction);
232         }
233
234         if (remoteAclsDeleted.isEmpty() && remoteAclsAdded.isEmpty()) {
235             return;
236         }
237
238         if (aclInterfaces != null) {
239             for (AclInterface aclInterface : aclInterfaces) {
240                 AclInterface aclInterfaceInCache =
241                         aclInterfaceCache.addOrUpdate(aclInterface.getInterfaceId(), (prevAclInterface, builder) -> {
242                             SortedSet<Integer> remoteAclTags =
243                                     aclServiceUtils.getRemoteAclTags(aclInterface.getSecurityGroups(), direction);
244                             if (DirectionEgress.class.equals(direction)) {
245                                 builder.egressRemoteAclTags(remoteAclTags);
246                             } else {
247                                 builder.ingressRemoteAclTags(remoteAclTags);
248                             }
249                         });
250
251                 aclDataUtil.addOrUpdateAclInterfaceMap(aclInterface.getSecurityGroups(), aclInterfaceInCache);
252             }
253         }
254     }
255
256     @Override
257     protected AclEventListener getDataTreeChangeListener() {
258         return this;
259     }
260
261     @Nonnull
262     private List<Ace> getChangedAceList(Acl updatedAcl, Acl currentAcl) {
263         if (updatedAcl == null) {
264             return Collections.emptyList();
265         }
266         List<Ace> updatedAceList =
267             updatedAcl.getAccessListEntries() == null || updatedAcl.getAccessListEntries().getAce() == null
268                 ? new ArrayList<>()
269                 : new ArrayList<>(updatedAcl.getAccessListEntries().getAce());
270         if (currentAcl == null) {
271             return updatedAceList;
272         }
273         List<Ace> currentAceList =
274             currentAcl.getAccessListEntries() == null || currentAcl.getAccessListEntries().getAce() == null
275                 ? new ArrayList<>()
276                 : new ArrayList<>(currentAcl.getAccessListEntries().getAce());
277         for (Iterator<Ace> iterator = updatedAceList.iterator(); iterator.hasNext();) {
278             Ace ace1 = iterator.next();
279             for (Ace ace2 : currentAceList) {
280                 if (Objects.equals(ace1.getRuleName(), ace2.getRuleName())) {
281                     iterator.remove();
282                 }
283             }
284         }
285         return updatedAceList;
286     }
287
288     private List<Ace> getDeletedAceList(Acl acl) {
289         if (acl == null || acl.getAccessListEntries() == null || acl.getAccessListEntries().getAce() == null) {
290             return null;
291         }
292         List<Ace> aceList = acl.getAccessListEntries().getAce();
293         List<Ace> deletedAceList = new ArrayList<>();
294         for (Ace ace: aceList) {
295             if (ace.augmentation(SecurityRuleAttr.class).isDeleted()) {
296                 deletedAceList.add(ace);
297             }
298         }
299         return deletedAceList;
300     }
301 }