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