Improve Singleton Service Logs
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / config / BgpPeer.java
index 4e51e63a2e8c874cce320309518b4be6c18b5667..135381098d6fcb2c06c5b7e2f2bbc6481ec296ff 100644 (file)
@@ -10,29 +10,42 @@ package org.opendaylight.protocol.bgp.rib.impl.config;
 
 import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getHoldTimer;
 import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getPeerAs;
+import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getSimpleRoutingPolicy;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Iterables;
+import com.google.common.util.concurrent.ListenableFuture;
 import io.netty.util.concurrent.Future;
+import java.net.InetSocketAddress;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
+import java.util.Objects;
+import java.util.Set;
 import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeMXBean;
 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpPeerState;
 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.protocol.bgp.openconfig.spi.BGPOpenConfigMappingService;
+import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
+import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
+import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
+import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
 import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
 import org.opendaylight.protocol.bgp.parser.spi.MultiprotocolCapabilitiesUtil;
 import org.opendaylight.protocol.bgp.rib.impl.BGPPeer;
-import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
+import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
+import org.opendaylight.protocol.bgp.rib.impl.spi.BgpDeployer.WriteConfiguration;
 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
+import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerState;
+import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerStateConsumer;
 import org.opendaylight.protocol.concepts.KeyMapping;
 import org.opendaylight.protocol.util.Ipv4Util;
+import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafi;
+import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.AfiSafis;
 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.Neighbor;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParametersBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
@@ -45,71 +58,81 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.mult
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.AddPathCapabilityBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.MultiprotocolCapabilityBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
 import org.osgi.framework.ServiceRegistration;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 
