BUG-2314 Migrate netconf-connector to NormalizedNode
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / config / yang / md / sal / connector / netconf / NetconfConnectorModule.java
1 /*
2  * Copyright (c) 2014 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.controller.config.yang.md.sal.connector.netconf;
9
10 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkCondition;
11 import static org.opendaylight.controller.config.api.JmxAttributeValidationException.checkNotNull;
12
13 import com.google.common.base.Optional;
14 import io.netty.util.concurrent.EventExecutor;
15 import java.math.BigDecimal;
16 import java.net.InetSocketAddress;
17 import java.util.List;
18 import java.util.concurrent.ExecutorService;
19 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
20 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
21 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
22 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
23 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
24 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
25 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
26 import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
27 import org.opendaylight.controller.sal.connect.netconf.NetconfDevice;
28 import org.opendaylight.controller.sal.connect.netconf.NetconfStateSchemas;
29 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
30 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
31 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceSalFacade;
32 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
33 import org.opendaylight.controller.sal.core.api.Broker;
34 import org.opendaylight.protocol.framework.ReconnectStrategy;
35 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
36 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
39 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
40 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
41 import org.osgi.framework.BundleContext;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  *
47  */
48 public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
49 {
50     private static final Logger logger = LoggerFactory.getLogger(NetconfConnectorModule.class);
51
52     private BundleContext bundleContext;
53     private Optional<NetconfSessionPreferences> userCapabilities;
54     private SchemaSourceRegistry schemaRegistry;
55     private SchemaContextFactory schemaContextFactory;
56
57     public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
58         super(identifier, dependencyResolver);
59     }
60
61     public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
62         super(identifier, dependencyResolver, oldModule, oldInstance);
63     }
64
65     @Override
66     protected void customValidation() {
67         checkNotNull(getAddress(), addressJmxAttribute);
68         checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
69         checkNotNull(getPort(), portJmxAttribute);
70         checkNotNull(getDomRegistry(), portJmxAttribute);
71         checkNotNull(getDomRegistry(), domRegistryJmxAttribute);
72
73         checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
74         checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
75
76         checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
77         checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
78
79         checkNotNull(getClientDispatcher(), clientDispatcherJmxAttribute);
80         checkNotNull(getBindingRegistry(), bindingRegistryJmxAttribute);
81         checkNotNull(getProcessingExecutor(), processingExecutorJmxAttribute);
82
83         // Check username + password in case of ssh
84         if(getTcpOnly() == false) {
85             checkNotNull(getUsername(), usernameJmxAttribute);
86             checkNotNull(getPassword(), passwordJmxAttribute);
87         }
88
89         userCapabilities = getUserCapabilities();
90     }
91
92     private boolean isHostAddressPresent(final Host address) {
93         return address.getDomainName() != null ||
94                address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
95     }
96
97     @Override
98     public java.lang.AutoCloseable createInstance() {
99         final RemoteDeviceId id = new RemoteDeviceId(getIdentifier(), getSocketAddress());
100
101         final ExecutorService globalProcessingExecutor = getProcessingExecutorDependency().getExecutor();
102
103         final Broker domBroker = getDomRegistryDependency();
104         final BindingAwareBroker bindingBroker = getBindingRegistryDependency();
105
106         final RemoteDeviceHandler<NetconfSessionPreferences> salFacade
107                 = new NetconfDeviceSalFacade(id, domBroker, bindingBroker, bundleContext);
108
109         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO =
110                 new NetconfDevice.SchemaResourcesDTO(schemaRegistry, schemaContextFactory, new NetconfStateSchemas.NetconfStateSchemasResolverImpl());
111
112         final NetconfDevice device =
113                 new NetconfDevice(schemaResourcesDTO, id, salFacade, globalProcessingExecutor, getReconnectOnChangedSchema());
114
115         final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
116                 new NetconfDeviceCommunicator(id, device, userCapabilities.get()) : new NetconfDeviceCommunicator(id, device);
117
118         final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
119         final NetconfClientDispatcher dispatcher = getClientDispatcherDependency();
120
121         listener.initializeRemoteConnection(dispatcher, clientConfig);
122
123         return new SalConnectorCloseable(listener, salFacade);
124     }
125
126     private Optional<NetconfSessionPreferences> getUserCapabilities() {
127         if(getYangModuleCapabilities() == null) {
128             return Optional.absent();
129         }
130
131         final List<String> capabilities = getYangModuleCapabilities().getCapability();
132         if(capabilities == null || capabilities.isEmpty()) {
133             return Optional.absent();
134         }
135
136         final NetconfSessionPreferences parsedOverrideCapabilities = NetconfSessionPreferences.fromStrings(capabilities);
137         JmxAttributeValidationException.checkCondition(
138                 parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
139                 "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
140                         " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
141                 yangModuleCapabilitiesJmxAttribute);
142
143         return Optional.of(parsedOverrideCapabilities);
144     }
145
146     public void setBundleContext(final BundleContext bundleContext) {
147         this.bundleContext = bundleContext;
148     }
149
150     public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
151         final InetSocketAddress socketAddress = getSocketAddress();
152         final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
153
154         final ReconnectStrategyFactory sf = new TimedReconnectStrategyFactory(
155             getEventExecutorDependency(), getMaxConnectionAttempts(), getBetweenAttemptsTimeoutMillis(), getSleepFactor());
156         final ReconnectStrategy strategy = sf.createReconnectStrategy();
157
158         return NetconfReconnectingClientConfigurationBuilder.create()
159         .withAddress(socketAddress)
160         .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
161         .withReconnectStrategy(strategy)
162         .withAuthHandler(new LoginPassword(getUsername(),getPassword()))
163         .withProtocol(getTcpOnly() ?
164                 NetconfClientConfiguration.NetconfClientProtocol.TCP :
165                 NetconfClientConfiguration.NetconfClientProtocol.SSH)
166         .withConnectStrategyFactory(sf)
167         .withSessionListener(listener)
168         .build();
169     }
170
171     private static final class SalConnectorCloseable implements AutoCloseable {
172         private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
173         private final NetconfDeviceCommunicator listener;
174
175         public SalConnectorCloseable(final NetconfDeviceCommunicator listener,
176                                      final RemoteDeviceHandler<NetconfSessionPreferences> salFacade) {
177             this.listener = listener;
178             this.salFacade = salFacade;
179         }
180
181         @Override
182         public void close() {
183             listener.close();
184             salFacade.close();
185         }
186     }
187
188     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
189         private final Long connectionAttempts;
190         private final EventExecutor executor;
191         private final double sleepFactor;
192         private final int minSleep;
193
194         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts, final int minSleep, final BigDecimal sleepFactor) {
195             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
196                 connectionAttempts = maxConnectionAttempts;
197             } else {
198                 logger.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
199                 connectionAttempts = null;
200             }
201
202             this.sleepFactor = sleepFactor.doubleValue();
203             this.executor = executor;
204             this.minSleep = minSleep;
205         }
206
207         @Override
208         public ReconnectStrategy createReconnectStrategy() {
209             final Long maxSleep = null;
210             final Long deadline = null;
211
212             return new TimedReconnectStrategy(executor, minSleep,
213                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
214         }
215     }
216
217     private InetSocketAddress getSocketAddress() {
218         if(getAddress().getDomainName() != null) {
219             return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
220         } else {
221             final IpAddress ipAddress = getAddress().getIpAddress();
222             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
223             return new InetSocketAddress(ip, getPort().getValue());
224         }
225     }
226
227     public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
228         this.schemaRegistry = schemaRegistry;
229     }
230
231     public void setSchemaContextFactory(final SchemaContextFactory schemaContextFactory) {
232         this.schemaContextFactory = schemaContextFactory;
233     }
234 }