ACL: NullPointerException in AclEventListener
[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.PostConstruct;
21 import javax.inject.Inject;
22 import javax.inject.Singleton;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
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         LOG.trace("On remove event, remove ACL: {}", acl);
97         String aclName = acl.getAclName();
98         this.aclDataUtil.removeAcl(aclName);
99         Integer aclTag = this.aclDataUtil.getAclTag(aclName);
100         if (aclTag != null) {
101             this.aclDataUtil.removeAclTag(aclName);
102         }
103
104         updateRemoteAclCache(AclServiceUtils.getAceListFromAcl(acl), aclName, AclServiceManager.Action.REMOVE);
105         if (aclClusterUtil.isEntityOwner()) {
106             if (aclTag != null) {
107                 this.aclServiceUtils.releaseAclTag(aclName);
108             }
109             // Handle Rule deletion If SG Remove event is received before SG Rule delete event
110             List<Ace> aceList = acl.getAccessListEntries().getAce();
111             Collection<AclInterface> aclInterfaces =
112                     ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
113             updateAceRules(aclInterfaces, aclName, aceList, AclServiceManager.Action.REMOVE);
114         }
115     }
116
117     @Override
118     protected void update(InstanceIdentifier<Acl> key, Acl aclBefore, Acl aclAfter) {
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         LOG.trace("On add event, add ACL: {}", acl);
160         this.aclDataUtil.addAcl(acl);
161
162         String aclName = acl.getAclName();
163         Integer aclTag = this.aclServiceUtils.allocateAclTag(aclName);
164         if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
165             this.aclDataUtil.addAclTag(aclName, aclTag);
166         }
167
168         updateRemoteAclCache(AclServiceUtils.getAceListFromAcl(acl), aclName, AclServiceManager.Action.ADD);
169     }
170
171     /**
172      * Update remote acl cache.
173      *
174      * @param aceList the ace list
175      * @param aclName the acl name
176      * @param action the action
177      */
178     private void updateRemoteAclCache(@Nullable List<Ace> aceList, String aclName, AclServiceManager.Action action) {
179         for (Ace ace : aceList) {
180             SecurityRuleAttr aceAttributes = ace.augmentation(SecurityRuleAttr.class);
181             if (AclServiceUtils.doesAceHaveRemoteGroupId(aceAttributes)) {
182                 if (action == AclServiceManager.Action.ADD) {
183                     aclDataUtil.addRemoteAclId(aceAttributes.getRemoteGroupId(), new Uuid(aclName),
184                             aceAttributes.getDirection());
185                 } else {
186                     aclDataUtil.removeRemoteAclId(aceAttributes.getRemoteGroupId(), new Uuid(aclName),
187                             aceAttributes.getDirection());
188                 }
189             }
190         }
191     }
192
193     private void updateAclCaches(Acl aclBefore, Acl aclAfter, Collection<AclInterface> aclInterfaces) {
194         String aclName = aclAfter.getAclName();
195         Integer aclTag = this.aclDataUtil.getAclTag(aclName);
196         if (aclTag == null) {
197             aclTag = this.aclServiceUtils.allocateAclTag(aclName);
198             if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
199                 this.aclDataUtil.addAclTag(aclName, aclTag);
200             }
201         }
202         this.aclDataUtil.addAcl(aclAfter);
203
204         updateAclCaches(aclBefore, aclAfter, aclInterfaces, DirectionEgress.class);
205         updateAclCaches(aclBefore, aclAfter, aclInterfaces, DirectionIngress.class);
206     }
207
208     private void updateAclCaches(Acl aclBefore, Acl aclAfter, Collection<AclInterface> aclInterfaces,
209             Class<? extends DirectionBase> direction) {
210         Uuid aclId = new Uuid(aclAfter.getAclName());
211         Set<Uuid> remoteAclsBefore = AclServiceUtils.getRemoteAclIdsByDirection(aclBefore, direction);
212         Set<Uuid> remoteAclsAfter = AclServiceUtils.getRemoteAclIdsByDirection(aclAfter, direction);
213
214         Set<Uuid> remoteAclsDeleted = new HashSet<>(remoteAclsBefore);
215         remoteAclsDeleted.removeAll(remoteAclsAfter);
216         for (Uuid remoteAcl : remoteAclsDeleted) {
217             aclDataUtil.removeRemoteAclId(remoteAcl, aclId, direction);
218         }
219
220         Set<Uuid> remoteAclsAdded = new HashSet<>(remoteAclsAfter);
221         remoteAclsAdded.removeAll(remoteAclsBefore);
222         for (Uuid remoteAcl : remoteAclsAdded) {
223             aclDataUtil.addRemoteAclId(remoteAcl, aclId, direction);
224         }
225
226         if (remoteAclsDeleted.isEmpty() && remoteAclsAdded.isEmpty()) {
227             return;
228         }
229
230         if (aclInterfaces != null) {
231             for (AclInterface aclInterface : aclInterfaces) {
232                 AclInterface aclInterfaceInCache =
233                         aclInterfaceCache.addOrUpdate(aclInterface.getInterfaceId(), (prevAclInterface, builder) -> {
234                             SortedSet<Integer> remoteAclTags =
235                                     aclServiceUtils.getRemoteAclTags(aclInterface.getSecurityGroups(), direction);
236                             if (DirectionEgress.class.equals(direction)) {
237                                 builder.egressRemoteAclTags(remoteAclTags);
238                             } else {
239                                 builder.ingressRemoteAclTags(remoteAclTags);
240                             }
241                         });
242
243                 aclDataUtil.addOrUpdateAclInterfaceMap(aclInterface.getSecurityGroups(), aclInterfaceInCache);
244             }
245         }
246     }
247
248     @Override
249     protected AclEventListener getDataTreeChangeListener() {
250         return this;
251     }
252
253     @NonNull
254     private List<Ace> getChangedAceList(Acl updatedAcl, Acl currentAcl) {
255         if (updatedAcl == null) {
256             return Collections.emptyList();
257         }
258         List<Ace> updatedAceList =
259             updatedAcl.getAccessListEntries() == null || updatedAcl.getAccessListEntries().getAce() == null
260                 ? new ArrayList<>()
261                 : new ArrayList<>(updatedAcl.getAccessListEntries().getAce());
262         if (currentAcl == null) {
263             return updatedAceList;
264         }
265         List<Ace> currentAceList =
266             currentAcl.getAccessListEntries() == null || currentAcl.getAccessListEntries().getAce() == null
267                 ? new ArrayList<>()
268                 : new ArrayList<>(currentAcl.getAccessListEntries().getAce());
269         for (Iterator<Ace> iterator = updatedAceList.iterator(); iterator.hasNext();) {
270             Ace ace1 = iterator.next();
271             for (Ace ace2 : currentAceList) {
272                 if (Objects.equals(ace1.getRuleName(), ace2.getRuleName())) {
273                     iterator.remove();
274                 }
275             }
276         }
277         return updatedAceList;
278     }
279
280     private List<Ace> getDeletedAceList(Acl acl) {
281         if (acl == null || acl.getAccessListEntries() == null || acl.getAccessListEntries().getAce() == null) {
282             return null;
283         }
284         List<Ace> aceList = acl.getAccessListEntries().getAce();
285         List<Ace> deletedAceList = new ArrayList<>();
286         for (Ace ace: aceList) {
287             if (ace.augmentation(SecurityRuleAttr.class).isDeleted()) {
288                 deletedAceList.add(ace);
289             }
290         }
291         return deletedAceList;
292     }
293 }