34d109907c408c8d82a256460d8c5bc3c0b9d485
[bgpcep.git] / pcep / topology-provider / src / main / java / org / opendaylight / bgpcep / pcep / topology / provider / ServerSessionManager.java
1 /*
2  * Copyright (c) 2013 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 package org.opendaylight.bgpcep.pcep.topology.provider;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.util.concurrent.CheckedFuture;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import java.net.InetAddress;
16 import java.net.InetSocketAddress;
17 import java.util.ArrayList;
18 import java.util.HashMap;
19 import java.util.Map;
20 import java.util.concurrent.TimeUnit;
21 import java.util.concurrent.atomic.AtomicBoolean;
22 import java.util.concurrent.atomic.AtomicReference;
23 import javax.annotation.concurrent.GuardedBy;
24 import org.opendaylight.controller.config.yang.pcep.topology.provider.ListenerStateRuntimeMXBean;
25 import org.opendaylight.controller.config.yang.pcep.topology.provider.ListenerStateRuntimeRegistration;
26 import org.opendaylight.controller.config.yang.pcep.topology.provider.PCEPTopologyProviderRuntimeMXBean;
27 import org.opendaylight.controller.config.yang.pcep.topology.provider.PCEPTopologyProviderRuntimeRegistration;
28 import org.opendaylight.controller.config.yang.pcep.topology.provider.PCEPTopologyProviderRuntimeRegistrator;
29 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
30 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
31 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
32 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
33 import org.opendaylight.protocol.pcep.PCEPPeerProposal;
34 import org.opendaylight.protocol.pcep.PCEPSession;
35 import org.opendaylight.protocol.pcep.PCEPSessionListener;
36 import org.opendaylight.protocol.pcep.PCEPSessionListenerFactory;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.TlvsBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.AddLspArgs;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.EnsureLspOperationalInput;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.OperationResult;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.RemoveLspArgs;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.TopologyTypes1;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.TopologyTypes1Builder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.TriggerSyncArgs;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.UpdateLspArgs;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.topology.pcep.type.TopologyPcepBuilder;
47 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
48 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
49 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
50 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
51 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
52 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.TopologyTypesBuilder;
53 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  *
59  */
60 final class ServerSessionManager implements PCEPSessionListenerFactory, TopologySessionRPCs,
61     PCEPTopologyProviderRuntimeMXBean, PCEPPeerProposal {
62     private static final Logger LOG = LoggerFactory.getLogger(ServerSessionManager.class);
63     private static final long DEFAULT_HOLD_STATE_NANOS = TimeUnit.MINUTES.toNanos(5);
64
65     @GuardedBy("this")
66     private final Map<NodeId, TopologySessionListener> nodes = new HashMap<>();
67     @GuardedBy("this")
68     private final Map<NodeId, TopologyNodeState> state = new HashMap<>();
69     private final TopologySessionListenerFactory listenerFactory;
70     private final InstanceIdentifier<Topology> topology;
71     private final DataBroker broker;
72     private final PCEPStatefulPeerProposal peerProposal;
73     private final AtomicBoolean isClosed = new AtomicBoolean(false);
74     private final short rpcTimeout;
75     private final AtomicReference<PCEPTopologyProviderRuntimeRegistration> runtimeRootRegistration = new AtomicReference<>();
76
77     public ServerSessionManager(final DataBroker broker, final InstanceIdentifier<Topology> topology,
78         final TopologySessionListenerFactory listenerFactory, final short rpcTimeout) {
79         this.broker = Preconditions.checkNotNull(broker);
80         this.topology = Preconditions.checkNotNull(topology);
81         this.listenerFactory = Preconditions.checkNotNull(listenerFactory);
82         this.peerProposal = PCEPStatefulPeerProposal.createStatefulPeerProposal(this.broker, this.topology);
83         this.rpcTimeout = rpcTimeout;
84     }
85
86     /**
87      * Create Base Topology
88      *
89      * @throws TransactionCommitFailedException exception
90      */
91     synchronized CheckedFuture<Void, TransactionCommitFailedException> instantiateServiceInstance() {
92         final TopologyKey key = InstanceIdentifier.keyOf(this.topology);
93         final TopologyId topologyId = key.getTopologyId();
94         final WriteTransaction tx = this.broker.newWriteOnlyTransaction();
95         tx.put(LogicalDatastoreType.OPERATIONAL, this.topology, new TopologyBuilder().setKey(key)
96             .setTopologyId(topologyId).setTopologyTypes(new TopologyTypesBuilder()
97                 .addAugmentation(TopologyTypes1.class, new TopologyTypes1Builder().setTopologyPcep(
98                     new TopologyPcepBuilder().build()).build()).build())
99             .setNode(new ArrayList<>()).build(), true);
100         final CheckedFuture<Void, TransactionCommitFailedException> future = tx.submit();
101         Futures.addCallback(future, new FutureCallback<Void>() {
102             @Override
103             public void onSuccess(final Void result) {
104                 LOG.debug("PCEP Topology {} created successfully.", topologyId.getValue());
105             }
106
107             @Override
108             public void onFailure(final Throwable t) {
109                 LOG.error("Failed to create PCEP Topology {}.", topologyId.getValue(), t);
110             }
111         });
112         return future;
113     }
114
115     private static NodeId createNodeId(final InetAddress addr) {
116         return new NodeId("pcc://" + addr.getHostAddress());
117     }
118
119     synchronized void releaseNodeState(final TopologyNodeState nodeState, final PCEPSession session, final boolean persistNode) {
120         this.nodes.remove(createNodeId(session.getRemoteAddress()));
121         if (nodeState != null) {
122             LOG.debug("Node {} unbound", nodeState.getNodeId());
123             nodeState.released(persistNode);
124         }
125     }
126
127     synchronized TopologyNodeState takeNodeState(final InetAddress address, final TopologySessionListener sessionListener, final boolean retrieveNode) {
128         final NodeId id = createNodeId(address);
129         if (this.isClosed.get()) {
130             LOG.error("Server Session Manager is closed. Unable to create topology node {} with listener {}", id, sessionListener);
131             return null;
132         }
133
134         LOG.debug("Node {} requested by listener {}", id, sessionListener);
135         TopologyNodeState ret = this.state.get(id);
136
137         if (ret == null) {
138             ret = new TopologyNodeState(this.broker, this.topology, id, DEFAULT_HOLD_STATE_NANOS);
139             LOG.debug("Created topology node {} for id {} at {}", ret, id, ret.getNodeId());
140             this.state.put(id, ret);
141         }
142         // FIXME: else check for conflicting session
143
144         ret.taken(retrieveNode);
145         this.nodes.put(id, sessionListener);
146         LOG.debug("Node {} bound to listener {}", id, sessionListener);
147         return ret;
148     }
149
150     @Override
151     public PCEPSessionListener getSessionListener() {
152         return this.listenerFactory.createTopologySessionListener(this);
153     }
154
155     private synchronized TopologySessionListener checkSessionPresence(final NodeId nodeId) {
156         // Get the listener corresponding to the node
157         final TopologySessionListener l = this.nodes.get(nodeId);
158         if (l == null) {
159             LOG.debug("Session for node {} not found", nodeId);
160             return null;
161         }
162         return l;
163     }
164
165     @Override
166     public synchronized ListenableFuture<OperationResult> addLsp(final AddLspArgs input) {
167         final TopologySessionListener l = checkSessionPresence(input.getNode());
168         return (l != null) ? l.addLsp(input) : OperationResults.UNSENT.future();
169     }
170
171     @Override
172     public synchronized ListenableFuture<OperationResult> removeLsp(final RemoveLspArgs input) {
173         final TopologySessionListener l = checkSessionPresence(input.getNode());
174         return (l != null) ? l.removeLsp(input) : OperationResults.UNSENT.future();
175     }
176
177     @Override
178     public synchronized ListenableFuture<OperationResult> updateLsp(final UpdateLspArgs input) {
179         final TopologySessionListener l = checkSessionPresence(input.getNode());
180         return (l != null) ? l.updateLsp(input) : OperationResults.UNSENT.future();
181     }
182
183     @Override
184     public synchronized ListenableFuture<OperationResult> ensureLspOperational(final EnsureLspOperationalInput input) {
185         final TopologySessionListener l = checkSessionPresence(input.getNode());
186         return (l != null) ? l.ensureLspOperational(input) : OperationResults.UNSENT.future();
187     }
188
189     @Override
190     public synchronized ListenableFuture<OperationResult> triggerSync(final TriggerSyncArgs input) {
191         final TopologySessionListener l = checkSessionPresence(input.getNode());
192         return (l != null) ? l.triggerSync(input) : OperationResults.UNSENT.future();
193     }
194
195     synchronized ListenableFuture<Void> closeServiceInstance() {
196         if (this.isClosed.getAndSet(true)) {
197             LOG.error("Session Manager has already been closed.");
198             Futures.immediateFuture(null);
199         }
200         final PCEPTopologyProviderRuntimeRegistration runtimeReg = this.runtimeRootRegistration.getAndSet(null);
201         if (runtimeReg != null) {
202             runtimeReg.close();
203         }
204         for (final TopologySessionListener sessionListener : this.nodes.values()) {
205             sessionListener.close();
206         }
207         this.nodes.clear();
208         for (final TopologyNodeState nodeState : this.state.values()) {
209             nodeState.close();
210         }
211         this.state.clear();
212         final WriteTransaction t = this.broker.newWriteOnlyTransaction();
213         t.delete(LogicalDatastoreType.OPERATIONAL, this.topology);
214         final CheckedFuture<Void, TransactionCommitFailedException> future = t.submit();
215         Futures.addCallback(future, new FutureCallback<Void>() {
216             @Override
217             public void onSuccess(final Void result) {
218                 LOG.debug("Topology {} removed", ServerSessionManager.this.topology);
219             }
220
221             @Override
222             public void onFailure(final Throwable t) {
223                 LOG.warn("Failed to remove Topology {}", ServerSessionManager.this.topology, t);
224             }
225         });
226         return future;
227     }
228
229     synchronized void setRuntimeRootRegistrator(final PCEPTopologyProviderRuntimeRegistrator runtimeRootRegistrator) {
230         if (!this.runtimeRootRegistration.compareAndSet(null, runtimeRootRegistrator.register(this))) {
231             LOG.error("Runtime root registration has been set before.");
232         }
233     }
234
235     ListenerStateRuntimeRegistration registerRuntimeRootRegistration(final ListenerStateRuntimeMXBean bean) {
236         final PCEPTopologyProviderRuntimeRegistration runtimeReg = this.runtimeRootRegistration.get();
237         if (runtimeReg != null) {
238             final ListenerStateRuntimeRegistration reg = runtimeReg.register(bean);
239             LOG.trace("Bean {} is successfully registered.", bean.getPeerId());
240             return reg;
241         }
242         return null;
243     }
244
245     @Override
246     public void setPeerSpecificProposal(final InetSocketAddress address, final TlvsBuilder openBuilder) {
247         Preconditions.checkNotNull(address);
248         this.peerProposal.setPeerProposal(createNodeId(address.getAddress()), openBuilder);
249     }
250
251     short getRpcTimeout() {
252         return this.rpcTimeout;
253     }
254 }