Id Manager allocateId optimization
[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             // Handle Rule deletion If SG Remove event is received before SG Rule delete event
108             List<Ace> aceList = AclServiceUtils.aceList(acl);
109             if (!aceList.isEmpty()) {
110                 Collection<AclInterface> aclInterfaces =
111                         ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
112                 updateAceRules(aclInterfaces, aclName, aceList, AclServiceManager.Action.REMOVE);
113             }
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 (!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         LOG.trace("update ace rules - action: {} , ace rules: {}", action.name(), aceList);
148         for (AclInterface port : interfaceList) {
149             BigInteger dpId = port.getDpId();
150             Long elanId = port.getElanId();
151             if (dpId != null && elanId != null) {
152                 for (Ace aceRule : aceList) {
153                     aclServiceManager.notifyAce(port, action, aclName, aceRule);
154                 }
155             } else {
156                 LOG.debug("Skip update ACE rules as DP ID or ELAN ID for interface {} is not present. "
157                         + "DP Id: {} ELAN ID: {}", port.getInterfaceId(), dpId, elanId);
158             }
159         }
160     }
161
162     @Override
163     protected void add(InstanceIdentifier<Acl> key, Acl acl) {
164         LOG.trace("On add event, add ACL: {}", acl);
165         this.aclDataUtil.addAcl(acl);
166
167         String aclName = acl.getAclName();
168         Integer aclTag = AclServiceUtils.getAclTag(acl);
169         if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
170             this.aclDataUtil.addAclTag(aclName, aclTag);
171         }
172
173         updateRemoteAclCache(AclServiceUtils.getAceListFromAcl(acl), 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(@NonNull List<Ace> aceList, String aclName, AclServiceManager.Action action) {
184         for (Ace ace : aceList) {
185             SecurityRuleAttr aceAttributes = ace.augmentation(SecurityRuleAttr.class);
186             if (AclServiceUtils.doesAceHaveRemoteGroupId(aceAttributes)) {
187                 if (action == AclServiceManager.Action.ADD) {
188                     aclDataUtil.addRemoteAclId(aceAttributes.getRemoteGroupId(), new Uuid(aclName),
189                             aceAttributes.getDirection());
190                 } else {
191                     aclDataUtil.removeRemoteAclId(aceAttributes.getRemoteGroupId(), new Uuid(aclName),
192                             aceAttributes.getDirection());
193                 }
194             }
195         }
196     }
197
198     private void updateAclCaches(Acl aclBefore, Acl aclAfter, Collection<AclInterface> aclInterfaces) {
199         String aclName = aclAfter.getAclName();
200         Integer aclTag = this.aclDataUtil.getAclTag(aclName);
201         if (aclTag == null) {
202             aclTag = AclServiceUtils.getAclTag(aclAfter);
203             if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
204                 this.aclDataUtil.addAclTag(aclName, aclTag);
205             }
206         }
207         this.aclDataUtil.addAcl(aclAfter);
208
209         updateAclCaches(aclBefore, aclAfter, aclInterfaces, DirectionEgress.class);
210         updateAclCaches(aclBefore, aclAfter, aclInterfaces, DirectionIngress.class);
211     }
212
213     private void updateAclCaches(Acl aclBefore, Acl aclAfter, Collection<AclInterface> aclInterfaces,
214             Class<? extends DirectionBase> direction) {
215         Uuid aclId = new Uuid(aclAfter.getAclName());
216         Set<Uuid> remoteAclsBefore = AclServiceUtils.getRemoteAclIdsByDirection(aclBefore, direction);
217         Set<Uuid> remoteAclsAfter = AclServiceUtils.getRemoteAclIdsByDirection(aclAfter, direction);
218
219         Set<Uuid> remoteAclsDeleted = new HashSet<>(remoteAclsBefore);
220         remoteAclsDeleted.removeAll(remoteAclsAfter);
221         for (Uuid remoteAcl : remoteAclsDeleted) {
222             aclDataUtil.removeRemoteAclId(remoteAcl, aclId, direction);
223         }
224
225         Set<Uuid> remoteAclsAdded = new HashSet<>(remoteAclsAfter);
226         remoteAclsAdded.removeAll(remoteAclsBefore);
227         for (Uuid remoteAcl : remoteAclsAdded) {
228             aclDataUtil.addRemoteAclId(remoteAcl, aclId, direction);
229         }
230
231         if (remoteAclsDeleted.isEmpty() && remoteAclsAdded.isEmpty()) {
232             return;
233         }
234
235         for (AclInterface aclInterface : aclInterfaces) {
236             AclInterface aclInterfaceInCache =
237                     aclInterfaceCache.addOrUpdate(aclInterface.getInterfaceId(), (prevAclInterface, builder) -> {
238                         SortedSet<Integer> remoteAclTags =
239                                 aclServiceUtils.getRemoteAclTags(aclInterface.getSecurityGroups(), direction);
240                         if (DirectionEgress.class.equals(direction)) {
241                             builder.egressRemoteAclTags(remoteAclTags);
242                         } else {
243                             builder.ingressRemoteAclTags(remoteAclTags);
244                         }
245                     });
246
247             aclDataUtil.addOrUpdateAclInterfaceMap(aclInterface.getSecurityGroups(), aclInterfaceInCache);
248         }
249     }
250
251     @Override
252     protected AclEventListener getDataTreeChangeListener() {
253         return this;
254     }
255
256     private static @NonNull List<Ace> getChangedAceList(Acl updatedAcl, Acl currentAcl) {
257         if (updatedAcl == null) {
258             return Collections.emptyList();
259         }
260         List<Ace> updatedAceList = AclServiceUtils.aceList(updatedAcl);
261         if (currentAcl == null) {
262             return updatedAceList;
263         }
264
265         List<Ace> currentAceList = AclServiceUtils.aceList(currentAcl);
266         updatedAceList = new ArrayList<>(updatedAceList);
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 }