NETVIRT-1643: Added checkes to resolve NPE
[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
12 import java.math.BigInteger;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.HashSet;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Objects;
20 import java.util.Set;
21 import java.util.SortedSet;
22 import javax.annotation.PostConstruct;
23 import javax.inject.Inject;
24 import javax.inject.Singleton;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
27 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
28 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
29 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
30 import org.opendaylight.netvirt.aclservice.api.AclInterfaceCache;
31 import org.opendaylight.netvirt.aclservice.api.AclServiceManager;
32 import org.opendaylight.netvirt.aclservice.api.utils.AclInterface;
33 import org.opendaylight.netvirt.aclservice.utils.AclClusterUtil;
34 import org.opendaylight.netvirt.aclservice.utils.AclConstants;
35 import org.opendaylight.netvirt.aclservice.utils.AclDataUtil;
36 import org.opendaylight.netvirt.aclservice.utils.AclServiceUtils;
37 import org.opendaylight.serviceutils.srm.RecoverableListener;
38 import org.opendaylight.serviceutils.srm.ServiceRecoveryRegistry;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionBase;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionEgress;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionIngress;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
47 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 @Singleton
52 public class AclEventListener extends AsyncDataTreeChangeListenerBase<Acl, AclEventListener> implements
53         ClusteredDataTreeChangeListener<Acl>, RecoverableListener {
54
55     private static final Logger LOG = LoggerFactory.getLogger(AclEventListener.class);
56
57     private final AclServiceManager aclServiceManager;
58     private final AclClusterUtil aclClusterUtil;
59     private final DataBroker dataBroker;
60     private final AclDataUtil aclDataUtil;
61     private final AclServiceUtils aclServiceUtils;
62     private final AclInterfaceCache aclInterfaceCache;
63
64     @Inject
65     public AclEventListener(AclServiceManager aclServiceManager, AclClusterUtil aclClusterUtil, DataBroker dataBroker,
66             AclDataUtil aclDataUtil, AclServiceUtils aclServicUtils, AclInterfaceCache aclInterfaceCache,
67             ServiceRecoveryRegistry serviceRecoveryRegistry) {
68         super(Acl.class, AclEventListener.class);
69         this.aclServiceManager = aclServiceManager;
70         this.aclClusterUtil = aclClusterUtil;
71         this.dataBroker = dataBroker;
72         this.aclDataUtil = aclDataUtil;
73         this.aclServiceUtils = aclServicUtils;
74         this.aclInterfaceCache = aclInterfaceCache;
75         serviceRecoveryRegistry.addRecoverableListener(AclServiceUtils.getRecoverServiceRegistryKey(), this);
76     }
77
78     @Override
79     @PostConstruct
80     public void init() {
81         LOG.info("{} start", getClass().getSimpleName());
82         registerListener();
83     }
84
85     @Override
86     public void registerListener() {
87         registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker);
88     }
89
90     @Override
91     protected InstanceIdentifier<Acl> getWildCardPath() {
92         return InstanceIdentifier.create(AccessLists.class).child(Acl.class);
93     }
94
95     @Override
96     protected void remove(InstanceIdentifier<Acl> key, Acl acl) {
97         LOG.trace("On remove event, remove ACL: {}", acl);
98         String aclName = acl.getAclName();
99         this.aclDataUtil.removeAcl(aclName);
100         Integer aclTag = this.aclDataUtil.getAclTag(aclName);
101         if (aclTag != null) {
102             this.aclDataUtil.removeAclTag(aclName);
103         }
104
105         updateRemoteAclCache(AclServiceUtils.getAceListFromAcl(acl), aclName, AclServiceManager.Action.REMOVE);
106         if (aclClusterUtil.isEntityOwner()) {
107             if (aclTag != null) {
108                 this.aclServiceUtils.releaseAclTag(aclName);
109             }
110             // Handle Rule deletion If SG Remove event is received before SG Rule delete event
111             List<Ace> aceList = AclServiceUtils.aceList(acl);
112             if (!aceList.isEmpty()) {
113                 Collection<AclInterface> aclInterfaces =
114                         ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
115                 updateAceRules(aclInterfaces, aclName, aceList, AclServiceManager.Action.REMOVE);
116             }
117         }
118     }
119
120     @Override
121     protected void update(InstanceIdentifier<Acl> key, Acl aclBefore, Acl aclAfter) {
122         String aclName = aclAfter.getAclName();
123         Collection<AclInterface> interfacesBefore =
124                 ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
125         // Find and update added ace rules in acl
126         List<Ace> addedAceRules = getChangedAceList(aclAfter, aclBefore);
127
128         // Find and update deleted ace rules in acl
129         List<Ace> deletedAceRules = getDeletedAceList(aclAfter);
130
131         if (aclClusterUtil.isEntityOwner()) {
132             LOG.debug("On update event, remove Ace rules: {} for ACL: {}", deletedAceRules, aclName);
133             updateAceRules(interfacesBefore, aclName, deletedAceRules, AclServiceManager.Action.REMOVE);
134             if (!deletedAceRules.isEmpty()) {
135                 aclServiceUtils.deleteAcesFromConfigDS(aclName, deletedAceRules);
136             }
137         }
138         updateAclCaches(aclBefore, aclAfter, interfacesBefore);
139
140         if (aclClusterUtil.isEntityOwner()) {
141             LOG.debug("On update event, add Ace rules: {} for ACL: {}", addedAceRules, aclName);
142             updateAceRules(interfacesBefore, aclName, addedAceRules, AclServiceManager.Action.ADD);
143
144             aclServiceManager.notifyAcl(aclBefore, aclAfter, interfacesBefore, AclServiceManager.Action.UPDATE);
145         }
146     }
147
148     private void updateAceRules(Collection<AclInterface> interfaceList, String aclName, List<Ace> aceList,
149             AclServiceManager.Action action) {
150         LOG.trace("update ace rules - action: {} , ace rules: {}", action.name(), aceList);
151         for (AclInterface port : interfaceList) {
152             BigInteger dpId = port.getDpId();
153             Long elanId = port.getElanId();
154             if (dpId != null && elanId != null) {
155                 for (Ace aceRule : aceList) {
156                     aclServiceManager.notifyAce(port, action, aclName, aceRule);
157                 }
158             } else {
159                 LOG.debug("Skip update ACE rules as DP ID or ELAN ID for interface {} is not present. "
160                         + "DP Id: {} ELAN ID: {}", port.getInterfaceId(), dpId, elanId);
161             }
162         }
163     }
164
165     @Override
166     protected void add(InstanceIdentifier<Acl> key, Acl acl) {
167         LOG.trace("On add event, add ACL: {}", acl);
168         this.aclDataUtil.addAcl(acl);
169
170         String aclName = acl.getAclName();
171         Integer aclTag = this.aclServiceUtils.allocateAclTag(aclName);
172         if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
173             this.aclDataUtil.addAclTag(aclName, aclTag);
174         }
175
176         updateRemoteAclCache(AclServiceUtils.getAceListFromAcl(acl), aclName, AclServiceManager.Action.ADD);
177     }
178
179     /**
180      * Update remote acl cache.
181      *
182      * @param aceList the ace list
183      * @param aclName the acl name
184      * @param action the action
185      */
186     private void updateRemoteAclCache(@NonNull List<Ace> aceList, String aclName, AclServiceManager.Action action) {
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         for (AclInterface aclInterface : aclInterfaces) {
239             AclInterface aclInterfaceInCache =
240                     aclInterfaceCache.addOrUpdate(aclInterface.getInterfaceId(), (prevAclInterface, builder) -> {
241                         SortedSet<Integer> remoteAclTags =
242                                 aclServiceUtils.getRemoteAclTags(aclInterface.getSecurityGroups(), direction);
243                         if (DirectionEgress.class.equals(direction)) {
244                             builder.egressRemoteAclTags(remoteAclTags);
245                         } else {
246                             builder.ingressRemoteAclTags(remoteAclTags);
247                         }
248                     });
249
250             aclDataUtil.addOrUpdateAclInterfaceMap(aclInterface.getSecurityGroups(), aclInterfaceInCache);
251         }
252     }
253
254     @Override
255     protected AclEventListener getDataTreeChangeListener() {
256         return this;
257     }
258
259     private static @NonNull List<Ace> getChangedAceList(Acl updatedAcl, Acl currentAcl) {
260         if (updatedAcl == null) {
261             return Collections.emptyList();
262         }
263         List<Ace> updatedAceList = AclServiceUtils.aceList(updatedAcl);
264         if (currentAcl == null) {
265             return updatedAceList;
266         }
267
268         List<Ace> currentAceList = AclServiceUtils.aceList(currentAcl);
269         updatedAceList = new ArrayList<>(updatedAceList);
270         for (Iterator<Ace> iterator = updatedAceList.iterator(); iterator.hasNext();) {
271             Ace ace1 = iterator.next();
272             for (Ace ace2 : currentAceList) {
273                 if (Objects.equals(ace1.getRuleName(), ace2.getRuleName())) {
274                     iterator.remove();
275                 }
276             }
277         }
278         return updatedAceList;
279     }
280
281     private List<Ace> getDeletedAceList(Acl acl) {
282         if (acl == null || acl.getAccessListEntries() == null || acl.getAccessListEntries().getAce() == null) {
283             return Collections.emptyList();
284         }
285         List<Ace> aceList = acl.getAccessListEntries().getAce();
286         List<Ace> deletedAceList = new ArrayList<>();
287         for (Ace ace: aceList) {
288             if (ace.augmentation(SecurityRuleAttr.class).isDeleted()) {
289                 deletedAceList.add(ace);
290             }
291         }
292         return deletedAceList;
293     }
294 }