79c083c1ed4a24d065ff0c8223ec6fa6a9672291
[controller.git] / opendaylight / netconf / netconf-cli / src / main / java / org / opendaylight / controller / netconf / cli / Main.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 java.io.IOException;
12 import java.net.InetAddress;
13 import java.net.InetSocketAddress;
14 import java.net.UnknownHostException;
15 import net.sourceforge.argparse4j.ArgumentParsers;
16 import net.sourceforge.argparse4j.inf.ArgumentGroup;
17 import net.sourceforge.argparse4j.inf.ArgumentParser;
18 import net.sourceforge.argparse4j.inf.ArgumentParserException;
19 import net.sourceforge.argparse4j.inf.Namespace;
20 import org.opendaylight.controller.netconf.cli.commands.CommandDispatcher;
21 import org.opendaylight.controller.netconf.cli.commands.local.Connect;
22 import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
23 import org.opendaylight.controller.netconf.cli.io.ConsoleIOImpl;
24 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
25 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
26 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
27 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
28
29 /**
30  * Parse arguments, start remote device connection and start CLI after the
31  * connection is fully up
32  */
33 public class Main {
34
35     public static void main(final String[] args) {
36         final CliArgumentParser cliArgs = new CliArgumentParser();
37         try {
38             cliArgs.parse(args);
39         } catch (final ArgumentParserException e) {
40             // Just end the cli, exception was handled by the CliArgumentParser
41             return;
42         }
43
44         final ConsoleIO consoleIO;
45         try {
46             consoleIO = new ConsoleIOImpl();
47         } catch (final IOException e) {
48             handleStartupException(e);
49             return;
50         }
51
52         final SchemaContext localSchema = CommandDispatcher.parseSchema(CommandDispatcher.LOCAL_SCHEMA_PATHS);
53         final SchemaContextRegistry schemaContextRegistry = new SchemaContextRegistry(localSchema);
54
55         final CommandDispatcher commandDispatcher = new CommandDispatcher();
56         final CommandArgHandlerRegistry argumentHandlerRegistry = new CommandArgHandlerRegistry(consoleIO,
57                 schemaContextRegistry);
58         final NetconfDeviceConnectionManager connectionManager = new NetconfDeviceConnectionManager(commandDispatcher,
59                 argumentHandlerRegistry, schemaContextRegistry, consoleIO);
60
61         commandDispatcher.addLocalCommands(connectionManager, localSchema, cliArgs.getConnectionTimeoutMs());
62
63         switch (cliArgs.connectionArgsPresent()) {
64         case TCP: {
65             // FIXME support pure TCP
66             handleRunningException(new UnsupportedOperationException("PURE TCP CONNECTIONS ARE NOT SUPPORTED YET, USE SSH INSTEAD BY PROVIDING USERNAME AND PASSWORD AS WELL"));
67             return;
68         }
69         case SSH: {
70             writeStatus(consoleIO, "Connecting to %s via SSH. Please wait.", cliArgs.getAddress());
71             connectionManager.connectBlocking(cliArgs.getAddress(), getClientSshConfig(cliArgs));
72             break;
73         }
74         case NONE: {/* Do not connect initially */
75             writeStatus(consoleIO, "No initial connection. To connect use the connect command");
76         }
77         }
78
79         try {
80             new Cli(consoleIO, commandDispatcher, argumentHandlerRegistry, schemaContextRegistry).run();
81         } catch (final Exception e) {
82             // TODO Running exceptions have to be handled properly
83             handleRunningException(e);
84             System.exit(0);
85         }
86     }
87
88     private static NetconfClientConfigurationBuilder getClientConfig(final CliArgumentParser cliArgs) {
89         return NetconfClientConfigurationBuilder.create().withAddress(cliArgs.getServerAddress())
90                 .withConnectionTimeoutMillis(cliArgs.getConnectionTimeoutMs())
91                 .withReconnectStrategy(Connect.getReconnectStrategy())
92                 .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TCP);
93     }
94
95     private static NetconfClientConfigurationBuilder getClientSshConfig(final CliArgumentParser cliArgs) {
96         return NetconfClientConfigurationBuilder.create().withAddress(cliArgs.getServerAddress())
97                 .withConnectionTimeoutMillis(cliArgs.getConnectionTimeoutMs())
98                 .withReconnectStrategy(Connect.getReconnectStrategy())
99                 .withAuthHandler(cliArgs.getCredentials())
100                 .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
101     }
102
103     private static void handleStartupException(final IOException e) {
104         handleException(e, "Unable to initialize CLI");
105     }
106
107     private static void handleException(final Exception e, final String message) {
108         // FIXME syserr the exception and stacktrace
109     }
110
111     private static void writeStatus(final ConsoleIO io, final String blueprint, final Object... args) {
112         try {
113             io.formatLn(blueprint, args);
114         } catch (final IOException e) {
115             handleStartupException(e);
116         }
117     }
118
119     private static void handleRunningException(final Exception e) {
120         handleException(e, "Unexpected CLI runtime exception");
121     }
122
123     private static final class CliArgumentParser {
124
125         public static final String USERNAME = "username";
126         public static final String PASSWORD = "password";
127         public static final String SERVER = "server";
128         public static final String PORT = "port";
129
130         public static final String CONNECT_TIMEOUT = "connectionTimeout";
131         public static final int DEFAULT_CONNECTION_TIMEOUT_MS = 50000;
132
133         private final ArgumentParser parser;
134         private Namespace parsed;
135
136         private CliArgumentParser() {
137             parser = ArgumentParsers.newArgumentParser("Netconf cli").defaultHelp(true)
138                     .description("Generic cli for netconf devices")
139                     .usage("Submit address + port for initial TCP connection (PURE TCP CONNECTIONS ARE NOT SUPPORTED YET)\n" +
140                             "Submit username + password in addition to address + port for initial SSH connection\n" +
141                             "If no arguments(or unexpected combination) is submitted, cli will be started without initial connection\n" +
142                             "To use with ODL controller, run with: java -jar netconf-cli-0.2.5-SNAPSHOT-executable.jar  --server localhost --port 1830 --username admin --password admin");
143
144             final ArgumentGroup tcpGroup = parser.addArgumentGroup("TCP")
145                     .description("Base arguments to initiate TCP connection right away");
146
147             tcpGroup.addArgument("--" + SERVER).help("Netconf device ip-address/domain name");
148             tcpGroup.addArgument("--" + PORT).type(Integer.class).help("Netconf device port");
149             tcpGroup.addArgument("--" + CONNECT_TIMEOUT)
150                     .type(Integer.class)
151                     .setDefault(DEFAULT_CONNECTION_TIMEOUT_MS)
152                     .help("Timeout(in ms) for connection to succeed, if the connection is not fully established by the time is up, " +
153                             "connection attempt is considered a failure. This attribute is not working as expected yet");
154
155             final ArgumentGroup sshGroup = parser.addArgumentGroup("SSH")
156                     .description("SSH credentials, if provided, initial connection will be attempted using SSH");
157
158             sshGroup.addArgument("--" + USERNAME).help("Username for SSH connection");
159             sshGroup.addArgument("--" + PASSWORD).help("Password for SSH connection");
160         }
161
162         public void parse(final String[] args) throws ArgumentParserException {
163             try {
164                 this.parsed = parser.parseArgs(args);
165             } catch (final ArgumentParserException e) {
166                 parser.handleError(e);
167                 throw e;
168             }
169         }
170
171         public InetSocketAddress getServerAddress() {
172             try {
173                 return new InetSocketAddress(InetAddress.getByName(getAddress()), getPort());
174             } catch (final UnknownHostException e) {
175                 throw new IllegalArgumentException(e);
176             }
177         }
178
179         private Integer getPort() {
180             checkParsed();
181             return parsed.getInt(PORT);
182         }
183
184         private String getAddress() {
185             checkParsed();
186             return getString(SERVER);
187         }
188
189         private Integer getConnectionTimeoutMs() {
190             checkParsed();
191             return parsed.getInt(CONNECT_TIMEOUT);
192         }
193
194         private void checkParsed() {
195             Preconditions.checkState(parsed != null, "No arguments were parsed yet");
196         }
197
198         public String getUsername() {
199             checkParsed();
200             return getString(USERNAME);
201         }
202
203         private String getString(final String key) {
204             return parsed.getString(key);
205         }
206
207         public LoginPassword getCredentials() {
208             return new LoginPassword(getUsername(), getPassword());
209         }
210
211         public String getPassword() {
212             checkParsed();
213             return getString(PASSWORD);
214         }
215
216         public InitialConnectionType connectionArgsPresent() {
217             if(getAddress() != null && getPort() != null) {
218                 if(getUsername() != null && getPassword() != null) {
219                     return InitialConnectionType.SSH;
220                 }
221                 return InitialConnectionType.TCP;
222             }
223             return InitialConnectionType.NONE;
224         }
225
226         enum InitialConnectionType {
227             TCP, SSH, NONE
228         }
229     }
230 }

©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.