View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.hbtop.terminal.impl;
19  
20  import static org.apache.hadoop.hbase.hbtop.terminal.impl.EscapeSequences.clearAll;
21  import static org.apache.hadoop.hbase.hbtop.terminal.impl.EscapeSequences.cursor;
22  import static org.apache.hadoop.hbase.hbtop.terminal.impl.EscapeSequences.moveCursor;
23  import static org.apache.hadoop.hbase.hbtop.terminal.impl.EscapeSequences.normal;
24  
25  import edu.umd.cs.findbugs.annotations.Nullable;
26  import java.io.BufferedReader;
27  import java.io.IOException;
28  import java.io.InputStreamReader;
29  import java.io.OutputStreamWriter;
30  import java.io.PrintWriter;
31  import java.nio.charset.StandardCharsets;
32  import java.util.Queue;
33  import java.util.StringTokenizer;
34  import java.util.concurrent.ConcurrentLinkedQueue;
35  
36  import org.apache.commons.logging.Log;
37  import org.apache.commons.logging.LogFactory;
38  import org.apache.hadoop.hbase.classification.InterfaceAudience;
39  import org.apache.hadoop.hbase.hbtop.terminal.CursorPosition;
40  import org.apache.hadoop.hbase.hbtop.terminal.KeyPress;
41  import org.apache.hadoop.hbase.hbtop.terminal.Terminal;
42  import org.apache.hadoop.hbase.hbtop.terminal.TerminalPrinter;
43  import org.apache.hadoop.hbase.hbtop.terminal.TerminalSize;
44  
45  /**
46   * The implementation of the {@link Terminal} interface.
47   */
48  @InterfaceAudience.Private
49  public class TerminalImpl implements Terminal {
50  
51    private static final Log LOG = LogFactory.getLog(TerminalImpl.class);
52  
53    private TerminalSize cachedTerminalSize;
54  
55    private final PrintWriter output;
56  
57    private final ScreenBuffer screenBuffer;
58  
59    private final Queue<KeyPress> keyPressQueue;
60    private final KeyPressGenerator keyPressGenerator;
61  
62    public TerminalImpl() {
63      this(null);
64    }
65  
66    public TerminalImpl(@Nullable String title) {
67      output = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
68      sttyRaw();
69  
70      if (title != null) {
71        setTitle(title);
72      }
73  
74      screenBuffer = new ScreenBuffer();
75  
76      cachedTerminalSize = queryTerminalSize();
77      updateTerminalSize(cachedTerminalSize.getColumns(), cachedTerminalSize.getRows());
78  
79      keyPressQueue = new ConcurrentLinkedQueue<>();
80      keyPressGenerator = new KeyPressGenerator(System.in, keyPressQueue);
81      keyPressGenerator.start();
82  
83      Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
84        @Override
85        public void run() {
86          output.printf("%s%s%s%s", moveCursor(0, 0), cursor(true), normal(), clearAll());
87          output.flush();
88          sttyCooked();
89        }
90      }));
91  
92      // Clear the terminal
93      output.write(clearAll());
94      output.flush();
95    }
96  
97    private void setTitle(String title) {
98      output.write(EscapeSequences.setTitle(title));
99      output.flush();
100   }
101 
102   private void updateTerminalSize(int columns, int rows) {
103     screenBuffer.reallocate(columns, rows);
104   }
105 
106   @Override
107   public void clear() {
108     screenBuffer.clear();
109   }
110 
111   @Override
112   public void refresh() {
113     screenBuffer.flush(output);
114   }
115 
116   @Override
117   public TerminalSize getSize() {
118     return cachedTerminalSize;
119   }
120 
121   @Nullable
122   @Override
123   public TerminalSize doResizeIfNecessary() {
124     TerminalSize currentTerminalSize = queryTerminalSize();
125     if (!currentTerminalSize.equals(cachedTerminalSize)) {
126       cachedTerminalSize = currentTerminalSize;
127       updateTerminalSize(cachedTerminalSize.getColumns(), cachedTerminalSize.getRows());
128       return cachedTerminalSize;
129     }
130     return null;
131   }
132 
133   @Nullable
134   @Override
135   public KeyPress pollKeyPress() {
136     return keyPressQueue.poll();
137   }
138 
139   @Override
140   public CursorPosition getCursorPosition() {
141     return screenBuffer.getCursorPosition();
142   }
143 
144   @Override
145   public void setCursorPosition(int column, int row) {
146     screenBuffer.setCursorPosition(column, row);
147   }
148 
149   @Override
150   public void hideCursor() {
151     screenBuffer.hideCursor();
152   }
153 
154   @Override
155   public TerminalPrinter getTerminalPrinter(int startRow) {
156     return new TerminalPrinterImpl(screenBuffer, startRow);
157   }
158 
159   @Override
160   public void close() {
161     keyPressGenerator.stop();
162   }
163 
164   private TerminalSize queryTerminalSize() {
165     String sizeString = doStty("size");
166 
167     int rows = 0;
168     int columns = 0;
169 
170     StringTokenizer tokenizer = new StringTokenizer(sizeString);
171     int rc = Integer.parseInt(tokenizer.nextToken());
172     if (rc > 0) {
173       rows = rc;
174     }
175 
176     rc = Integer.parseInt(tokenizer.nextToken());
177     if (rc > 0) {
178       columns = rc;
179     }
180     return new TerminalSize(columns, rows);
181   }
182 
183   private void sttyRaw() {
184     doStty("-ignbrk -brkint -parmrk -istrip -inlcr -igncr -icrnl -ixon -opost " +
185       "-echo -echonl -icanon -isig -iexten -parenb cs8 min 1");
186   }
187 
188   private void sttyCooked() {
189     doStty("sane cooked");
190   }
191 
192   private String doStty(String sttyOptionsString) {
193     String [] cmd = {"/bin/sh", "-c", "stty " + sttyOptionsString + " < /dev/tty"};
194 
195     try {
196       Process process = Runtime.getRuntime().exec(cmd);
197 
198       String ret;
199 
200       // stdout
201       try (BufferedReader stdout = new BufferedReader(new InputStreamReader(
202         process.getInputStream(), StandardCharsets.UTF_8))) {
203         ret = stdout.readLine();
204       }
205 
206       // stderr
207       try (BufferedReader stderr = new BufferedReader(new InputStreamReader(
208         process.getErrorStream(), StandardCharsets.UTF_8))) {
209         String line = stderr.readLine();
210         if ((line != null) && (line.length() > 0)) {
211           LOG.error("Error output from stty: " + line);
212         }
213       }
214 
215       try {
216         process.waitFor();
217       } catch (InterruptedException ignored) {
218       }
219 
220       int exitValue = process.exitValue();
221       if (exitValue != 0) {
222         LOG.error("stty returned error code: " + exitValue);
223       }
224       return ret;
225     } catch (IOException e) {
226       throw new RuntimeException(e);
227     }
228   }
229 }