BGPCEP-578: Extended peer-group support
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / config / BgpDeployerImpl.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, 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.protocol.bgp.rib.impl.config;
10
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.MoreExecutors;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.Optional;
25 import java.util.concurrent.ExecutionException;
26 import javax.annotation.concurrent.GuardedBy;
27 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
28 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
29 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
30 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
31 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
32 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
33 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
34 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
35 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
36 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
37 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.peer.group.PeerGroup;
38 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.peer.group.PeerGroupKey;
39 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.Bgp;
40 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.Global;
41 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.Neighbors;
42 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.PeerGroups;
43 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.NetworkInstances;
44 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.NetworkInstance;
45 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.NetworkInstanceBuilder;
46 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.NetworkInstanceKey;
47 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.network.instance.Protocols;
48 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.network.instance.ProtocolsBuilder;
49 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.network.instance.protocols.Protocol;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev180321.NetworkInstanceProtocol;
51 import org.opendaylight.yangtools.concepts.ListenerRegistration;
52 import org.opendaylight.yangtools.yang.binding.DataObject;
53 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
54 import org.osgi.framework.BundleContext;
55 import org.osgi.service.blueprint.container.BlueprintContainer;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public final class BgpDeployerImpl implements ClusteredDataTreeChangeListener<Bgp>, PeerGroupConfigLoader,
60         AutoCloseable {
61     private static final Logger LOG = LoggerFactory.getLogger(BgpDeployerImpl.class);
62     private final InstanceIdentifier<NetworkInstance> networkInstanceIId;
63     private final BlueprintContainer container;
64     private final BundleContext bundleContext;
65     private final BGPTableTypeRegistryConsumer tableTypeRegistry;
66     private final ClusterSingletonServiceProvider provider;
67     private final LoadingCache<InstanceIdentifier<PeerGroup>, Optional<PeerGroup>> peerGroups = CacheBuilder.newBuilder()
68             .build(new CacheLoader<InstanceIdentifier<PeerGroup>, Optional<PeerGroup>>() {
69                 @Override
70                 public Optional<PeerGroup> load(final InstanceIdentifier<PeerGroup> key)
71                         throws ExecutionException, InterruptedException {
72                     return loadPeerGroup(key);
73                 }
74             });
75     private ListenerRegistration<BgpDeployerImpl> registration;
76     @GuardedBy("this")
77     private final Map<InstanceIdentifier<Bgp>, BGPClusterSingletonService> bgpCss = new HashMap<>();
78     private final DataBroker dataBroker;
79     private final String networkInstanceName;
80     @GuardedBy("this")
81     private boolean closed;
82
83     public BgpDeployerImpl(final String networkInstanceName, final ClusterSingletonServiceProvider provider,
84             final BlueprintContainer container,
85             final BundleContext bundleContext, final DataBroker dataBroker,
86             final BGPTableTypeRegistryConsumer mappingService) {
87         this.dataBroker = requireNonNull(dataBroker);
88         this.provider = requireNonNull(provider);
89         this.networkInstanceName = requireNonNull(networkInstanceName);
90         this.container = requireNonNull(container);
91         this.bundleContext = requireNonNull(bundleContext);
92         this.tableTypeRegistry = requireNonNull(mappingService);
93         this.networkInstanceIId = InstanceIdentifier.create(NetworkInstances.class)
94                 .child(NetworkInstance.class, new NetworkInstanceKey(networkInstanceName));
95         Futures.addCallback(initializeNetworkInstance(dataBroker, this.networkInstanceIId), new FutureCallback<Void>() {
96             @Override
97             public void onSuccess(final Void result) {
98                 LOG.debug("Network Instance {} initialized successfully.", networkInstanceName);
99             }
100
101             @Override
102             public void onFailure(final Throwable t) {
103                 LOG.error("Failed to initialize Network Instance {}.", networkInstanceName, t);
104             }
105         }, MoreExecutors.directExecutor());
106     }
107
108     public synchronized void init() {
109         this.registration = this.dataBroker.registerDataTreeChangeListener(
110                 new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
111                         this.networkInstanceIId.child(Protocols.class).child(Protocol.class)
112                                 .augmentation(NetworkInstanceProtocol.class).child(Bgp.class)), this);
113         LOG.info("BGP Deployer {} started.", this.networkInstanceName);
114     }
115
116     private Optional<PeerGroup> loadPeerGroup(final InstanceIdentifier<PeerGroup> peerGroupIid)
117             throws ExecutionException, InterruptedException {
118         final ReadOnlyTransaction tr = this.dataBroker.newReadOnlyTransaction();
119         final Optional<PeerGroup> result = tr.read(LogicalDatastoreType.CONFIGURATION, peerGroupIid).get().toJavaUtil();
120         return result;
121     }
122
123     @Override
124     public synchronized void onDataTreeChanged(final Collection<DataTreeModification<Bgp>> changes) {
125         if (this.closed) {
126             LOG.trace("BGP Deployer was already closed, skipping changes.");
127             return;
128         }
129         for (final DataTreeModification<Bgp> dataTreeModification : changes) {
130             final InstanceIdentifier<Bgp> rootIdentifier = dataTreeModification.getRootPath().getRootIdentifier();
131             final DataObjectModification<Bgp> rootNode = dataTreeModification.getRootNode();
132             LOG.trace("BGP configuration has changed: {}", rootNode);
133             for (final DataObjectModification<? extends DataObject> dataObjectModification :
134                     rootNode.getModifiedChildren()) {
135                 if (dataObjectModification.getDataType().equals(Global.class)) {
136                     onGlobalChanged((DataObjectModification<Global>) dataObjectModification, rootIdentifier);
137                 } else if (dataObjectModification.getDataType().equals(Neighbors.class)) {
138                     onNeighborsChanged((DataObjectModification<Neighbors>) dataObjectModification, rootIdentifier);
139                 } else if (dataObjectModification.getDataType().equals(PeerGroups.class)) {
140                     rebootNeighbors((DataObjectModification<PeerGroups>) dataObjectModification);
141                 }
142             }
143         }
144     }
145
146     private synchronized void rebootNeighbors(final DataObjectModification<PeerGroups> dataObjectModification) {
147         PeerGroups peerGroups = dataObjectModification.getDataAfter();
148         if (peerGroups == null) {
149             peerGroups = dataObjectModification.getDataBefore();
150         }
151         if (peerGroups == null) {
152             return;
153         }
154         for (final PeerGroup peerGroup: peerGroups.getPeerGroup()) {
155             this.bgpCss.values().forEach(css->css.restartNeighbors(peerGroup.getPeerGroupName()));
156         }
157     }
158
159     @Override
160     public synchronized void close() {
161         LOG.info("Closing BGP Deployer.");
162         if (this.registration != null) {
163             this.registration.close();
164             this.registration = null;
165         }
166         this.closed = true;
167
168         this.bgpCss.values().iterator().forEachRemaining(service -> {
169             try {
170                 service.close();
171             } catch (Exception e) {
172                 LOG.warn("Failed to close BGP Cluster Singleton Service.");
173             }
174         });
175
176     }
177
178     private static ListenableFuture<Void> initializeNetworkInstance(
179             final DataBroker dataBroker, final InstanceIdentifier<NetworkInstance> networkInstance) {
180         final WriteTransaction wTx = dataBroker.newWriteOnlyTransaction();
181         wTx.merge(LogicalDatastoreType.CONFIGURATION, networkInstance,
182                 new NetworkInstanceBuilder().setName(networkInstance.firstKeyOf(NetworkInstance.class).getName())
183                         .setProtocols(new ProtocolsBuilder().build()).build());
184         return wTx.submit();
185     }
186
187     @VisibleForTesting
188     synchronized void onGlobalChanged(final DataObjectModification<Global> dataObjectModification,
189             final InstanceIdentifier<Bgp> bgpInstanceIdentifier) {
190         BGPClusterSingletonService old = this.bgpCss.get(bgpInstanceIdentifier);
191         if (old == null) {
192             old = new BGPClusterSingletonService(this, this.provider, this.tableTypeRegistry,
193                     this.container, this.bundleContext, bgpInstanceIdentifier);
194             this.bgpCss.put(bgpInstanceIdentifier, old);
195         }
196         old.onGlobalChanged(dataObjectModification);
197     }
198
199     @VisibleForTesting
200     synchronized void onNeighborsChanged(final DataObjectModification<Neighbors> dataObjectModification,
201             final InstanceIdentifier<Bgp> bgpInstanceIdentifier) {
202         BGPClusterSingletonService old = this.bgpCss.get(bgpInstanceIdentifier);
203         if (old == null) {
204             old = new BGPClusterSingletonService(this, this.provider, this.tableTypeRegistry,
205                     this.container, this.bundleContext, bgpInstanceIdentifier);
206             this.bgpCss.put(bgpInstanceIdentifier, old);
207         }
208         old.onNeighborsChanged(dataObjectModification);
209     }
210
211     @VisibleForTesting
212     BGPTableTypeRegistryConsumer getTableTypeRegistry() {
213         return this.tableTypeRegistry;
214     }
215
216     @Override
217     public PeerGroup getPeerGroup(final InstanceIdentifier<Bgp> bgpIid, final String peerGroupName) {
218         final InstanceIdentifier<PeerGroup> peerGroupsIid =
219         bgpIid.child(PeerGroups.class).child(PeerGroup.class, new PeerGroupKey(peerGroupName));
220         return this.peerGroups.getUnchecked(peerGroupsIid).orElse(null);
221     }
222 }