NETVIRT-1630 migrate to md-sal APIs
[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.PreDestroy;
23 import javax.inject.Inject;
24 import javax.inject.Singleton;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.opendaylight.infrautils.utils.concurrent.Executors;
27 import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
28 import org.opendaylight.mdsal.binding.api.DataBroker;
29 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
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.serviceutils.tools.listener.AbstractAsyncDataTreeChangeListener;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.AccessLists;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.Acl;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.access.control.list.rev160218.access.lists.acl.access.list.entries.Ace;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionBase;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionEgress;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionIngress;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.SecurityRuleAttr;
48 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 @Singleton
53 public class AclEventListener extends AbstractAsyncDataTreeChangeListener<Acl> implements
54         ClusteredDataTreeChangeListener<Acl>, RecoverableListener {
55
56     private static final Logger LOG = LoggerFactory.getLogger(AclEventListener.class);
57
58     private final AclServiceManager aclServiceManager;
59     private final AclClusterUtil aclClusterUtil;
60     private final DataBroker dataBroker;
61     private final AclDataUtil aclDataUtil;
62     private final AclServiceUtils aclServiceUtils;
63     private final AclInterfaceCache aclInterfaceCache;
64
65     @Inject
66     public AclEventListener(AclServiceManager aclServiceManager, AclClusterUtil aclClusterUtil, DataBroker dataBroker,
67             AclDataUtil aclDataUtil, AclServiceUtils aclServicUtils, AclInterfaceCache aclInterfaceCache,
68             ServiceRecoveryRegistry serviceRecoveryRegistry) {
69         super(dataBroker, LogicalDatastoreType.CONFIGURATION,
70                 InstanceIdentifier.create(AccessLists.class).child(Acl.class),
71                 Executors.newListeningSingleThreadExecutor("AclEventListener", LOG));
72         this.aclServiceManager = aclServiceManager;
73         this.aclClusterUtil = aclClusterUtil;
74         this.dataBroker = dataBroker;
75         this.aclDataUtil = aclDataUtil;
76         this.aclServiceUtils = aclServicUtils;
77         this.aclInterfaceCache = aclInterfaceCache;
78         serviceRecoveryRegistry.addRecoverableListener(AclServiceUtils.getRecoverServiceRegistryKey(), this);
79     }
80
81     public void init() {
82         LOG.info("{} start", getClass().getSimpleName());
83     }
84
85     @Override
86     public void registerListener() {
87         super.register();
88     }
89
90     @Override
91     public void deregisterListener() {
92         super.close();
93     }
94
95     @Override
96     public 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     public 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     public 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     private static @NonNull List<Ace> getChangedAceList(Acl updatedAcl, Acl currentAcl) {
252         if (updatedAcl == null) {
253             return Collections.emptyList();
254         }
255         List<Ace> updatedAceList = AclServiceUtils.aceList(updatedAcl);
256         if (currentAcl == null) {
257             return updatedAceList;
258         }
259
260         List<Ace> currentAceList = AclServiceUtils.aceList(currentAcl);
261         updatedAceList = new ArrayList<>(updatedAceList);
262         for (Iterator<Ace> iterator = updatedAceList.iterator(); iterator.hasNext();) {
263             Ace ace1 = iterator.next();
264             for (Ace ace2 : currentAceList) {
265                 if (Objects.equals(ace1.getRuleName(), ace2.getRuleName())) {
266                     iterator.remove();
267                 }
268             }
269         }
270         return updatedAceList;
271     }
272
273     private List<Ace> getDeletedAceList(Acl acl) {
274         if (acl == null || acl.getAccessListEntries() == null || acl.getAccessListEntries().getAce() == null) {
275             return Collections.emptyList();
276         }
277         List<Ace> aceList = acl.getAccessListEntries().getAce();
278         List<Ace> deletedAceList = new ArrayList<>();
279         for (Ace ace: aceList) {
280             if (ace.augmentation(SecurityRuleAttr.class).isDeleted()) {
281                 deletedAceList.add(ace);
282             }
283         }
284         return deletedAceList;
285     }
286
287     @Override
288     @PreDestroy
289     public void close() {
290         super.close();
291         Executors.shutdownAndAwaitTermination(getExecutorService());
292     }
293 }