aboutsummaryrefslogtreecommitdiffstats
path: root/ui/terminal
diff options
context:
space:
mode:
authorDan Willemsen <dwillemsen@google.com>2018-05-17 16:37:09 -0700
committerDan Willemsen <dwillemsen@google.com>2018-07-12 14:15:31 -0700
commitb82471ad6dfec4790b2d86e49525dadc3fc06416 (patch)
treebca7e73da63c7506bbc3c967468034a351aaad94 /ui/terminal
parent5e48b1d183a8333528f529c7e677c4ab644f8caf (diff)
downloadandroid_build_soong-b82471ad6dfec4790b2d86e49525dadc3fc06416.tar.gz
android_build_soong-b82471ad6dfec4790b2d86e49525dadc3fc06416.tar.bz2
android_build_soong-b82471ad6dfec4790b2d86e49525dadc3fc06416.zip
Add a unified status reporting UI
This adds a new status package that merges the running of "actions" (ninja calls them edges) of multiple tools into one view of the current state, and gives that to a number of different outputs. For inputs: Kati's output parser has been rewritten (and moved) to map onto the StartAction/FinishAction API. A byproduct of this is that the build servers should be able to extract errors from Kati better, since they look like the errors that Ninja used to write. Ninja is no longer directly connected to the terminal, but its output is read via the protobuf frontend API, so it's just another tool whose output becomes merged together. multiproduct_kati loses its custom status routines, and uses the common one instead. For outputs: The primary output is the ui/terminal.Status type, which along with ui/terminal.Writer now controls everything about the terminal output. Today, this doesn't really change any behaviors, but having all terminal output going through here allows a more complicated (multi-line / full window) status display in the future. The tracer acts as an output of the status package, tracing all the action start / finish events. This replaces reading the .ninja_log file, so it now properly handles multiple output files from a single action. A new rotated log file (out/error.log, or out/dist/logs/error.log) just contains a description of all of the errors that happened during the current build. Another new compressed and rotated log file (out/verbose.log.gz, or out/dist/logs/verbose.log.gz) contains the full verbose (showcommands) log of every execution run by the build. Since this is now written on every build, the showcommands argument is now ignored -- if you want to get the commands run, look at the log file after the build. Test: m Test: <built-in tests> Test: NINJA_ARGS="-t list" m Test: check the build.trace.gz Test: check the new log files Change-Id: If1d8994890d43ef68f65aa10ddd8e6e06dc7013a
Diffstat (limited to 'ui/terminal')
-rw-r--r--ui/terminal/Android.bp37
-rw-r--r--ui/terminal/status.go142
-rw-r--r--ui/terminal/util.go101
-rw-r--r--ui/terminal/util_darwin.go21
-rw-r--r--ui/terminal/util_linux.go21
-rw-r--r--ui/terminal/util_test.go64
-rw-r--r--ui/terminal/writer.go229
7 files changed, 615 insertions, 0 deletions
diff --git a/ui/terminal/Android.bp b/ui/terminal/Android.bp
new file mode 100644
index 00000000..7104a504
--- /dev/null
+++ b/ui/terminal/Android.bp
@@ -0,0 +1,37 @@
+// Copyright 2018 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+bootstrap_go_package {
+ name: "soong-ui-terminal",
+ pkgPath: "android/soong/ui/terminal",
+ deps: ["soong-ui-status"],
+ srcs: [
+ "status.go",
+ "writer.go",
+ "util.go",
+ ],
+ testSrcs: [
+ "util_test.go",
+ ],
+ darwin: {
+ srcs: [
+ "util_darwin.go",
+ ],
+ },
+ linux: {
+ srcs: [
+ "util_linux.go",
+ ],
+ },
+}
diff --git a/ui/terminal/status.go b/ui/terminal/status.go
new file mode 100644
index 00000000..5719456f
--- /dev/null
+++ b/ui/terminal/status.go
@@ -0,0 +1,142 @@
+// Copyright 2018 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package terminal
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "android/soong/ui/status"
+)
+
+type statusOutput struct {
+ writer Writer
+ format string
+
+ start time.Time
+}
+
+// NewStatusOutput returns a StatusOutput that represents the
+// current build status similarly to Ninja's built-in terminal
+// output.
+//
+// statusFormat takes nearly all the same options as NINJA_STATUS.
+// %c is currently unsupported.
+func NewStatusOutput(w Writer, statusFormat string) status.StatusOutput {
+ return &statusOutput{
+ writer: w,
+ format: statusFormat,
+
+ start: time.Now(),
+ }
+}
+
+func (s *statusOutput) Message(level status.MsgLevel, message string) {
+ if level > status.StatusLvl {
+ s.writer.Print(fmt.Sprintf("%s%s", level.Prefix(), message))
+ } else if level == status.StatusLvl {
+ s.writer.StatusLine(message)
+ }
+}
+
+func (s *statusOutput) StartAction(action *status.Action, counts status.Counts) {
+ if !s.writer.isSmartTerminal() {
+ return
+ }
+
+ str := action.Description
+ if str == "" {
+ str = action.Command
+ }
+
+ s.writer.StatusLine(s.progress(counts) + str)
+}
+
+func (s *statusOutput) FinishAction(result status.ActionResult, counts status.Counts) {
+ str := result.Description
+ if str == "" {
+ str = result.Command
+ }
+
+ progress := s.progress(counts) + str
+
+ if result.Error != nil {
+ hasCommand := ""
+ if result.Command != "" {
+ hasCommand = "\n"
+ }
+
+ s.writer.StatusAndMessage(progress, fmt.Sprintf("FAILED: %s\n%s%s%s",
+ strings.Join(result.Outputs, " "), result.Command, hasCommand, result.Output))
+ } else if result.Output != "" {
+ s.writer.StatusAndMessage(progress, result.Output)
+ } else {
+ s.writer.StatusLine(progress)
+ }
+}
+
+func (s *statusOutput) Flush() {}
+
+func (s *statusOutput) progress(counts status.Counts) string {
+ if s.format == "" {
+ return fmt.Sprintf("[%3d%% %d/%d] ", 100*counts.FinishedActions/counts.TotalActions, counts.FinishedActions, counts.TotalActions)
+ }
+
+ buf := &strings.Builder{}
+ for i := 0; i < len(s.format); i++ {
+ c := s.format[i]
+ if c != '%' {
+ buf.WriteByte(c)
+ continue
+ }
+
+ i = i + 1
+ if i == len(s.format) {
+ buf.WriteByte(c)
+ break
+ }
+
+ c = s.format[i]
+ switch c {
+ case '%':
+ buf.WriteByte(c)
+ case 's':
+ fmt.Fprintf(buf, "%d", counts.StartedActions)
+ case 't':
+ fmt.Fprintf(buf, "%d", counts.TotalActions)
+ case 'r':
+ fmt.Fprintf(buf, "%d", counts.RunningActions)
+ case 'u':
+ fmt.Fprintf(buf, "%d", counts.TotalActions-counts.StartedActions)
+ case 'f':
+ fmt.Fprintf(buf, "%d", counts.FinishedActions)
+ case 'o':
+ fmt.Fprintf(buf, "%.1f", float64(counts.FinishedActions)/time.Since(s.start).Seconds())
+ case 'c':
+ // TODO: implement?
+ buf.WriteRune('?')
+ case 'p':
+ fmt.Fprintf(buf, "%3d%%", 100*counts.FinishedActions/counts.TotalActions)
+ case 'e':
+ fmt.Fprintf(buf, "%.3f", time.Since(s.start).Seconds())
+ default:
+ buf.WriteString("unknown placeholder '")
+ buf.WriteByte(c)
+ buf.WriteString("'")
+ }
+ }
+ return buf.String()
+}
diff --git a/ui/terminal/util.go b/ui/terminal/util.go
new file mode 100644
index 00000000..a85a517b
--- /dev/null
+++ b/ui/terminal/util.go
@@ -0,0 +1,101 @@
+// Copyright 2017 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package terminal
+
+import (
+ "bytes"
+ "io"
+ "os"
+ "syscall"
+ "unsafe"
+)
+
+func isTerminal(w io.Writer) bool {
+ if f, ok := w.(*os.File); ok {
+ var termios syscall.Termios
+ _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, f.Fd(),
+ ioctlGetTermios, uintptr(unsafe.Pointer(&termios)),
+ 0, 0, 0)
+ return err == 0
+ }
+ return false
+}
+
+func termWidth(w io.Writer) (int, bool) {
+ if f, ok := w.(*os.File); ok {
+ var winsize struct {
+ ws_row, ws_column uint16
+ ws_xpixel, ws_ypixel uint16
+ }
+ _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, f.Fd(),
+ syscall.TIOCGWINSZ, uintptr(unsafe.Pointer(&winsize)),
+ 0, 0, 0)
+ return int(winsize.ws_column), err == 0
+ }
+ return 0, false
+}
+
+// stripAnsiEscapes strips ANSI control codes from a byte array in place.
+func stripAnsiEscapes(input []byte) []byte {
+ // read represents the remaining part of input that needs to be processed.
+ read := input
+ // write represents where we should be writing in input.
+ // It will share the same backing store as input so that we make our modifications
+ // in place.
+ write := input
+
+ // advance will copy count bytes from read to write and advance those slices
+ advance := func(write, read []byte, count int) ([]byte, []byte) {
+ copy(write, read[:count])
+ return write[count:], read[count:]
+ }
+
+ for {
+ // Find the next escape sequence
+ i := bytes.IndexByte(read, 0x1b)
+ // If it isn't found, or if there isn't room for <ESC>[, finish
+ if i == -1 || i+1 >= len(read) {
+ copy(write, read)
+ break
+ }
+
+ // Not a CSI code, continue searching
+ if read[i+1] != '[' {
+ write, read = advance(write, read, i+1)
+ continue
+ }
+
+ // Found a CSI code, advance up to the <ESC>
+ write, read = advance(write, read, i)
+
+ // Find the end of the CSI code
+ i = bytes.IndexFunc(read, func(r rune) bool {
+ return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
+ })
+ if i == -1 {
+ // We didn't find the end of the code, just remove the rest
+ i = len(read) - 1
+ }
+
+ // Strip off the end marker too
+ i = i + 1
+
+ // Skip the reader forward and reduce final length by that amount
+ read = read[i:]
+ input = input[:len(input)-i]
+ }
+
+ return input
+}
diff --git a/ui/terminal/util_darwin.go b/ui/terminal/util_darwin.go
new file mode 100644
index 00000000..109a37f0
--- /dev/null
+++ b/ui/terminal/util_darwin.go
@@ -0,0 +1,21 @@
+// Copyright 2017 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package terminal
+
+import (
+ "syscall"
+)
+
+const ioctlGetTermios = syscall.TIOCGETA
diff --git a/ui/terminal/util_linux.go b/ui/terminal/util_linux.go
new file mode 100644
index 00000000..0a3d9dd1
--- /dev/null
+++ b/ui/terminal/util_linux.go
@@ -0,0 +1,21 @@
+// Copyright 2017 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package terminal
+
+import (
+ "syscall"
+)
+
+const ioctlGetTermios = syscall.TCGETS
diff --git a/ui/terminal/util_test.go b/ui/terminal/util_test.go
new file mode 100644
index 00000000..82bde7c5
--- /dev/null
+++ b/ui/terminal/util_test.go
@@ -0,0 +1,64 @@
+// Copyright 2017 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package terminal
+
+import (
+ "testing"
+)
+
+func TestStripAnsiEscapes(t *testing.T) {
+ testcases := []struct {
+ input string
+ output string
+ }{
+ {
+ "",
+ "",
+ },
+ {
+ "This is a test",
+ "This is a test",
+ },
+ {
+ "interrupted: \x1b[12",
+ "interrupted: ",
+ },
+ {
+ "other \x1bescape \x1b",
+ "other \x1bescape \x1b",
+ },
+ { // from pretty-error macro
+ "\x1b[1mart/Android.mk: \x1b[31merror:\x1b[0m\x1b[1m art: test error \x1b[0m",
+ "art/Android.mk: error: art: test error ",
+ },
+ { // from envsetup.sh make wrapper
+ "\x1b[0;31m#### make failed to build some targets (2 seconds) ####\x1b[00m",
+ "#### make failed to build some targets (2 seconds) ####",
+ },
+ { // from clang (via ninja testcase)
+ "\x1b[1maffixmgr.cxx:286:15: \x1b[0m\x1b[0;1;35mwarning: \x1b[0m\x1b[1musing the result... [-Wparentheses]\x1b[0m",
+ "affixmgr.cxx:286:15: warning: using the result... [-Wparentheses]",
+ },
+ }
+ for _, tc := range testcases {
+ got := string(stripAnsiEscapes([]byte(tc.input)))
+ if got != tc.output {
+ t.Errorf("output strings didn't match\n"+
+ "input: %#v\n"+
+ " want: %#v\n"+
+ " got: %#v", tc.input, tc.output, got)
+ }
+ }
+}
diff --git a/ui/terminal/writer.go b/ui/terminal/writer.go
new file mode 100644
index 00000000..dd322268
--- /dev/null
+++ b/ui/terminal/writer.go
@@ -0,0 +1,229 @@
+// Copyright 2018 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package terminal provides a set of interfaces that can be used to interact
+// with the terminal (including falling back when the terminal is detected to
+// be a redirect or other dumb terminal)
+package terminal
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "strings"
+ "sync"
+)
+
+// Writer provides an interface to write temporary and permanent messages to
+// the terminal.
+//
+// The terminal is considered to be a dumb terminal if TERM==dumb, or if a
+// terminal isn't detected on stdout/stderr (generally because it's a pipe or
+// file). Dumb terminals will strip out all ANSI escape sequences, including
+// colors.
+type Writer interface {
+ // Print prints the string to the terminal, overwriting any current
+ // status being displayed.
+ //
+ // On a dumb terminal, the status messages will be kept.
+ Print(str string)
+
+ // Status prints the first line of the string to the terminal,
+ // overwriting any previous status line. Strings longer than the width
+ // of the terminal will be cut off.
+ //
+ // On a dumb terminal, previous status messages will remain, and the
+ // entire first line of the string will be printed.
+ StatusLine(str string)
+
+ // StatusAndMessage prints the first line of status to the terminal,
+ // similarly to StatusLine(), then prints the full msg below that. The
+ // status line is retained.
+ //
+ // There is guaranteed to be no other output in between the status and
+ // message.
+ StatusAndMessage(status, msg string)
+
+ // Finish ensures that the output ends with a newline (preserving any
+ // current status line that is current displayed).
+ //
+ // This does nothing on dumb terminals.
+ Finish()
+
+ // Write implements the io.Writer interface. This is primarily so that
+ // the logger can use this interface to print to stderr without
+ // breaking the other semantics of this interface.
+ //
+ // Try to use any of the other functions if possible.
+ Write(p []byte) (n int, err error)
+
+ isSmartTerminal() bool
+}
+
+// NewWriter creates a new Writer based on the stdio and the TERM
+// environment variable.
+func NewWriter(stdio StdioInterface) Writer {
+ w := &writerImpl{
+ stdio: stdio,
+
+ haveBlankLine: true,
+ }
+
+ if term, ok := os.LookupEnv("TERM"); ok && term != "dumb" {
+ w.stripEscapes = !isTerminal(stdio.Stderr())
+ w.smartTerminal = isTerminal(stdio.Stdout()) && !w.stripEscapes
+ }
+
+ return w
+}
+
+type writerImpl struct {
+ stdio StdioInterface
+
+ haveBlankLine bool
+
+ // Protecting the above, we assume that smartTerminal and stripEscapes
+ // does not change after initial setup.
+ lock sync.Mutex
+
+ smartTerminal bool
+ stripEscapes bool
+}
+
+func (w *writerImpl) isSmartTerminal() bool {
+ return w.smartTerminal
+}
+
+func (w *writerImpl) requestLine() {
+ if !w.haveBlankLine {
+ fmt.Fprintln(w.stdio.Stdout())
+ w.haveBlankLine = true
+ }
+}
+
+func (w *writerImpl) Print(str string) {
+ if w.stripEscapes {
+ str = string(stripAnsiEscapes([]byte(str)))
+ }
+
+ w.lock.Lock()
+ defer w.lock.Unlock()
+ w.print(str)
+}
+
+func (w *writerImpl) print(str string) {
+ if !w.haveBlankLine {
+ fmt.Fprint(w.stdio.Stdout(), "\r", "\x1b[K")
+ w.haveBlankLine = true
+ }
+ fmt.Fprint(w.stdio.Stderr(), str)
+ if len(str) == 0 || str[len(str)-1] != '\n' {
+ fmt.Fprint(w.stdio.Stderr(), "\n")
+ }
+}
+
+func (w *writerImpl) StatusLine(str string) {
+ w.lock.Lock()
+ defer w.lock.Unlock()
+
+ w.statusLine(str)
+}
+
+func (w *writerImpl) statusLine(str string) {
+ if !w.smartTerminal {
+ fmt.Fprintln(w.stdio.Stdout(), str)
+ return
+ }
+
+ idx := strings.IndexRune(str, '\n')
+ if idx != -1 {
+ str = str[0:idx]
+ }
+
+ // Limit line width to the terminal width, otherwise we'll wrap onto
+ // another line and we won't delete the previous line.
+ //
+ // Run this on every line in case the window has been resized while
+ // we're printing. This could be optimized to only re-run when we get
+ // SIGWINCH if it ever becomes too time consuming.
+ if max, ok := termWidth(w.stdio.Stdout()); ok {
+ if len(str) > max {
+ // TODO: Just do a max. Ninja elides the middle, but that's
+ // more complicated and these lines aren't that important.
+ str = str[:max]
+ }
+ }
+
+ // Move to the beginning on the line, print the output, then clear
+ // the rest of the line.
+ fmt.Fprint(w.stdio.Stdout(), "\r", str, "\x1b[K")
+ w.haveBlankLine = false
+}
+
+func (w *writerImpl) StatusAndMessage(status, msg string) {
+ if w.stripEscapes {
+ msg = string(stripAnsiEscapes([]byte(msg)))
+ }
+
+ w.lock.Lock()
+ defer w.lock.Unlock()
+
+ w.statusLine(status)
+ w.requestLine()
+ w.print(msg)
+}
+
+func (w *writerImpl) Finish() {
+ w.lock.Lock()
+ defer w.lock.Unlock()
+
+ w.requestLine()
+}
+
+func (w *writerImpl) Write(p []byte) (n int, err error) {
+ w.Print(string(p))
+ return len(p), nil
+}
+
+// StdioInterface represents a set of stdin/stdout/stderr Reader/Writers
+type StdioInterface interface {
+ Stdin() io.Reader
+ Stdout() io.Writer
+ Stderr() io.Writer
+}
+
+// StdioImpl uses the OS stdin/stdout/stderr to implement StdioInterface
+type StdioImpl struct{}
+
+func (StdioImpl) Stdin() io.Reader { return os.Stdin }
+func (StdioImpl) Stdout() io.Writer { return os.Stdout }
+func (StdioImpl) Stderr() io.Writer { return os.Stderr }
+
+var _ StdioInterface = StdioImpl{}
+
+type customStdio struct {
+ stdin io.Reader
+ stdout io.Writer
+ stderr io.Writer
+}
+
+func NewCustomStdio(stdin io.Reader, stdout, stderr io.Writer) StdioInterface {
+ return customStdio{stdin, stdout, stderr}
+}
+
+func (c customStdio) Stdin() io.Reader { return c.stdin }
+func (c customStdio) Stdout() io.Writer { return c.stdout }
+func (c customStdio) Stderr() io.Writer { return c.stderr }
+
+var _ StdioInterface = customStdio{}