6b7ce297ed7306bb77ca3398f56fb7762c6dd726
[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.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
25 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
28 import org.opendaylight.netvirt.aclservice.api.AclInterfaceCache;
29 import org.opendaylight.netvirt.aclservice.api.AclServiceManager;
30 import org.opendaylight.netvirt.aclservice.api.utils.AclInterface;
31 import org.opendaylight.netvirt.aclservice.utils.AclClusterUtil;
32 import org.opendaylight.netvirt.aclservice.utils.AclConstants;
33 import org.opendaylight.netvirt.aclservice.utils.AclDataUtil;
34 import org.opendaylight.netvirt.aclservice.utils.AclServiceUtils;
35 import org.opendaylight.serviceutils.srm.RecoverableListener;
36 import org.opendaylight.serviceutils.srm.ServiceRecoveryRegistry;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionBase;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionEgress;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionIngress;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 @Singleton
50 public class AclEventListener extends AsyncDataTreeChangeListenerBase<Acl, AclEventListener> implements
51         ClusteredDataTreeChangeListener<Acl>, RecoverableListener {
52
53     private static final Logger LOG = LoggerFactory.getLogger(AclEventListener.class);
54
55     private final AclServiceManager aclServiceManager;
56     private final AclClusterUtil aclClusterUtil;
57     private final DataBroker dataBroker;
58     private final AclDataUtil aclDataUtil;
59     private final AclServiceUtils aclServiceUtils;
60     private final AclInterfaceCache aclInterfaceCache;
61
62     @Inject
63     public AclEventListener(AclServiceManager aclServiceManager, AclClusterUtil aclClusterUtil, DataBroker dataBroker,
64             AclDataUtil aclDataUtil, AclServiceUtils aclServicUtils, AclInterfaceCache aclInterfaceCache,
65             ServiceRecoveryRegistry serviceRecoveryRegistry) {
66         super(Acl.class, AclEventListener.class);
67         this.aclServiceManager = aclServiceManager;
68         this.aclClusterUtil = aclClusterUtil;
69         this.dataBroker = dataBroker;
70         this.aclDataUtil = aclDataUtil;
71         this.aclServiceUtils = aclServicUtils;
72         this.aclInterfaceCache = aclInterfaceCache;
73         serviceRecoveryRegistry.addRecoverableListener(AclServiceUtils.getRecoverServiceRegistryKey(), this);
74     }
75
76     @Override
77     @PostConstruct
78     public void init() {
79         LOG.info("{} start", getClass().getSimpleName());
80         registerListener();
81     }
82
83     @Override
84     public void registerListener() {
85         registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker);
86     }
87
88     @Override
89     protected InstanceIdentifier<Acl> getWildCardPath() {
90         return InstanceIdentifier.create(AccessLists.class).child(Acl.class);
91     }
92
93     @Override
94     protected void remove(InstanceIdentifier<Acl> key, Acl acl) {
95         LOG.trace("On remove event, remove ACL: {}", acl);
96         String aclName = acl.getAclName();
97         this.aclDataUtil.removeAcl(aclName);
98         Integer aclTag = this.aclDataUtil.getAclTag(aclName);
99         if (aclTag != null) {
100             this.aclDataUtil.removeAclTag(aclName);
101         }
102
103         updateRemoteAclCache(AclServiceUtils.getAceListFromAcl(acl), aclName, AclServiceManager.Action.REMOVE);
104         if (aclClusterUtil.isEntityOwner()) {
105             if (aclTag != null) {
106                 this.aclServiceUtils.releaseAclTag(aclName);
107             }
108             // Handle Rule deletion If SG Remove event is received before SG Rule delete event
109             List<Ace> aceList = AclServiceUtils.aceList(acl);
110             if (!aceList.isEmpty()) {
111                 Collection<AclInterface> aclInterfaces =
112                         ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
113                 updateAceRules(aclInterfaces, aclName, aceList, AclServiceManager.Action.REMOVE);
114             }
115         }
116     }
117
118     @Override
119     protected void update(InstanceIdentifier<Acl> key, Acl aclBefore, Acl aclAfter) {
120         String aclName = aclAfter.getAclName();
121         Collection<AclInterface> interfacesBefore =
122                 ImmutableSet.copyOf(aclDataUtil.getInterfaceList(new Uuid(aclName)));
123         // Find and update added ace rules in acl
124         List<Ace> addedAceRules = getChangedAceList(aclAfter, aclBefore);
125
126         // Find and update deleted ace rules in acl
127         List<Ace> deletedAceRules = getDeletedAceList(aclAfter);
128
129         if (aclClusterUtil.isEntityOwner()) {
130             LOG.debug("On update event, remove Ace rules: {} for ACL: {}", deletedAceRules, aclName);
131             updateAceRules(interfacesBefore, aclName, deletedAceRules, AclServiceManager.Action.REMOVE);
132             if (!deletedAceRules.isEmpty()) {
133                 aclServiceUtils.deleteAcesFromConfigDS(aclName, deletedAceRules);
134             }
135         }
136         updateAclCaches(aclBefore, aclAfter, interfacesBefore);
137
138         if (aclClusterUtil.isEntityOwner()) {
139             LOG.debug("On update event, add Ace rules: {} for ACL: {}", addedAceRules, aclName);
140             updateAceRules(interfacesBefore, aclName, addedAceRules, AclServiceManager.Action.ADD);
141
142             aclServiceManager.notifyAcl(aclBefore, aclAfter, interfacesBefore, AclServiceManager.Action.UPDATE);
143         }
144     }
145
146     private void updateAceRules(Collection<AclInterface> interfaceList, String aclName, List<Ace> aceList,
147             AclServiceManager.Action action) {
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     @Override
157     protected void add(InstanceIdentifier<Acl> key, Acl acl) {
158         LOG.trace("On add event, add ACL: {}", acl);
159         this.aclDataUtil.addAcl(acl);
160
161         String aclName = acl.getAclName();
162         Integer aclTag = this.aclServiceUtils.allocateAclTag(aclName);
163         if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
164             this.aclDataUtil.addAclTag(aclName, aclTag);
165         }
166
167         updateRemoteAclCache(AclServiceUtils.getAceListFromAcl(acl), aclName, AclServiceManager.Action.ADD);
168     }
169
170     /**
171      * Update remote acl cache.
172      *
173      * @param aceList the ace list
174      * @param aclName the acl name
175      * @param action the action
176      */
177     private void updateRemoteAclCache(@NonNull List<Ace> aceList, String aclName, AclServiceManager.Action action) {
178         for (Ace ace : aceList) {
179             SecurityRuleAttr aceAttributes = ace.augmentation(SecurityRuleAttr.class);
180             if (AclServiceUtils.doesAceHaveRemoteGroupId(aceAttributes)) {
181                 if (action == AclServiceManager.Action.ADD) {
182                     aclDataUtil.addRemoteAclId(aceAttributes.getRemoteGroupId(), new Uuid(aclName),
183                             aceAttributes.getDirection());
184                 } else {
185                     aclDataUtil.removeRemoteAclId(aceAttributes.getRemoteGroupId(), new Uuid(aclName),
186                             aceAttributes.getDirection());
187                 }
188             }
189         }
190     }
191
192     private void updateAclCaches(Acl aclBefore, Acl aclAfter, Collection<AclInterface> aclInterfaces) {
193         String aclName = aclAfter.getAclName();
194         Integer aclTag = this.aclDataUtil.getAclTag(aclName);
195         if (aclTag == null) {
196             aclTag = this.aclServiceUtils.allocateAclTag(aclName);
197             if (aclTag != null && aclTag != AclConstants.INVALID_ACL_TAG) {
198                 this.aclDataUtil.addAclTag(aclName, aclTag);
199             }
200         }
201         this.aclDataUtil.addAcl(aclAfter);
202
203         updateAclCaches(aclBefore, aclAfter, aclInterfaces, DirectionEgress.class);
204         updateAclCaches(aclBefore, aclAfter, aclInterfaces, DirectionIngress.class);
205     }
206
207     private void updateAclCaches(Acl aclBefore, Acl aclAfter, Collection<AclInterface> aclInterfaces,
208             Class<? extends DirectionBase> direction) {
209         Uuid aclId = new Uuid(aclAfter.getAclName());
210         Set<Uuid> remoteAclsBefore = AclServiceUtils.getRemoteAclIdsByDirection(aclBefore, direction);
211         Set<Uuid> remoteAclsAfter = AclServiceUtils.getRemoteAclIdsByDirection(aclAfter, direction);
212
213         Set<Uuid> remoteAclsDeleted = new HashSet<>(remoteAclsBefore);
214         remoteAclsDeleted.removeAll(remoteAclsAfter);
215         for (Uuid remoteAcl : remoteAclsDeleted) {
216             aclDataUtil.removeRemoteAclId(remoteAcl, aclId, direction);
217         }
218
219         Set<Uuid> remoteAclsAdded = new HashSet<>(remoteAclsAfter);
220         remoteAclsAdded.removeAll(remoteAclsBefore);
221         for (Uuid remoteAcl : remoteAclsAdded) {
222             aclDataUtil.addRemoteAclId(remoteAcl, aclId, direction);
223         }
224
225         if (remoteAclsDeleted.isEmpty() && remoteAclsAdded.isEmpty()) {
226             return;
227         }
228
229         for (AclInterface aclInterface : aclInterfaces) {
230             AclInterface aclInterfaceInCache =
231                     aclInterfaceCache.addOrUpdate(aclInterface.getInterfaceId(), (prevAclInterface, builder) -> {
232                         SortedSet<Integer> remoteAclTags =
233                                 aclServiceUtils.getRemoteAclTags(aclInterface.getSecurityGroups(), direction);
234                         if (DirectionEgress.class.equals(direction)) {
235                             builder.egressRemoteAclTags(remoteAclTags);
236                         } else {
237                             builder.ingressRemoteAclTags(remoteAclTags);
238                         }
239                     });
240
241             aclDataUtil.addOrUpdateAclInterfaceMap(aclInterface.getSecurityGroups(), aclInterfaceInCache);
242         }
243     }
244
245     @Override
246     protected AclEventListener getDataTreeChangeListener() {
247         return this;
248     }
249
250     private static @NonNull List<Ace> getChangedAceList(Acl updatedAcl, Acl currentAcl) {
251         if (updatedAcl == null) {
252             return Collections.emptyList();
253         }
254         List<Ace> updatedAceList = AclServiceUtils.aceList(updatedAcl);
255         if (currentAcl == null) {
256             return updatedAceList;
257         }
258
259         List<Ace> currentAceList = AclServiceUtils.aceList(currentAcl);
260         updatedAceList = new ArrayList<>(updatedAceList);
261         for (Iterator<Ace> iterator = updatedAceList.iterator(); iterator.hasNext();) {
262             Ace ace1 = iterator.next();
263             for (Ace ace2 : currentAceList) {
264                 if (Objects.equals(ace1.getRuleName(), ace2.getRuleName())) {
265                     iterator.remove();
266                 }
267             }
268         }
269         return updatedAceList;
270     }
271
272     private List<Ace> getDeletedAceList(Acl acl) {
273         if (acl == null || acl.getAccessListEntries() == null || acl.getAccessListEntries().getAce() == null) {
274             return Collections.emptyList();
275         }
276         List<Ace> aceList = acl.getAccessListEntries().getAce();
277         List<Ace> deletedAceList = new ArrayList<>();
278         for (Ace ace: aceList) {
279             if (ace.augmentation(SecurityRuleAttr.class).isDeleted()) {
280                 deletedAceList.add(ace);
281             }
282         }
283         return deletedAceList;
284     }
285 }