Optimize method in AclEventListener.java
[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             if (null != acl.getAccessListEntries() && null != acl.getAccessListEntries().getAce()) {
111                 List<Ace> aceList = acl.getAccessListEntries().getAce();
112                 Collection<AclInterface> aclInterfaces =
113                         ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
114                 updateAceRules(aclInterfaces, aclName, aceList, AclServiceManager.Action.REMOVE);
115             }
116         }
117     }
118
119     @Override
120     protected void update(InstanceIdentifier<Acl> key, Acl aclBefore, Acl aclAfter) {
121         String aclName = aclAfter.getAclName();
122         Collection<AclInterface> interfacesBefore =
123                 ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
124         // Find and update added ace rules in acl
125         List<Ace> addedAceRules = getChangedAceList(aclAfter, aclBefore);
126
127         // Find and update deleted ace rules in acl
128         List<Ace> deletedAceRules = getDeletedAceList(aclAfter);
129
130         if (aclClusterUtil.isEntityOwner()) {
131             LOG.debug("On update event, remove Ace rules: {} for ACL: {}", deletedAceRules, aclName);
132             updateAceRules(interfacesBefore, aclName, deletedAceRules, AclServiceManager.Action.REMOVE);
133             if (!deletedAceRules.isEmpty()) {
134                 aclServiceUtils.deleteAcesFromConfigDS(aclName, deletedAceRules);
135             }
136         }
137         updateAclCaches(aclBefore, aclAfter, interfacesBefore);
138
139         if (aclClusterUtil.isEntityOwner()) {
140             LOG.debug("On update event, add Ace rules: {} for ACL: {}", addedAceRules, aclName);
141             updateAceRules(interfacesBefore, aclName, addedAceRules, AclServiceManager.Action.ADD);
142
143             aclServiceManager.notifyAcl(aclBefore, aclAfter, interfacesBefore, AclServiceManager.Action.UPDATE);
144         }
145     }
146
147     private void updateAceRules(Collection<AclInterface> interfaceList, String aclName, List<Ace> aceList,
148             AclServiceManager.Action action) {
149         LOG.trace("update ace rules - action: {} , ace rules: {}", action.name(), aceList);
150         for (AclInterface port : interfaceList) {
151             for (Ace aceRule : aceList) {
152                 aclServiceManager.notifyAce(port, action, aclName, aceRule);
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         for (AclInterface aclInterface : aclInterfaces) {
231             AclInterface aclInterfaceInCache =
232                     aclInterfaceCache.addOrUpdate(aclInterface.getInterfaceId(), (prevAclInterface, builder) -> {
233                         SortedSet<Integer> remoteAclTags =
234                                 aclServiceUtils.getRemoteAclTags(aclInterface.getSecurityGroups(), direction);
235                         if (DirectionEgress.class.equals(direction)) {
236                             builder.egressRemoteAclTags(remoteAclTags);
237                         } else {
238                             builder.ingressRemoteAclTags(remoteAclTags);
239                         }
240                     });
241
242             aclDataUtil.addOrUpdateAclInterfaceMap(aclInterface.getSecurityGroups(), aclInterfaceInCache);
243         }
244     }
245
246     @Override
247     protected AclEventListener getDataTreeChangeListener() {
248         return this;
249     }
250
251     @NonNull
252     private List<Ace> getChangedAceList(Acl updatedAcl, Acl currentAcl) {
253         if (updatedAcl == null) {
254             return Collections.emptyList();
255         }
256         List<Ace> updatedAceList =
257             updatedAcl.getAccessListEntries() == null || updatedAcl.getAccessListEntries().getAce() == null
258                 ? new ArrayList<>()
259                 : new ArrayList<>(updatedAcl.getAccessListEntries().getAce());
260         if (currentAcl == null) {
261             return updatedAceList;
262         }
263         List<Ace> currentAceList =
264             currentAcl.getAccessListEntries() == null || currentAcl.getAccessListEntries().getAce() == null
265                 ? new ArrayList<>()
266                 : new ArrayList<>(currentAcl.getAccessListEntries().getAce());
267         for (Iterator<Ace> iterator = updatedAceList.iterator(); iterator.hasNext();) {
268             Ace ace1 = iterator.next();
269             for (Ace ace2 : currentAceList) {
270                 if (Objects.equals(ace1.getRuleName(), ace2.getRuleName())) {
271                     iterator.remove();
272                 }
273             }
274         }
275         return updatedAceList;
276     }
277
278     private List<Ace> getDeletedAceList(Acl acl) {
279         if (acl == null || acl.getAccessListEntries() == null || acl.getAccessListEntries().getAce() == null) {
280             return Collections.emptyList();
281         }
282         List<Ace> aceList = acl.getAccessListEntries().getAce();
283         List<Ace> deletedAceList = new ArrayList<>();
284         for (Ace ace: aceList) {
285             if (ace.augmentation(SecurityRuleAttr.class).isDeleted()) {
286                 deletedAceList.add(ace);
287             }
288         }
289         return deletedAceList;
290     }
291 }