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