BUG-1511 - Datastore: cleanup ListenerTreeAPI
[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 import com.google.common.base.Optional;
13 import io.netty.util.concurrent.EventExecutor;
14 import java.math.BigDecimal;
15 import java.net.InetSocketAddress;
16 import java.util.List;
17 import java.util.concurrent.ExecutorService;
18 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
19 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
20 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
21 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
22 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
23 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
24 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
25 import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
26 import org.opendaylight.controller.sal.connect.netconf.NetconfDevice;
27 import org.opendaylight.controller.sal.connect.netconf.NetconfStateSchemas;
28 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
29 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
30 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceSalFacade;
31 import org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
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
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());
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
121         final NetconfClientDispatcher dispatcher = getClientDispatcherDependency();
122         listener.initializeRemoteConnection(dispatcher, clientConfig);
123
124         return new MyAutoCloseable(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 MyReconnectStrategyFactory(
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         .withSessionListener(listener)
164         .withAuthHandler(new LoginPassword(getUsername(),getPassword()))
165         .withProtocol(getTcpOnly() ?
166                 NetconfClientConfiguration.NetconfClientProtocol.TCP :
167                 NetconfClientConfiguration.NetconfClientProtocol.SSH)
168         .withConnectStrategyFactory(sf)
169         .build();
170     }
171
172     private static final class MyAutoCloseable implements AutoCloseable {
173         private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
174         private final NetconfDeviceCommunicator listener;
175
176         public MyAutoCloseable(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 MyReconnectStrategyFactory implements ReconnectStrategyFactory {
190         private final Long connectionAttempts;
191         private final EventExecutor executor;
192         private final double sleepFactor;
193         private final int minSleep;
194
195         MyReconnectStrategyFactory(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 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.