VpnManager: Log categorization
[vpnservice.git] / vpnmanager / vpnmanager-impl / src / main / java / org / opendaylight / vpnservice / VpnManager.java
1 /*
2  * Copyright (c) 2015 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.vpnservice;
9
10 import java.util.ArrayList;
11 import java.util.Arrays;
12 import java.util.Collection;
13 import java.util.List;
14 import java.util.concurrent.ExecutionException;
15 import java.util.concurrent.Future;
16
17 import org.opendaylight.bgpmanager.api.IBgpManager;
18 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
19 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
22 import org.opendaylight.yangtools.concepts.ListenerRegistration;
23 import org.opendaylight.yangtools.yang.binding.DataObject;
24 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
25 import org.opendaylight.yangtools.yang.common.RpcResult;
26 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
27 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
28 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnAfConfig;
29 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstance;
30 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.VpnInstances;
31 import org.opendaylight.yang.gen.v1.urn.huawei.params.xml.ns.yang.l3vpn.rev140815.vpn.instances.VpnInstanceBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.VpnInstance1;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.VpnInstance1Builder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.FibEntries;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.fibentries.VrfTables;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.fibentries.VrfTablesKey;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.vrfentries.VrfEntry;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.GetUniqueIdInput;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.GetUniqueIdInputBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.GetUniqueIdOutput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.idmanager.rev150403.IdManagerService;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import com.google.common.base.Optional;
46 import com.google.common.util.concurrent.FutureCallback;
47 import com.google.common.util.concurrent.Futures;
48
49 public class VpnManager extends AbstractDataChangeListener<VpnInstance> implements AutoCloseable {
50     private static final Logger LOG = LoggerFactory.getLogger(VpnManager.class);
51     private ListenerRegistration<DataChangeListener> listenerRegistration, fibListenerRegistration;
52     private final DataBroker broker;
53     private final IBgpManager bgpManager;
54     private IdManagerService idManager;
55     private final FibEntriesListener fibListener;
56
57     private static final FutureCallback<Void> DEFAULT_CALLBACK =
58             new FutureCallback<Void>() {
59                 public void onSuccess(Void result) {
60                     LOG.debug("Success in Datastore operation");
61                 }
62
63                 public void onFailure(Throwable error) {
64                     LOG.error("Error in Datastore operation", error);
65                 };
66             };
67
68     /**
69      * Listens for data change related to VPN Instance
70      * Informs the BGP about VRF information
71      * 
72      * @param db - dataBroker reference
73      */
74     public VpnManager(final DataBroker db, final IBgpManager bgpManager) {
75         super(VpnInstance.class);
76         broker = db;
77         this.bgpManager = bgpManager;
78         this.fibListener = new FibEntriesListener();
79         registerListener(db);
80     }
81
82     private void registerListener(final DataBroker db) {
83         try {
84             listenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION,
85                     getWildCardPath(), VpnManager.this, DataChangeScope.SUBTREE);
86             fibListenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.CONFIGURATION,
87                     getFibEntryListenerPath(), fibListener, DataChangeScope.BASE);
88         } catch (final Exception e) {
89             LOG.error("VPN Service DataChange listener registration fail!", e);
90             throw new IllegalStateException("VPN Service registration Listener failed.", e);
91         }
92     }
93
94     public void setIdManager(IdManagerService idManager) {
95         this.idManager = idManager;
96     }
97
98     @Override
99     protected void remove(InstanceIdentifier<VpnInstance> identifier, VpnInstance del) {
100         LOG.trace("Remove event - Key: {}, value: {}", identifier, del);
101         String vpnName = del.getVpnInstanceName();
102         InstanceIdentifier<VpnInstance> vpnIdentifier = VpnUtil.getVpnInstanceIdentifier(vpnName);
103         delete(LogicalDatastoreType.OPERATIONAL, vpnIdentifier);
104
105         String rd = del.getIpv4Family().getRouteDistinguisher();
106         try {
107             bgpManager.deleteVrf(rd);
108         } catch(Exception e) {
109             LOG.error("Exception when removing VRF from BGP", e);
110         }
111     }
112
113     @Override
114     protected void update(InstanceIdentifier<VpnInstance> identifier,
115             VpnInstance original, VpnInstance update) {
116         LOG.trace("Update event - Key: {}, value: {}", identifier, update);
117     }
118
119     @Override
120     protected void add(InstanceIdentifier<VpnInstance> identifier,
121             VpnInstance value) {
122         LOG.trace("key: {}, value: {}", identifier, value);
123
124         long vpnId = getUniqueId(value.getVpnInstanceName());
125
126         VpnInstance opValue = new VpnInstanceBuilder(value).
127                  addAugmentation(VpnInstance1.class, new VpnInstance1Builder().setVpnId(vpnId).build()).build();
128
129         asyncWrite(LogicalDatastoreType.OPERATIONAL, identifier, opValue, DEFAULT_CALLBACK);
130
131         //public void addVrf(String rd, Collection<String> importRts, Collection<String> exportRts)
132         VpnAfConfig config = value.getIpv4Family();
133         String rd = config.getRouteDistinguisher();
134         List<String> importRts = Arrays.asList(config.getImportRoutePolicy().split(","));
135         List<String> exportRts = Arrays.asList(config.getExportRoutePolicy().split(","));
136         try {
137             bgpManager.addVrf(rd, importRts, exportRts);
138         } catch(Exception e) {
139             LOG.error("Exception when adding VRF to BGP", e);
140         }
141     }
142
143     private InstanceIdentifier<?> getWildCardPath() {
144         return InstanceIdentifier.create(VpnInstances.class).child(VpnInstance.class);
145     }
146
147     private InstanceIdentifier<?> getFibEntryListenerPath() {
148         return InstanceIdentifier.create(FibEntries.class).child(VrfTables.class)
149                 .child(VrfEntry.class);
150     }
151
152     @Override
153     public void close() throws Exception {
154         if (listenerRegistration != null) {
155             try {
156                 listenerRegistration.close();
157             } catch (final Exception e) {
158                 LOG.error("Error when cleaning up Vpn DataChangeListener.", e);
159             }
160             listenerRegistration = null;
161         }
162         if (fibListenerRegistration != null) {
163             try {
164                 fibListenerRegistration.close();
165             } catch (final Exception e) {
166                 LOG.error("Error when cleaning up Fib entries DataChangeListener.", e);
167             }
168             fibListenerRegistration = null;
169         }
170         LOG.trace("VPN Manager Closed");
171     }
172
173     private <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
174             InstanceIdentifier<T> path) {
175
176         ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
177
178         Optional<T> result = Optional.absent();
179         try {
180             result = tx.read(datastoreType, path).get();
181         } catch (Exception e) {
182             throw new RuntimeException(e);
183         }
184
185         return result;
186     }
187
188     private <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
189             InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
190         WriteTransaction tx = broker.newWriteOnlyTransaction();
191         tx.put(datastoreType, path, data, true);
192         Futures.addCallback(tx.submit(), callback);
193     }
194
195     private VpnInstance getVpnForRD(String rd) {
196         InstanceIdentifier<VpnInstances> id = InstanceIdentifier.create(VpnInstances.class);
197         Optional<VpnInstances> vpnInstances = read(LogicalDatastoreType.OPERATIONAL, id);
198         if(vpnInstances.isPresent()) {
199             List<VpnInstance> vpns = vpnInstances.get().getVpnInstance();
200             for(VpnInstance vpn : vpns) {
201                 if(vpn.getIpv4Family().getRouteDistinguisher().equals(rd)) {
202                     return vpn;
203                 }
204             }
205         }
206         return null;
207     }
208
209     private Integer getUniqueId(String idKey) {
210         GetUniqueIdInput getIdInput = new GetUniqueIdInputBuilder()
211                                            .setPoolName(VpnConstants.VPN_IDPOOL_NAME)
212                                            .setIdKey(idKey).build();
213
214         try {
215             Future<RpcResult<GetUniqueIdOutput>> result = idManager.getUniqueId(getIdInput);
216             RpcResult<GetUniqueIdOutput> rpcResult = result.get();
217             if(rpcResult.isSuccessful()) {
218                 return rpcResult.getResult().getIdValue().intValue();
219             } else {
220                 LOG.warn("RPC Call to Get Unique Id returned with Errors {}", rpcResult.getErrors());
221             }
222         } catch (NullPointerException | InterruptedException | ExecutionException e) {
223             LOG.warn("Exception when getting Unique Id",e);
224         }
225         return 0;
226     }
227
228     private <T extends DataObject> void delete(LogicalDatastoreType datastoreType, InstanceIdentifier<T> path) {
229         WriteTransaction tx = broker.newWriteOnlyTransaction();
230         tx.delete(datastoreType, path);
231         Futures.addCallback(tx.submit(), DEFAULT_CALLBACK);
232     }
233
234     private class FibEntriesListener extends AbstractDataChangeListener<VrfEntry>  {
235
236         public FibEntriesListener() {
237             super(VrfEntry.class);
238         }
239
240         @Override
241         protected void remove(InstanceIdentifier<VrfEntry> identifier,
242                 VrfEntry del) {
243             LOG.trace("Remove Fib event - Key : {}, value : {} ", identifier, del);
244             final VrfTablesKey key = identifier.firstKeyOf(VrfTables.class, VrfTablesKey.class);
245             String rd = key.getRouteDistinguisher();
246             Long label = del.getLabel();
247             VpnInstance vpn = getVpnForRD(rd);
248             if(vpn != null) {
249                 InstanceIdentifier<VpnInstance> id = VpnUtil.getVpnInstanceIdentifier(vpn.getVpnInstanceName());
250                 InstanceIdentifier<VpnInstance1> augId = id.augmentation(VpnInstance1.class);
251                 Optional<VpnInstance1> vpnAugmenation = read(LogicalDatastoreType.OPERATIONAL, augId);
252                 if(vpnAugmenation.isPresent()) {
253                     VpnInstance1 vpnAug = vpnAugmenation.get();
254                     List<Long> routeIds = vpnAug.getRouteEntryId();
255                     if(routeIds == null) {
256                         LOG.debug("Fib Route entry is empty.");
257                         return;
258                     }
259                     LOG.debug("Removing label from vpn info - {}", label);
260                     routeIds.remove(label);
261                     asyncWrite(LogicalDatastoreType.OPERATIONAL, augId,
262                             new VpnInstance1Builder(vpnAug).setRouteEntryId(routeIds).build(), DEFAULT_CALLBACK);
263                 } else {
264                     LOG.warn("VPN Augmentation not found for vpn instance {}", vpn.getVpnInstanceName());
265                 }
266             } else {
267                 LOG.warn("No VPN Instance found for RD: {}", rd);
268             }
269         }
270
271         @Override
272         protected void update(InstanceIdentifier<VrfEntry> identifier,
273                 VrfEntry original, VrfEntry update) {
274             // TODO Auto-generated method stub
275
276         }
277
278         @Override
279         protected void add(InstanceIdentifier<VrfEntry> identifier,
280                 VrfEntry add) {
281             LOG.trace("Add Vrf Entry event - Key : {}, value : {}", identifier, add);
282             final VrfTablesKey key = identifier.firstKeyOf(VrfTables.class, VrfTablesKey.class);
283             String rd = key.getRouteDistinguisher();
284             Long label = add.getLabel();
285             VpnInstance vpn = getVpnForRD(rd);
286             if(vpn != null) {
287                 InstanceIdentifier<VpnInstance> id = VpnUtil.getVpnInstanceIdentifier(vpn.getVpnInstanceName());
288                 InstanceIdentifier<VpnInstance1> augId = id.augmentation(VpnInstance1.class);
289                 Optional<VpnInstance1> vpnAugmenation = read(LogicalDatastoreType.OPERATIONAL, augId);
290                 if(vpnAugmenation.isPresent()) {
291                     VpnInstance1 vpnAug = vpnAugmenation.get();
292                     List<Long> routeIds = vpnAug.getRouteEntryId();
293                     if(routeIds == null) {
294                         routeIds = new ArrayList<>();
295                     }
296                     LOG.debug("Adding label to vpn info - {}", label);
297                     routeIds.add(label);
298                     asyncWrite(LogicalDatastoreType.OPERATIONAL, augId,
299                             new VpnInstance1Builder(vpnAug).setRouteEntryId(routeIds).build(), DEFAULT_CALLBACK);
300                 } else {
301                     LOG.warn("VPN Augmentation not found for vpn instance {}", vpn.getVpnInstanceName());
302                 }
303             } else {
304                 LOG.warn("No VPN Instance found for RD: {}", rd);
305             }
306         }
307     }
308 }