blob: c09e3a089f8e2033faf3a3f0b5def44ffb40f93f [file] [log] [blame]
Hyunsun Moon483e29f2016-02-05 16:55:33 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2016-present Open Networking Laboratory
Hyunsun Moon483e29f2016-02-05 16:55:33 -08003 *
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 */
Hyunsun Moon7f4ed9d2016-04-14 16:13:42 -070016package org.onosproject.cordvtn.impl;
Hyunsun Moon483e29f2016-02-05 16:55:33 -080017
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 Moon7f4ed9d2016-04-14 16:13:42 -070026import org.onosproject.cordvtn.api.NetworkAddress;
27import org.onosproject.cordvtn.api.SshAccessInfo;
Hyunsun Moon483e29f2016-02-05 16:55:33 -080028import org.slf4j.Logger;
29
30import java.io.IOException;
31import java.io.InputStream;
32import java.io.InputStreamReader;
33import java.util.Set;
34import java.util.regex.Pattern;
35import java.util.stream.Collectors;
36
37import static org.slf4j.LoggerFactory.getLogger;
38
39/**
40 * {@code RemoteIpCommandUtil} provides methods to help execute Linux IP commands to a remote server.
41 * It opens individual exec channels for each command. User can create a session with {@code connect}
42 * method and then execute a series commands. After done with all commands, the session must be closed
43 * explicitly by calling {@code disconnect}.
44 */
45public final class RemoteIpCommandUtil {
46
47 protected static final Logger log = getLogger(RemoteIpCommandUtil.class);
48
49 private static final String STRICT_HOST_CHECKING = "StrictHostKeyChecking";
50 private static final String DEFAULT_STRICT_HOST_CHECKING = "no";
51 private static final int DEFAULT_SESSION_TIMEOUT = 60000; // milliseconds
52
Hyunsun Moon133fd792016-02-09 01:55:48 -080053 private static final String IP_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
54 "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
55 "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
56 "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
Hyunsun Moon483e29f2016-02-05 16:55:33 -080057
58 private static final String IP_ADDR_SHOW = "sudo ip addr show %s";
59 private static final String IP_ADDR_FLUSH = "sudo ip addr flush %s";
60 private static final String IP_ADDR_ADD = "sudo ip addr add %s dev %s";
61 private static final String IP_ADDR_DELETE = "sudo ip addr delete %s dev %s";
62 private static final String IP_LINK_SHOW = "sudo ip link show %s";
63 private static final String IP_LINK_UP = "sudo ip link set %s up";
64
65 /**
66 * Default constructor.
67 */
68 private RemoteIpCommandUtil() {
69 }
70
71 /**
72 * Adds a given IP address to a given device.
73 *
74 * @param session ssh connection
Hyunsun Moon133fd792016-02-09 01:55:48 -080075 * @param ip network address
Hyunsun Moon483e29f2016-02-05 16:55:33 -080076 * @param device device name to assign the ip address
77 * @return true if the command succeeds, or false
78 */
Hyunsun Moon133fd792016-02-09 01:55:48 -080079 public static boolean addIp(Session session, NetworkAddress ip, String device) {
Hyunsun Moon483e29f2016-02-05 16:55:33 -080080 if (session == null || !session.isConnected()) {
81 return false;
82 }
83
Hyunsun Moon133fd792016-02-09 01:55:48 -080084 executeCommand(session, String.format(IP_ADDR_ADD, ip.cidr(), device));
85 Set<IpAddress> result = getCurrentIps(session, device);
86 return result.contains(ip.ip());
Hyunsun Moon483e29f2016-02-05 16:55:33 -080087 }
88
89 /**
90 * Removes the IP address from a given device.
91 *
92 * @param session ssh connection
93 * @param ip ip address
94 * @param device device name
95 * @return true if the command succeeds, or false
96 */
Hyunsun Moon133fd792016-02-09 01:55:48 -080097 public static boolean deleteIp(Session session, IpAddress ip, String device) {
Hyunsun Moon483e29f2016-02-05 16:55:33 -080098 if (session == null || !session.isConnected()) {
99 return false;
100 }
101
102 executeCommand(session, String.format(IP_ADDR_DELETE, ip, device));
Hyunsun Moon133fd792016-02-09 01:55:48 -0800103 Set<IpAddress> result = getCurrentIps(session, device);
Hyunsun Moon483e29f2016-02-05 16:55:33 -0800104 return !result.contains(ip);
105 }
106
107 /**
108 * Removes all IP address on a given device.
109 *
110 * @param session ssh connection
111 * @param device device name
112 * @return true if the command succeeds, or false
113 */
114 public static boolean flushIp(Session session, String device) {
115 if (session == null || !session.isConnected()) {
116 return false;
117 }
118
119 executeCommand(session, String.format(IP_ADDR_FLUSH, device));
120 return getCurrentIps(session, device).isEmpty();
121 }
122
123 /**
124 * Returns a set of IP address that a given device has.
125 *
126 * @param session ssh connection
127 * @param device device name
128 * @return set of IP prefix or empty set
129 */
Hyunsun Moon133fd792016-02-09 01:55:48 -0800130 public static Set<IpAddress> getCurrentIps(Session session, String device) {
Hyunsun Moon483e29f2016-02-05 16:55:33 -0800131 if (session == null || !session.isConnected()) {
132 return Sets.newHashSet();
133 }
134
135 String output = executeCommand(session, String.format(IP_ADDR_SHOW, device));
Hyunsun Moon133fd792016-02-09 01:55:48 -0800136 Set<IpAddress> result = Pattern.compile(" |/")
Hyunsun Moon483e29f2016-02-05 16:55:33 -0800137 .splitAsStream(output)
138 .filter(s -> s.matches(IP_PATTERN))
Hyunsun Moon133fd792016-02-09 01:55:48 -0800139 .map(IpAddress::valueOf)
Hyunsun Moon483e29f2016-02-05 16:55:33 -0800140 .collect(Collectors.toSet());
141
142 return result;
143 }
144
145 /**
146 * Sets link state up for a given device.
147 *
148 * @param session ssh connection
149 * @param device device name
150 * @return true if the command succeeds, or false
151 */
152 public static boolean setInterfaceUp(Session session, String device) {
153 if (session == null || !session.isConnected()) {
154 return false;
155 }
156
157 executeCommand(session, String.format(IP_LINK_UP, device));
158 return isInterfaceUp(session, device);
159 }
160
161 /**
162 * Checks if a given interface is up or not.
163 *
164 * @param session ssh connection
165 * @param device device name
166 * @return true if the interface is up, or false
167 */
168 public static boolean isInterfaceUp(Session session, String device) {
169 if (session == null || !session.isConnected()) {
170 return false;
171 }
172
173 String output = executeCommand(session, String.format(IP_LINK_SHOW, device));
174 return output != null && output.contains("UP");
175 }
176
177 /**
178 * Creates a new session with a given access information.
179 *
180 * @param sshInfo information to ssh to the remove server
181 * @return ssh session, or null
182 */
183 public static Session connect(SshAccessInfo sshInfo) {
184 try {
185 JSch jsch = new JSch();
186 jsch.addIdentity(sshInfo.privateKey());
187
188 Session session = jsch.getSession(sshInfo.user(),
189 sshInfo.remoteIp().toString(),
190 sshInfo.port().toInt());
191 session.setConfig(STRICT_HOST_CHECKING, DEFAULT_STRICT_HOST_CHECKING);
192 session.connect(DEFAULT_SESSION_TIMEOUT);
193
194 return session;
195 } catch (JSchException e) {
196 log.debug("Failed to connect to {} due to {}", sshInfo.toString(), e.toString());
197 return null;
198 }
199 }
200
201 /**
202 * Closes a connection.
203 *
204 * @param session session
205 */
206 public static void disconnect(Session session) {
207 if (session.isConnected()) {
208 session.disconnect();
209 }
210 }
211
212 /**
213 * Executes a given command. It opens exec channel for the command and closes
214 * the channel when it's done.
215 *
216 * @param session ssh connection to a remote server
217 * @param command command to execute
218 * @return command output string if the command succeeds, or null
219 */
220 private static String executeCommand(Session session, String command) {
221 if (session == null || !session.isConnected()) {
222 return null;
223 }
224
Hyunsun Moon6d247342016-02-12 12:48:47 -0800225 log.trace("Execute command {} to {}", command, session.getHost());
Hyunsun Moon483e29f2016-02-05 16:55:33 -0800226
227 try {
228 Channel channel = session.openChannel("exec");
229 ((ChannelExec) channel).setCommand(command);
230 channel.setInputStream(null);
231 InputStream output = channel.getInputStream();
232
233 channel.connect();
234 String result = CharStreams.toString(new InputStreamReader(output));
235 channel.disconnect();
236
237 return result;
238 } catch (JSchException | IOException e) {
239 log.debug("Failed to execute command {} due to {}", command, e.toString());
240 return null;
241 }
242 }
243}