blob: 4d9962153882631991f385d5dae38591943c884e [file] [log] [blame]
Dan Willemsenb82471a2018-05-17 16:37:09 -07001// Copyright 2018 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package status
16
17import (
18 "bufio"
19 "fmt"
20 "io"
21 "os"
Spandan Das05063612021-06-25 01:39:04 +000022 "regexp"
23 "strings"
Dan Willemsenb82471a2018-05-17 16:37:09 -070024 "syscall"
Colin Crossb98d3bc2019-03-21 16:02:58 -070025 "time"
Dan Willemsenb82471a2018-05-17 16:37:09 -070026
Dan Willemsen4591b642021-05-24 14:24:12 -070027 "google.golang.org/protobuf/proto"
Dan Willemsenb82471a2018-05-17 16:37:09 -070028
29 "android/soong/ui/logger"
30 "android/soong/ui/status/ninja_frontend"
31)
32
Colin Crossb98d3bc2019-03-21 16:02:58 -070033// NewNinjaReader reads the protobuf frontend format from ninja and translates it
Dan Willemsenb82471a2018-05-17 16:37:09 -070034// into calls on the ToolStatus API.
Colin Crossb98d3bc2019-03-21 16:02:58 -070035func NewNinjaReader(ctx logger.Logger, status ToolStatus, fifo string) *NinjaReader {
Dan Willemsenb82471a2018-05-17 16:37:09 -070036 os.Remove(fifo)
37
38 err := syscall.Mkfifo(fifo, 0666)
39 if err != nil {
40 ctx.Fatalf("Failed to mkfifo(%q): %v", fifo, err)
41 }
42
Colin Crossb98d3bc2019-03-21 16:02:58 -070043 n := &NinjaReader{
44 status: status,
45 fifo: fifo,
46 done: make(chan bool),
47 cancel: make(chan bool),
48 }
49
50 go n.run()
51
52 return n
Dan Willemsenb82471a2018-05-17 16:37:09 -070053}
54
Colin Crossb98d3bc2019-03-21 16:02:58 -070055type NinjaReader struct {
56 status ToolStatus
57 fifo string
58 done chan bool
59 cancel chan bool
60}
61
62const NINJA_READER_CLOSE_TIMEOUT = 5 * time.Second
63
64// Close waits for NinjaReader to finish reading from the fifo, or 5 seconds.
65func (n *NinjaReader) Close() {
66 // Signal the goroutine to stop if it is blocking opening the fifo.
67 close(n.cancel)
68
69 timeoutCh := time.After(NINJA_READER_CLOSE_TIMEOUT)
70
71 select {
72 case <-n.done:
73 // Nothing
74 case <-timeoutCh:
75 n.status.Error(fmt.Sprintf("ninja fifo didn't finish after %s", NINJA_READER_CLOSE_TIMEOUT.String()))
Dan Willemsenb82471a2018-05-17 16:37:09 -070076 }
Colin Crossb98d3bc2019-03-21 16:02:58 -070077
78 return
79}
80
81func (n *NinjaReader) run() {
82 defer close(n.done)
83
84 // Opening the fifo can block forever if ninja never opens the write end, do it in a goroutine so this
85 // method can exit on cancel.
86 fileCh := make(chan *os.File)
87 go func() {
88 f, err := os.Open(n.fifo)
89 if err != nil {
90 n.status.Error(fmt.Sprintf("Failed to open fifo: %v", err))
91 close(fileCh)
92 return
93 }
94 fileCh <- f
95 }()
96
97 var f *os.File
98
99 select {
100 case f = <-fileCh:
101 // Nothing
102 case <-n.cancel:
103 return
104 }
105
Dan Willemsenb82471a2018-05-17 16:37:09 -0700106 defer f.Close()
107
108 r := bufio.NewReader(f)
109
110 running := map[uint32]*Action{}
111
112 for {
113 size, err := readVarInt(r)
114 if err != nil {
115 if err != io.EOF {
Colin Crossb98d3bc2019-03-21 16:02:58 -0700116 n.status.Error(fmt.Sprintf("Got error reading from ninja: %s", err))
Dan Willemsenb82471a2018-05-17 16:37:09 -0700117 }
118 return
119 }
120
121 buf := make([]byte, size)
122 _, err = io.ReadFull(r, buf)
123 if err != nil {
124 if err == io.EOF {
Colin Crossb98d3bc2019-03-21 16:02:58 -0700125 n.status.Print(fmt.Sprintf("Missing message of size %d from ninja\n", size))
Dan Willemsenb82471a2018-05-17 16:37:09 -0700126 } else {
Colin Crossb98d3bc2019-03-21 16:02:58 -0700127 n.status.Error(fmt.Sprintf("Got error reading from ninja: %s", err))
Dan Willemsenb82471a2018-05-17 16:37:09 -0700128 }
129 return
130 }
131
132 msg := &ninja_frontend.Status{}
133 err = proto.Unmarshal(buf, msg)
134 if err != nil {
Colin Crossb98d3bc2019-03-21 16:02:58 -0700135 n.status.Print(fmt.Sprintf("Error reading message from ninja: %v", err))
Dan Willemsenb82471a2018-05-17 16:37:09 -0700136 continue
137 }
138
139 // Ignore msg.BuildStarted
140 if msg.TotalEdges != nil {
Colin Crossb98d3bc2019-03-21 16:02:58 -0700141 n.status.SetTotalActions(int(msg.TotalEdges.GetTotalEdges()))
Dan Willemsenb82471a2018-05-17 16:37:09 -0700142 }
143 if msg.EdgeStarted != nil {
144 action := &Action{
145 Description: msg.EdgeStarted.GetDesc(),
146 Outputs: msg.EdgeStarted.Outputs,
Colin Cross7b624532019-06-21 15:08:30 -0700147 Inputs: msg.EdgeStarted.Inputs,
Dan Willemsenb82471a2018-05-17 16:37:09 -0700148 Command: msg.EdgeStarted.GetCommand(),
149 }
Colin Crossb98d3bc2019-03-21 16:02:58 -0700150 n.status.StartAction(action)
Dan Willemsenb82471a2018-05-17 16:37:09 -0700151 running[msg.EdgeStarted.GetId()] = action
152 }
153 if msg.EdgeFinished != nil {
154 if started, ok := running[msg.EdgeFinished.GetId()]; ok {
155 delete(running, msg.EdgeFinished.GetId())
156
157 var err error
158 exitCode := int(msg.EdgeFinished.GetStatus())
159 if exitCode != 0 {
160 err = fmt.Errorf("exited with code: %d", exitCode)
161 }
162
Spandan Das05063612021-06-25 01:39:04 +0000163 outputWithErrorHint := errorHintGenerator.GetOutputWithErrorHint(msg.EdgeFinished.GetOutput(), exitCode)
Colin Crossb98d3bc2019-03-21 16:02:58 -0700164 n.status.FinishAction(ActionResult{
Dan Willemsenb82471a2018-05-17 16:37:09 -0700165 Action: started,
Spandan Das05063612021-06-25 01:39:04 +0000166 Output: outputWithErrorHint,
Dan Willemsenb82471a2018-05-17 16:37:09 -0700167 Error: err,
Colin Crossd888b6b2020-10-15 13:46:32 -0700168 Stats: ActionResultStats{
169 UserTime: msg.EdgeFinished.GetUserTime(),
170 SystemTime: msg.EdgeFinished.GetSystemTime(),
171 MaxRssKB: msg.EdgeFinished.GetMaxRssKb(),
172 MinorPageFaults: msg.EdgeFinished.GetMinorPageFaults(),
173 MajorPageFaults: msg.EdgeFinished.GetMajorPageFaults(),
174 IOInputKB: msg.EdgeFinished.GetIoInputKb(),
175 IOOutputKB: msg.EdgeFinished.GetIoOutputKb(),
176 VoluntaryContextSwitches: msg.EdgeFinished.GetVoluntaryContextSwitches(),
177 InvoluntaryContextSwitches: msg.EdgeFinished.GetInvoluntaryContextSwitches(),
178 },
Dan Willemsenb82471a2018-05-17 16:37:09 -0700179 })
180 }
181 }
182 if msg.Message != nil {
183 message := "ninja: " + msg.Message.GetMessage()
184 switch msg.Message.GetLevel() {
185 case ninja_frontend.Status_Message_INFO:
Colin Crossb98d3bc2019-03-21 16:02:58 -0700186 n.status.Status(message)
Dan Willemsenb82471a2018-05-17 16:37:09 -0700187 case ninja_frontend.Status_Message_WARNING:
Colin Crossb98d3bc2019-03-21 16:02:58 -0700188 n.status.Print("warning: " + message)
Dan Willemsenb82471a2018-05-17 16:37:09 -0700189 case ninja_frontend.Status_Message_ERROR:
Colin Crossb98d3bc2019-03-21 16:02:58 -0700190 n.status.Error(message)
Dan Willemsen08218222020-05-18 14:02:02 -0700191 case ninja_frontend.Status_Message_DEBUG:
192 n.status.Verbose(message)
Dan Willemsenb82471a2018-05-17 16:37:09 -0700193 default:
Colin Crossb98d3bc2019-03-21 16:02:58 -0700194 n.status.Print(message)
Dan Willemsenb82471a2018-05-17 16:37:09 -0700195 }
196 }
197 if msg.BuildFinished != nil {
Colin Crossb98d3bc2019-03-21 16:02:58 -0700198 n.status.Finish()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700199 }
200 }
201}
202
203func readVarInt(r *bufio.Reader) (int, error) {
204 ret := 0
205 shift := uint(0)
206
207 for {
208 b, err := r.ReadByte()
209 if err != nil {
210 return 0, err
211 }
212
213 ret += int(b&0x7f) << (shift * 7)
214 if b&0x80 == 0 {
215 break
216 }
217 shift += 1
218 if shift > 4 {
219 return 0, fmt.Errorf("Expected varint32 length-delimited message")
220 }
221 }
222
223 return ret, nil
224}
Spandan Das05063612021-06-25 01:39:04 +0000225
226// key is pattern in stdout/stderr
227// value is error hint
228var allErrorHints = map[string]string{
229 "Read-only file system": `\nWrite to a read-only file system detected. Possible fixes include
2301. Generate file directly to out/ which is ReadWrite, #recommend solution
2312. BUILD_BROKEN_SRC_DIR_RW_ALLOWLIST := <my/path/1> <my/path/2> #discouraged, subset of source tree will be RW
2323. BUILD_BROKEN_SRC_DIR_IS_WRITABLE := true #highly discouraged, entire source tree will be RW
233`,
234}
235var errorHintGenerator = *newErrorHintGenerator(allErrorHints)
236
237type ErrorHintGenerator struct {
238 allErrorHints map[string]string
239 allErrorHintPatternsCompiled *regexp.Regexp
240}
241
242func newErrorHintGenerator(allErrorHints map[string]string) *ErrorHintGenerator {
243 var allErrorHintPatterns []string
244 for errorHintPattern, _ := range allErrorHints {
245 allErrorHintPatterns = append(allErrorHintPatterns, errorHintPattern)
246 }
247 allErrorHintPatternsRegex := strings.Join(allErrorHintPatterns[:], "|")
248 re := regexp.MustCompile(allErrorHintPatternsRegex)
249 return &ErrorHintGenerator{
250 allErrorHints: allErrorHints,
251 allErrorHintPatternsCompiled: re,
252 }
253}
254
255func (errorHintGenerator *ErrorHintGenerator) GetOutputWithErrorHint(rawOutput string, buildExitCode int) string {
256 if buildExitCode == 0 {
257 return rawOutput
258 }
259 errorHint := errorHintGenerator.getErrorHint(rawOutput)
260 if errorHint == nil {
261 return rawOutput
262 }
263 return rawOutput + *errorHint
264}
265
266// Returns the error hint corresponding to the FIRST match in raw output
267func (errorHintGenerator *ErrorHintGenerator) getErrorHint(rawOutput string) *string {
268 firstMatch := errorHintGenerator.allErrorHintPatternsCompiled.FindString(rawOutput)
269 if _, found := errorHintGenerator.allErrorHints[firstMatch]; found {
270 errorHint := errorHintGenerator.allErrorHints[firstMatch]
271 return &errorHint
272 }
273 return nil
274}