Merge "Startup arch - remove artifactId prefix from dir names."
[controller.git] / opendaylight / netconf / netconf-cli / src / main / java / org / opendaylight / controller / netconf / cli / NetconfDeviceConnectionManager.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.netconf.cli;
9
10 import com.google.common.base.Preconditions;
11 import io.netty.channel.nio.NioEventLoopGroup;
12 import io.netty.util.HashedWheelTimer;
13 import java.io.Closeable;
14 import java.io.File;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.net.InetSocketAddress;
18 import java.util.Set;
19 import java.util.concurrent.ExecutorService;
20 import java.util.concurrent.Executors;
21 import org.opendaylight.controller.netconf.cli.commands.CommandDispatcher;
22 import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
23 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
24 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
25 import org.opendaylight.controller.sal.connect.netconf.NetconfDevice;
26 import org.opendaylight.controller.sal.connect.netconf.NetconfDevice.SchemaResourcesDTO;
27 import org.opendaylight.controller.sal.connect.netconf.NetconfStateSchemas.NetconfStateSchemasResolverImpl;
28 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
29 import org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
30 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
31 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
32 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
33 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
34 import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache;
35 import org.opendaylight.yangtools.yang.model.util.repo.AbstractCachingSchemaSourceProvider;
36 import org.opendaylight.yangtools.yang.model.util.repo.FilesystemSchemaCachingProvider;
37 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
38 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
39 import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository;
40 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
41
42 /**
43  * Manages connect/disconnect to 1 remote device
44  */
45 public class NetconfDeviceConnectionManager implements Closeable {
46
47     private final CommandDispatcher commandDispatcher;
48     private final SchemaContextRegistry schemaContextRegistry;
49     private final ConsoleIO console;
50
51     private final ExecutorService executor;
52     private final NioEventLoopGroup nettyThreadGroup;
53     private final NetconfClientDispatcherImpl netconfClientDispatcher;
54
55     private static final String CACHE = "cache/schema";
56
57     // Connection
58     private NetconfDeviceConnectionHandler handler;
59     private NetconfDevice device;
60     private NetconfDeviceCommunicator listener;
61
62     public NetconfDeviceConnectionManager(final CommandDispatcher commandDispatcher,
63             final CommandArgHandlerRegistry argumentHandlerRegistry, final SchemaContextRegistry schemaContextRegistry,
64             final ConsoleIO consoleIO) {
65         this.commandDispatcher = commandDispatcher;
66         this.schemaContextRegistry = schemaContextRegistry;
67         this.console = consoleIO;
68
69         executor = Executors.newSingleThreadExecutor();
70         nettyThreadGroup = new NioEventLoopGroup();
71         netconfClientDispatcher = new NetconfClientDispatcherImpl(nettyThreadGroup, nettyThreadGroup,
72                 new HashedWheelTimer());
73     }
74
75     // TODO we receive configBuilder in order to add SessionListener, Session
76     // Listener should not be part of config
77     public synchronized void connect(final String name, final InetSocketAddress address, final NetconfClientConfigurationBuilder configBuilder) {
78         // TODO change IllegalState exceptions to custom ConnectionException
79         Preconditions.checkState(listener == null, "Already connected");
80
81         final RemoteDeviceId deviceId = new RemoteDeviceId(name, address);
82
83         handler = new NetconfDeviceConnectionHandler(commandDispatcher, schemaContextRegistry,
84                 console, name);
85
86         final SharedSchemaRepository repository = new SharedSchemaRepository("repo");
87         final SchemaContextFactory schemaContextFactory = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
88         final FilesystemSchemaSourceCache<YangTextSchemaSource> cache = new FilesystemSchemaSourceCache<>(repository, YangTextSchemaSource.class, new File(CACHE));
89         repository.registerSchemaSourceListener(cache);
90         repository.registerSchemaSourceListener(TextToASTTransformer.create(repository, repository));
91
92         device = new NetconfDevice(new SchemaResourcesDTO(repository, schemaContextFactory, new NetconfStateSchemasResolverImpl()),
93                 deviceId, handler, executor, new NetconfMessageTransformer());
94         listener = new NetconfDeviceCommunicator(deviceId, device);
95         configBuilder.withSessionListener(listener);
96         listener.initializeRemoteConnection(netconfClientDispatcher, configBuilder.build());
97     }
98
99     /**
100      * Blocks thread until connection is fully established
101      */
102     public synchronized Set<String> connectBlocking(final String name, final InetSocketAddress address, final NetconfClientConfigurationBuilder configBuilder) {
103         this.connect(name, address, configBuilder);
104         synchronized (handler) {
105             while (handler.isUp() == false) {
106                 try {
107                     // TODO implement Timeout for unsuccessful connection
108                     handler.wait();
109                 } catch (final InterruptedException e) {
110                     Thread.currentThread().interrupt();
111                     throw new IllegalArgumentException(e);
112                 }
113             }
114         }
115
116         return commandDispatcher.getRemoteCommandIds();
117     }
118
119     public synchronized void disconnect() {
120         Preconditions.checkState(listener != null, "Not connected yet");
121         Preconditions.checkState(handler.isUp(), "Not connected yet");
122         listener.close();
123         listener = null;
124         device = null;
125         handler.close();
126         handler = null;
127     }
128
129     private static AbstractCachingSchemaSourceProvider<String, InputStream> getGlobalNetconfSchemaProvider() {
130         // FIXME move to args
131         final String storageFile = "cache/schema";
132         final File directory = new File(storageFile);
133         final SchemaSourceProvider<String> defaultProvider = SchemaSourceProviders.noopProvider();
134         return FilesystemSchemaCachingProvider.createFromStringSourceProvider(defaultProvider, directory);
135     }
136
137     @Override
138     public void close() throws IOException {
139         executor.shutdownNow();
140         nettyThreadGroup.shutdownGracefully();
141     }
142 }