Refresh IETF client/server models
[netconf.git] / apps / callhome-provider / src / main / java / org / opendaylight / netconf / topology / callhome / CallHomeMountService.java
1 /*
2  * Copyright (c) 2023 PANTHEON.tech s.r.o. 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.netconf.topology.callhome;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.util.concurrent.ListenableFuture;
12 import com.google.common.util.concurrent.SettableFuture;
13 import io.netty.channel.Channel;
14 import java.net.InetSocketAddress;
15 import java.net.SocketAddress;
16 import java.util.Map;
17 import java.util.concurrent.ConcurrentHashMap;
18 import javax.annotation.PreDestroy;
19 import javax.inject.Inject;
20 import javax.inject.Singleton;
21 import org.opendaylight.mdsal.binding.api.DataBroker;
22 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
23 import org.opendaylight.netconf.client.NetconfClientFactory;
24 import org.opendaylight.netconf.client.NetconfClientSession;
25 import org.opendaylight.netconf.client.NetconfClientSessionListener;
26 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
27 import org.opendaylight.netconf.client.conf.NetconfClientConfigurationBuilder;
28 import org.opendaylight.netconf.client.mdsal.api.BaseNetconfSchemas;
29 import org.opendaylight.netconf.client.mdsal.api.DeviceActionFactory;
30 import org.opendaylight.netconf.client.mdsal.api.SchemaResourceManager;
31 import org.opendaylight.netconf.common.NetconfTimer;
32 import org.opendaylight.netconf.shaded.sshd.client.session.ClientSession;
33 import org.opendaylight.netconf.topology.spi.NetconfClientConfigurationBuilderFactory;
34 import org.opendaylight.netconf.topology.spi.NetconfNodeHandler;
35 import org.opendaylight.netconf.topology.spi.NetconfNodeUtils;
36 import org.opendaylight.netconf.topology.spi.NetconfTopologySchemaAssembler;
37 import org.opendaylight.netconf.transport.api.UnsupportedConfigurationException;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.client.rev240208.netconf.client.initiate.stack.grouping.transport.ssh.ssh.TcpClientParametersBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.connection.parameters.Protocol;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240120.connection.parameters.ProtocolBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev231121.NetconfNodeBuilder;
45 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
46 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
47 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
48 import org.opendaylight.yangtools.yang.common.Decimal64;
49 import org.opendaylight.yangtools.yang.common.Uint16;
50 import org.opendaylight.yangtools.yang.common.Uint32;
51 import org.osgi.service.component.annotations.Activate;
52 import org.osgi.service.component.annotations.Component;
53 import org.osgi.service.component.annotations.Deactivate;
54 import org.osgi.service.component.annotations.Reference;
55
56 /**
57  * Service is responsible for call-home to topology integration.
58  *
59  * <p>
60  * To manage remote device as a topology node the topology component (based on
61  * {@link org.opendaylight.netconf.topology.spi.AbstractNetconfTopology AbstractNetconfTopology}) creates an instance
62  * of {@link org.opendaylight.netconf.topology.spi.NetconfNodeHandler NetconfNodeHandler} based on provided
63  * {@link Node}.
64  *
65  * <p>
66  * The mentioned NetconfNodeHandler initializes connection to remote device via sequence of following actions (see
67  * {@link org.opendaylight.netconf.topology.spi.AbstractNetconfTopology#ensureNode(Node) ensureNode(Node)} and
68  * {@link NetconfNodeHandler#lockedConnect() connect()}):
69  *
70  * <ul>
71  *     <li>Builds an instance of {@link org.opendaylight.netconf.client.mdsal.NetconfDeviceCommunicator
72  *     NetconfDeviceCommunicator} implementation of {@link NetconfClientSessionListener} which is used to check the
73  *     NETCONF session state and communicate with device using NETCONF protocol </li>
74  *     <li>Builds Netconf client configuration using provided {@link NetconfClientConfigurationBuilderFactory}</li>
75  *     <li>Builds Netconf client using configuration composed and triggers connection</li>
76  * </ul>
77  *
78  * <p>
79  * This service uses custom implementations of {@link NetconfClientConfigurationBuilderFactory} and
80  * {@link NetconfClientFactory} in order to capture the instance of {@link NetconfClientSessionListener} from topology
81  * component which is required to establish NETCONF layer. See {@link #createClientConfigurationBuilderFactory()}
82  * and {@link #createClientFactory()}.
83  *
84  * <p>
85  * Following sequence of actions is performed when incoming connection is mapped to topology node:
86  *
87  * <ul>
88  *     <li>When incoming connection is identified the {@link CallHomeSshSessionContext} instance expected to be created.
89  *     The createContext() method is invoked within protocol associated {@link CallHomeSessionContextManager} --
90  *     see {@link #createSshSessionContextManager()} and
91  *     {@link #createTlsSessionContextManager(CallHomeTlsAuthProvider, CallHomeStatusRecorder)}</li>
92  *     <li>Due to both {@link NetconfClientSessionListener} and {@link SettableFuture} are required to build session
93  *     context the {@link CallHomeTopology#enableNode(Node)} (Node)} is called using synthetic {@link Node} instance
94  *     composed via {@link #asNode(String, SocketAddress, Protocol)}. This triggers Netconf client construct/connect
95  *     logic (as explained above) resulting captured object placed into {@link #netconfLayerMapping}.</li>
96  *     <li>Accepted instance of {@link NetconfClientSessionListener} is used to establish Netconf layer --
97  *     see {@link CallHomeTransportChannelListener}</li>
98  *     <li>Accepted instance of {@link SettableFuture} (representing connection to remote device) is used to
99  *     signal connection state to topology component</li>
100  * </ul>
101  */
102 @Component(service = CallHomeMountService.class, immediate = true)
103 @Singleton
104 public final class CallHomeMountService implements AutoCloseable {
105     private static final Protocol SSH_PROTOCOL = new ProtocolBuilder().setName(Protocol.Name.SSH).build();
106     private static final Protocol TLS_PROTOCOL = new ProtocolBuilder().setName(Protocol.Name.TLS).build();
107
108     private final Map<String, NetconfLayer> netconfLayerMapping = new ConcurrentHashMap<>();
109     private final CallHomeTopology topology;
110
111     @Activate
112     @Inject
113     public CallHomeMountService(
114             final @Reference NetconfTimer timer,
115             final @Reference NetconfTopologySchemaAssembler schemaAssembler,
116             final @Reference SchemaResourceManager schemaRepositoryProvider,
117             final @Reference BaseNetconfSchemas baseSchemas,
118             final @Reference DataBroker dataBroker,
119             final @Reference DOMMountPointService mountService,
120             final @Reference DeviceActionFactory deviceActionFactory) {
121         this(NetconfNodeUtils.DEFAULT_TOPOLOGY_NAME, timer, schemaAssembler, schemaRepositoryProvider, baseSchemas,
122             dataBroker, mountService, deviceActionFactory);
123     }
124
125     public CallHomeMountService(final String topologyId, final NetconfTimer timer,
126             final NetconfTopologySchemaAssembler schemaAssembler, final SchemaResourceManager schemaRepositoryProvider,
127             final BaseNetconfSchemas baseSchemas, final DataBroker dataBroker, final DOMMountPointService mountService,
128             final DeviceActionFactory deviceActionFactory) {
129
130         final var clientConfBuilderFactory = createClientConfigurationBuilderFactory();
131         final var clientFactory = createClientFactory();
132         topology = new CallHomeTopology(topologyId, clientFactory, timer, schemaAssembler,
133             schemaRepositoryProvider, dataBroker, mountService, clientConfBuilderFactory,
134             baseSchemas, deviceActionFactory);
135     }
136
137     @VisibleForTesting
138     CallHomeMountService(final CallHomeTopology topology) {
139         this.topology = topology;
140     }
141
142     @VisibleForTesting
143     static NetconfClientConfigurationBuilderFactory createClientConfigurationBuilderFactory() {
144         // use minimal configuration, only id and session listener are used
145         return (nodeId, node) -> NetconfClientConfigurationBuilder.create()
146             .withName(nodeId.getValue())
147             // below parameters are only required to pass configuration validation
148             // actual values play no role
149             .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TCP)
150             .withTcpParameters(new TcpClientParametersBuilder().build());
151     }
152
153     @VisibleForTesting
154     NetconfClientFactory createClientFactory() {
155         return new NetconfClientFactory() {
156             @Override
157             public ListenableFuture<NetconfClientSession> createClient(
158                     final NetconfClientConfiguration clientConfiguration) throws UnsupportedConfigurationException {
159                 final var future = SettableFuture.<NetconfClientSession>create();
160                 final var pending = new NetconfLayer(clientConfiguration.getName(),
161                     clientConfiguration.getSessionListener(), future);
162                 netconfLayerMapping.put(pending.id, pending);
163                 return future;
164             }
165
166             @Override
167             public void close() throws Exception {
168                 // do nothing
169             }
170         };
171     }
172
173     private static Node asNode(final String id, final SocketAddress socketAddress, final Protocol protocol) {
174         final var nodeAddress = socketAddress instanceof InetSocketAddress inetSocketAddress
175             ? inetSocketAddress : new InetSocketAddress("0.0.0.0", 0);
176         // construct synthetic Node object with minimal required parameters
177         return new NodeBuilder()
178             .setNodeId(new NodeId(id))
179             .addAugmentation(new NetconfNodeBuilder()
180                 .setHost(new Host(IetfInetUtil.ipAddressFor(nodeAddress.getAddress())))
181                 .setPort(new PortNumber(Uint16.valueOf(nodeAddress.getPort())))
182                 .setTcpOnly(false)
183                 .setProtocol(protocol)
184                 // below parameters are required for NetconfNodeHandler
185                 .setSchemaless(false)
186                 .setReconnectOnChangedSchema(false)
187                 .setConnectionTimeoutMillis(Uint32.valueOf(20000))
188                 .setDefaultRequestTimeoutMillis(Uint32.valueOf(60000))
189                 .setMaxConnectionAttempts(Uint32.ZERO)
190                 .setMinBackoffMillis(Uint16.valueOf(2000))
191                 .setMaxBackoffMillis(Uint32.valueOf(1800000))
192                 .setBackoffMultiplier(Decimal64.valueOf("1.5"))
193                 .setBackoffJitter(Decimal64.valueOf("0.1"))
194                 .setKeepaliveDelay(Uint32.valueOf(120))
195                 .setConcurrentRpcLimit(Uint16.ZERO)
196                 .setActorResponseWaitTime(Uint16.valueOf(5))
197                 .setLockDatastore(true)
198                 .build())
199             .build();
200     }
201
202     public CallHomeSshSessionContextManager createSshSessionContextManager() {
203         return new CallHomeSshSessionContextManager() {
204             @Override
205             public CallHomeSshSessionContext createContext(final String id, final ClientSession clientSession) {
206                 final var remoteAddr = clientSession.getRemoteAddress();
207                 topology.enableNode(asNode(id, remoteAddr, SSH_PROTOCOL));
208                 final var netconfLayer = netconfLayerMapping.remove(id);
209                 return netconfLayer == null ? null : new CallHomeSshSessionContext(id, remoteAddr, clientSession,
210                     netconfLayer.sessionListener, netconfLayer.netconfSessionFuture);
211             }
212
213             @Override
214             public void remove(final String id) {
215                 super.remove(id);
216                 topology.disableNode(new NodeId(id));
217             }
218         };
219     }
220
221     public CallHomeTlsSessionContextManager createTlsSessionContextManager(final CallHomeTlsAuthProvider authProvider,
222             final CallHomeStatusRecorder statusRecorder) {
223         return new CallHomeTlsSessionContextManager(authProvider, statusRecorder) {
224             @Override
225             public CallHomeTlsSessionContext createContext(final String id, final Channel channel) {
226                 topology.enableNode(asNode(id, channel.remoteAddress(), TLS_PROTOCOL));
227                 final var netconfLayer = netconfLayerMapping.remove(id);
228                 return netconfLayer == null ? null : new CallHomeTlsSessionContext(id, channel,
229                     netconfLayer.sessionListener, netconfLayer.netconfSessionFuture());
230             }
231
232             @Override
233             public void remove(final String id) {
234                 super.remove(id);
235                 topology.disableNode(new NodeId(id));
236             }
237         };
238     }
239
240     @PreDestroy
241     @Deactivate
242     @Override
243     public void close() {
244         netconfLayerMapping.forEach((key, value) -> value.netconfSessionFuture.cancel(true));
245         netconfLayerMapping.clear();
246     }
247
248     private record NetconfLayer(String id, NetconfClientSessionListener sessionListener,
249         SettableFuture<NetconfClientSession> netconfSessionFuture) {
250     }
251 }