Bump odlparent->6.0.0,mdsal->5.0.3
[netvirt.git] / natservice / impl / src / main / java / org / opendaylight / netvirt / natservice / ha / SnatCentralizedSwitchChangeListener.java
1 /*
2  * Copyright (c) 2017, 2018 Red Hat, Inc. 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
9 package org.opendaylight.netvirt.natservice.ha;
10
11 import static org.opendaylight.genius.infra.Datastore.CONFIGURATION;
12
13 import java.time.Duration;
14 import java.util.Objects;
15 import java.util.concurrent.ExecutionException;
16 import javax.annotation.PostConstruct;
17 import javax.inject.Inject;
18 import javax.inject.Singleton;
19 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
22 import org.opendaylight.genius.datastoreutils.listeners.DataTreeEventCallbackRegistrar;
23 import org.opendaylight.genius.infra.Datastore;
24 import org.opendaylight.genius.infra.ManagedNewTransactionRunner;
25 import org.opendaylight.genius.infra.ManagedNewTransactionRunnerImpl;
26 import org.opendaylight.genius.infra.TypedReadWriteTransaction;
27 import org.opendaylight.infrautils.utils.concurrent.ListenableFutures;
28 import org.opendaylight.netvirt.natservice.api.SnatServiceManager;
29 import org.opendaylight.netvirt.natservice.internal.NatConstants;
30 import org.opendaylight.netvirt.natservice.internal.NatUtil;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.config.rev170206.NatserviceConfig;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.config.rev170206.NatserviceConfig.NatMode;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.NaptSwitches;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.Routers;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.napt.switches.RouterToNaptSwitch;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.opendaylight.yangtools.yang.common.Uint32;
38 import org.opendaylight.yangtools.yang.common.Uint64;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * CentralizedSwitchChangeListener detect changes in switch:router mapping and
44  * update flows accordingly.
45  */
46 @Singleton
47 public class SnatCentralizedSwitchChangeListener
48         extends AsyncDataTreeChangeListenerBase<RouterToNaptSwitch, SnatCentralizedSwitchChangeListener> {
49
50     private static final Logger LOG = LoggerFactory.getLogger(SnatCentralizedSwitchChangeListener.class);
51     private final DataBroker dataBroker;
52     private final ManagedNewTransactionRunner txRunner;
53     private final SnatServiceManager snatServiceManger;
54     private final NatDataUtil natDataUtil;
55     private final DataTreeEventCallbackRegistrar eventCallbacks;
56     private final NatMode natMode;
57
58     @Inject
59     public SnatCentralizedSwitchChangeListener(final DataBroker dataBroker,
60             final SnatServiceManager snatServiceManger, NatDataUtil natDataUtil, final NatserviceConfig config,
61             final DataTreeEventCallbackRegistrar dataTreeEventCallbackRegistrar) {
62         super(RouterToNaptSwitch.class, SnatCentralizedSwitchChangeListener.class);
63         this.dataBroker = dataBroker;
64         this.txRunner = new ManagedNewTransactionRunnerImpl(dataBroker);
65         this.snatServiceManger = snatServiceManger;
66         this.natDataUtil = natDataUtil;
67         this.eventCallbacks = dataTreeEventCallbackRegistrar;
68         if (config != null) {
69             this.natMode = config.getNatMode();
70         } else {
71             LOG.info("NAT mode configured default as Controller as config is missing");
72             this.natMode = NatMode.Controller;
73         }
74     }
75
76     @Override
77     @PostConstruct
78     public void init() {
79         LOG.info("{} init", getClass().getSimpleName());
80         registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker);
81     }
82
83     @Override
84     protected InstanceIdentifier<RouterToNaptSwitch> getWildCardPath() {
85         return InstanceIdentifier.create(NaptSwitches.class).child(RouterToNaptSwitch.class);
86     }
87
88     @Override
89     protected void remove(InstanceIdentifier<RouterToNaptSwitch> key, RouterToNaptSwitch routerToNaptSwitch) {
90         LOG.debug("Deleting {}", routerToNaptSwitch);
91         if (natMode == NatMode.Controller) {
92             LOG.info("Do Not Processing this remove() event for (routerName:designatedDpn) {}:{}"
93                     + "configured in Controller Mode",
94                     routerToNaptSwitch.getRouterName(), routerToNaptSwitch.getPrimarySwitchId());
95             return;
96         }
97         Uint64 primarySwitchId = routerToNaptSwitch.getPrimarySwitchId();
98         Routers router = natDataUtil.getRouter(routerToNaptSwitch.getRouterName());
99         if (router != null) {
100             ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
101                 confTx -> snatServiceManger.notify(confTx, router, null, primarySwitchId, null,
102                     SnatServiceManager.Action.SNAT_ALL_SWITCH_DISBL)), LOG,
103                 "error handling SNAT centralized switch removal");
104             natDataUtil.removeFromRouterMap(router);
105         }
106     }
107
108     @Override
109     protected void update(InstanceIdentifier<RouterToNaptSwitch> key, RouterToNaptSwitch origRouterToNaptSwitch,
110             RouterToNaptSwitch updatedRouterToNaptSwitch) {
111         LOG.debug("Updating old {} new {}", origRouterToNaptSwitch, updatedRouterToNaptSwitch);
112         if (natMode == NatMode.Controller) {
113             LOG.info("Do Not Processing this update() event for (routerName:designatedDpn) {}:{}"
114                             + "configured in Controller Mode",
115                     updatedRouterToNaptSwitch.getRouterName(), updatedRouterToNaptSwitch.getPrimarySwitchId());
116             return;
117         }
118         Uint64 origPrimarySwitchId = origRouterToNaptSwitch.getPrimarySwitchId();
119         Uint64 updatedPrimarySwitchId = updatedRouterToNaptSwitch.getPrimarySwitchId();
120         ListenableFutures.addErrorLogging(txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION, confTx -> {
121             Routers origRouter = NatUtil.getRoutersFromConfigDS(confTx, origRouterToNaptSwitch.getRouterName());
122             Routers updatedRouter = NatUtil.getRoutersFromConfigDS(confTx, updatedRouterToNaptSwitch.getRouterName());
123             if (!Objects.equals(origPrimarySwitchId, updatedPrimarySwitchId)) {
124                 if (origRouter != null) {
125                     snatServiceManger.notify(confTx, origRouter, null, origPrimarySwitchId, null,
126                             SnatServiceManager.Action.CNT_ROUTER_ALL_SWITCH_DISBL);
127                     if (origRouterToNaptSwitch.isEnableSnat()) {
128                         snatServiceManger.notify(confTx, origRouter, null, origPrimarySwitchId, null,
129                                 SnatServiceManager.Action.SNAT_ALL_SWITCH_DISBL);
130                     }
131                     natDataUtil.removeFromRouterMap(origRouter);
132                 }
133                 if (updatedRouter != null) {
134                     natDataUtil.updateRouterMap(updatedRouter);
135                     snatServiceManger.notify(confTx, updatedRouter, null, updatedPrimarySwitchId, null,
136                             SnatServiceManager.Action.CNT_ROUTER_ALL_SWITCH_ENBL);
137                     if (updatedRouterToNaptSwitch.isEnableSnat()) {
138                         snatServiceManger.notify(confTx, updatedRouter, null, updatedPrimarySwitchId, null,
139                                 SnatServiceManager.Action.SNAT_ALL_SWITCH_ENBL);
140                     }
141                 }
142             } else {
143                 boolean origIsSnatEnabled = false;
144                 boolean updatedIsSnatEnabled = false;
145                 if (origRouterToNaptSwitch.isEnableSnat() != null) {
146                     origIsSnatEnabled = origRouterToNaptSwitch.isEnableSnat();
147                 }
148                 if (updatedRouterToNaptSwitch.isEnableSnat() != null) {
149                     updatedIsSnatEnabled = updatedRouterToNaptSwitch.isEnableSnat();
150                 }
151                 if (origIsSnatEnabled != updatedIsSnatEnabled) {
152                     if (updatedRouterToNaptSwitch.isEnableSnat()) {
153                         snatServiceManger.notify(confTx, updatedRouter, null, updatedPrimarySwitchId, null,
154                                 SnatServiceManager.Action.SNAT_ALL_SWITCH_ENBL);
155                     } else {
156                         snatServiceManger.notify(confTx, origRouter, null, origPrimarySwitchId, null,
157                                 SnatServiceManager.Action.SNAT_ALL_SWITCH_DISBL);
158                     }
159                 }
160             }
161         }), LOG, "Error handling SNAT centralized switch update");
162     }
163
164     @Override
165     protected void add(InstanceIdentifier<RouterToNaptSwitch> key, RouterToNaptSwitch routerToNaptSwitch) {
166         LOG.debug("Adding {}", routerToNaptSwitch);
167         if (natMode == NatMode.Controller) {
168             LOG.info("Do Not Processing this add() event for (routerName:designatedDpn) {}:{}"
169                             + "configured in Controller Mode",
170                     routerToNaptSwitch.getRouterName(), routerToNaptSwitch.getPrimarySwitchId());
171             return;
172         }
173         Uint64 primarySwitchId = routerToNaptSwitch.getPrimarySwitchId();
174         String routerName = routerToNaptSwitch.getRouterName();
175         Routers router = NatUtil.getRoutersFromConfigDS(dataBroker, routerName);
176         final boolean isEnableSnat;
177         if (routerToNaptSwitch.isEnableSnat() != null) {
178             isEnableSnat = routerToNaptSwitch.isEnableSnat();
179         } else {
180             isEnableSnat = false;
181         }
182         Uint32 vpnId = NatUtil.getVpnId(dataBroker, routerName);
183         if (vpnId == NatConstants.INVALID_ID) {
184             LOG.warn("VpnId not unavailable for router {} yet", routerName);
185             eventCallbacks.onAddOrUpdate(LogicalDatastoreType.CONFIGURATION,
186                 NatUtil.getVpnInstanceToVpnIdIdentifier(routerName), (unused, newVpnId) -> {
187                     ListenableFutures.addErrorLogging(
188                         txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
189                             innerConfTx -> handleAdd(innerConfTx, routerName, router, primarySwitchId,
190                                     isEnableSnat)), LOG,
191                         "Error handling router addition");
192                     return DataTreeEventCallbackRegistrar.NextAction.UNREGISTER;
193                 }, Duration.ofSeconds(5), iid -> LOG.error("VpnId not found for router {}", routerName));
194             return;
195         }
196         ListenableFutures.addErrorLogging(
197             txRunner.callWithNewReadWriteTransactionAndSubmit(CONFIGURATION,
198                 confTx -> handleAdd(confTx, routerName, router, primarySwitchId,
199                         isEnableSnat)), LOG, "Error handling router addition");
200     }
201
202     private void handleAdd(TypedReadWriteTransaction<Datastore.Configuration> confTx,
203             String routerName, Routers router, Uint64 primarySwitchId, boolean isSnatEnabled)
204             throws ExecutionException, InterruptedException {
205         if (router != null) {
206             natDataUtil.addtoRouterMap(router);
207             snatServiceManger.notify(confTx, router, null, primarySwitchId, null,
208                     SnatServiceManager.Action.CNT_ROUTER_ALL_SWITCH_ENBL);
209             if (isSnatEnabled) {
210                 snatServiceManger.notify(confTx, router, null, primarySwitchId, null,
211                         SnatServiceManager.Action.SNAT_ALL_SWITCH_ENBL);
212             }
213         } else {
214             LOG.error("Router {} not found for primarySwitch {}", routerName, primarySwitchId);
215         }
216     }
217
218     @Override
219     protected SnatCentralizedSwitchChangeListener getDataTreeChangeListener() {
220         return this;
221     }
222 }