Merge "Added hosttracker shell for karaf (rebased)"
[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 java.io.File;
14 import java.io.InputStream;
15 import java.net.InetSocketAddress;
16 import java.util.List;
17 import java.util.concurrent.ExecutorService;
18
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.listener.NetconfDeviceCommunicator;
29 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
30 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceSalFacade;
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.util.repo.AbstractCachingSchemaSourceProvider;
39 import org.opendaylight.yangtools.yang.model.util.repo.FilesystemSchemaCachingProvider;
40 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
41 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
42 import org.osgi.framework.BundleContext;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 import com.google.common.base.Optional;
47
48 /**
49  *
50  */
51 public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
52 {
53     private static final Logger logger = LoggerFactory.getLogger(NetconfConnectorModule.class);
54
55     private static AbstractCachingSchemaSourceProvider<String, InputStream> GLOBAL_NETCONF_SOURCE_PROVIDER = null;
56     private BundleContext bundleContext;
57     private Optional<NetconfSessionCapabilities> userCapabilities;
58
59     public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
60         super(identifier, dependencyResolver);
61     }
62
63     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) {
64         super(identifier, dependencyResolver, oldModule, oldInstance);
65     }
66
67     @Override
68     protected void customValidation() {
69         checkNotNull(getAddress(), addressJmxAttribute);
70         checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
71         checkNotNull(getPort(), portJmxAttribute);
72         checkNotNull(getDomRegistry(), portJmxAttribute);
73         checkNotNull(getDomRegistry(), domRegistryJmxAttribute);
74
75         checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
76         checkCondition(getConnectionTimeoutMillis() > 0, "must be > 0", connectionTimeoutMillisJmxAttribute);
77
78         checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
79         checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
80
81         checkNotNull(getClientDispatcher(), clientDispatcherJmxAttribute);
82         checkNotNull(getBindingRegistry(), bindingRegistryJmxAttribute);
83         checkNotNull(getProcessingExecutor(), processingExecutorJmxAttribute);
84
85         // Check username + password in case of ssh
86         if(getTcpOnly() == false) {
87             checkNotNull(getUsername(), usernameJmxAttribute);
88             checkNotNull(getPassword(), passwordJmxAttribute);
89         }
90
91         userCapabilities = getUserCapabilities();
92
93     }
94
95     private boolean isHostAddressPresent(final Host address) {
96         return address.getDomainName() != null ||
97                address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
98     }
99
100     @Override
101     public java.lang.AutoCloseable createInstance() {
102         final RemoteDeviceId id = new RemoteDeviceId(getIdentifier());
103
104         final ExecutorService globalProcessingExecutor = getProcessingExecutorDependency().getExecutor();
105
106         final Broker domBroker = getDomRegistryDependency();
107         final BindingAwareBroker bindingBroker = getBindingRegistryDependency();
108
109         final RemoteDeviceHandler<NetconfSessionCapabilities> salFacade
110                 = new NetconfDeviceSalFacade(id, domBroker, bindingBroker, bundleContext, globalProcessingExecutor);
111         final NetconfDevice device =
112                 NetconfDevice.createNetconfDevice(id, getGlobalNetconfSchemaProvider(), globalProcessingExecutor, salFacade);
113
114         final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
115                 new NetconfDeviceCommunicator(id, device, userCapabilities.get()) : new NetconfDeviceCommunicator(id, device);
116
117         final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
118
119         final NetconfClientDispatcher dispatcher = getClientDispatcherDependency();
120         listener.initializeRemoteConnection(dispatcher, clientConfig);
121
122         return new AutoCloseable() {
123             @Override
124             public void close() throws Exception {
125                 listener.close();
126                 salFacade.close();
127             }
128         };
129     }
130
131     private Optional<NetconfSessionCapabilities> getUserCapabilities() {
132         if(getYangModuleCapabilities() == null) {
133             return Optional.absent();
134         }
135
136         final List<String> capabilities = getYangModuleCapabilities().getCapability();
137         if(capabilities == null || capabilities.isEmpty()) {
138             return Optional.absent();
139         }
140
141         final NetconfSessionCapabilities parsedOverrideCapabilities = NetconfSessionCapabilities.fromStrings(capabilities);
142         JmxAttributeValidationException.checkCondition(
143                 parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
144                 "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
145                         " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
146                 yangModuleCapabilitiesJmxAttribute);
147
148         return Optional.of(parsedOverrideCapabilities);
149     }
150
151     private synchronized AbstractCachingSchemaSourceProvider<String, InputStream> getGlobalNetconfSchemaProvider() {
152         if(GLOBAL_NETCONF_SOURCE_PROVIDER == null) {
153             final String storageFile = "cache/schema";
154             //            File directory = bundleContext.getDataFile(storageFile);
155             final File directory = new File(storageFile);
156             final SchemaSourceProvider<String> defaultProvider = SchemaSourceProviders.noopProvider();
157             GLOBAL_NETCONF_SOURCE_PROVIDER = FilesystemSchemaCachingProvider.createFromStringSourceProvider(defaultProvider, directory);
158         }
159         return GLOBAL_NETCONF_SOURCE_PROVIDER;
160     }
161
162     public void setBundleContext(final BundleContext bundleContext) {
163         this.bundleContext = bundleContext;
164     }
165
166     public NetconfReconnectingClientConfiguration getClientConfig(final NetconfDeviceCommunicator listener) {
167         final InetSocketAddress socketAddress = getSocketAddress();
168         final ReconnectStrategy strategy = getReconnectStrategy();
169         final long clientConnectionTimeoutMillis = getConnectionTimeoutMillis();
170
171         return NetconfReconnectingClientConfigurationBuilder.create()
172         .withAddress(socketAddress)
173         .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
174         .withReconnectStrategy(strategy)
175         .withSessionListener(listener)
176         .withAuthHandler(new LoginPassword(getUsername(),getPassword()))
177         .withProtocol(getTcpOnly() ?
178                 NetconfClientConfiguration.NetconfClientProtocol.TCP :
179                 NetconfClientConfiguration.NetconfClientProtocol.SSH)
180         .withConnectStrategyFactory(new ReconnectStrategyFactory() {
181             @Override
182             public ReconnectStrategy createReconnectStrategy() {
183                 return getReconnectStrategy();
184             }
185         })
186         .build();
187     }
188
189     private ReconnectStrategy getReconnectStrategy() {
190         final Long connectionAttempts;
191         if (getMaxConnectionAttempts() != null && getMaxConnectionAttempts() > 0) {
192             connectionAttempts = getMaxConnectionAttempts();
193         } else {
194             logger.trace("Setting {} on {} to infinity", maxConnectionAttemptsJmxAttribute, this);
195             connectionAttempts = null;
196         }
197         final double sleepFactor = getSleepFactor().doubleValue();
198         final int minSleep = getBetweenAttemptsTimeoutMillis();
199         final Long maxSleep = null;
200         final Long deadline = null;
201
202         return new TimedReconnectStrategy(getEventExecutorDependency(), getBetweenAttemptsTimeoutMillis(),
203                 minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
204     }
205
206     private InetSocketAddress getSocketAddress() {
207         if(getAddress().getDomainName() != null) {
208             return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
209         } else {
210             final IpAddress ipAddress = getAddress().getIpAddress();
211             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
212             return new InetSocketAddress(ip, getPort().getValue());
213         }
214     }
215 }