package mac import ( "path" "regexp" "sort" "strconv" "strings" "sync" "unicode/utf8" ) // Why P2's srt run did not fully succeed: the step that failed, its // exit, whether the run timed out, and the first error lines, bounded // and with nothing secret in them. The probe's detail carries the short // form; runner.log the excerpt, once per probe run. // p2Phases are the steps of P2's srt run in the order they run. The // script build stands alone; each package step needs the one before. var p2Phases = []struct{ key, label string }{ {"script-build", "script build"}, {"package-resolve", "package resolve"}, {"test-build", "test build"}, {"simulator-boot", "simulator boot"}, {"test-run", "test run"}, } // p2Succeeded are xcodebuild's own last lines for its three steps that // build or test (build, build-for-testing, test-without-building). var p2Succeeded = []string{"** BUILD SUCCEEDED **", "** TEST BUILD SUCCEEDED **", "** TEST EXECUTE SUCCEEDED **"} const ( // p2AttemptLines bounds the report lines kept (15 are expected; the // first for each attempt counts). p2AttemptLines = 64 // p2ErrorLines and p2ExcerptBytes bound the excerpt; p2ShortBytes its // first line in the probe's detail. p2ErrorLines = 5 p2ExcerptBytes = 400 p2ShortBytes = 120 ) var ( phaseLine = regexp.MustCompile(`^EQUIPO-PHASE (script-build|package-resolve|test-build|simulator-boot|test-run) ([0-9]{1,3})$`) // failureLine: xcodebuild's and the compilers' error lines, srt's own // ("Error: ...", a refused settings file), a nested sandbox that // could not be applied, a denial a tool printed, a write Unix // permissions refused, and the fixture finding no targets. failureLine = regexp.MustCompile(`(?i)\berror:|^refusing to run|^failed to execute|sandbox_apply|sandbox-exec:|\bdeny\(\d+\)|operation not permitted|permission denied|^EQUIPO-PROBE \w+ targets missing`) ansiEscape = regexp.MustCompile("\x1b\\[[0-9;?]*[ -/]*[@-~]") ) // p2Watch reads the whole of P2's output as it comes, so what decides P2 // does not depend on the gate's last 200 lines: a full build and test // prints more than that, and the script build's lines come first. type p2Watch struct { mu sync.Mutex attempts []string phases map[string]int succeeded map[string]bool errors []string } func newP2Watch() *p2Watch { return &p2Watch{phases: map[string]int{}, succeeded: map[string]bool{}} } func (w *p2Watch) line(l string) { t := strings.TrimSpace(l) w.mu.Lock() defer w.mu.Unlock() if attemptLine.MatchString(t) { if len(w.attempts) < p2AttemptLines { w.attempts = append(w.attempts, t) } return } if m := phaseLine.FindStringSubmatch(t); m != nil { if _, seen := w.phases[m[1]]; !seen { w.phases[m[1]], _ = strconv.Atoi(m[2]) } return } for _, s := range p2Succeeded { if t == s { w.succeeded[s] = true } } if len(w.errors) < p2ErrorLines && failureLine.MatchString(t) { for _, e := range w.errors { if e == t { return } } w.errors = append(w.errors, t) } } // attemptsSeen is the report lines, one per line, for ParseAttempts. func (w *p2Watch) attemptsSeen() string { w.mu.Lock() defer w.mu.Unlock() return strings.Join(w.attempts, "\n") } // ran: the run exited 0, every step said it exited 0, and xcodebuild // said each build and test succeeded. func (w *p2Watch) ran(res Result) bool { w.mu.Lock() defer w.mu.Unlock() if res.Code != 0 { return false } for _, p := range p2Phases { if c, ok := w.phases[p.key]; !ok || c != 0 { return false } } for _, s := range p2Succeeded { if !w.succeeded[s] { return false } } return true } // p2Failure is why the srt run did not fully succeed. type p2Failure struct { // Phase is the first step that failed, else the first that did not // finish: "srt start" when no step reported, "gate start" when the // gate could not start, "run end" when every step exited 0 and the // run still did not succeed. Failed is every step that failed, with // its exit ("script build exit 65"); Unfinished the step the run was // stopped in ("test build timed out"). Phase string Failed []string Unfinished string Exit int TimedOut bool // Excerpt is up to p2ErrorLines redacted lines, at most // p2ExcerptBytes; First the first of them, at most p2ShortBytes. Excerpt, First string } // failure says why a run that did not fully succeed failed. func (w *p2Watch) failure(res Result, r redactor) p2Failure { w.mu.Lock() defer w.mu.Unlock() f := p2Failure{Exit: res.Code, TimedOut: res.Reason == "checks_timeout"} stopped := f.TimedOut || res.Reason == "cancelled" missing := "" for _, p := range p2Phases { c, ok := w.phases[p.key] if ok && c != 0 { f.Failed = append(f.Failed, p.label+" exit "+strconv.Itoa(c)) if f.Phase == "" { f.Phase, f.Exit = p.label, c } } if !ok && missing == "" { missing = p.label } } switch { case len(w.phases) == 0 && res.Reason == "checks_unavailable": missing = "gate start" case len(w.phases) == 0 && !stopped: missing = "srt start" } if stopped && missing != "" { f.Unfinished = missing + map[bool]string{true: " timed out", false: " stopped"}[f.TimedOut] } if f.Phase == "" { f.Phase = firstNonEmpty(missing, "run end") } var lines []string size := 0 for _, e := range w.errors { if e = cut(r.line(e), p2ExcerptBytes-size); e == "" { continue } lines = append(lines, e) if size += len(e) + len(" | "); size >= p2ExcerptBytes { break } } f.Excerpt = cut(strings.Join(lines, " | "), p2ExcerptBytes) if len(lines) > 0 { f.First = cut(lines[0], p2ShortBytes) } return f } // short is the failure for the probe's detail ("test build exit 65: // error: ..."); clean then keeps it inside the capability string rules. func (f p2Failure) short() string { parts := append([]string{}, f.Failed...) if f.Unfinished != "" { parts = append(parts, f.Unfinished) } if len(parts) == 0 { if f.Exit < 0 { parts = append(parts, f.Phase+" failed") } else { parts = append(parts, f.Phase+" exit "+strconv.Itoa(f.Exit)) } } s := strings.Join(parts, ", ") if f.First != "" { s += ": " + f.First } return s } // redactor takes out of an output line what must never leave the Mac: // the secrets it is given (the sentinel secret and its prefixes, the // Keychain service, the targets file's lines and values) and every path // under a home, kept as its last element only. type redactor struct { secrets []string homes *regexp.Regexp } func newRedactor(secrets, homes []string) redactor { var s []string for _, x := range secrets { if x != "" { s = append(s, x) } } // Longest first: a prefix must not leave the rest of a longer one. sort.SliceStable(s, func(i, j int) bool { return len(s[i]) > len(s[j]) }) h := []string{regexp.QuoteMeta("/Users/")} for _, x := range homes { if x = strings.TrimRight(x, "/"); x != "" { h = append(h, regexp.QuoteMeta(x)) } } sort.SliceStable(h, func(i, j int) bool { return len(h[i]) > len(h[j]) }) return redactor{secrets: s, homes: regexp.MustCompile("(?:/private)?(?:" + strings.Join(h, "|") + ")[^\\s'\"`:,;()<>\\[\\]]*")} } func (r redactor) line(s string) string { s = strings.ToValidUTF8(s, "") s = ansiEscape.ReplaceAllString(s, "") s = strings.Map(func(c rune) rune { if c < 0x20 || c == 0x7f || c >= 0x80 && c < 0xa0 { return ' ' } return c }, s) s = r.redact(s) s = r.homes.ReplaceAllStringFunc(s, func(p string) string { base := path.Base(strings.TrimRight(p, "/")) if base == "." || base == "/" || base == "Users" { return "[home]" } return "[home]..." + base }) // Again after the paths: a last element keeps no part of a secret. s = r.redact(s) return strings.Join(strings.Fields(s), " ") } func (r redactor) redact(s string) string { for _, x := range r.secrets { s = strings.ReplaceAll(s, x, "[redacted]") } return s } // cut keeps at most n bytes of s, whole runes only. func cut(s string, n int) string { if n <= 0 { return "" } if len(s) <= n { return s } s = s[:n] for len(s) > 0 && !utf8.ValidString(s) { s = s[:len(s)-1] } return s }