-public class BgpPeer implements AutoCloseable, BGPPeerRuntimeMXBean {
-
-    //FIXME make configurable
-    private static final PortNumber PORT = new PortNumber(179);
+public final class BgpPeer implements PeerBean, BGPPeerStateConsumer, BGPPeerRuntimeMXBean {
 
     private static final Logger LOG = LoggerFactory.getLogger(BgpPeer.class);
 
     private final RpcProviderRegistry rpcRegistry;
-    private final BGPPeerRegistry peerRegistry;
-    private BGPPeer bgpPeer;
-
-    private IpAddress neighborAddress;
-
-    private Future<Void> connection;
-
     private ServiceRegistration<?> serviceRegistration;
+    private Neighbor currentConfiguration;
+    private BgpPeerSingletonService bgpPeerSingletonService;
 
-    public BgpPeer(final RpcProviderRegistry rpcRegistry, final BGPPeerRegistry peerRegistry) {
+    public BgpPeer(final RpcProviderRegistry rpcRegistry) {
         this.rpcRegistry = rpcRegistry;
-        this.peerRegistry = peerRegistry;
     }
 
-    public void start(final RIB rib, final Neighbor neighbor, final BGPOpenConfigMappingService mappingService) {
-        Preconditions.checkState(this.bgpPeer == null, "Previous peer instance {} was not closed.");
-        this.neighborAddress = neighbor.getNeighborAddress();
-        this.bgpPeer = new BGPPeer(Ipv4Util.toStringIP(this.neighborAddress), rib,
-                mappingService.toPeerRole(neighbor), this.rpcRegistry);
-        final List<BgpParameters> bgpParameters = getBgpParameters(neighbor, rib, mappingService);
-        final KeyMapping key = OpenConfigMappingUtil.getNeighborKey(neighbor);
-        final BGPSessionPreferences prefs = new BGPSessionPreferences(rib.getLocalAs(),
-                getHoldTimer(neighbor), rib.getBgpIdentifier(), getPeerAs(neighbor, rib), bgpParameters, getPassword(key));
-        this.peerRegistry.addPeer(this.neighborAddress, this.bgpPeer, prefs);
-        if (OpenConfigMappingUtil.isActive(neighbor)) {
-            this.connection = rib.getDispatcher().createReconnectingClient(
-                    Ipv4Util.toInetSocketAddress(this.neighborAddress, PORT), this.peerRegistry,
-                    OpenConfigMappingUtil.getRetryTimer(neighbor), Optional.fromNullable(key));
-        }
+    @Override
+    public void start(final RIB rib, final Neighbor neighbor, final BGPTableTypeRegistryConsumer tableTypeRegistry,
+        final WriteConfiguration configurationWriter) {
+        Preconditions.checkState(this.bgpPeerSingletonService == null, "Previous peer instance was not closed.");
+        this.bgpPeerSingletonService = new BgpPeerSingletonService(rib, neighbor, tableTypeRegistry, configurationWriter);
+        this.currentConfiguration = neighbor;
+    }
 
+    @Override
+    public void restart(final RIB rib, final BGPTableTypeRegistryConsumer tableTypeRegistry) {
+        Preconditions.checkState(this.currentConfiguration != null);
+        start(rib, this.currentConfiguration, tableTypeRegistry, null);
     }
 
     @Override
     public void close() {
-        if (this.bgpPeer != null) {
-            if (this.connection != null) {
-                this.connection.cancel(true);
-                this.connection = null;
-            }
-            this.bgpPeer.close();
-            this.bgpPeer = null;
-            this.peerRegistry.removePeer(this.neighborAddress);
-            this.neighborAddress = null;
-            if (this.serviceRegistration != null) {
-                this.serviceRegistration.unregister();
-                this.serviceRegistration = null;
-            }
+        closeSingletonService();
+        if (this.serviceRegistration != null) {
+            this.serviceRegistration.unregister();
+            this.serviceRegistration = null;
         }
     }
 
+    private void closeSingletonService() {
+        try {
+            this.bgpPeerSingletonService.close();
+            this.bgpPeerSingletonService = null;
+        } catch (final Exception e) {
+            LOG.warn("Failed to close peer instance", e);
+        }
+    }
+
+    @Override
+    public Boolean containsEqualConfiguration(final Neighbor neighbor) {
+        final AfiSafis actAfiSafi = this.currentConfiguration.getAfiSafis();
+        final AfiSafis extAfiSafi = neighbor.getAfiSafis();
+        final List<AfiSafi> actualSafi = actAfiSafi != null ? actAfiSafi.getAfiSafi() : Collections.emptyList();
+        final List<AfiSafi> extSafi = extAfiSafi != null ? extAfiSafi.getAfiSafi() : Collections.emptyList();
+        return actualSafi.containsAll(extSafi) && extSafi.containsAll(actualSafi)
+        && Objects.equals(this.currentConfiguration.getConfig(), neighbor.getConfig())
+        && Objects.equals(this.currentConfiguration.getNeighborAddress(), neighbor.getNeighborAddress())
+        && Objects.equals(this.currentConfiguration.getAddPaths(),neighbor.getAddPaths())
+        && Objects.equals(this.currentConfiguration.getApplyPolicy(), neighbor.getApplyPolicy())
+        && Objects.equals(this.currentConfiguration.getAsPathOptions(), neighbor.getAsPathOptions())
+        && Objects.equals(this.currentConfiguration.getEbgpMultihop(), neighbor.getEbgpMultihop())
+        && Objects.equals(this.currentConfiguration.getGracefulRestart(), neighbor.getGracefulRestart())
+        && Objects.equals(this.currentConfiguration.getErrorHandling(), neighbor.getErrorHandling())
+        && Objects.equals(this.currentConfiguration.getLoggingOptions(), neighbor.getLoggingOptions())
+        && Objects.equals(this.currentConfiguration.getRouteReflector(), neighbor.getRouteReflector())
+        && Objects.equals(this.currentConfiguration.getState(), neighbor.getState())
+        && Objects.equals(this.currentConfiguration.getTimers(), neighbor.getTimers())
+        && Objects.equals(this.currentConfiguration.getTransport(), neighbor.getTransport());
+    }
+
     private static List<BgpParameters> getBgpParameters(final Neighbor neighbor, final RIB rib,
-            final BGPOpenConfigMappingService mappingService) {
+            final BGPTableTypeRegistryConsumer tableTypeRegistry) {
         final List<BgpParameters> tlvs = new ArrayList<>();
         final List<OptionalCapabilities> caps = new ArrayList<>();
         caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().setAs4BytesCapability(
@@ -118,14 +141,15 @@ public class BgpPeer implements AutoCloseable, BGPPeerRuntimeMXBean {
         caps.add(new OptionalCapabilitiesBuilder().setCParameters(BgpExtendedMessageUtil.EXTENDED_MESSAGE_CAPABILITY).build());
         caps.add(new OptionalCapabilitiesBuilder().setCParameters(MultiprotocolCapabilitiesUtil.RR_CAPABILITY).build());
 
-        final List<AddressFamilies> addPathCapability = mappingService.toAddPathCapability(neighbor.getAfiSafis().getAfiSafi());
+        final List<AfiSafi> afiSafi = OpenConfigMappingUtil.getAfiSafiWithDefault(neighbor.getAfiSafis(), false);
+        final List<AddressFamilies> addPathCapability = OpenConfigMappingUtil.toAddPathCapability(afiSafi, tableTypeRegistry);
         if (!addPathCapability.isEmpty()) {
             caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
                     new CParameters1Builder().setAddPathCapability(
                             new AddPathCapabilityBuilder().setAddressFamilies(addPathCapability).build()).build()).build()).build());
         }
 
-        final List<BgpTableType> tableTypes = mappingService.toTableTypes(neighbor.getAfiSafis().getAfiSafi());
+        final List<BgpTableType> tableTypes = OpenConfigMappingUtil.toTableTypes(afiSafi, tableTypeRegistry);
         for (final BgpTableType tableType : tableTypes) {
             if (!rib.getLocalTables().contains(tableType)) {
                 LOG.info("RIB instance does not list {} in its local tables. Incoming data will be dropped.", tableType);
@@ -149,28 +173,123 @@ public class BgpPeer implements AutoCloseable, BGPPeerRuntimeMXBean {
 
     @Override
     public BgpPeerState getBgpPeerState() {
-        return this.bgpPeer.getBgpPeerState();
+        return this.bgpPeerSingletonService.getPeer().getBgpPeerState();
     }
 
     @Override
     public BgpSessionState getBgpSessionState() {
-        return this.bgpPeer.getBgpSessionState();
+        return this.bgpPeerSingletonService.getPeer().getBgpSessionState();
     }
 
     @Override
-    public void resetStats() {
-        this.bgpPeer.resetStats();
-
+    public void resetSession() {
+        this.bgpPeerSingletonService.getPeer().resetSession();
     }
 
     @Override
-    public void resetSession() {
-        this.bgpPeer.resetSession();
+    public void resetStats() {
+        this.bgpPeerSingletonService.getPeer().resetStats();
+    }
 
+    @Override
+    public BGPPeerState getPeerState() {
+        if (this.bgpPeerSingletonService == null) {
+            return null;
+        }
+        return this.bgpPeerSingletonService.getPeerState();
     }
 
-    public void setServiceRegistration(final ServiceRegistration<?> serviceRegistration) {
+    void setServiceRegistration(final ServiceRegistration<?> serviceRegistration) {
         this.serviceRegistration = serviceRegistration;
     }
 
+    private final class BgpPeerSingletonService implements BGPPeerStateConsumer, ClusterSingletonService,
+        AutoCloseable {
+        private final ServiceGroupIdentifier serviceGroupIdentifier;
+        private final boolean activeConnection;
+        private final BGPDispatcher dispatcher;
+        private final InetSocketAddress inetAddress;
+        private final int retryTimer;
+        private final Optional<KeyMapping> key;
+        private final WriteConfiguration configurationWriter;
+        private ClusterSingletonServiceRegistration registration;
+        private final BGPPeer bgpPeer;
+        private final IpAddress neighborAddress;
+        private final BGPSessionPreferences prefs;
+        private Future<Void> connection;
+
+        private BgpPeerSingletonService(final RIB rib, final Neighbor neighbor,
+            final BGPTableTypeRegistryConsumer tableTypeRegistry, final WriteConfiguration configurationWriter) {
+            this.neighborAddress = neighbor.getNeighborAddress();
+            final AfiSafis afisSAfis = Preconditions.checkNotNull(neighbor.getAfiSafis());
+            final Set<TablesKey> afiSafisAdvertized = OpenConfigMappingUtil
+                .toTableKey(afisSAfis.getAfiSafi(), tableTypeRegistry);
+            this.bgpPeer = new BGPPeer(Ipv4Util.toStringIP(this.neighborAddress), rib,
+                OpenConfigMappingUtil.toPeerRole(neighbor), getSimpleRoutingPolicy(neighbor), BgpPeer.this.rpcRegistry,
+                afiSafisAdvertized, Collections.emptySet());
+            final List<BgpParameters> bgpParameters = getBgpParameters(neighbor, rib, tableTypeRegistry);
+            final KeyMapping keyMapping = OpenConfigMappingUtil.getNeighborKey(neighbor);
+            this.prefs = new BGPSessionPreferences(rib.getLocalAs(), getHoldTimer(neighbor), rib.getBgpIdentifier(),
+                getPeerAs(neighbor, rib), bgpParameters, getPassword(keyMapping));
+            this.activeConnection = OpenConfigMappingUtil.isActive(neighbor);
+            this.dispatcher = rib.getDispatcher();
+            this.inetAddress = Ipv4Util.toInetSocketAddress(this.neighborAddress, OpenConfigMappingUtil.getPort(neighbor));
+            this.retryTimer = OpenConfigMappingUtil.getRetryTimer(neighbor);
+            this.key = Optional.fromNullable(keyMapping);
+            this.configurationWriter = configurationWriter;
+            this.serviceGroupIdentifier = rib.getRibIServiceGroupIdentifier();
+            LOG.info("Peer Singleton Service {} registered", this.serviceGroupIdentifier.getValue());
+            //this need to be always the last step
+            this.registration = rib.registerClusterSingletonService(this);
+        }
+
+        @Override
+        public void close() throws Exception {
+            if (this.registration != null) {
+                this.registration.close();
+                this.registration = null;
+            }
+        }
+
+        @Override
+        public void instantiateServiceInstance() {
+            if(this.configurationWriter != null) {
+                this.configurationWriter.apply();
+            }
+            LOG.info("Peer Singleton Service {} instantiated, Peer {}", getIdentifier().getValue(), this.neighborAddress);
+            this.bgpPeer.instantiateServiceInstance();
+            this.dispatcher.getBGPPeerRegistry().addPeer(this.neighborAddress, this.bgpPeer, this.prefs);
+            if (this.activeConnection) {
+                this.connection = this.dispatcher.createReconnectingClient(this.inetAddress, this.retryTimer, this.key);
+            }
+        }
+
+        @Override
+        public ListenableFuture<Void> closeServiceInstance() {
+            LOG.info("Close Peer Singleton Service {}, Peer {}", getIdentifier().getValue(), this.neighborAddress);
+            if (this.connection != null) {
+                this.connection.cancel(true);
+                this.connection = null;
+            }
+            final ListenableFuture<Void> future = this.bgpPeer.close();
+            if(BgpPeer.this.currentConfiguration != null) {
+                this.dispatcher.getBGPPeerRegistry().removePeer(BgpPeer.this.currentConfiguration.getNeighborAddress());
+            }
+            return future;
+        }
+
+        @Override
+        public ServiceGroupIdentifier getIdentifier() {
+            return this.serviceGroupIdentifier;
+        }
+
+        BGPPeerRuntimeMXBean getPeer() {
+            return this.bgpPeer;
+        }
+
+        @Override
+        public BGPPeerState getPeerState() {
+            return this.bgpPeer.getPeerState();
+        }
+    }
 }