| 1 | package main |
| 2 | |
| 3 | // How long each decision took, said in the integrator's own output. |
| 4 | // |
| 5 | // Every decision the integrator reports also gets one timing line: which |
| 6 | // request, what was decided, how long the whole decision took, and how |
| 7 | // that time divides among the stages it went through. The line is JSON |
| 8 | // after a fixed label, so it can be read out of the journal without |
| 9 | // parsing the rest. It is output and nothing else: no ref, record or event |
| 10 | // carries it, and nothing the integrator decides reads it. |
| 11 | // |
| 12 | // Nor may it stand in the way of a decision. The line is printed after the |
| 13 | // attempt to record the outcome, whether or not that attempt succeeds. The |
| 14 | // caller waits at most timingDeadline for the write, and a write still |
| 15 | // blocked then may finish later. |
| 16 | // |
| 17 | // Where the host names a telemetry stream in VALLEY_TELEMETRY_DIR, the |
| 18 | // same timing is also stored there as a decision record (../telemetry), |
| 19 | // which the collector serves. The record is the producer's own: the |
| 20 | // collector never reads one out of the printed line. It is stored after |
| 21 | // the attempt to record the outcome too, and dropped when it cannot be |
| 22 | // stored within telemetry.EmitDeadline. |
| 23 | // |
| 24 | // A decision begins when the integrator starts judging a request. Its line |
| 25 | // also says when this process first saw the request at its head, and which |
| 26 | // pass of which process made the decision (sightings). That is when this |
| 27 | // integrator process first listed the request ref. It is neither the |
| 28 | // approval's time nor the time the host accepted the ref, and nothing |
| 29 | // before the process started is known to it. |
| 30 | |
| 31 | import ( |
| 32 | "bytes" |
| 33 | "encoding/json" |
| 34 | "errors" |
| 35 | "fmt" |
| 36 | "io" |
| 37 | "os" |
| 38 | "syscall" |
| 39 | "time" |
| 40 | |
| 41 | "the-valley/telemetry" |
| 42 | ) |
| 43 | |
| 44 | // The stages a decision is timed in. A stage a decision did not reach is |
| 45 | // absent from its line. |
| 46 | const ( |
| 47 | stageRefusal = "refusal" // the record and merge rules, before judging and again before landing |
| 48 | stageCheckout = "checkout" // the worktree of the target's tip |
| 49 | stageEvidence = "evidence" // the head's tree digest and verifying its notes |
| 50 | stagePolicy = "policy" // composing the policy and deriving the required checks |
| 51 | stageApply = "apply" // merging the delta onto the tip |
| 52 | stageClosures = "closures" // recomputing input closures on a moved tree |
| 53 | stageSign = "sign" // composing and signing the transfer statement |
| 54 | stageLand = "land" // the ref transaction that moves the target and records the landing |
| 55 | stageRecord = "record" // building what the transaction records: evidence trees, landing and outcome records |
| 56 | stagePublish = "publish" // the publisher's queue and the bus events |
| 57 | ) |
| 58 | |
| 59 | // stopwatch times one decision, as a whole and by stage. A nil stopwatch |
| 60 | // times nothing, so a caller with no decision to time can pass none. |
| 61 | type stopwatch struct { |
| 62 | began time.Time |
| 63 | stages map[string]time.Duration |
| 64 | } |
| 65 | |
| 66 | func newStopwatch() *stopwatch { |
| 67 | return &stopwatch{began: time.Now(), stages: map[string]time.Duration{}} |
| 68 | } |
| 69 | |
| 70 | // stage starts timing a stage and returns the function that stops it. A |
| 71 | // stage timed more than once adds up. |
| 72 | func (s *stopwatch) stage(name string) func() { |
| 73 | if s == nil { |
| 74 | return func() {} |
| 75 | } |
| 76 | began := time.Now() |
| 77 | return func() { s.stages[name] += time.Since(began) } |
| 78 | } |
| 79 | |
| 80 | // decisionTiming is the timing line's JSON. |
| 81 | type decisionTiming struct { |
| 82 | Time string `json:"time"` // when the decision began, UTC |
| 83 | Project string `json:"project"` |
| 84 | Request string `json:"request"` |
| 85 | Change string `json:"change"` |
| 86 | Head string `json:"head"` |
| 87 | Target string `json:"target"` |
| 88 | Tip string `json:"tip"` |
| 89 | Outcome string `json:"outcome"` |
| 90 | DurationMS int64 `json:"duration_ms"` |
| 91 | StagesMS map[string]int64 `json:"stages_ms"` |
| 92 | observation |
| 93 | } |
| 94 | |
| 95 | // observation says when the process that made a decision first saw its |
| 96 | // request, and which of its passes made the decision. A decision made |
| 97 | // outside a pass, as a test makes one, has it empty. |
| 98 | type observation struct { |
| 99 | Process string `json:"process"` // this start of the integrator, apart from every other |
| 100 | Pass int `json:"pass"` // the deciding pass, counted from 1 in its process |
| 101 | PassReason string `json:"pass_reason"` // why that pass started (passReason) |
| 102 | PassListed string `json:"pass_listed"` // when that pass listed the requests, UTC |
| 103 | // When this process first listed the request at its head, UTC, and in |
| 104 | // which pass. A request first listed by the process's first pass may |
| 105 | // have waited from before the process started. |
| 106 | FirstSeen string `json:"first_seen"` |
| 107 | FirstSeenPass int `json:"first_seen_pass"` |
| 108 | FirstSeenAtStart bool `json:"first_seen_at_start"` |
| 109 | SeenToBeganMS int64 `json:"seen_to_began_ms"` // from first_seen to the decision's start |
| 110 | ListedToBeganMS int64 `json:"listed_to_began_ms"` // from pass_listed to the decision's start |
| 111 | } |
| 112 | |
| 113 | // timing composes the timing line for one decision about a request, and |
| 114 | // returns what prints it. The line is composed as the decision is made and |
| 115 | // printed after the attempt to record its outcome, so recording is not part |
| 116 | // of the time it reports, and printing it cannot keep the outcome from |
| 117 | // being recorded. |
| 118 | func (in *integrator) timing(r request, tip, outcome string, s *stopwatch) func() { |
| 119 | t := decisionTiming{ |
| 120 | Time: s.began.UTC().Format("2006-01-02T15:04:05.000Z"), |
| 121 | Project: in.project, |
| 122 | Request: r.ref, |
| 123 | Change: r.change, |
| 124 | Head: r.head, |
| 125 | Target: r.target, |
| 126 | Tip: tip, |
| 127 | Outcome: outcome, |
| 128 | DurationMS: time.Since(s.began).Milliseconds(), |
| 129 | StagesMS: map[string]int64{}, |
| 130 | } |
| 131 | t.observation = in.sightings.of(r, s.began) |
| 132 | for name, d := range s.stages { |
| 133 | t.StagesMS[name] = d.Milliseconds() |
| 134 | } |
| 135 | record := decisionRecord(t, s.began) |
| 136 | line, err := json.Marshal(t) |
| 137 | if err != nil || in.timings == nil { |
| 138 | return record |
| 139 | } |
| 140 | return func() { |
| 141 | fmt.Fprintf(in.timings, " timing %s\n", line) |
| 142 | record() |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | // decisionRecord returns what stores a decision's timing as a telemetry |
| 147 | // record, or does nothing where the host names no stream. Each decision |
| 148 | // is a run of its own. |
| 149 | func decisionRecord(t decisionTiming, began time.Time) func() { |
| 150 | dir := os.Getenv("VALLEY_TELEMETRY_DIR") |
| 151 | if dir == "" { |
| 152 | return func() {} |
| 153 | } |
| 154 | data := map[string]any{"request": t.Request, "target": t.Target, "tip": t.Tip, "outcome": t.Outcome, |
| 155 | "duration_ms": t.DurationMS, "began": telemetry.Stamp(began)} |
| 156 | for name, ms := range t.StagesMS { |
| 157 | data["stage_"+name+"_ms"] = ms |
| 158 | } |
| 159 | if o := t.observation; o.FirstSeen != "" { |
| 160 | data["process"], data["pass"], data["pass_reason"], data["pass_listed"] = o.Process, o.Pass, o.PassReason, o.PassListed |
| 161 | data["first_seen"], data["first_seen_pass"], data["first_seen_at_start"] = o.FirstSeen, o.FirstSeenPass, o.FirstSeenAtStart |
| 162 | data["seen_to_began_ms"], data["listed_to_began_ms"] = o.SeenToBeganMS, o.ListedToBeganMS |
| 163 | } |
| 164 | return func() { |
| 165 | e := telemetry.NewEmitter(dir, telemetry.Self("integrator", ""), "") |
| 166 | e.Emit("decision", telemetry.Record{Project: t.Project, Change: t.Change, Head: t.Head}, data) |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | // sightings is what one integrator process remembers of when it first |
| 171 | // saw each request. Like the rest of this file it is output only: nothing |
| 172 | // the integrator decides reads it. |
| 173 | // |
| 174 | // A pass sees a request when it lists it. A request whose head moves is |
| 175 | // seen again, as a new request. Only this process's own sightings are |
| 176 | // kept, so a request that was waiting when the process started is first |
| 177 | // seen by its first pass, and its decisions say so. A request a pass no |
| 178 | // longer lists has landed, been voided or been deleted, and is forgotten |
| 179 | // after the next successful listing that omits it. A failed listing leaves |
| 180 | // the table as it was. A nil sightings sees nothing. |
| 181 | type sightings struct { |
| 182 | process string // this start of the integrator |
| 183 | passes int // the passes this process has started |
| 184 | reason passReason |
| 185 | listed time.Time // when the pass in progress listed the requests |
| 186 | seen map[string]sighting |
| 187 | } |
| 188 | |
| 189 | // sighting is when a request was first seen at its head. |
| 190 | type sighting struct { |
| 191 | head string |
| 192 | at time.Time |
| 193 | pass int |
| 194 | } |
| 195 | |
| 196 | func newSightings() *sightings { |
| 197 | return &sightings{process: telemetry.NewRunID(), seen: map[string]sighting{}} |
| 198 | } |
| 199 | |
| 200 | // start counts a pass that starts for reason. |
| 201 | func (s *sightings) start(reason passReason) { |
| 202 | if s == nil { |
| 203 | return |
| 204 | } |
| 205 | s.passes++ |
| 206 | s.reason = reason |
| 207 | s.listed = time.Time{} |
| 208 | } |
| 209 | |
| 210 | // list remembers the requests the pass in progress listed: those it has |
| 211 | // not seen at their heads are seen now, and those it no longer lists are |
| 212 | // forgotten. |
| 213 | func (s *sightings) list(requests []request) { |
| 214 | if s == nil { |
| 215 | return |
| 216 | } |
| 217 | s.listed = time.Now() |
| 218 | listed := make(map[string]bool, len(requests)) |
| 219 | for _, r := range requests { |
| 220 | listed[r.ref] = true |
| 221 | if was, ok := s.seen[r.ref]; !ok || was.head != r.head { |
| 222 | s.seen[r.ref] = sighting{head: r.head, at: s.listed, pass: s.passes} |
| 223 | } |
| 224 | } |
| 225 | for ref := range s.seen { |
| 226 | if !listed[ref] { |
| 227 | delete(s.seen, ref) |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | // of is the observation of a decision about r that began at began, or |
| 233 | // none where the pass in progress did not list r. |
| 234 | func (s *sightings) of(r request, began time.Time) observation { |
| 235 | if s == nil || s.listed.IsZero() { |
| 236 | return observation{} |
| 237 | } |
| 238 | seen, ok := s.seen[r.ref] |
| 239 | if !ok || seen.head != r.head { |
| 240 | return observation{} |
| 241 | } |
| 242 | return observation{ |
| 243 | Process: s.process, |
| 244 | Pass: s.passes, |
| 245 | PassReason: string(s.reason), |
| 246 | PassListed: telemetry.Stamp(s.listed), |
| 247 | FirstSeen: telemetry.Stamp(seen.at), |
| 248 | FirstSeenPass: seen.pass, |
| 249 | FirstSeenAtStart: seen.pass == 1, |
| 250 | SeenToBeganMS: began.Sub(seen.at).Milliseconds(), |
| 251 | ListedToBeganMS: began.Sub(s.listed).Milliseconds(), |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // timingDeadline is how long printing one timing line may take. |
| 256 | const timingDeadline = time.Second |
| 257 | |
| 258 | // errDropped is what a timing line that was dropped says. |
| 259 | var errDropped = errors.New("dropped: not written within " + timingDeadline.String()) |
| 260 | |
| 261 | // droppable writes timing lines, which may be lost. Each write is made |
| 262 | // apart from the caller, which waits for it at most timingDeadline. A |
| 263 | // write that fails or takes longer is dropped, though a slow one is not |
| 264 | // cancelled and may finish later. While one is still stuck, |
| 265 | // every later one is dropped at once rather than queued behind it. |
| 266 | type droppable struct { |
| 267 | w io.Writer |
| 268 | busy chan struct{} // holds a token while a write is in flight |
| 269 | } |
| 270 | |
| 271 | func newDroppable(w io.Writer) *droppable { |
| 272 | return &droppable{w: w, busy: make(chan struct{}, 1)} |
| 273 | } |
| 274 | |
| 275 | func (d *droppable) Write(p []byte) (int, error) { |
| 276 | select { |
| 277 | case d.busy <- struct{}{}: |
| 278 | default: |
| 279 | return 0, errDropped |
| 280 | } |
| 281 | line := bytes.Clone(p) |
| 282 | done := make(chan error, 1) |
| 283 | go func() { |
| 284 | _, err := d.w.Write(line) |
| 285 | <-d.busy |
| 286 | done <- err |
| 287 | }() |
| 288 | timer := time.NewTimer(timingDeadline) |
| 289 | defer timer.Stop() |
| 290 | select { |
| 291 | case err := <-done: |
| 292 | if err != nil { |
| 293 | return 0, err |
| 294 | } |
| 295 | return len(p), nil |
| 296 | case <-timer.C: |
| 297 | return 0, errDropped |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | // duplicate duplicates the descriptor of standard output, for timing |
| 302 | // lines. Go ends a process whose write to its own standard output fails |
| 303 | // because nobody reads it, as SIGPIPE would. Through a duplicate, the same |
| 304 | // write fails with EPIPE and nothing more. Output that cannot be |
| 305 | // duplicated gets no timing lines. |
| 306 | func duplicate(fd int, name string) io.Writer { |
| 307 | syscall.ForkLock.RLock() |
| 308 | dup, err := syscall.Dup(fd) |
| 309 | if err == nil { |
| 310 | syscall.CloseOnExec(dup) |
| 311 | } |
| 312 | syscall.ForkLock.RUnlock() |
| 313 | if err != nil { |
| 314 | return io.Discard |
| 315 | } |
| 316 | return os.NewFile(uintptr(dup), name) |
| 317 | } |