startCleaner starts the cleaner in a subprocess. holdThis is an opaque reference that needs to be kept from being garbage collected until we are done with all test databases (e.g. the end of the process).
(ctx context.Context, _ TBSubset, parentUUID uuid.UUID, dsn string)
| 48 | // startCleaner starts the cleaner in a subprocess. holdThis is an opaque reference that needs to be kept from being |
| 49 | // garbage collected until we are done with all test databases (e.g. the end of the process). |
| 50 | func startCleaner(ctx context.Context, _ TBSubset, parentUUID uuid.UUID, dsn string) (holdThis any, err error) { |
| 51 | bin, err := os.Executable() |
| 52 | if err != nil { |
| 53 | return nil, xerrors.Errorf("could not get executable path: %w", err) |
| 54 | } |
| 55 | cmd := exec.Command(bin) |
| 56 | cmd.Env = append(os.Environ(), |
| 57 | fmt.Sprintf("%s=%s", envCleanerParentUUID, parentUUID.String()), |
| 58 | fmt.Sprintf("%s=%s", envCleanerDSN, dsn), |
| 59 | fmt.Sprintf("%s=%s", envCleanerMagic, envCleanerMagicValue), |
| 60 | ) |
| 61 | |
| 62 | // Here we don't actually use the reference to the stdin pipe, because we never write anything to it. When this |
| 63 | // process exits, the pipe is closed by the OS and this triggers the cleaner to do its cleaning work. But, we do |
| 64 | // need to hang on to a reference to it so that it doesn't get garbage collected and trigger cleanup early. |
| 65 | stdin, err := cmd.StdinPipe() |
| 66 | if err != nil { |
| 67 | return nil, xerrors.Errorf("failed to open stdin pipe: %w", err) |
| 68 | } |
| 69 | stdout, err := cmd.StdoutPipe() |
| 70 | if err != nil { |
| 71 | return nil, xerrors.Errorf("failed to open stdout pipe: %w", err) |
| 72 | } |
| 73 | // uncomment this to see log output from the cleaner |
| 74 | // cmd.Stderr = os.Stderr |
| 75 | err = cmd.Start() |
| 76 | if err != nil { |
| 77 | return nil, xerrors.Errorf("failed to start broker: %w", err) |
| 78 | } |
| 79 | outCh := make(chan []byte, 1) |
| 80 | errCh := make(chan error, 1) |
| 81 | go func() { |
| 82 | buf := make([]byte, 1024) |
| 83 | n, readErr := stdout.Read(buf) |
| 84 | if readErr != nil { |
| 85 | errCh <- readErr |
| 86 | return |
| 87 | } |
| 88 | outCh <- buf[:n] |
| 89 | }() |
| 90 | select { |
| 91 | case <-ctx.Done(): |
| 92 | _ = cmd.Process.Kill() |
| 93 | return nil, ctx.Err() |
| 94 | case err := <-errCh: |
| 95 | return nil, xerrors.Errorf("failed to read db test cleaner output: %w", err) |
| 96 | case out := <-outCh: |
| 97 | if string(out) != cleanerRespOK { |
| 98 | return nil, xerrors.Errorf("db test cleaner error: %s", string(out)) |
| 99 | } |
| 100 | return stdin, nil |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | type cleaner struct { |
| 105 | parentUUID uuid.UUID |