Switch to JDT annotations for Nullable and NonNull
[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         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         if (aclClusterUtil.isEntityOwner()) {
111             // Handle Rule deletion If SG Remove event is received before SG Rule delete event
112             List<Ace> aceList = acl.getAccessListEntries().getAce();
113             Collection<AclInterface> aclInterfaces =
114                     ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
115             updateAceRules(aclInterfaces, aclName, aceList, AclServiceManager.Action.REMOVE);
116         }
117     }
118
119     @Override
120     protected void update(InstanceIdentifier<Acl> key, Acl aclBefore, Acl aclAfter) {
121         if (!AclServiceUtils.isOfAclInterest(aclAfter) && !AclServiceUtils.isOfAclInterest(aclBefore)) {
122             LOG.trace("before {} and after {} does not have SecurityRuleAttr augmentation",
123                     aclBefore.getAclName(), aclAfter.getAclName());
124             return;
125         }
126         String aclName = aclAfter.getAclName();
127         Collection<AclInterface> interfacesBefore =
128                 ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
129         // Find and update added ace rules in acl
130         List<Ace> addedAceRules = getChangedAceList(aclAfter, aclBefore);
131
132         // Find and update deleted ace rules in acl
133         List<Ace> deletedAceRules = getDeletedAceList(aclAfter);
134
135         if (aclClusterUtil.isEntityOwner()) {
136             LOG.debug("On update event, remove Ace rules: {} for ACL: {}", deletedAceRules, aclName);
137             updateAceRules(interfacesBefore, aclName, deletedAceRules, AclServiceManager.Action.REMOVE);
138             if (null != deletedAceRules && !deletedAceRules.isEmpty()) {
139                 aclServiceUtils.deleteAcesFromConfigDS(aclName, deletedAceRules);
140             }
141         }
142         updateAclCaches(aclBefore, aclAfter, interfacesBefore);
143
144         if (aclClusterUtil.isEntityOwner()) {
145             LOG.debug("On update event, add Ace rules: {} for ACL: {}", addedAceRules, aclName);
146             updateAceRules(interfacesBefore, aclName, addedAceRules, AclServiceManager.Action.ADD);
147
148             aclServiceManager.notifyAcl(aclBefore, aclAfter, interfacesBefore, AclServiceManager.Action.UPDATE);
149         }
150     }
151
152     private void updateAceRules(Collection<AclInterface> interfaceList, String aclName, List<Ace> aceList,
153             AclServiceManager.Action action) {
154         if (null != aceList && !aceList.isEmpty()) {
155             LOG.trace("update ace rules - action: {} , ace rules: {}", action.name(), aceList);
156             for (AclInterface port : interfaceList) {
157                 for (Ace aceRule : aceList) {
158                     aclServiceManager.notifyAce(port, action, aclName, aceRule);
159                 }
160             }
161         }
162     }
163
164     @Override
165     protected void add(InstanceIdentifier<Acl> key, Acl acl) {
166         String aclName = acl.getAclName();
167         if (!AclServiceUtils.isOfAclInterest(acl)) {
168             LOG.trace("{} does not have SecurityRuleAttr augmentation", aclName);
169             return;
170         }
171
172         LOG.trace("On add event, add ACL: {}", acl);
173         this.aclDataUtil.addAcl(acl);
174
175         Integer aclTag = this.aclServiceUtils.allocateAclTag(aclName);
176         if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
177             this.aclDataUtil.addAclTag(aclName, aclTag);
178         }
179
180         updateRemoteAclCache(acl.getAccessListEntries().getAce(), aclName, AclServiceManager.Action.ADD);
181     }
182
183     /**
184      * Update remote acl cache.
185      *
186      * @param aceList the ace list
187      * @param aclName the acl name
188      * @param action the action
189      */
190     private void updateRemoteAclCache(@Nullable List<Ace> aceList, String aclName, AclServiceManager.Action action) {
191         if (null == aceList) {
192             return;
193         }
194         for (Ace ace : aceList) {
195             SecurityRuleAttr aceAttributes = ace.augmentation(SecurityRuleAttr.class);
196             if (AclServiceUtils.doesAceHaveRemoteGroupId(aceAttributes)) {
197                 if (action == AclServiceManager.Action.ADD) {
198                     aclDataUtil.addRemoteAclId(aceAttributes.getRemoteGroupId(), new Uuid(aclName),
199                             aceAttributes.getDirection());
200                 } else {
201                     aclDataUtil.removeRemoteAclId(aceAttributes.getRemoteGroupId(), new Uuid(aclName),
202                             aceAttributes.getDirection());
203                 }
204             }
205         }
206     }
207
208     private void updateAclCaches(Acl aclBefore, Acl aclAfter, Collection<AclInterface> aclInterfaces) {
209         String aclName = aclAfter.getAclName();
210         Integer aclTag = this.aclDataUtil.getAclTag(aclName);
211         if (aclTag == null) {
212             aclTag = this.aclServiceUtils.allocateAclTag(aclName);
213             if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
214                 this.aclDataUtil.addAclTag(aclName, aclTag);
215             }
216         }
217         this.aclDataUtil.addAcl(aclAfter);
218
219         updateAclCaches(aclBefore, aclAfter, aclInterfaces, DirectionEgress.class);
220         updateAclCaches(aclBefore, aclAfter, aclInterfaces, DirectionIngress.class);
221     }
222
223     private void updateAclCaches(Acl aclBefore, Acl aclAfter, Collection<AclInterface> aclInterfaces,
224             Class<? extends DirectionBase> direction) {
225         Uuid aclId = new Uuid(aclAfter.getAclName());
226         Set<Uuid> remoteAclsBefore = AclServiceUtils.getRemoteAclIdsByDirection(aclBefore, direction);
227         Set<Uuid> remoteAclsAfter = AclServiceUtils.getRemoteAclIdsByDirection(aclAfter, direction);
228
229         Set<Uuid> remoteAclsDeleted = new HashSet<>(remoteAclsBefore);
230         remoteAclsDeleted.removeAll(remoteAclsAfter);
231         for (Uuid remoteAcl : remoteAclsDeleted) {
232             aclDataUtil.removeRemoteAclId(remoteAcl, aclId, direction);
233         }
234
235         Set<Uuid> remoteAclsAdded = new HashSet<>(remoteAclsAfter);
236         remoteAclsAdded.removeAll(remoteAclsBefore);
237         for (Uuid remoteAcl : remoteAclsAdded) {
238             aclDataUtil.addRemoteAclId(remoteAcl, aclId, direction);
239         }
240
241         if (remoteAclsDeleted.isEmpty() && remoteAclsAdded.isEmpty()) {
242             return;
243         }
244
245         if (aclInterfaces != null) {
246             for (AclInterface aclInterface : aclInterfaces) {
247                 AclInterface aclInterfaceInCache =
248                         aclInterfaceCache.addOrUpdate(aclInterface.getInterfaceId(), (prevAclInterface, builder) -> {
249                             SortedSet<Integer> remoteAclTags =
250                                     aclServiceUtils.getRemoteAclTags(aclInterface.getSecurityGroups(), direction);
251                             if (DirectionEgress.class.equals(direction)) {
252                                 builder.egressRemoteAclTags(remoteAclTags);
253                             } else {
254                                 builder.ingressRemoteAclTags(remoteAclTags);
255                             }
256                         });
257
258                 aclDataUtil.addOrUpdateAclInterfaceMap(aclInterface.getSecurityGroups(), aclInterfaceInCache);
259             }
260         }
261     }
262
263     @Override
264     protected AclEventListener getDataTreeChangeListener() {
265         return this;
266     }
267
268     @NonNull
269     private List<Ace> getChangedAceList(Acl updatedAcl, Acl currentAcl) {
270         if (updatedAcl == null) {
271             return Collections.emptyList();
272         }
273         List<Ace> updatedAceList =
274             updatedAcl.getAccessListEntries() == null || updatedAcl.getAccessListEntries().getAce() == null
275                 ? new ArrayList<>()
276                 : new ArrayList<>(updatedAcl.getAccessListEntries().getAce());
277         if (currentAcl == null) {
278             return updatedAceList;
279         }
280         List<Ace> currentAceList =
281             currentAcl.getAccessListEntries() == null || currentAcl.getAccessListEntries().getAce() == null
282                 ? new ArrayList<>()
283                 : new ArrayList<>(currentAcl.getAccessListEntries().getAce());
284         for (Iterator<Ace> iterator = updatedAceList.iterator(); iterator.hasNext();) {
285             Ace ace1 = iterator.next();
286             for (Ace ace2 : currentAceList) {
287                 if (Objects.equals(ace1.getRuleName(), ace2.getRuleName())) {
288                     iterator.remove();
289                 }
290             }
291         }
292         return updatedAceList;
293     }
294
295     private List<Ace> getDeletedAceList(Acl acl) {
296         if (acl == null || acl.getAccessListEntries() == null || acl.getAccessListEntries().getAce() == null) {
297             return null;
298         }
299         List<Ace> aceList = acl.getAccessListEntries().getAce();
300         List<Ace> deletedAceList = new ArrayList<>();
301         for (Ace ace: aceList) {
302             if (ace.augmentation(SecurityRuleAttr.class).isDeleted()) {
303                 deletedAceList.add(ace);
304             }
305         }
306         return deletedAceList;
307     }
308 }