format code

This commit is contained in:
hengyunabc committed 2018-11-09 01:44:37 +08:00
1 parent a082c3cdf8
commit 8ff23ff272
3 files changed
+310 -309

No files matched your search

@@ -1,4 +1,5 @@
package com.taobao.arthas.client; package com.taobao.arthas.client;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
@@ -16,57 +17,57 @@ import java.io.Writer;
public final class IOUtil { public final class IOUtil {
public static final void readWrite(final InputStream remoteInput, final OutputStream remoteOutput, public static final void readWrite(final InputStream remoteInput, final OutputStream remoteOutput,
final InputStream localInput, final Writer localOutput) { final InputStream localInput, final Writer localOutput) {
Thread reader, writer; Thread reader, writer;
reader = new Thread() { reader = new Thread() {
@Override @Override
public void run() { public void run() {
int ch; int ch;
try { try {
while (!interrupted() && (ch = localInput.read()) != -1) { while (!interrupted() && (ch = localInput.read()) != -1) {
remoteOutput.write(ch); remoteOutput.write(ch);
remoteOutput.flush(); remoteOutput.flush();
} }
} catch (IOException e) { } catch (IOException e) {
// e.printStackTrace(); // e.printStackTrace();
} }
} }
}; };
writer = new Thread() { writer = new Thread() {
@Override @Override
public void run() { public void run() {
try { try {
while (true) { while (true) {
int singleByte = remoteInput.read(); int singleByte = remoteInput.read();
if (singleByte < 0) { if (singleByte < 0) {
break; break;
} }
localOutput.write(singleByte); localOutput.write(singleByte);
localOutput.flush(); localOutput.flush();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
System.exit(1); System.exit(1);
} }
} }
}; };
writer.setPriority(Thread.currentThread().getPriority() + 1); writer.setPriority(Thread.currentThread().getPriority() + 1);
writer.start(); writer.start();
reader.setDaemon(true); reader.setDaemon(true);
reader.start(); reader.start();
try { try {
writer.join(); writer.join();
reader.interrupt(); reader.interrupt();
} catch (InterruptedException e) { } catch (InterruptedException e) {
// Ignored // Ignored
} }
} }
} }
@@ -2,12 +2,12 @@ package com.taobao.arthas.client;
public class OSUtils { public class OSUtils {
public static boolean isWindowsOS() { public static boolean isWindowsOS() {
boolean isWindowsOS = false; boolean isWindowsOS = false;
String osName = System.getProperty("os.name"); String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) { if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true; isWindowsOS = true;
} }
return isWindowsOS; return isWindowsOS;
} }
} }
@@ -40,306 +40,306 @@ import jline.console.KeyMap;
@Name("arthas-client") @Name("arthas-client")
@Summary("Arthas Telnet Client") @Summary("Arthas Telnet Client")
@Description("EXAMPLES:\n" + " java -jar arthas-client.jar 127.0.0.1 3658\n" @Description("EXAMPLES:\n" + " java -jar arthas-client.jar 127.0.0.1 3658\n"
+ " java -jar arthas-client.jar -c 'dashboard -n 1' \n" + " java -jar arthas-client.jar -c 'dashboard -n 1' \n"
+ " java -jar arthas-client.jar -f batch.as 127.0.0.1\n") + " java -jar arthas-client.jar -f batch.as 127.0.0.1\n")
public class TelnetConsole { public class TelnetConsole {
private static final String PROMPT = "$"; private static final String PROMPT = "$";
private static final int DEFAULT_CONNECTION_TIMEOUT = 5000; // 5000 ms private static final int DEFAULT_CONNECTION_TIMEOUT = 5000; // 5000 ms
private static final int DEFAULT_BUFFER_SIZE = 1024; private static final int DEFAULT_BUFFER_SIZE = 1024;
private static final byte CTRL_C = 0x03; private static final byte CTRL_C = 0x03;
private boolean help = false; private boolean help = false;
private String targetIp = "127.0.0.1"; private String targetIp = "127.0.0.1";
private int port = 3658; private int port = 3658;
private String command; private String command;
private String batchFile; private String batchFile;
private Integer width = null; private Integer width = null;
private Integer height = null; private Integer height = null;
@Argument(argName = "target-ip", index = 0, required = false) @Argument(argName = "target-ip", index = 0, required = false)
@Description("Target ip") @Description("Target ip")
public void setTargetIp(String targetIp) { public void setTargetIp(String targetIp) {
this.targetIp = targetIp; this.targetIp = targetIp;
} }
@Argument(argName = "port", index = 1, required = false) @Argument(argName = "port", index = 1, required = false)
@Description("The remote server port") @Description("The remote server port")
public void setPort(int port) { public void setPort(int port) {
this.port = port; this.port = port;
} }
@Option(longName = "help", flag = true) @Option(longName = "help", flag = true)
@Description("Print usage") @Description("Print usage")
public void setHelp(boolean help) { public void setHelp(boolean help) {
this.help = help; this.help = help;
} }
@Option(shortName = "c", longName = "command") @Option(shortName = "c", longName = "command")
@Description("Command to execute, multiple commands separated by ;") @Description("Command to execute, multiple commands separated by ;")
public void setCommand(String command) { public void setCommand(String command) {
this.command = command; this.command = command;
} }
@Option(shortName = "f", longName = "batch-file") @Option(shortName = "f", longName = "batch-file")
@Description("The batch file to execute") @Description("The batch file to execute")
public void setBatchFile(String batchFile) { public void setBatchFile(String batchFile) {
this.batchFile = batchFile; this.batchFile = batchFile;
} }
@Option(shortName = "w", longName = "width") @Option(shortName = "w", longName = "width")
@Description("The terminal width") @Description("The terminal width")
public void setWidth(int width) { public void setWidth(int width) {
this.width = width; this.width = width;
} }
@Option(shortName = "h", longName = "height") @Option(shortName = "h", longName = "height")
@Description("The terminal height") @Description("The terminal height")
public void setheight(int height) { public void setheight(int height) {
this.height = height; this.height = height;
} }
public TelnetConsole() { public TelnetConsole() {
} }
private static String readUntil(InputStream in, String prompt) { private static String readUntil(InputStream in, String prompt) {
try { try {
StringBuilder sBuffer = new StringBuilder(); StringBuilder sBuffer = new StringBuilder();
byte[] b = new byte[DEFAULT_BUFFER_SIZE]; byte[] b = new byte[DEFAULT_BUFFER_SIZE];
while (true) { while (true) {
int size = in.read(b); int size = in.read(b);
if (-1 != size) { if (-1 != size) {
sBuffer.append(new String(b, 0, size)); sBuffer.append(new String(b, 0, size));
String data = sBuffer.toString(); String data = sBuffer.toString();
if (data.trim().endsWith(prompt)) { if (data.trim().endsWith(prompt)) {
break; break;
} }
} }
} }
return sBuffer.toString(); return sBuffer.toString();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
private static List<String> readLines(File batchFile) { private static List<String> readLines(File batchFile) {
List<String> list = new ArrayList<String>(); List<String> list = new ArrayList<String>();
BufferedReader br = null; BufferedReader br = null;
try { try {
br = new BufferedReader(new FileReader(batchFile)); br = new BufferedReader(new FileReader(batchFile));
String line = br.readLine(); String line = br.readLine();
while (line != null) { while (line != null) {
list.add(line); list.add(line);
line = br.readLine(); line = br.readLine();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (br != null) { if (br != null) {
try { try {
br.close(); br.close();
} catch (IOException e) { } catch (IOException e) {
// ignore // ignore
} }
} }
} }
return list; return list;
} }
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
// support mingw/cygw jline color // support mingw/cygw jline color
if (System.getProperty("os.name").startsWith("Windows")) { if (System.getProperty("os.name").startsWith("Windows")) {
if ((System.getenv("MSYSTEM") != null && System.getenv("MSYSTEM").startsWith("MINGW")) if ((System.getenv("MSYSTEM") != null && System.getenv("MSYSTEM").startsWith("MINGW"))
|| "/bin/shell".equals(System.getenv("SHELL"))) { || "/bin/shell".equals(System.getenv("SHELL"))) {
System.setProperty("jline.terminal", System.getProperty("jline.terminal", "jline.UnixTerminal")); System.setProperty("jline.terminal", System.getProperty("jline.terminal", "jline.UnixTerminal"));
} }
} }
TelnetConsole telnetConsole = new TelnetConsole(); TelnetConsole telnetConsole = new TelnetConsole();
CLI cli = CLIConfigurator.define(TelnetConsole.class); CLI cli = CLIConfigurator.define(TelnetConsole.class);
try { try {
CommandLine commandLine = cli.parse(Arrays.asList(args)); CommandLine commandLine = cli.parse(Arrays.asList(args));
CLIConfigurator.inject(commandLine, telnetConsole); CLIConfigurator.inject(commandLine, telnetConsole);
if (telnetConsole.isHelp()) { if (telnetConsole.isHelp()) {
System.out.println(usage(cli)); System.out.println(usage(cli));
System.exit(0); System.exit(0);
} }
// Try to read cmds // Try to read cmds
List<String> cmds = new ArrayList<String>(); List<String> cmds = new ArrayList<String>();
if (telnetConsole.getCommand() != null) { if (telnetConsole.getCommand() != null) {
for (String c : telnetConsole.getCommand().split(";")) { for (String c : telnetConsole.getCommand().split(";")) {
cmds.add(c.trim()); cmds.add(c.trim());
} }
} else if (telnetConsole.getBatchFile() != null) { } else if (telnetConsole.getBatchFile() != null) {
File file = new File(telnetConsole.getBatchFile()); File file = new File(telnetConsole.getBatchFile());
if (!file.exists()) { if (!file.exists()) {
throw new IllegalArgumentException("batch file do not exist: " + telnetConsole.getBatchFile()); throw new IllegalArgumentException("batch file do not exist: " + telnetConsole.getBatchFile());
} else { } else {
cmds.addAll(readLines(file)); cmds.addAll(readLines(file));
} }
} }
final ConsoleReader consoleReader = new ConsoleReader(System.in, System.out); final ConsoleReader consoleReader = new ConsoleReader(System.in, System.out);
consoleReader.setHandleUserInterrupt(true); consoleReader.setHandleUserInterrupt(true);
Terminal terminal = consoleReader.getTerminal(); Terminal terminal = consoleReader.getTerminal();
if (terminal instanceof TerminalSupport) { if (terminal instanceof TerminalSupport) {
((TerminalSupport) terminal).disableInterruptCharacter(); ((TerminalSupport) terminal).disableInterruptCharacter();
} }
// support catch ctrl+c event // support catch ctrl+c event
terminal.disableInterruptCharacter(); terminal.disableInterruptCharacter();
if (terminal instanceof UnixTerminal) { if (terminal instanceof UnixTerminal) {
((UnixTerminal) terminal).disableLitteralNextCharacter(); ((UnixTerminal) terminal).disableLitteralNextCharacter();
} }
int width = TerminalSupport.DEFAULT_WIDTH; int width = TerminalSupport.DEFAULT_WIDTH;
int height = TerminalSupport.DEFAULT_HEIGHT; int height = TerminalSupport.DEFAULT_HEIGHT;
if (!cmds.isEmpty()) { if (!cmds.isEmpty()) {
// batch mode // batch mode
if (telnetConsole.getWidth() != null) { if (telnetConsole.getWidth() != null) {
width = telnetConsole.getWidth(); width = telnetConsole.getWidth();
} }
if (telnetConsole.getheight() != null) { if (telnetConsole.getheight() != null) {
height = telnetConsole.getheight(); height = telnetConsole.getheight();
} }
} else { } else {
// normal telnet client, get current terminal size // normal telnet client, get current terminal size
if (telnetConsole.getWidth() != null) { if (telnetConsole.getWidth() != null) {
width = telnetConsole.getWidth(); width = telnetConsole.getWidth();
} else { } else {
width = terminal.getWidth(); width = terminal.getWidth();
// hack for windows dos // hack for windows dos
if (OSUtils.isWindowsOS()) { if (OSUtils.isWindowsOS()) {
width--; width--;
} }
} }
if (telnetConsole.getheight() != null) { if (telnetConsole.getheight() != null) {
height = telnetConsole.getheight(); height = telnetConsole.getheight();
} else { } else {
height = terminal.getHeight(); height = terminal.getHeight();
} }
} }
final TelnetClient telnet = new TelnetClient(); final TelnetClient telnet = new TelnetClient();
telnet.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT); telnet.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT);
// send init terminal size // send init terminal size
TelnetOptionHandler sizeOpt = new WindowSizeOptionHandler(width, height, true, true, false, false); TelnetOptionHandler sizeOpt = new WindowSizeOptionHandler(width, height, true, true, false, false);
try { try {
telnet.addOptionHandler(sizeOpt); telnet.addOptionHandler(sizeOpt);
} catch (InvalidTelnetOptionException e) { } catch (InvalidTelnetOptionException e) {
// ignore // ignore
} }
// ctrl + c event callback // ctrl + c event callback
consoleReader.getKeys().bind(new Character((char) CTRL_C).toString(), new ActionListener() { consoleReader.getKeys().bind(new Character((char) CTRL_C).toString(), new ActionListener() {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
try { try {
consoleReader.getCursorBuffer().clear(); // clear current line consoleReader.getCursorBuffer().clear(); // clear current line
telnet.getOutputStream().write(CTRL_C); telnet.getOutputStream().write(CTRL_C);
telnet.getOutputStream().flush(); telnet.getOutputStream().flush();
} catch (Exception e1) { } catch (Exception e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
} }
}); });
// ctrl + d event call back // ctrl + d event call back
consoleReader.getKeys().bind(new Character(KeyMap.CTRL_D).toString(), new ActionListener() { consoleReader.getKeys().bind(new Character(KeyMap.CTRL_D).toString(), new ActionListener() {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
System.exit(0); System.exit(0);
} }
}); });
try { try {
telnet.connect(telnetConsole.getTargetIp(), telnetConsole.getPort()); telnet.connect(telnetConsole.getTargetIp(), telnetConsole.getPort());
} catch (IOException e) { } catch (IOException e) {
System.out.println("Connect to telnet server error: " + telnetConsole.getTargetIp() + " " System.out.println("Connect to telnet server error: " + telnetConsole.getTargetIp() + " "
+ telnetConsole.getPort()); + telnetConsole.getPort());
throw e; throw e;
} }
if (cmds.isEmpty()) { if (cmds.isEmpty()) {
IOUtil.readWrite(telnet.getInputStream(), telnet.getOutputStream(), System.in, IOUtil.readWrite(telnet.getInputStream(), telnet.getOutputStream(), System.in,
consoleReader.getOutput()); consoleReader.getOutput());
} else { } else {
batchModeRun(telnet, cmds); batchModeRun(telnet, cmds);
telnet.disconnect(); telnet.disconnect();
} }
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
System.out.println(usage(cli)); System.out.println(usage(cli));
System.exit(1); System.exit(1);
} }
} }
private static void batchModeRun(TelnetClient telnet, List<String> commands) throws IOException { private static void batchModeRun(TelnetClient telnet, List<String> commands) throws IOException {
InputStream inputStream = telnet.getInputStream(); InputStream inputStream = telnet.getInputStream();
OutputStream outputStream = telnet.getOutputStream(); OutputStream outputStream = telnet.getOutputStream();
for (String command : commands) { for (String command : commands) {
if (command.trim().isEmpty()) { if (command.trim().isEmpty()) {
continue; continue;
} }
// send command to server // send command to server
outputStream.write((command + " | plaintext\n").getBytes()); outputStream.write((command + " | plaintext\n").getBytes());
outputStream.flush(); outputStream.flush();
// read result from server and output // read result from server and output
String response = readUntil(inputStream, PROMPT); String response = readUntil(inputStream, PROMPT);
System.out.print(response); System.out.print(response);
System.out.flush(); System.out.flush();
} }
} }
private static String usage(CLI cli) { private static String usage(CLI cli) {
StringBuilder usageStringBuilder = new StringBuilder(); StringBuilder usageStringBuilder = new StringBuilder();
UsageMessageFormatter usageMessageFormatter = new UsageMessageFormatter(); UsageMessageFormatter usageMessageFormatter = new UsageMessageFormatter();
usageMessageFormatter.setOptionComparator(null); usageMessageFormatter.setOptionComparator(null);
cli.usage(usageStringBuilder, usageMessageFormatter); cli.usage(usageStringBuilder, usageMessageFormatter);
return usageStringBuilder.toString(); return usageStringBuilder.toString();
} }
public String getTargetIp() { public String getTargetIp() {
return targetIp; return targetIp;
} }
public int getPort() { public int getPort() {
return port; return port;
} }
public String getCommand() { public String getCommand() {
return command; return command;
} }
public String getBatchFile() { public String getBatchFile() {
return batchFile; return batchFile;
} }
public Integer getWidth() { public Integer getWidth() {
return width; return width;
} }
public Integer getheight() { public Integer getheight() {
return height; return height;
} }
public boolean isHelp() { public boolean isHelp() {
return help; return help;
} }
} }