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