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
diff --git a/ui/tracer/Android.bp b/ui/tracer/Android.bp
index 9729c7e..af588f1 100644
--- a/ui/tracer/Android.bp
+++ b/ui/tracer/Android.bp
@@ -15,10 +15,13 @@
 bootstrap_go_package {
     name: "soong-ui-tracer",
     pkgPath: "android/soong/ui/tracer",
-    deps: ["soong-ui-logger"],
+    deps: [
+        "soong-ui-logger",
+        "soong-ui-status",
+    ],
     srcs: [
         "microfactory.go",
-        "ninja.go",
+        "status.go",
         "tracer.go",
     ],
 }
diff --git a/ui/tracer/microfactory.go b/ui/tracer/microfactory.go
index acb9be4..c4c37c2 100644
--- a/ui/tracer/microfactory.go
+++ b/ui/tracer/microfactory.go
@@ -17,10 +17,48 @@
 import (
 	"bufio"
 	"os"
+	"sort"
 	"strconv"
 	"strings"
 )
 
+type eventEntry struct {
+	Name  string
+	Begin uint64
+	End   uint64
+}
+
+func (t *tracerImpl) importEvents(entries []*eventEntry) {
+	sort.Slice(entries, func(i, j int) bool {
+		return entries[i].Begin < entries[j].Begin
+	})
+
+	cpus := []uint64{}
+	for _, entry := range entries {
+		tid := -1
+		for cpu, endTime := range cpus {
+			if endTime <= entry.Begin {
+				tid = cpu
+				cpus[cpu] = entry.End
+				break
+			}
+		}
+		if tid == -1 {
+			tid = len(cpus)
+			cpus = append(cpus, entry.End)
+		}
+
+		t.writeEvent(&viewerEvent{
+			Name:  entry.Name,
+			Phase: "X",
+			Time:  entry.Begin,
+			Dur:   entry.End - entry.Begin,
+			Pid:   1,
+			Tid:   uint64(tid),
+		})
+	}
+}
+
 func (t *tracerImpl) ImportMicrofactoryLog(filename string) {
 	if _, err := os.Stat(filename); err != nil {
 		return
diff --git a/ui/tracer/ninja.go b/ui/tracer/ninja.go
deleted file mode 100644
index 1980559..0000000
--- a/ui/tracer/ninja.go
+++ /dev/null
@@ -1,131 +0,0 @@
-// Copyright 2016 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 tracer
-
-import (
-	"bufio"
-	"os"
-	"sort"
-	"strconv"
-	"strings"
-	"time"
-)
-
-type eventEntry struct {
-	Name  string
-	Begin uint64
-	End   uint64
-}
-
-func (t *tracerImpl) importEvents(entries []*eventEntry) {
-	sort.Slice(entries, func(i, j int) bool {
-		return entries[i].Begin < entries[j].Begin
-	})
-
-	cpus := []uint64{}
-	for _, entry := range entries {
-		tid := -1
-		for cpu, endTime := range cpus {
-			if endTime <= entry.Begin {
-				tid = cpu
-				cpus[cpu] = entry.End
-				break
-			}
-		}
-		if tid == -1 {
-			tid = len(cpus)
-			cpus = append(cpus, entry.End)
-		}
-
-		t.writeEvent(&viewerEvent{
-			Name:  entry.Name,
-			Phase: "X",
-			Time:  entry.Begin,
-			Dur:   entry.End - entry.Begin,
-			Pid:   1,
-			Tid:   uint64(tid),
-		})
-	}
-}
-
-// ImportNinjaLog reads a .ninja_log file from ninja and writes the events out
-// to the trace.
-//
-// startOffset is when the ninja process started, and is used to position the
-// relative times from the ninja log into the trace. It's also used to skip
-// reading the ninja log if nothing was run.
-func (t *tracerImpl) ImportNinjaLog(thread Thread, filename string, startOffset time.Time) {
-	t.Begin("ninja log import", thread)
-	defer t.End(thread)
-
-	if stat, err := os.Stat(filename); err != nil {
-		t.log.Println("Missing ninja log:", err)
-		return
-	} else if stat.ModTime().Before(startOffset) {
-		t.log.Verboseln("Ninja log not modified, not importing any entries.")
-		return
-	}
-
-	f, err := os.Open(filename)
-	if err != nil {
-		t.log.Println("Error opening ninja log:", err)
-		return
-	}
-	defer f.Close()
-
-	s := bufio.NewScanner(f)
-	header := true
-	entries := []*eventEntry{}
-	prevEnd := 0
-	offset := uint64(startOffset.UnixNano()) / 1000
-	for s.Scan() {
-		if header {
-			hdr := s.Text()
-			if hdr != "# ninja log v5" {
-				t.log.Printf("Unknown ninja log header: %q", hdr)
-				return
-			}
-			header = false
-			continue
-		}
-
-		fields := strings.Split(s.Text(), "\t")
-		begin, err := strconv.Atoi(fields[0])
-		if err != nil {
-			t.log.Printf("Unable to parse ninja entry %q: %v", s.Text(), err)
-			return
-		}
-		end, err := strconv.Atoi(fields[1])
-		if err != nil {
-			t.log.Printf("Unable to parse ninja entry %q: %v", s.Text(), err)
-			return
-		}
-		if end < prevEnd {
-			entries = nil
-		}
-		prevEnd = end
-		entries = append(entries, &eventEntry{
-			Name:  fields[3],
-			Begin: offset + uint64(begin)*1000,
-			End:   offset + uint64(end)*1000,
-		})
-	}
-	if err := s.Err(); err != nil {
-		t.log.Println("Unable to parse ninja log:", err)
-		return
-	}
-
-	t.importEvents(entries)
-}
diff --git a/ui/tracer/status.go b/ui/tracer/status.go
new file mode 100644
index 0000000..af50e2d
--- /dev/null
+++ b/ui/tracer/status.go
@@ -0,0 +1,87 @@
+// 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 tracer
+
+import (
+	"android/soong/ui/status"
+	"time"
+)
+
+func (t *tracerImpl) StatusTracer() status.StatusOutput {
+	return &statusOutput{
+		tracer: t,
+
+		running: map[*status.Action]actionStatus{},
+	}
+}
+
+type actionStatus struct {
+	cpu   int
+	start time.Time
+}
+
+type statusOutput struct {
+	tracer *tracerImpl
+
+	cpus    []bool
+	running map[*status.Action]actionStatus
+}
+
+func (s *statusOutput) StartAction(action *status.Action, counts status.Counts) {
+	cpu := -1
+	for i, busy := range s.cpus {
+		if !busy {
+			cpu = i
+			s.cpus[i] = true
+			break
+		}
+	}
+
+	if cpu == -1 {
+		cpu = len(s.cpus)
+		s.cpus = append(s.cpus, true)
+	}
+
+	s.running[action] = actionStatus{
+		cpu:   cpu,
+		start: time.Now(),
+	}
+}
+
+func (s *statusOutput) FinishAction(result status.ActionResult, counts status.Counts) {
+	start, ok := s.running[result.Action]
+	if !ok {
+		return
+	}
+	delete(s.running, result.Action)
+	s.cpus[start.cpu] = false
+
+	str := result.Action.Description
+	if len(result.Action.Outputs) > 0 {
+		str = result.Action.Outputs[0]
+	}
+
+	s.tracer.writeEvent(&viewerEvent{
+		Name:  str,
+		Phase: "X",
+		Time:  uint64(start.start.UnixNano()) / 1000,
+		Dur:   uint64(time.Since(start.start).Nanoseconds()) / 1000,
+		Pid:   1,
+		Tid:   uint64(start.cpu),
+	})
+}
+
+func (s *statusOutput) Flush()                                        {}
+func (s *statusOutput) Message(level status.MsgLevel, message string) {}
diff --git a/ui/tracer/tracer.go b/ui/tracer/tracer.go
index 8705040..b8fc87b 100644
--- a/ui/tracer/tracer.go
+++ b/ui/tracer/tracer.go
@@ -31,6 +31,7 @@
 	"time"
 
 	"android/soong/ui/logger"
+	"android/soong/ui/status"
 )
 
 type Thread uint64
@@ -46,7 +47,8 @@
 	Complete(name string, thread Thread, begin, end uint64)
 
 	ImportMicrofactoryLog(filename string)
-	ImportNinjaLog(thread Thread, filename string, startOffset time.Time)
+
+	StatusTracer() status.StatusOutput
 
 	NewThread(name string) Thread
 }