blob: eeb7b54950d3f236a0386194281a6ed4a9ff5c34 [file] [log] [blame]
Hyunsun Moon483e29f2016-02-05 16:55:33 -08001/*
2 * Copyright 2016 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.cordvtn;
17
18import com.google.common.collect.Sets;
19import com.google.common.io.CharStreams;
20import com.jcraft.jsch.Channel;
21import com.jcraft.jsch.ChannelExec;
22import com.jcraft.jsch.JSch;
23import com.jcraft.jsch.JSchException;
24import com.jcraft.jsch.Session;
Hyunsun Moon133fd792016-02-09 01:55:48 -080025import org.onlab.packet.IpAddress;
Hyunsun Moon483e29f2016-02-05 16:55:33 -080026import org.slf4j.Logger;
27
28import java.io.IOException;
29import java.io.InputStream;
30import java.io.InputStreamReader;
31import java.util.Set;
32import java.util.regex.Pattern;
33import java.util.stream.Collectors;
34
35import static org.slf4j.LoggerFactory.getLogger;
36
37/**
38 * {@code RemoteIpCommandUtil} provides methods to help execute Linux IP commands to a remote server.
39 * It opens individual exec channels for each command. User can create a session with {@code connect}
40 * method and then execute a series commands. After done with all commands, the session must be closed
41 * explicitly by calling {@code disconnect}.
42 */
43public final class RemoteIpCommandUtil {
44
45 protected static final Logger log = getLogger(RemoteIpCommandUtil.class);
46
47 private static final String STRICT_HOST_CHECKING = "StrictHostKeyChecking";
48 private static final String DEFAULT_STRICT_HOST_CHECKING = "no";
49 private static final int DEFAULT_SESSION_TIMEOUT = 60000; // milliseconds
50
Hyunsun Moon133fd792016-02-09 01:55:48 -080051 private static final String IP_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
52 "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
53 "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
54 "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
Hyunsun Moon483e29f2016-02-05 16:55:33 -080055
56 private static final String IP_ADDR_SHOW = "sudo ip addr show %s";
57 private static final String IP_ADDR_FLUSH = "sudo ip addr flush %s";
58 private static final String IP_ADDR_ADD = "sudo ip addr add %s dev %s";
59 private static final String IP_ADDR_DELETE = "sudo ip addr delete %s dev %s";
60 private static final String IP_LINK_SHOW = "sudo ip link show %s";
61 private static final String IP_LINK_UP = "sudo ip link set %s up";
62
63 /**
64 * Default constructor.
65 */
66 private RemoteIpCommandUtil() {
67 }
68
69 /**
70 * Adds a given IP address to a given device.
71 *
72 * @param session ssh connection
Hyunsun Moon133fd792016-02-09 01:55:48 -080073 * @param ip network address
Hyunsun Moon483e29f2016-02-05 16:55:33 -080074 * @param device device name to assign the ip address
75 * @return true if the command succeeds, or false
76 */
Hyunsun Moon133fd792016-02-09 01:55:48 -080077 public static boolean addIp(Session session, NetworkAddress ip, String device) {
Hyunsun Moon483e29f2016-02-05 16:55:33 -080078 if (session == null || !session.isConnected()) {
79 return false;
80 }
81
Hyunsun Moon133fd792016-02-09 01:55:48 -080082 executeCommand(session, String.format(IP_ADDR_ADD, ip.cidr(), device));
83 Set<IpAddress> result = getCurrentIps(session, device);
84 return result.contains(ip.ip());
Hyunsun Moon483e29f2016-02-05 16:55:33 -080085 }
86
87 /**
88 * Removes the IP address from a given device.
89 *
90 * @param session ssh connection
91 * @param ip ip address
92 * @param device device name
93 * @return true if the command succeeds, or false
94 */
Hyunsun Moon133fd792016-02-09 01:55:48 -080095 public static boolean deleteIp(Session session, IpAddress ip, String device) {
Hyunsun Moon483e29f2016-02-05 16:55:33 -080096 if (session == null || !session.isConnected()) {
97 return false;
98 }
99
100 executeCommand(session, String.format(IP_ADDR_DELETE, ip, device));
Hyunsun Moon133fd792016-02-09 01:55:48 -0800101 Set<IpAddress> result = getCurrentIps(session, device);
Hyunsun Moon483e29f2016-02-05 16:55:33 -0800102 return !result.contains(ip);
103 }
104
105 /**
106 * Removes all IP address on a given device.
107 *
108 * @param session ssh connection
109 * @param device device name
110 * @return true if the command succeeds, or false
111 */
112 public static boolean flushIp(Session session, String device) {
113 if (session == null || !session.isConnected()) {
114 return false;
115 }
116
117 executeCommand(session, String.format(IP_ADDR_FLUSH, device));
118 return getCurrentIps(session, device).isEmpty();
119 }
120
121 /**
122 * Returns a set of IP address that a given device has.
123 *
124 * @param session ssh connection
125 * @param device device name
126 * @return set of IP prefix or empty set
127 */
Hyunsun Moon133fd792016-02-09 01:55:48 -0800128 public static Set<IpAddress> getCurrentIps(Session session, String device) {
Hyunsun Moon483e29f2016-02-05 16:55:33 -0800129 if (session == null || !session.isConnected()) {
130 return Sets.newHashSet();
131 }
132
133 String output = executeCommand(session, String.format(IP_ADDR_SHOW, device));
Hyunsun Moon133fd792016-02-09 01:55:48 -0800134 Set<IpAddress> result = Pattern.compile(" |/")
Hyunsun Moon483e29f2016-02-05 16:55:33 -0800135 .splitAsStream(output)
136 .filter(s -> s.matches(IP_PATTERN))
Hyunsun Moon133fd792016-02-09 01:55:48 -0800137 .map(IpAddress::valueOf)
Hyunsun Moon483e29f2016-02-05 16:55:33 -0800138 .collect(Collectors.toSet());
139
140 return result;
141 }
142
143 /**
144 * Sets link state up for a given device.
145 *
146 * @param session ssh connection
147 * @param device device name
148 * @return true if the command succeeds, or false
149 */
150 public static boolean setInterfaceUp(Session session, String device) {
151 if (session == null || !session.isConnected()) {
152 return false;
153 }
154
155 executeCommand(session, String.format(IP_LINK_UP, device));
156 return isInterfaceUp(session, device);
157 }
158
159 /**
160 * Checks if a given interface is up or not.
161 *
162 * @param session ssh connection
163 * @param device device name
164 * @return true if the interface is up, or false
165 */
166 public static boolean isInterfaceUp(Session session, String device) {
167 if (session == null || !session.isConnected()) {
168 return false;
169 }
170
171 String output = executeCommand(session, String.format(IP_LINK_SHOW, device));
172 return output != null && output.contains("UP");
173 }
174
175 /**
176 * Creates a new session with a given access information.
177 *
178 * @param sshInfo information to ssh to the remove server
179 * @return ssh session, or null
180 */
181 public static Session connect(SshAccessInfo sshInfo) {
182 try {
183 JSch jsch = new JSch();
184 jsch.addIdentity(sshInfo.privateKey());
185
186 Session session = jsch.getSession(sshInfo.user(),
187 sshInfo.remoteIp().toString(),
188 sshInfo.port().toInt());
189 session.setConfig(STRICT_HOST_CHECKING, DEFAULT_STRICT_HOST_CHECKING);
190 session.connect(DEFAULT_SESSION_TIMEOUT);
191
192 return session;
193 } catch (JSchException e) {
194 log.debug("Failed to connect to {} due to {}", sshInfo.toString(), e.toString());
195 return null;
196 }
197 }
198
199 /**
200 * Closes a connection.
201 *
202 * @param session session
203 */
204 public static void disconnect(Session session) {
205 if (session.isConnected()) {
206 session.disconnect();
207 }
208 }
209
210 /**
211 * Executes a given command. It opens exec channel for the command and closes
212 * the channel when it's done.
213 *
214 * @param session ssh connection to a remote server
215 * @param command command to execute
216 * @return command output string if the command succeeds, or null
217 */
218 private static String executeCommand(Session session, String command) {
219 if (session == null || !session.isConnected()) {
220 return null;
221 }
222
Hyunsun Moon6d247342016-02-12 12:48:47 -0800223 log.trace("Execute command {} to {}", command, session.getHost());
Hyunsun Moon483e29f2016-02-05 16:55:33 -0800224
225 try {
226 Channel channel = session.openChannel("exec");
227 ((ChannelExec) channel).setCommand(command);
228 channel.setInputStream(null);
229 InputStream output = channel.getInputStream();
230
231 channel.connect();
232 String result = CharStreams.toString(new InputStreamReader(output));
233 channel.disconnect();
234
235 return result;
236 } catch (JSchException | IOException e) {
237 log.debug("Failed to execute command {} due to {}", command, e.toString());
238 return null;
239 }
240 }
241}