diff --git a/cmd/partforge/main.go b/cmd/partforge/main.go index ece527c..79955a8 100644 --- a/cmd/partforge/main.go +++ b/cmd/partforge/main.go @@ -2969,6 +2969,7 @@ func runImportFinished(ctx context.Context, args []string) error { clickHousePassword = fs.String("clickhouse-password", "", "destination ClickHouse HTTP password") workDir = fs.String("work-dir", "", "import scratch directory; empty uses a directory on the destination ClickHouse disk") requireEmpty = fs.Bool("require-empty", true, "fail if the destination table already has active parts, preventing accidental duplicate attaches") + parallelism = fs.Int("parallelism", 1, "number of finished artifacts to claim and download concurrently; attaches are serialized") ) if err := parseFlags(fs, args); err != nil { return err @@ -2982,6 +2983,9 @@ func runImportFinished(ctx context.Context, args []string) error { if *database == "" || *table == "" || *jobID == "" { return errors.New("database, table, and job-id are required") } + if *parallelism < 1 { + return fmt.Errorf("parallelism must be at least 1, got %d", *parallelism) + } slog.Info( "import-finished started", @@ -2991,6 +2995,7 @@ func runImportFinished(ctx context.Context, args []string) error { "destination_table", chhttp.TableSQL(*database, *table), "work_dir", *workDir, "require_empty", *requireEmpty, + "parallelism", *parallelism, ) slog.Info("initializing Postgres state store", "stage", "init_state", "state_table", *stateTable) stateStore, err := state.New(ctx, state.Config{ @@ -3037,6 +3042,7 @@ func runImportFinished(ctx context.Context, args []string) error { Database: *database, Table: *table, RequireEmpty: *requireEmpty, + Parallelism: *parallelism, MarkImporting: func(ctx context.Context, artifact parts.FinishedArtifact) error { part, ok := partsByID[artifact.PartID] if !ok { diff --git a/docs/setup.md b/docs/setup.md index 03e09bb..bae5bc7 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -246,6 +246,7 @@ Notes: - **The destination table must be empty by default** (`-require-empty=true`). Attaching the same artifacts twice duplicates data, and there is no transaction spanning S3 and ClickHouse. Use `-require-empty=false` only after verifying the target manually. - `import-finished -part-id=` imports a single finished part, for controlling import load. After the first attach the table is no longer empty, so subsequent single-part imports need `-require-empty=false`. +- `-parallelism=N` (default 1) claims and downloads up to N artifacts at once. Attaches stay serialized. If one artifact fails, in-flight downloads stop and their parts go back to `FINISHED`; only the failing artifact is marked `FAILED`. The work-dir needs room for N extracted artifacts. - The import work-dir must be on the **same filesystem** as the destination table's `detached` directory (parts are moved, not copied). Unset, it defaults to a directory on the destination ClickHouse disk; if `-work-dir` is set and fails that check, the command errors before downloading anything. Track campaign progress with `partforge overview`, scan individual jobs with `partforge list-jobs`, and inspect one job with `partforge job-status -job-id=` (see [operations.md](operations.md)). diff --git a/e2e/run.sh b/e2e/run.sh index 6a9a359..ef58b6b 100755 --- a/e2e/run.sh +++ b/e2e/run.sh @@ -628,7 +628,8 @@ CLICKHOUSE_DATA_DIR="$DATA_DIR" docker compose run --rm --user "$clickhouse_owne -job-id="$JOB_ID" \ -clickhouse-url="$CH_HTTP_DOCKER" \ -s3-endpoint=http://localstack:4566 \ - -postgres-url="$POSTGRES_URL" + -postgres-url="$POSTGRES_URL" \ + -parallelism=4 docker compose exec -T clickhouse clickhouse-client --query \ "SELECT id, name, amount_text, event_date, migrated FROM dst.events_new ORDER BY id FORMAT TSV" \ diff --git a/internal/parts/importer.go b/internal/parts/importer.go index fb1f23d..22af2dd 100644 --- a/internal/parts/importer.go +++ b/internal/parts/importer.go @@ -9,6 +9,7 @@ import ( "path/filepath" "sort" "strings" + "sync" "syscall" "time" @@ -32,11 +33,14 @@ type FinishedArtifact struct { } type ImportJob struct { - Artifacts []FinishedArtifact - JobID string - Database string - Table string - RequireEmpty bool + Artifacts []FinishedArtifact + JobID string + Database string + Table string + RequireEmpty bool + // Parallelism is how many artifacts are claimed and downloaded at once. + // Attaches are serialized regardless. + Parallelism int MarkImporting func(context.Context, FinishedArtifact) error MarkImported func(context.Context, FinishedArtifact) error ReleaseImport func(context.Context, FinishedArtifact) error @@ -47,6 +51,9 @@ func (i Importer) ImportJob(ctx context.Context, job ImportJob) error { if len(job.Artifacts) == 0 { return fmt.Errorf("no finished artifacts found for job %s", job.JobID) } + if job.Parallelism < 1 { + return fmt.Errorf("import parallelism must be at least 1, got %d", job.Parallelism) + } startedAt := time.Now() artifacts := append([]FinishedArtifact(nil), job.Artifacts...) sort.Slice(artifacts, func(i, j int) bool { @@ -58,7 +65,7 @@ func (i Importer) ImportJob(ctx context.Context, job ImportJob) error { } } - slog.Info("import job started", "stage", "start_import", "job_id", job.JobID, "destination_table", chhttp.TableSQL(job.Database, job.Table), "artifacts", len(artifacts), "require_empty", job.RequireEmpty) + slog.Info("import job started", "stage", "start_import", "job_id", job.JobID, "destination_table", chhttp.TableSQL(job.Database, job.Table), "artifacts", len(artifacts), "require_empty", job.RequireEmpty, "parallelism", job.Parallelism) slog.Info("locating destination table data path", "stage", "prepare_destination", "job_id", job.JobID, "destination_table", chhttp.TableSQL(job.Database, job.Table)) dataPath, err := i.tableDataPath(ctx, job.Database, job.Table) if err != nil { @@ -105,74 +112,178 @@ func (i Importer) ImportJob(ctx context.Context, job ImportJob) error { if err := ensureSameFilesystem(root, detachedPath); err != nil { return err } - slog.Info("prepared import work directory", "stage", "prepare_destination", "job_id", job.JobID, "work_dir", root, "detached_path", detachedPath) + workers := min(job.Parallelism, len(artifacts)) + slog.Info("prepared import work directory", "stage", "prepare_destination", "job_id", job.JobID, "work_dir", root, "detached_path", detachedPath, "parallelism", workers) - for idx, artifact := range artifacts { - artifactWorkDir := filepath.Join(root, fmt.Sprintf("%06d", idx)) - artifactStartedAt := time.Now() - slog.Info( - "importing artifact", - "stage", "import_artifact", - "job_id", job.JobID, - "artifact_index", idx+1, - "artifacts_total", len(artifacts), - "part_id", artifact.PartID, - "bucket", artifact.Bucket, - "key", artifact.Key, - ) - if job.MarkImporting != nil { - if err := job.MarkImporting(ctx, artifact); err != nil { - return err - } - } - if err := i.importArtifact(ctx, job, artifact, detachedPath, artifactWorkDir, owner); err != nil { - if ctx.Err() != nil && job.ReleaseImport != nil { - cleanupErr := os.RemoveAll(root) - releaseCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - releaseErr := job.ReleaseImport(releaseCtx, artifact) - cancel() - if cleanupErr != nil || releaseErr != nil { - return fmt.Errorf("cancel import artifact s3://%s/%s: %w", artifact.Bucket, artifact.Key, errors.Join(err, cleanupErr, releaseErr)) - } - return err - } - if job.MarkImportFailed != nil { - if markErr := job.MarkImportFailed(ctx, artifact, err); markErr != nil { - return fmt.Errorf("import artifact s3://%s/%s: %w; additionally failed to mark import failed: %v", artifact.Bucket, artifact.Key, err, markErr) + // runCtx stops downloads in sibling workers once one artifact fails. ATTACH + // runs under ctx so a sibling failure never interrupts a partial attach. + runCtx, cancelRun := context.WithCancel(ctx) + defer cancelRun() + run := importRun{ + attachMu: &sync.Mutex{}, + importer: i, + job: job, + total: len(artifacts), + root: root, + detachedPath: detachedPath, + owner: owner, + } + var ( + errMu sync.Mutex + errs []error + wg sync.WaitGroup + ) + indexes := make(chan int) + for range workers { + wg.Add(1) + go func() { + defer wg.Done() + for idx := range indexes { + if err := run.importOne(ctx, runCtx, idx, artifacts[idx]); err != nil { + errMu.Lock() + errs = append(errs, err) + errMu.Unlock() + cancelRun() } } + }() + } +feed: + for idx := range artifacts { + select { + case indexes <- idx: + case <-runCtx.Done(): + break feed + } + } + close(indexes) + wg.Wait() + if len(errs) > 0 { + return errors.Join(errs...) + } + if err := ctx.Err(); err != nil { + return err + } + elapsed := time.Since(startedAt) + slog.Info("import complete", "stage", "complete", "job_id", job.JobID, "artifacts", len(artifacts), "elapsed", elapsed, "artifacts_per_second", countRatePerSecond(len(artifacts), elapsed)) + return nil +} + +type importRun struct { + importer Importer + job ImportJob + total int + root string + detachedPath string + owner pathOwner + attachMu *sync.Mutex +} + +// importOne claims, downloads, and attaches one artifact. A nil error with a +// cancelled runCtx means the artifact was released back to FINISHED or never +// claimed. +func (r importRun) importOne(ctx, runCtx context.Context, idx int, artifact FinishedArtifact) error { + if runCtx.Err() != nil { + return nil + } + job := r.job + workDir := filepath.Join(r.root, fmt.Sprintf("%06d", idx)) + startedAt := time.Now() + slog.Info( + "importing artifact", + "stage", "import_artifact", + "job_id", job.JobID, + "artifact_index", idx+1, + "artifacts_total", r.total, + "part_id", artifact.PartID, + "bucket", artifact.Bucket, + "key", artifact.Key, + ) + if job.MarkImporting != nil { + if err := job.MarkImporting(ctx, artifact); err != nil { return err } - if job.MarkImported != nil { - if err := job.MarkImported(ctx, artifact); err != nil { - return err - } + } + extractRoot, partNames, err := r.importer.downloadArtifact(runCtx, job, artifact, workDir, r.owner) + if err != nil { + if runCtx.Err() != nil { + return r.release(artifact, workDir, err) } - if err := os.RemoveAll(artifactWorkDir); err != nil { - return fmt.Errorf("remove imported artifact work directory %s: %w", artifactWorkDir, err) + return r.markFailed(ctx, artifact, err) + } + if err := r.attach(ctx, runCtx, artifact, extractRoot, partNames); err != nil { + if ctx.Err() != nil || errors.Is(err, errAttachSkipped) { + return r.release(artifact, workDir, err) } - slog.Info( - "imported artifact", - "stage", "import_artifact", - "job_id", job.JobID, - "artifact_index", idx+1, - "artifacts_total", len(artifacts), - "part_id", artifact.PartID, - "key", artifact.Key, - "elapsed", time.Since(artifactStartedAt), - ) + return r.markFailed(ctx, artifact, err) } - elapsed := time.Since(startedAt) - slog.Info("import complete", "stage", "complete", "job_id", job.JobID, "artifacts", len(artifacts), "elapsed", elapsed, "artifacts_per_second", countRatePerSecond(len(artifacts), elapsed)) + if job.MarkImported != nil { + if err := job.MarkImported(ctx, artifact); err != nil { + return err + } + } + if err := os.RemoveAll(workDir); err != nil { + return fmt.Errorf("remove imported artifact work directory %s: %w", workDir, err) + } + slog.Info( + "imported artifact", + "stage", "import_artifact", + "job_id", job.JobID, + "artifact_index", idx+1, + "artifacts_total", r.total, + "part_id", artifact.PartID, + "key", artifact.Key, + "elapsed", time.Since(startedAt), + ) + return nil +} + +var errAttachSkipped = errors.New("import stopped before attach") + +// attach moves extracted parts into detached/ and attaches them. Attaches are +// serialized across workers; once the lock is held and runCtx is still live, +// the attach runs under ctx so only an external cancellation interrupts it. +func (r importRun) attach(ctx, runCtx context.Context, artifact FinishedArtifact, extractRoot string, partNames []string) error { + r.attachMu.Lock() + defer r.attachMu.Unlock() + if runCtx.Err() != nil { + return errAttachSkipped + } + return r.importer.attachParts(ctx, r.job, artifact, r.detachedPath, extractRoot, partNames) +} + +func (r importRun) release(artifact FinishedArtifact, workDir string, cause error) error { + cleanupErr := os.RemoveAll(workDir) + var releaseErr error + if r.job.ReleaseImport != nil { + releaseCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + releaseErr = r.job.ReleaseImport(releaseCtx, artifact) + cancel() + } + if cleanupErr != nil || releaseErr != nil { + return fmt.Errorf("cancel import artifact s3://%s/%s: %w", artifact.Bucket, artifact.Key, errors.Join(cause, cleanupErr, releaseErr)) + } + slog.Info("released import artifact", "stage", "import_artifact", "job_id", r.job.JobID, "part_id", artifact.PartID, "key", artifact.Key, "cause", cause) return nil } -func (i Importer) importArtifact(ctx context.Context, job ImportJob, artifact FinishedArtifact, detachedPath, workDir string, owner pathOwner) error { +func (r importRun) markFailed(ctx context.Context, artifact FinishedArtifact, cause error) error { + if r.job.MarkImportFailed != nil { + if markErr := r.job.MarkImportFailed(ctx, artifact, cause); markErr != nil { + return fmt.Errorf("import artifact s3://%s/%s: %w; additionally failed to mark import failed: %v", artifact.Bucket, artifact.Key, cause, markErr) + } + } + return cause +} + +// downloadArtifact downloads and extracts one artifact into workDir and sets +// the destination owner on the extracted parts. Empty outputs return no parts. +func (i Importer) downloadArtifact(ctx context.Context, job ImportJob, artifact FinishedArtifact, workDir string, owner pathOwner) (string, []string, error) { if err := os.MkdirAll(workDir, 0o755); err != nil { - return err + return "", nil, err } if artifact.EmptyOutput { - return nil + return "", nil, nil } downloadRoot := filepath.Join(workDir, "data") extractRoot := filepath.Join(workDir, "extracted") @@ -180,22 +291,30 @@ func (i Importer) importArtifact(ctx context.Context, job ImportJob, artifact Fi slog.Info("downloading finished artifact", "stage", "download_finished", "job_id", job.JobID, "part_id", artifact.PartID, "bucket", artifact.Bucket, "key", sourceKey) downloadStartedAt := time.Now() if err := i.S3Copy.DownloadPrefix(ctx, artifact.Bucket, sourceKey, downloadRoot); err != nil { - return fmt.Errorf("download finished artifact s3://%s/%s: %w", artifact.Bucket, sourceKey, err) + return "", nil, fmt.Errorf("download finished artifact s3://%s/%s: %w", artifact.Bucket, sourceKey, err) } downloadStats, err := fileutil.StatDir(downloadRoot) if err != nil { - return fmt.Errorf("stat finished artifact s3://%s/%s: %w", artifact.Bucket, artifact.Key, err) + return "", nil, fmt.Errorf("stat finished artifact s3://%s/%s: %w", artifact.Bucket, artifact.Key, err) } downloadElapsed := time.Since(downloadStartedAt) slog.Info("downloaded finished artifact", "stage", "download_finished", "job_id", job.JobID, "part_id", artifact.PartID, "files", downloadStats.Files, "bytes", downloadStats.Bytes, "elapsed", downloadElapsed, "bytes_per_second", ratePerSecond(downloadStats.Bytes, downloadElapsed)) partNames, err := artifactpkg.ExtractFinishedTarballsFromDirContext(ctx, downloadRoot, extractRoot) if err != nil { - return fmt.Errorf("extract downloaded finished parts s3://%s/%s: %w", artifact.Bucket, sourceKey, err) + return "", nil, fmt.Errorf("extract downloaded finished parts s3://%s/%s: %w", artifact.Bucket, sourceKey, err) } if len(partNames) == 0 { - return fmt.Errorf("finished artifact s3://%s/%s contains no part tarballs", artifact.Bucket, sourceKey) + return "", nil, fmt.Errorf("finished artifact s3://%s/%s contains no part tarballs", artifact.Bucket, sourceKey) } + for _, partName := range partNames { + if err := chownTree(filepath.Join(extractRoot, partName), owner); err != nil { + return "", nil, fmt.Errorf("set ownership on finished part %s to %d:%d: %w", partName, owner.uid, owner.gid, err) + } + } + return extractRoot, partNames, nil +} +func (i Importer) attachParts(ctx context.Context, job ImportJob, artifact FinishedArtifact, detachedPath, extractRoot string, partNames []string) error { for _, partName := range partNames { src := filepath.Join(extractRoot, partName) dst := filepath.Join(detachedPath, partName) @@ -207,9 +326,6 @@ func (i Importer) importArtifact(ctx context.Context, job ImportJob, artifact Fi if err := fileutil.MoveDir(src, dst); err != nil { return fmt.Errorf("move finished part %s into detached directory: %w", partName, err) } - if err := chownTree(dst, owner); err != nil { - return fmt.Errorf("set ownership on finished part %s to %d:%d: %w", partName, owner.uid, owner.gid, err) - } partStats, err := fileutil.StatDir(dst) if err != nil { return fmt.Errorf("stat finished part %s: %w", partName, err) @@ -219,7 +335,9 @@ func (i Importer) importArtifact(ctx context.Context, job ImportJob, artifact Fi return fmt.Errorf("attach finished part %s: %w", partName, err) } } - slog.Info("attached finished artifact parts", "stage", "attach_finished_part", "job_id", job.JobID, "part_id", artifact.PartID, "key", artifact.Key, "parts", len(partNames)) + if len(partNames) > 0 { + slog.Info("attached finished artifact parts", "stage", "attach_finished_part", "job_id", job.JobID, "part_id", artifact.PartID, "key", artifact.Key, "parts", len(partNames)) + } return nil } diff --git a/internal/parts/importer_test.go b/internal/parts/importer_test.go index abfa2fc..ea9ed00 100644 --- a/internal/parts/importer_test.go +++ b/internal/parts/importer_test.go @@ -10,6 +10,8 @@ import ( "os" "path/filepath" "strings" + "sync" + "sync/atomic" "testing" "time" @@ -30,7 +32,7 @@ func TestImportJobEmptyOutput(t *testing.T) { defer server.Close() var transitions []string err := (Importer{ClickHouse: chhttp.Client{URL: server.URL}, WorkDir: t.TempDir()}).ImportJob(context.Background(), ImportJob{ - JobID: "job-1", Database: "db", Table: "dst", + JobID: "job-1", Database: "db", Table: "dst", Parallelism: 1, Artifacts: []FinishedArtifact{{Bucket: "bucket", Key: "finished/part-1", PartID: "part-1", EmptyOutput: true}}, MarkImporting: func(context.Context, FinishedArtifact) error { transitions = append(transitions, "importing") @@ -84,17 +86,18 @@ func TestImportArtifactDownloadsFinishedTarballs(t *testing.T) { PartID: "part-1", } - err = (Importer{ + importer := Importer{ S3Copy: s3copy.Copier{Binary: binary}, ClickHouse: chhttp.Client{URL: server.URL}, - }).importArtifact(context.Background(), ImportJob{ - JobID: "job-1", - Database: "db", - Table: "dst", - }, artifact, detachedPath, filepath.Join(root, "work"), owner) + } + job := ImportJob{JobID: "job-1", Database: "db", Table: "dst"} + extractRoot, partNames, err := importer.downloadArtifact(context.Background(), job, artifact, filepath.Join(root, "work"), owner) if err != nil { t.Fatal(err) } + if err := importer.attachParts(context.Background(), job, artifact, detachedPath, extractRoot, partNames); err != nil { + t.Fatal(err) + } raw, err := os.ReadFile(logFile) if err != nil { @@ -161,10 +164,11 @@ wait ClickHouse: chhttp.Client{URL: server.URL}, WorkDir: workDir, }).ImportJob(ctx, ImportJob{ - Artifacts: []FinishedArtifact{{Bucket: "bucket", Key: "finished/part-1", PartID: "part-1"}}, - JobID: "job-1", - Database: "db", - Table: "table", + Artifacts: []FinishedArtifact{{Bucket: "bucket", Key: "finished/part-1", PartID: "part-1"}}, + JobID: "job-1", + Database: "db", + Table: "table", + Parallelism: 1, ReleaseImport: func(ctx context.Context, _ FinishedArtifact) error { released = ctx.Err() == nil return nil @@ -248,9 +252,10 @@ func TestImportJobCleansEachArtifactWorkDirectory(t *testing.T) { {Bucket: "bucket", Key: "finished/part-1", PartID: "part-1"}, {Bucket: "bucket", Key: "finished/part-2", PartID: "part-2"}, }, - JobID: "job-1", - Database: "db", - Table: "table", + JobID: "job-1", + Database: "db", + Table: "table", + Parallelism: 1, MarkImporting: func(context.Context, FinishedArtifact) error { importsStarted++ if importsStarted == 2 { @@ -266,6 +271,209 @@ func TestImportJobCleansEachArtifactWorkDirectory(t *testing.T) { } } +func TestImportJobParallelDownloadsSerializeAttach(t *testing.T) { + root := t.TempDir() + dataPath := filepath.Join(root, "table") + if err := os.Mkdir(dataPath, 0o755); err != nil { + t.Fatal(err) + } + partRoot := filepath.Join(root, "source", "all_1_1_0") + createPart(t, partRoot) + tarPath := filepath.Join(root, "all_1_1_0.tar") + if err := artifact.WriteFinishedTar(tarPath, []string{partRoot}); err != nil { + t.Fatal(err) + } + + // Each fake download blocks until all three are running, so the import only + // succeeds if downloads overlap. + const parallelism = 3 + dir := t.TempDir() + startedDir := filepath.Join(dir, "started") + if err := os.Mkdir(startedDir, 0o755); err != nil { + t.Fatal(err) + } + binary := filepath.Join(dir, "s5cmd") + script := fmt.Sprintf(`#!/bin/sh +dest= +for arg do dest=$arg; done +dest=${dest%%/} +mkdir -p "$dest" +touch %s/$$ +i=0 +while [ "$(ls %s | wc -l)" -lt %d ]; do + i=$((i+1)) + if [ $i -gt 500 ]; then echo "downloads did not overlap" >&2; exit 1; fi + sleep 0.01 +done +cp %s "$dest/all_1_1_0.tar" +`, shellQuote(startedDir), shellQuote(startedDir), parallelism, shellQuote(tarPath)) + if err := os.WriteFile(binary, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + + var ( + inFlight atomic.Int32 + maxInFlight atomic.Int32 + attaches atomic.Int32 + ) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + if strings.Contains(string(body), "system.tables") { + fmt.Fprintln(w, dataPath) + return + } + if strings.Contains(string(body), "ATTACH PART") { + n := inFlight.Add(1) + defer inFlight.Add(-1) + for { + prev := maxInFlight.Load() + if n <= prev || maxInFlight.CompareAndSwap(prev, n) { + break + } + } + time.Sleep(20 * time.Millisecond) + attaches.Add(1) + if err := os.RemoveAll(filepath.Join(dataPath, "detached", "all_1_1_0")); err != nil { + t.Error(err) + } + } + })) + defer server.Close() + + var mu sync.Mutex + var imported []string + err := (Importer{ + S3Copy: s3copy.Copier{Binary: binary}, + ClickHouse: chhttp.Client{URL: server.URL}, + WorkDir: filepath.Join(root, "work"), + }).ImportJob(context.Background(), ImportJob{ + Artifacts: []FinishedArtifact{ + {Bucket: "bucket", Key: "finished/part-1", PartID: "part-1"}, + {Bucket: "bucket", Key: "finished/part-2", PartID: "part-2"}, + {Bucket: "bucket", Key: "finished/part-3", PartID: "part-3"}, + }, + JobID: "job-1", + Database: "db", + Table: "table", + Parallelism: parallelism, + MarkImported: func(_ context.Context, a FinishedArtifact) error { + mu.Lock() + imported = append(imported, a.PartID) + mu.Unlock() + return nil + }, + }) + if err != nil { + t.Fatal(err) + } + if got := attaches.Load(); got != parallelism { + t.Fatalf("attaches = %d, want %d", got, parallelism) + } + if got := maxInFlight.Load(); got != 1 { + t.Fatalf("max concurrent attaches = %d, want 1", got) + } + if len(imported) != parallelism { + t.Fatalf("imported = %v", imported) + } +} + +func TestImportJobFailureReleasesInFlightSiblings(t *testing.T) { + root := t.TempDir() + dataPath := filepath.Join(root, "table") + if err := os.Mkdir(dataPath, 0o755); err != nil { + t.Fatal(err) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintln(w, dataPath) + })) + defer server.Close() + + // part-fail waits for part-slow to start downloading, then downloads + // nothing so extraction fails without s5cmd retries. part-slow blocks + // until it is terminated. + dir := t.TempDir() + slowReady := filepath.Join(dir, "slow-ready") + binary := filepath.Join(dir, "s5cmd") + script := fmt.Sprintf(`#!/bin/sh +dest= +for arg do dest=$arg; done +dest=${dest%%/} +mkdir -p "$dest" +case "$*" in +*part-fail*) + while [ ! -f %s ]; do sleep 0.01; done + exit 0 + ;; +*) + trap 'exit 1' TERM + printf ready > %s + sleep 5 & + wait + ;; +esac +`, shellQuote(slowReady), shellQuote(slowReady)) + if err := os.WriteFile(binary, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + + var mu sync.Mutex + failed := map[string]bool{} + released := map[string]bool{} + err := (Importer{ + S3Copy: s3copy.Copier{Binary: binary}, + ClickHouse: chhttp.Client{URL: server.URL}, + WorkDir: filepath.Join(root, "work"), + }).ImportJob(context.Background(), ImportJob{ + Artifacts: []FinishedArtifact{ + {Bucket: "bucket", Key: "finished/part-fail", PartID: "part-fail"}, + {Bucket: "bucket", Key: "finished/part-slow", PartID: "part-slow"}, + }, + JobID: "job-1", + Database: "db", + Table: "table", + Parallelism: 2, + ReleaseImport: func(_ context.Context, a FinishedArtifact) error { + mu.Lock() + released[a.PartID] = true + mu.Unlock() + return nil + }, + MarkImportFailed: func(_ context.Context, a FinishedArtifact, _ error) error { + mu.Lock() + failed[a.PartID] = true + mu.Unlock() + return nil + }, + }) + if err == nil || !strings.Contains(err.Error(), "finished/part-fail contains no part tarballs") { + t.Fatalf("error = %v, want part-fail extraction error", err) + } + if strings.Contains(err.Error(), "part-slow") { + t.Fatalf("error = %v, should not report the released sibling", err) + } + if !failed["part-fail"] || failed["part-slow"] { + t.Fatalf("failed = %v", failed) + } + if !released["part-slow"] || released["part-fail"] { + t.Fatalf("released = %v", released) + } +} + +func TestImportJobRejectsZeroParallelism(t *testing.T) { + err := (Importer{}).ImportJob(context.Background(), ImportJob{ + JobID: "job-1", + Artifacts: []FinishedArtifact{{Bucket: "bucket", Key: "finished/part-1", PartID: "part-1"}}, + }) + if err == nil || !strings.Contains(err.Error(), "parallelism") { + t.Fatalf("error = %v, want parallelism error", err) + } +} + func TestDefaultImportWorkDirUsesClickHouseDisk(t *testing.T) { got := defaultImportWorkDir("/var/lib/clickhouse/") want := filepath.Join("/var/lib/clickhouse", "partforge-import-work")