NETVIRT-1630 migrate to md-sal APIs
[netvirt.git] / aclservice / impl / src / main / java / org / opendaylight / netvirt / aclservice / listeners / AclInterfaceListener.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 java.util.ArrayList;
11 import java.util.List;
12 import javax.annotation.PreDestroy;
13 import javax.inject.Inject;
14 import javax.inject.Singleton;
15 import org.eclipse.jdt.annotation.Nullable;
16 import org.opendaylight.infrautils.utils.concurrent.Executors;
17 import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
18 import org.opendaylight.mdsal.binding.api.DataBroker;
19 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
20 import org.opendaylight.netvirt.aclservice.api.AclInterfaceCache;
21 import org.opendaylight.netvirt.aclservice.api.AclServiceManager;
22 import org.opendaylight.netvirt.aclservice.api.AclServiceManager.Action;
23 import org.opendaylight.netvirt.aclservice.api.utils.AclInterface;
24 import org.opendaylight.netvirt.aclservice.utils.AclClusterUtil;
25 import org.opendaylight.netvirt.aclservice.utils.AclDataUtil;
26 import org.opendaylight.netvirt.aclservice.utils.AclServiceUtils;
27 import org.opendaylight.serviceutils.srm.RecoverableListener;
28 import org.opendaylight.serviceutils.srm.ServiceRecoveryRegistry;
29 import org.opendaylight.serviceutils.tools.listener.AbstractAsyncDataTreeChangeListener;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.ParentRefs;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionEgress;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.DirectionIngress;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.InterfaceAcl;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.aclservice.rev160608.interfaces._interface.AllowedAddressPairs;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 @Singleton
43 public class AclInterfaceListener extends AbstractAsyncDataTreeChangeListener<Interface>
44         implements ClusteredDataTreeChangeListener<Interface>, RecoverableListener {
45     private static final Logger LOG = LoggerFactory.getLogger(AclInterfaceListener.class);
46
47     private final AclServiceManager aclServiceManager;
48     private final AclClusterUtil aclClusterUtil;
49     private final DataBroker dataBroker;
50     private final AclDataUtil aclDataUtil;
51     private final AclInterfaceCache aclInterfaceCache;
52     private final AclServiceUtils aclServiceUtils;
53
54     @Inject
55     public AclInterfaceListener(AclServiceManager aclServiceManager, AclClusterUtil aclClusterUtil,
56             DataBroker dataBroker, AclDataUtil aclDataUtil, AclInterfaceCache aclInterfaceCache,
57             AclServiceUtils aclServicUtils, ServiceRecoveryRegistry serviceRecoveryRegistry) {
58         super(dataBroker, LogicalDatastoreType.CONFIGURATION,
59                 InstanceIdentifier.create(Interfaces.class).child(Interface.class),
60                 Executors.newListeningSingleThreadExecutor("AclEventListener", LOG));
61         this.aclServiceManager = aclServiceManager;
62         this.aclClusterUtil = aclClusterUtil;
63         this.dataBroker = dataBroker;
64         this.aclDataUtil = aclDataUtil;
65         this.aclInterfaceCache = aclInterfaceCache;
66         this.aclServiceUtils = aclServicUtils;
67         serviceRecoveryRegistry.addRecoverableListener(AclServiceUtils.getRecoverServiceRegistryKey(), this);
68     }
69
70     public void init() {
71         LOG.info("{} start", getClass().getSimpleName());
72     }
73
74     @Override
75     public void registerListener() {
76         super.register();
77     }
78
79     @Override
80     public void deregisterListener() {
81         super.close();
82     }
83
84     @Override
85     public void remove(InstanceIdentifier<Interface> key, Interface port) {
86         LOG.trace("Received AclInterface remove event, port={}", port);
87         String interfaceId = port.getName();
88         AclInterface aclInterface = aclInterfaceCache.remove(interfaceId);
89         if (AclServiceUtils.isOfInterest(aclInterface)) {
90             if (aclClusterUtil.isEntityOwner()) {
91                 LOG.debug("On remove event, notify ACL unbind/remove for interface: {}", interfaceId);
92                 aclServiceManager.notify(aclInterface, null, Action.UNBIND);
93                 if (aclInterface.getDpId() != null) {
94                     aclServiceManager.notify(aclInterface, null, Action.REMOVE);
95                 }
96             }
97         }
98     }
99
100     @Override
101     public void update(@Nullable InstanceIdentifier<Interface> key, Interface portBefore, Interface portAfter) {
102         if (portBefore.augmentation(ParentRefs.class) == null
103                 && portAfter.augmentation(ParentRefs.class) != null) {
104             LOG.trace("Ignoring event for update in ParentRefs for {} ", portAfter.getName());
105             return;
106         }
107         LOG.trace("Received AclInterface update event, portBefore={}, portAfter={}", portBefore, portAfter);
108         InterfaceAcl aclInPortAfter = portAfter.augmentation(InterfaceAcl.class);
109         InterfaceAcl aclInPortBefore = portBefore.augmentation(InterfaceAcl.class);
110
111         String interfaceId = portAfter.getName();
112         org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state
113             .Interface interfaceState = AclServiceUtils.getInterfaceStateFromOperDS(dataBroker, interfaceId);
114
115         AclInterface aclInterfaceBefore = aclInterfaceCache.get(interfaceId);
116         if (aclInterfaceBefore == null || isPortSecurityEnabledNow(aclInPortBefore, aclInPortAfter)) {
117             // Updating cache now as it might have not updated when
118             // port-security-enable=false
119             aclInterfaceBefore = addOrUpdateAclInterfaceCache(interfaceId, aclInPortBefore, true, interfaceState);
120         }
121         if (AclServiceUtils.isOfInterest(aclInPortAfter) || AclServiceUtils.isOfInterest(aclInPortBefore)) {
122             List<Uuid> sgsBefore = null;
123             if (aclInPortBefore != null) {
124                 sgsBefore = aclInPortBefore.getSecurityGroups();
125             }
126             boolean isSgChanged = isSecurityGroupsChanged(sgsBefore, aclInPortAfter.getSecurityGroups());
127             AclInterface aclInterfaceAfter =
128                     addOrUpdateAclInterfaceCache(interfaceId, aclInPortAfter, isSgChanged, interfaceState);
129             updateCacheWithAddedAcls(aclInterfaceBefore, aclInterfaceAfter);
130
131             if (aclClusterUtil.isEntityOwner()) {
132                 // Handle bind/unbind service irrespective of interface state (up/down)
133                 boolean isPortSecurityEnable = aclInterfaceAfter.isPortSecurityEnabled();
134                 boolean isPortSecurityEnableBefore = aclInterfaceBefore.isPortSecurityEnabled();
135                 // if port security enable is changed and is disabled, unbind ACL service
136                 if (isPortSecurityEnableBefore != isPortSecurityEnable && !isPortSecurityEnable) {
137                     LOG.debug("Notify unbind ACL service for interface={}, isPortSecurityEnable={}", interfaceId,
138                             isPortSecurityEnable);
139                     aclServiceManager.notify(aclInterfaceAfter, null, Action.UNBIND);
140                 }
141                 if (interfaceState != null && org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces
142                         .rev140508.interfaces.state.Interface.OperStatus.Up.equals(interfaceState.getOperStatus())) {
143                     // if port security enable is changed and is enabled, bind ACL service
144                     if (isPortSecurityEnableBefore != isPortSecurityEnable && isPortSecurityEnable) {
145                         LOG.debug("Notify bind ACL service for interface={}, isPortSecurityEnable={}", interfaceId,
146                                 isPortSecurityEnable);
147                         aclServiceManager.notify(aclInterfaceAfter, null, Action.BIND);
148                     }
149                     LOG.debug("On update event, notify ACL service manager to update ACL for interface: {}",
150                             interfaceId);
151                     // handle add for AclPortsLookup before processing update
152                     aclServiceUtils.addAclPortsLookupForInterfaceUpdate(aclInterfaceBefore, aclInterfaceAfter);
153
154                     aclServiceManager.notify(aclInterfaceAfter, aclInterfaceBefore, AclServiceManager.Action.UPDATE);
155                     // handle delete for AclPortsLookup after processing update
156                     aclServiceUtils.deleteAclPortsLookupForInterfaceUpdate(aclInterfaceBefore, aclInterfaceAfter);
157                 }
158             }
159             updateCacheWithAclChange(aclInterfaceBefore, aclInterfaceAfter);
160         }
161     }
162
163     private void updateCacheWithAclChange(AclInterface aclInterfaceBefore, AclInterface aclInterfaceAfter) {
164         List<Uuid> deletedAcls = AclServiceUtils.getUpdatedAclList(aclInterfaceBefore.getSecurityGroups(),
165                 aclInterfaceAfter.getSecurityGroups());
166         if (!deletedAcls.isEmpty()) {
167             aclDataUtil.removeAclInterfaceMap(deletedAcls, aclInterfaceAfter);
168         }
169         List<AllowedAddressPairs> addedAap = AclServiceUtils.getUpdatedAllowedAddressPairs(aclInterfaceAfter
170                 .getAllowedAddressPairs(), aclInterfaceBefore.getAllowedAddressPairs());
171         List<AllowedAddressPairs> deletedAap = AclServiceUtils.getUpdatedAllowedAddressPairs(aclInterfaceBefore
172                 .getAllowedAddressPairs(), aclInterfaceAfter.getAllowedAddressPairs());
173         if (!deletedAap.isEmpty() || !addedAap.isEmpty()) {
174             LOG.debug("Update cache with new AAP = {}", aclInterfaceAfter.getInterfaceId());
175             aclDataUtil.addOrUpdateAclInterfaceMap(aclInterfaceAfter.getSecurityGroups(), aclInterfaceAfter);
176         }
177     }
178
179     private void updateCacheWithAddedAcls(AclInterface aclInterfaceBefore, AclInterface aclInterfaceAfter) {
180         List<Uuid> addedAcls = AclServiceUtils.getUpdatedAclList(aclInterfaceAfter.getSecurityGroups(),
181                 aclInterfaceBefore.getSecurityGroups());
182         if (addedAcls != null && !addedAcls.isEmpty()) {
183             LOG.debug("Update cache by adding interface={}", aclInterfaceAfter.getInterfaceId());
184             aclDataUtil.addOrUpdateAclInterfaceMap(addedAcls, aclInterfaceAfter);
185         }
186     }
187
188     private boolean isPortSecurityEnabledNow(InterfaceAcl aclInPortBefore, InterfaceAcl aclInPortAfter) {
189         return aclInPortBefore != null && !aclInPortBefore.isPortSecurityEnabled() && aclInPortAfter != null
190                 && aclInPortAfter.isPortSecurityEnabled();
191     }
192
193     private boolean isSecurityGroupsChanged(@Nullable List<Uuid> sgsBefore, @Nullable List<Uuid> sgsAfter) {
194         if (sgsBefore == null && sgsAfter == null) {
195             return false;
196         }
197         if (sgsBefore == null || sgsAfter == null) {
198             return true;
199         }
200         return !(sgsBefore.containsAll(sgsAfter) && sgsAfter.containsAll(sgsBefore));
201     }
202
203     private AclInterface addOrUpdateAclInterfaceCache(String interfaceId, InterfaceAcl aclInPort) {
204         return addOrUpdateAclInterfaceCache(interfaceId, aclInPort, true, null);
205     }
206
207     private AclInterface addOrUpdateAclInterfaceCache(String interfaceId, InterfaceAcl aclInPort, boolean isSgChanged,
208             org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state
209                 .@Nullable Interface interfaceState) {
210         AclInterface aclInterface = aclInterfaceCache.addOrUpdate(interfaceId, (prevAclInterface, builder) -> {
211             List<Uuid> sgs = new ArrayList<>();
212             if (aclInPort != null) {
213                 sgs = aclInPort.getSecurityGroups();
214                 builder.portSecurityEnabled(aclInPort.isPortSecurityEnabled())
215                         .interfaceType(aclInPort.getInterfaceType()).securityGroups(sgs)
216                         .allowedAddressPairs(aclInPort.getAllowedAddressPairs()).subnetInfo(aclInPort.getSubnetInfo());
217             }
218
219             if ((prevAclInterface == null || prevAclInterface.getLPortTag() == null) && interfaceState != null) {
220                 builder.dpId(AclServiceUtils.getDpIdFromIterfaceState(interfaceState))
221                         .lPortTag(interfaceState.getIfIndex()).isMarkedForDelete(false);
222             }
223
224             if (prevAclInterface == null || prevAclInterface.getElanId() == null) {
225                 builder.elanId(AclServiceUtils.getElanIdFromInterface(interfaceId, dataBroker));
226             }
227             if (prevAclInterface == null || isSgChanged) {
228                 builder.ingressRemoteAclTags(aclServiceUtils.getRemoteAclTags(sgs, DirectionIngress.class))
229                         .egressRemoteAclTags(aclServiceUtils.getRemoteAclTags(sgs, DirectionEgress.class));
230             }
231         });
232         // Clone and return the ACL interface object
233         return AclInterface.builder(aclInterface).build();
234     }
235
236     @Override
237     public void add(InstanceIdentifier<Interface> key, Interface port) {
238         LOG.trace("Received AclInterface add event, port={}", port);
239         InterfaceAcl aclInPort = port.augmentation(InterfaceAcl.class);
240         if (AclServiceUtils.isOfInterest(aclInPort)) {
241             String interfaceId = port.getName();
242             AclInterface aclInterface = addOrUpdateAclInterfaceCache(interfaceId, aclInPort);
243
244             // if interface state event comes first followed by interface config event.
245             if (aclInterface.getDpId() != null && aclInterface.getElanId() != null && aclClusterUtil.isEntityOwner()) {
246                 LOG.debug("On add event, notify ACL bind/add for interface: {}", interfaceId);
247                 aclServiceManager.notify(aclInterface, null, Action.BIND);
248                 aclServiceManager.notify(aclInterface, null, Action.ADD);
249             }
250         }
251     }
252
253     @Override
254     @PreDestroy
255     public void close() {
256         super.close();
257         Executors.shutdownAndAwaitTermination(getExecutorService());
258     }
259 }