| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/base64" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "regexp" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | "gorm.io/gorm" |
| 13 | ) |
| 14 | |
| 15 | // Candidates travel as packs, not credentials (Mac runners spec §2). A |
| 16 | // worker has no clone and no forge access: the primary uploads the exact |
| 17 | // candidate a worker judges (inbound), and a worker's own commit comes |
| 18 | // back to the primary (outbound), which alone publishes it. A transfer |
| 19 | // row authorises every chunk; chunks travel to the receiver as blob |
| 20 | // commands in its mailbox. |
| 21 | |
| 22 | // Transfer states. |
| 23 | const ( |
| 24 | transferOpen = "open" |
| 25 | transferComplete = "complete" |
| 26 | transferClosed = "closed" |
| 27 | ) |
| 28 | |
| 29 | var hexDigest = regexp.MustCompile(`^[0-9a-f]{64}$`) |
| 30 | |
| 31 | // openTransfer opens a transfer for one attempt, in the transaction that |
| 32 | // placed it (inbound) or accepted its candidate (outbound), and asks the |
| 33 | // sender for the pack (send_pack names the transfer it uploads under). h |
| 34 | // gives the direction and the commits (kind, base, old base, candidate); |
| 35 | // the attempt's own fields come from the step. |
| 36 | func (t *txn) openTransfer(k taskRecord, s stepRecord, from, to string, h wire.TransferHeader) (transferRecord, error) { |
| 37 | var p projectRecord |
| 38 | if err := t.db.Where("id = ?", k.ProjectID).First(&p).Error; err != nil { |
| 39 | return transferRecord{}, err |
| 40 | } |
| 41 | now := t.now() |
| 42 | tr := transferRecord{ID: newID("tr_"), Person: s.Person, FromRunner: from, ToRunner: to, Repo: p.Repo, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, BaseSHA: h.BaseSHA, CandidateSHA: h.CandidateSHA, Kind: h.Kind, OldBaseSHA: h.OldBaseSHA, Direction: h.Direction, State: transferOpen, ExpiresAt: now.Add(wire.TransferTTL), CreatedAt: now} |
| 43 | if err := t.db.Create(&tr).Error; err != nil { |
| 44 | return tr, err |
| 45 | } |
| 46 | return tr, t.commandTo(from, s.Person, wire.FrameSendPack, wire.SendPackCommand{Transfer: transferHeader(tr), Have: []string{}}) |
| 47 | } |
| 48 | |
| 49 | func transferHeader(tr transferRecord) wire.TransferHeader { |
| 50 | return wire.TransferHeader{ID: tr.ID, Direction: tr.Direction, Repo: tr.Repo, TaskID: tr.TaskID, StepID: tr.StepID, Attempt: tr.Attempt, BaseSHA: tr.BaseSHA, CandidateSHA: tr.CandidateSHA, Kind: tr.Kind, OldBaseSHA: tr.OldBaseSHA} |
| 51 | } |
| 52 | |
| 53 | // closeTransfers ends every transfer of a step attempt: nothing of it is |
| 54 | // served again and its chunks are gone. |
| 55 | func (t *txn) closeTransfers(stepID string, attempt int64) error { |
| 56 | var trs []transferRecord |
| 57 | if err := t.db.Where("step_id = ? AND attempt = ? AND state <> ?", stepID, attempt, transferClosed).Find(&trs).Error; err != nil { |
| 58 | return err |
| 59 | } |
| 60 | for _, tr := range trs { |
| 61 | if err := t.dropChunks(tr); err != nil { |
| 62 | return err |
| 63 | } |
| 64 | if err := t.db.Model(&transferRecord{}).Where("id = ?", tr.ID).Update("state", transferClosed).Error; err != nil { |
| 65 | return err |
| 66 | } |
| 67 | } |
| 68 | return nil |
| 69 | } |
| 70 | |
| 71 | // dropChunks voids a transfer's unacked chunks and send_pack, and empties |
| 72 | // every chunk it relayed. |
| 73 | func (t *txn) dropChunks(tr transferRecord) error { |
| 74 | like := `%"transfer":{"id":"` + tr.ID + `"%` |
| 75 | if err := t.db.Model(&commandRecord{}).Where("kind IN ? AND acked_at IS NULL AND body LIKE ?", []string{wire.FrameBlob, wire.FrameSendPack}, like).Update("acked_at", t.now()).Error; err != nil { |
| 76 | return err |
| 77 | } |
| 78 | return t.db.Model(&commandRecord{}).Where("kind = ? AND body LIKE ?", wire.FrameBlob, like).Update("body", "{}").Error |
| 79 | } |
| 80 | |
| 81 | // errTransferRefused refuses a chunk: logged, acked, no effect. |
| 82 | func errTransferRefused(why string) error { |
| 83 | return fmt.Errorf("%w: transfer_refused: %s", ErrRefused, why) |
| 84 | } |
| 85 | |
| 86 | // blob accepts one chunk only from the connection of the transfer's |
| 87 | // sender, for an open transfer whose attempt is the step's current one |
| 88 | // and neither withdrawn nor ended, with the header exactly as opened, and |
| 89 | // within bounds. Anything else is refused before a byte is kept. |
| 90 | func (t *txn) blob(l Lease, v *wire.Blob) error { |
| 91 | var tr transferRecord |
| 92 | if err := t.db.Where("id = ?", v.Transfer.ID).First(&tr).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 93 | return errTransferRefused("no such transfer") |
| 94 | } else if err != nil { |
| 95 | return err |
| 96 | } |
| 97 | if tr.FromRunner != l.Runner.RunnerID || tr.Person != l.Runner.Person { |
| 98 | return errTransferRefused("not this runner's transfer") |
| 99 | } |
| 100 | if tr.State != transferOpen { |
| 101 | return errTransferRefused("transfer not open") |
| 102 | } |
| 103 | if transferHeader(tr) != v.Transfer { |
| 104 | return errTransferRefused("header does not match the transfer") |
| 105 | } |
| 106 | var s stepRecord |
| 107 | if err := t.db.Where("id = ?", tr.StepID).First(&s).Error; err != nil { |
| 108 | return err |
| 109 | } |
| 110 | k, err := t.loadTask(s.TaskID) |
| 111 | if err != nil { |
| 112 | return err |
| 113 | } |
| 114 | if s.Attempt != tr.Attempt || s.Withdrawn || wire.FinalStage(k.Stage) || k.CancelRequested || tr.Direction == wire.TransferInbound && wire.StepTerminal(s.State) { |
| 115 | return errTransferRefused("attempt not current") |
| 116 | } |
| 117 | if v.Total > wire.MaxTransferChunks { |
| 118 | // Declared too large to relay: the checks cannot run on that runner, |
| 119 | // nor Engineering on that Mac. |
| 120 | return t.tooLarge(&k, &s, tr) |
| 121 | } |
| 122 | data, err := base64.StdEncoding.DecodeString(v.Data) |
| 123 | if err != nil || len(v.Data) > wire.MaxBlobData || !hexDigest.MatchString(v.SHA256) || v.Total < 1 || v.Index < 0 || v.Index >= v.Total { |
| 124 | return errTransferRefused("bad chunk") |
| 125 | } |
| 126 | if tr.Received > 0 && (v.Total != tr.Total || v.SHA256 != tr.SHA256) || v.Index != tr.Received { |
| 127 | return errTransferRefused("chunk out of order") |
| 128 | } |
| 129 | if tr.Bytes+int64(len(data)) > wire.MaxTransferBytes { |
| 130 | return t.tooLarge(&k, &s, tr) |
| 131 | } |
| 132 | tr.Total, tr.SHA256, tr.Received, tr.Bytes = v.Total, v.SHA256, tr.Received+1, tr.Bytes+int64(len(data)) |
| 133 | if tr.Received == tr.Total { |
| 134 | tr.State = transferComplete |
| 135 | } |
| 136 | if err := t.db.Model(&transferRecord{}).Where("id = ?", tr.ID).Select("total", "sha256", "received", "bytes", "state").Updates(&tr).Error; err != nil { |
| 137 | return err |
| 138 | } |
| 139 | if err := t.commandTo(tr.ToRunner, tr.Person, wire.FrameBlob, v); err != nil { |
| 140 | return err |
| 141 | } |
| 142 | if tr.State == transferComplete && tr.Direction == wire.TransferOutbound { |
| 143 | return t.publish(&k, &s, tr) |
| 144 | } |
| 145 | return nil |
| 146 | } |
| 147 | |
| 148 | // tooLarge closes a transfer past the bound; inbound, its checks end as |
| 149 | // not run (checks_unavailable), and Engineering on a Mac ends |
| 150 | // workspace_too_large with Needs you (it never runs on Linux instead). |
| 151 | // Outbound, a worker's commit that cannot reach the primary ends its |
| 152 | // step workspace_too_large too, with Needs you and Retry. |
| 153 | func (t *txn) tooLarge(k *taskRecord, s *stepRecord, tr transferRecord) error { |
| 154 | if err := t.dropChunks(tr); err != nil { |
| 155 | return err |
| 156 | } |
| 157 | if err := t.db.Model(&transferRecord{}).Where("id = ?", tr.ID).Update("state", transferClosed).Error; err != nil { |
| 158 | return err |
| 159 | } |
| 160 | if tr.Direction == wire.TransferOutbound { |
| 161 | return t.outboundTooLarge(k, s) |
| 162 | } |
| 163 | if tr.Direction != wire.TransferInbound || wire.StepTerminal(s.State) { |
| 164 | return nil |
| 165 | } |
| 166 | if tr.Kind == wire.TransferKindEngineering { |
| 167 | return t.withdrawFailing(k, s, wire.ReasonWorkspaceTooLarge) |
| 168 | } |
| 169 | return t.withdrawResolving(k, s, "checks_unavailable") |
| 170 | } |
| 171 | |
| 172 | // outboundTooLarge ends a worker's Engineering attempt whose commit is |
| 173 | // past the transfer bound: workspace_too_large, never published. Still |
| 174 | // running, it is withdrawn and ends once its termination is reported; |
| 175 | // already done (unpublished), it fails now. |
| 176 | func (t *txn) outboundTooLarge(k *taskRecord, s *stepRecord) error { |
| 177 | if k.MoveProject != "" || s.Retired || s.Withdrawn || s.Pushed || wire.FinalStage(k.Stage) { |
| 178 | return nil |
| 179 | } |
| 180 | if !wire.StepTerminal(s.State) { |
| 181 | return t.withdrawFailing(k, s, wire.ReasonWorkspaceTooLarge) |
| 182 | } |
| 183 | if s.State != wire.StepDone { |
| 184 | return nil |
| 185 | } |
| 186 | now := t.now() |
| 187 | s.State, s.Reason, s.FinishedAt, s.Publication, s.PublicationID, s.PublicationRunner = wire.StepFailed, wire.ReasonWorkspaceTooLarge, &now, "", "", "" |
| 188 | if err := t.saveStep(s, k); err != nil { |
| 189 | return err |
| 190 | } |
| 191 | return t.advance(k) |
| 192 | } |
| 193 | |
| 194 | // withdrawFailing withdraws an Engineering attempt that will end failed |
| 195 | // for reason: at once when it never started, else once its termination |
| 196 | // is reported (withdrawnSettle). |
| 197 | func (t *txn) withdrawFailing(k *taskRecord, s *stepRecord, reason string) error { |
| 198 | if s.StartedAt == nil { |
| 199 | if err := t.voidAttempt(*s); err != nil { |
| 200 | return err |
| 201 | } |
| 202 | endFailed(t, s, reason) |
| 203 | if err := t.saveStep(s, k); err != nil { |
| 204 | return err |
| 205 | } |
| 206 | return t.advance(k) |
| 207 | } |
| 208 | s.Withdrawn, s.Reason = true, reason |
| 209 | if err := t.saveStep(s, k); err != nil { |
| 210 | return err |
| 211 | } |
| 212 | return t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt}) |
| 213 | } |
| 214 | |
| 215 | // endFailed ends an attempt failed for reason, its end proven. |
| 216 | func endFailed(t *txn, s *stepRecord, reason string) { |
| 217 | now := t.now() |
| 218 | s.State, s.Reason, s.Terminated, s.FinishedAt, s.Withdrawn, s.Placement = wire.StepFailed, reason, true, &now, false, "" |
| 219 | } |
| 220 | |
| 221 | // blobAcked closes a transfer once its receiver acked the last chunk. |
| 222 | func (t *txn) blobAcked(body string) error { |
| 223 | var v wire.Blob |
| 224 | if err := json.Unmarshal([]byte(body), &v); err != nil || v.Index != v.Total-1 { |
| 225 | return nil |
| 226 | } |
| 227 | var tr transferRecord |
| 228 | if err := t.db.Where("id = ? AND state = ?", v.Transfer.ID, transferComplete).First(&tr).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 229 | return nil |
| 230 | } else if err != nil { |
| 231 | return err |
| 232 | } |
| 233 | if err := t.dropChunks(tr); err != nil { |
| 234 | return err |
| 235 | } |
| 236 | return t.db.Model(&transferRecord{}).Where("id = ?", tr.ID).Update("state", transferClosed).Error |
| 237 | } |
| 238 | |
| 239 | // withdrawResolving withdraws an attempt that will end as not run for |
| 240 | // reason (checks): resolved at once when it never started, else once its |
| 241 | // termination is reported. |
| 242 | func (t *txn) withdrawResolving(k *taskRecord, s *stepRecord, reason string) error { |
| 243 | if s.StartedAt == nil { |
| 244 | if err := t.voidAttempt(*s); err != nil { |
| 245 | return err |
| 246 | } |
| 247 | if err := t.resolveNotRun(k, s, reason); err != nil { |
| 248 | return err |
| 249 | } |
| 250 | return nil |
| 251 | } |
| 252 | s.Withdrawn, s.Reason = true, reason |
| 253 | if err := t.saveStep(s, k); err != nil { |
| 254 | return err |
| 255 | } |
| 256 | return t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt}) |
| 257 | } |
| 258 | |
| 259 | // resolveNotRun ends checks as not run, with reason; review goes on. |
| 260 | func (t *txn) resolveNotRun(k *taskRecord, s *stepRecord, reason string) error { |
| 261 | now := t.now() |
| 262 | s.State, s.Checks, s.Reason, s.Gate, s.ExitCode, s.Terminated, s.FinishedAt, s.Placement, s.Withdrawn = wire.StepDone, wire.ChecksCannotRun, reason, "", nil, true, &now, "", false |
| 263 | if err := t.saveStep(s, k); err != nil { |
| 264 | return err |
| 265 | } |
| 266 | return t.advance(k) |
| 267 | } |
| 268 | |
| 269 | // publish asks the primary to publish a worker's commit once its pack |
| 270 | // has arrived: the step's publication is pending with a new id, and the |
| 271 | // command is written in the same transaction. |
| 272 | func (t *txn) publish(k *taskRecord, s *stepRecord, tr transferRecord) error { |
| 273 | if k.MoveProject != "" || s.Retired { |
| 274 | return nil |
| 275 | } |
| 276 | primary, err := t.s.authority.PrimaryRunner(t.db, s.Person) |
| 277 | if err != nil || primary == "" { |
| 278 | return err |
| 279 | } |
| 280 | if tr.ToRunner != primary { |
| 281 | // The pack went to a primary since replaced: this one has none of |
| 282 | // it, and that one publishes nothing now. |
| 283 | return t.redirectOutbound(k, s, tr, primary) |
| 284 | } |
| 285 | s.Publication, s.PublicationID, s.PublicationRunner = wire.PublicationPending, newID("pb_"), primary |
| 286 | if err := t.saveStep(s, k); err != nil { |
| 287 | return err |
| 288 | } |
| 289 | // Diffs an earlier publication of this attempt left unaccepted are |
| 290 | // stale: only this publication's primary uploads count now. |
| 291 | if err := t.db.Where("step_id = ? AND attempt = ? AND accepted = ?", s.ID, s.Attempt, false).Delete(&changeDiffRecord{}).Error; err != nil { |
| 292 | return err |
| 293 | } |
| 294 | return t.commandTo(primary, s.Person, wire.FramePublish, wire.PublishCommand{Publication: s.PublicationID, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, Repo: tr.Repo, Branch: k.Branch, Person: s.Person, BaseSHA: tr.BaseSHA, CandidateSHA: tr.CandidateSHA, Transfer: tr.ID, OutcomePhase: s.OutcomePhase}) |
| 295 | } |
| 296 | |
| 297 | // workerOutcome is the outcome a worker's committed report names, if it |
| 298 | // is one ("" is an ordinary commit). |
| 299 | func workerOutcome(phase string) string { |
| 300 | switch phase { |
| 301 | case wire.OutcomeCommitted, wire.OutcomeUnfinished, wire.OutcomeNoShell: |
| 302 | return phase |
| 303 | } |
| 304 | return "" |
| 305 | } |
| 306 | |
| 307 | // takeOutcome: once a worker's commit is published, the step ends as its |
| 308 | // outcome says: step_timeout for unfinished work, shell_unavailable for |
| 309 | // a fix round without a shell (each over proposal_failed, as on the |
| 310 | // primary). |
| 311 | func takeOutcome(s *stepRecord) { |
| 312 | if !s.Pushed || s.Publication != wire.PublicationPublished { |
| 313 | return |
| 314 | } |
| 315 | switch s.OutcomePhase { |
| 316 | case wire.OutcomeUnfinished: |
| 317 | s.Reason = reasonUnfinished |
| 318 | case wire.OutcomeNoShell: |
| 319 | s.Reason = wire.ReasonShellUnavailable |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | // published applies the primary's answer: only the primary, only for the |
| 324 | // pending publication of the current attempt and its candidate. Pushed |
| 325 | // is set only here for a worker's commit; then checks and review follow. |
| 326 | func (t *txn) published(l Lease, v *wire.PublishedReport) error { |
| 327 | primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person) |
| 328 | if err != nil { |
| 329 | return err |
| 330 | } |
| 331 | if primary != l.Runner.RunnerID { |
| 332 | return fmt.Errorf("%w: published from a runner that is not the primary", ErrRefused) |
| 333 | } |
| 334 | var s stepRecord |
| 335 | if err := t.db.Where("id = ? AND task_id = ? AND person = ?", v.StepID, v.TaskID, l.Runner.Person).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 336 | return fmt.Errorf("%w: published for no such step", ErrRefused) |
| 337 | } else if err != nil { |
| 338 | return err |
| 339 | } |
| 340 | if s.Attempt != v.Attempt || s.PublicationID != v.Publication || s.Publication != wire.PublicationPending || s.CandidateSHA != v.CandidateSHA { |
| 341 | return nil |
| 342 | } |
| 343 | if s.PublicationRunner != l.Runner.RunnerID { |
| 344 | return fmt.Errorf("%w: published from a primary the publication was not given to", ErrRefused) |
| 345 | } |
| 346 | k, err := t.loadTask(s.TaskID) |
| 347 | if err != nil { |
| 348 | return err |
| 349 | } |
| 350 | if s.Retired && !k.MoveAbandoned { |
| 351 | return nil |
| 352 | } |
| 353 | if s.Retired && v.Pushed { |
| 354 | if err := t.abandonedPush(k, s, v.CandidateSHA); err != nil { |
| 355 | return err |
| 356 | } |
| 357 | } |
| 358 | if v.Pushed { |
| 359 | s.Pushed, s.Publication = true, wire.PublicationPublished |
| 360 | if v.Reason == "proposal_failed" { |
| 361 | s.Reason = v.Reason |
| 362 | } |
| 363 | if s.State == wire.StepDone { |
| 364 | takeOutcome(&s) |
| 365 | } |
| 366 | // The primary's measurement of the candidate it pushed (protocol |
| 367 | // 37): its files here, its diffs from the uploads naming this |
| 368 | // publication. |
| 369 | if l.Protocol >= wire.ProtocolMacEngineering { |
| 370 | s.ChangeFiles = acceptChangeFiles(l, wire.RolePrimary, s, v.ChangeFiles) |
| 371 | } |
| 372 | } else { |
| 373 | s.Publication = wire.PublicationFailed |
| 374 | switch v.Reason { |
| 375 | case "push_conflict", "cancelled", "candidate_unavailable": |
| 376 | s.Reason = v.Reason |
| 377 | default: |
| 378 | s.Reason = "push_failed" |
| 379 | } |
| 380 | } |
| 381 | if err := t.saveStep(&s, &k); err != nil { |
| 382 | return err |
| 383 | } |
| 384 | if v.Pushed && !s.Retired && l.Protocol >= wire.ProtocolMacEngineering { |
| 385 | if err := t.acceptChangeDiffs(l, s, v.DiffCollection, l.Runner.RunnerID); err != nil { |
| 386 | return err |
| 387 | } |
| 388 | } |
| 389 | if s.Retired { |
| 390 | return t.finishAbandon(&k) |
| 391 | } |
| 392 | return t.advance(&k) |
| 393 | } |
| 394 | |
| 395 | // AuthorizePublication is the primary's confirmation immediately before |
| 396 | // it pushes a worker's commit: the publication is still the step's |
| 397 | // pending one, the task is neither cancelled nor ended, and a maker |
| 398 | // step's binding still holds. |
| 399 | func (s *Store) AuthorizePublication(ctx context.Context, l Lease, stepID string, attempt int64, publication string) (refused string, err error) { |
| 400 | err = s.tx(ctx, func(t *txn) error { |
| 401 | if _, err := t.current(l); err != nil { |
| 402 | return err |
| 403 | } |
| 404 | refused, err = t.authorizePublication(l, stepID, attempt, publication) |
| 405 | return err |
| 406 | }) |
| 407 | return refused, err |
| 408 | } |
| 409 | |
| 410 | func (t *txn) authorizePublication(l Lease, stepID string, attempt int64, publication string) (string, error) { |
| 411 | primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person) |
| 412 | if err != nil { |
| 413 | return "", err |
| 414 | } |
| 415 | var s stepRecord |
| 416 | if err := t.db.Where("id = ? AND person = ?", stepID, l.Runner.Person).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 417 | return "withdrawn", nil |
| 418 | } else if err != nil { |
| 419 | return "", err |
| 420 | } |
| 421 | k, err := t.loadTask(s.TaskID) |
| 422 | if err != nil { |
| 423 | return "", err |
| 424 | } |
| 425 | if primary != l.Runner.RunnerID || s.PublicationRunner != l.Runner.RunnerID || s.Attempt != attempt || s.PublicationID != publication || s.Publication != wire.PublicationPending || k.CancelRequested || wire.FinalStage(k.Stage) { |
| 426 | return "cancelled", nil |
| 427 | } |
| 428 | // A maker step's commit is pushed only while its binding holds |
| 429 | // (grantFor for the task's project, as at its start). |
| 430 | if s.SpecialistID != "" || k.MakerSpecialistID != "" && s.Specialist == wire.SpecialistEngineering { |
| 431 | holds, err := t.bindingHolds(s, k) |
| 432 | if err != nil { |
| 433 | return "", err |
| 434 | } |
| 435 | if !holds || s.SpecialistID != k.MakerSpecialistID { |
| 436 | return "cancelled", nil |
| 437 | } |
| 438 | } |
| 439 | return "", nil |
| 440 | } |
| 441 | |
| 442 | // candidateCommitted opens the outbound transfer for a worker's commit |
| 443 | // when the instance accepts its committed report, for exactly that |
| 444 | // candidate. With no primary to publish to, the step waits for one |
| 445 | // (waiting_runner, the step's line says so) and reconcileUnpublished |
| 446 | // asks for it when a primary connects. |
| 447 | func (t *txn) candidateCommitted(k taskRecord, s *stepRecord) error { |
| 448 | primary, err := t.s.authority.PrimaryRunner(t.db, s.Person) |
| 449 | if err != nil || primary == s.RunnerID { |
| 450 | return err |
| 451 | } |
| 452 | if primary == "" { |
| 453 | now := t.now() |
| 454 | s.Placement, s.WaitingSince = wire.PlacementWaiting, &now |
| 455 | return nil |
| 456 | } |
| 457 | var open int64 |
| 458 | if err := t.db.Model(&transferRecord{}).Where("step_id = ? AND attempt = ? AND direction = ?", s.ID, s.Attempt, wire.TransferOutbound).Count(&open).Error; err != nil || open > 0 { |
| 459 | return err |
| 460 | } |
| 461 | _, err = t.openTransfer(k, *s, s.RunnerID, primary, wire.TransferHeader{Direction: wire.TransferOutbound, BaseSHA: s.BaseSHA, CandidateSHA: s.CandidateSHA}) |
| 462 | return err |
| 463 | } |
| 464 | |
| 465 | // reconcileUnpublished runs when the person's primary connects: every |
| 466 | // worker Engineering commit with no publication and no live outbound |
| 467 | // transfer (it came while there was no primary, or its transfer was |
| 468 | // pruned) is asked for again, from the step's durable record, for this |
| 469 | // primary. |
| 470 | func (t *txn) reconcileUnpublished(person, primary string) error { |
| 471 | if current, err := t.s.authority.PrimaryRunner(t.db, person); err != nil || current != primary { |
| 472 | return err |
| 473 | } |
| 474 | var rows []stepRecord |
| 475 | if err := t.db.Where("person = ? AND specialist = ? AND on_worker = ? AND state IN ? AND coalesce(candidate_sha, '') <> '' AND pushed = ? AND coalesce(publication, '') = '' AND withdrawn = ? AND retired = ?", person, wire.SpecialistEngineering, true, []string{wire.StepRunning, wire.StepDone}, false, false, false).Find(&rows).Error; err != nil { |
| 476 | return err |
| 477 | } |
| 478 | for i := range rows { |
| 479 | s := rows[i] |
| 480 | var live int64 |
| 481 | if err := t.db.Model(&transferRecord{}).Where("step_id = ? AND attempt = ? AND direction = ? AND state <> ?", s.ID, s.Attempt, wire.TransferOutbound, transferClosed).Count(&live).Error; err != nil || live > 0 { |
| 482 | if err != nil { |
| 483 | return err |
| 484 | } |
| 485 | continue |
| 486 | } |
| 487 | k, err := t.loadTask(s.TaskID) |
| 488 | if err != nil { |
| 489 | return err |
| 490 | } |
| 491 | if k.MoveProject != "" || k.CancelRequested || wire.FinalStage(k.Stage) || s.RunnerID == primary { |
| 492 | continue |
| 493 | } |
| 494 | s.Placement, s.WaitingSince = "", nil |
| 495 | if err := t.saveStep(&s, &k); err != nil { |
| 496 | return err |
| 497 | } |
| 498 | if _, err := t.openTransfer(k, s, s.RunnerID, primary, wire.TransferHeader{Direction: wire.TransferOutbound, BaseSHA: s.BaseSHA, CandidateSHA: s.CandidateSHA}); err != nil { |
| 499 | return err |
| 500 | } |
| 501 | } |
| 502 | return nil |
| 503 | } |
| 504 | |
| 505 | // redirectOutbound supersedes tr, an outbound transfer to a primary |
| 506 | // since replaced: it is closed, and the worker is asked for its retained |
| 507 | // candidate again, to primary (it answers a second send_pack from its |
| 508 | // store). An attempt that no longer publishes only has it closed. When |
| 509 | // the worker cannot be asked (primary is that worker), the publication |
| 510 | // fails as an unpushed commit, which Retry sends again. |
| 511 | func (t *txn) redirectOutbound(k *taskRecord, s *stepRecord, tr transferRecord, primary string) error { |
| 512 | if err := t.dropChunks(tr); err != nil { |
| 513 | return err |
| 514 | } |
| 515 | if err := t.db.Model(&transferRecord{}).Where("id = ?", tr.ID).Update("state", transferClosed).Error; err != nil { |
| 516 | return err |
| 517 | } |
| 518 | if k.MoveProject != "" || s.Retired || s.Withdrawn || k.CancelRequested || wire.FinalStage(k.Stage) || s.Attempt != tr.Attempt || s.CandidateSHA != tr.CandidateSHA || s.Pushed || wire.StepTerminal(s.State) && s.State != wire.StepDone { |
| 519 | return nil |
| 520 | } |
| 521 | if primary == s.RunnerID { |
| 522 | s.Publication, s.Reason = wire.PublicationFailed, "push_failed" |
| 523 | if err := t.saveStep(s, k); err != nil { |
| 524 | return err |
| 525 | } |
| 526 | return t.advance(k) |
| 527 | } |
| 528 | _, err := t.openTransfer(*k, *s, s.RunnerID, primary, wire.TransferHeader{Direction: wire.TransferOutbound, BaseSHA: tr.BaseSHA, CandidateSHA: tr.CandidateSHA}) |
| 529 | return err |
| 530 | } |
| 531 | |
| 532 | // reconcileOutbound runs when the person's primary connects: an |
| 533 | // outbound transfer still open to another runner (a primary since |
| 534 | // replaced), or one that completed with no publication (no primary was |
| 535 | // there to publish it), is redirected to this primary. |
| 536 | func (t *txn) reconcileOutbound(person, primary string) error { |
| 537 | if current, err := t.s.authority.PrimaryRunner(t.db, person); err != nil || current != primary { |
| 538 | return err |
| 539 | } |
| 540 | var trs []transferRecord |
| 541 | if err := t.db.Where("person = ? AND direction = ? AND state IN ? AND to_runner <> ?", person, wire.TransferOutbound, []string{transferOpen, transferComplete}, primary).Find(&trs).Error; err != nil { |
| 542 | return err |
| 543 | } |
| 544 | for _, tr := range trs { |
| 545 | var s stepRecord |
| 546 | if err := t.db.Where("id = ?", tr.StepID).First(&s).Error; err != nil { |
| 547 | return err |
| 548 | } |
| 549 | if tr.State == transferComplete && s.Attempt == tr.Attempt && s.Publication != "" { |
| 550 | // Its publication was given to the old primary: |
| 551 | // reassignPublications fails it, and Retry sends it again. |
| 552 | continue |
| 553 | } |
| 554 | k, err := t.loadTask(s.TaskID) |
| 555 | if err != nil { |
| 556 | return err |
| 557 | } |
| 558 | if err := t.redirectOutbound(&k, &s, tr, primary); err != nil { |
| 559 | return err |
| 560 | } |
| 561 | } |
| 562 | return nil |
| 563 | } |
| 564 | |
| 565 | // reassignPublications runs when the person's primary connects: a |
| 566 | // pending publication given to another runner (a primary since replaced) |
| 567 | // can no longer be answered by anyone, so it fails as an unpushed commit |
| 568 | // and the person's Retry has the worker send its commit to this primary. |
| 569 | func (t *txn) reassignPublications(person, primary string) error { |
| 570 | if current, err := t.s.authority.PrimaryRunner(t.db, person); err != nil || current != primary { |
| 571 | return err |
| 572 | } |
| 573 | var rows []stepRecord |
| 574 | if err := t.db.Where("person = ? AND publication = ? AND coalesce(publication_runner, '') <> ?", person, wire.PublicationPending, primary).Find(&rows).Error; err != nil { |
| 575 | return err |
| 576 | } |
| 577 | for i := range rows { |
| 578 | s := rows[i] |
| 579 | k, err := t.loadTask(s.TaskID) |
| 580 | if err != nil { |
| 581 | return err |
| 582 | } |
| 583 | if s.Retired || wire.FinalStage(k.Stage) || k.MoveProject != "" { |
| 584 | continue |
| 585 | } |
| 586 | s.Publication, s.Reason = wire.PublicationFailed, "push_failed" |
| 587 | if err := t.saveStep(&s, &k); err != nil { |
| 588 | return err |
| 589 | } |
| 590 | if err := t.advance(&k); err != nil { |
| 591 | return err |
| 592 | } |
| 593 | } |
| 594 | return nil |
| 595 | } |
| 596 | |