Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions cmd/zoekt-merge-index/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ import (
)

// merge merges the input shards into a compound shard in dstDir. It returns the
// full path to the compound shard. The input shards are removed on success.
// full path to the compound shard, or an empty path when no live repositories
// remain. The input shards are removed on success.
func merge(dstDir string, names []string) (string, error) {
var files []index.IndexFile
for _, fn := range names {
f, err := os.Open(fn)
if err != nil {
return "", nil
return "", err
}
defer f.Close()

Expand All @@ -45,7 +46,7 @@ func merge(dstDir string, names []string) (string, error) {
files = append(files, indexFile)
}

tmpName, dstName, err := index.Merge(dstDir, files...)
result, err := index.Merge(dstDir, files...)
if err != nil {
return "", err
}
Expand All @@ -63,13 +64,15 @@ func merge(dstDir string, names []string) (string, error) {
}
}

// We only rename the compound shard if all simple shards could be deleted in the
// previous step. This guarantees we won't have duplicate indexes.
if err := os.Rename(tmpName, dstName); err != nil {
return "", fmt.Errorf("zoekt-merge-index: failed to rename compound shard: %w", err)
if result.HasOutput() {
// We only rename the compound shard if all simple shards could be deleted in the
// previous step. This guarantees we won't have duplicate indexes.
if err := os.Rename(result.TempPath, result.FinalPath); err != nil {
return "", fmt.Errorf("zoekt-merge-index: failed to rename compound shard: %w", err)
}
}

return dstName, nil
return result.FinalPath, nil
}

func mergeCmd(paths []string) (string, error) {
Expand Down Expand Up @@ -115,7 +118,9 @@ func main() {
if err != nil {
log.Fatal(err)
}
fmt.Println(compoundShardPath)
if compoundShardPath != "" {
fmt.Println(compoundShardPath)
}
case "explode":
if flag.NArg() != 2 {
log.Fatal("explode requires exactly one compound shard path")
Expand Down
28 changes: 28 additions & 0 deletions cmd/zoekt-merge-index/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"os"
"path/filepath"
"sort"
"testing"
Expand Down Expand Up @@ -46,6 +47,33 @@ func TestMerge(t *testing.T) {
require.Len(t, result.Files, 2)
}

func TestMergeAllTombstonedDeletesInputWithoutOutput(t *testing.T) {
dir := t.TempDir()
inputPath := filepath.Join(dir, "all-tombstoned.zoekt")

sb, err := index.NewShardBuilder(&zoekt.Repository{ID: 1, Name: "deleted", Tombstone: true})
require.NoError(t, err)
require.NoError(t, sb.Add(index.Document{Name: "f", Content: []byte("content")}))
f, err := os.Create(inputPath)
require.NoError(t, err)
require.NoError(t, sb.Write(f))
require.NoError(t, f.Close())

outputPath, err := merge(dir, []string{inputPath})
require.NoError(t, err)
require.Empty(t, outputPath)
_, err = os.Stat(inputPath)
require.ErrorIs(t, err, os.ErrNotExist)
matches, err := filepath.Glob(filepath.Join(dir, "*.zoekt"))
require.NoError(t, err)
require.Empty(t, matches)
}

func TestMergeReturnsInputOpenError(t *testing.T) {
_, err := merge(t.TempDir(), []string{filepath.Join(t.TempDir(), "missing.zoekt")})
require.Error(t, err)
}

// Merge 2 simple shards and then explode them.
func TestExplode(t *testing.T) {
v16Shards, err := filepath.Glob("../../testdata/shards/repo*_v16.*.zoekt")
Expand Down
30 changes: 11 additions & 19 deletions cmd/zoekt-sourcegraph-indexserver/cleanup.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"errors"
"fmt"
"os"
"os/exec"
Expand Down Expand Up @@ -48,8 +49,8 @@ func (c *cleanupScheduler) run(mu *indexMutex, cleanup func()) {
// cleanup trashes shards in indexDir that do not exist in repos. For repos
// that do not exist in indexDir, but do in indexDir/.trash it will move them
// back into indexDir. Additionally it uses now to remove shards that have
// been in the trash for 24 hours. It also deletes files left behind by
// interrupted index operations.
// been in the trash for 24 hours and removes legacy repositoryless shards. It
// also deletes files left behind by interrupted index operations.
func cleanup(indexDir string, repos []uint32, now time.Time, shardMerging bool, timings *phaseTimings) {
start := time.Now()
timings.next("stale_files")
Expand All @@ -61,11 +62,11 @@ func cleanup(indexDir string, repos []uint32, now time.Time, shardMerging bool,
removeStaleShardFiles(trashDir)

timings.next("scan_trash")
trash := getShards(trashDir)
trash := getShards(trashDir, true)
timings.next("scan_tombstones")
tombtones := getTombstonedRepos(indexDir)
timings.next("scan_index")
indexShards := getShards(indexDir)
indexShards := getShards(indexDir, true)

// trash: Remove old shards and conflicts with index
timings.next("prune_trash")
Expand Down Expand Up @@ -233,7 +234,7 @@ type shard struct {
RepoTombstone bool
}

func getShards(dir string) map[uint32][]shard {
func getShards(dir string, removeRepositoryless bool) map[uint32][]shard {
d, err := os.Open(dir)
if err != nil {
debugLog.Printf("failed to getShards: %s", dir)
Expand All @@ -257,6 +258,11 @@ func getShards(dir string) map[uint32][]shard {

repos, _, err := index.ReadMetadataPathAlive(path)
if err != nil {
if removeRepositoryless && errors.Is(err, index.ErrEmptyShard) {
infoLog.Printf("removing repositoryless shard: %s", path)
removeAll(shard{Path: path})
continue
}
debugLog.Printf("failed to read shard: %v", err)
continue
}
Expand Down Expand Up @@ -549,20 +555,6 @@ func removeTombstones(fn string) ([]*zoekt.Repository, error) {
return nil, nil
}

defer func() {
paths, err := index.IndexFilePaths(fn)
if err != nil {
return
}
for _, path := range paths {
os.Remove(path)
}
}()
// Merging would write an empty compound shard that zoekt-webserver cannot
// load. Removing the shard (deferred above) is all that is left to do.
if len(tombstones) == len(repos) {
return tombstones, nil
}
err = runMerge()
if err != nil {
return nil, fmt.Errorf("runMerge: %s", err)
Expand Down
79 changes: 55 additions & 24 deletions cmd/zoekt-sourcegraph-indexserver/cleanup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,7 @@ func TestVacuum(t *testing.T) {
}

mockMerger = func() error { return mergeHelper(t, fn) }
t.Cleanup(func() { mockMerger = nil })
got, err := removeTombstones(fn)
if err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -337,37 +338,48 @@ func TestVacuum(t *testing.T) {
}
}

// TestVacuumAllTombstoned checks that vacuuming a compound shard whose repos
// are all tombstoned deletes the shard instead of writing an empty compound
// shard, which zoekt-webserver cannot load.
func TestVacuumAllTombstoned(t *testing.T) {
func TestVacuumDeletesAllTombstonedShard(t *testing.T) {
tmpDir := t.TempDir()
fn := createCompoundShard(t, tmpDir, []uint32{1, 2})
for _, id := range []uint32{1, 2} {
if err := index.SetTombstone(fn, id); err != nil {
for _, repoID := range []uint32{1, 2} {
if err := index.SetTombstone(fn, repoID); err != nil {
t.Fatal(err)
}
}

if err := mergeHelper(t, fn); err == nil {
t.Fatal("index.Merge should refuse to write a compound shard without repos")
}

mockMerger = func() error { return mergeHelper(t, fn) }
got, err := removeTombstones(fn)
t.Cleanup(func() { mockMerger = nil })
removed, err := removeTombstones(fn)
if err != nil {
t.Fatal(err)
}
if len(got) != 2 {
t.Fatalf("wanted 2 tombstones, got %d", len(got))
if len(removed) != 2 {
t.Fatalf("removed %d repositories, want 2", len(removed))
}
if _, err := os.Stat(fn); !os.IsNotExist(err) {
t.Fatalf("all-tombstoned shard was not removed: %v", err)
}
if matches, err := filepath.Glob(filepath.Join(tmpDir, "compound-*")); err != nil {
t.Fatal(err)
} else if len(matches) != 0 {
t.Fatalf("vacuum left compound shards behind: %v", matches)
}
}

shards, err := filepath.Glob(tmpDir + "/compound-*")
if err != nil {
func TestCleanupRemovesRepositorylessShard(t *testing.T) {
dir := t.TempDir()
path := createCompoundShard(t, dir, []uint32{1})
if err := os.WriteFile(path+".meta", []byte("[]"), 0o600); err != nil {
t.Fatal(err)
}
if len(shards) != 0 {
t.Fatalf("expected no compound shards, got %v", shards)

// Cleanup runs independently of shard merging, so legacy repositoryless
// shards are recovered even if vacuum is disabled.
cleanup(dir, []uint32{1}, time.Now(), false, &phaseTimings{})
for _, path := range []string{path, path + ".meta"} {
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("repositoryless shard path %s was not removed: %v", path, err)
}
}
}

Expand Down Expand Up @@ -511,8 +523,8 @@ func TestCleanupCompoundShards(t *testing.T) {

cleanup(dir, repos, now, true, &phaseTimings{})

index := getShards(dir)
trash := getShards(filepath.Join(dir, ".trash"))
index := getShards(dir, false)
trash := getShards(filepath.Join(dir, ".trash"), false)

if len(trash) != 0 {
t.Fatalf("expected empty trash, got %+v", trash)
Expand Down Expand Up @@ -590,19 +602,22 @@ func createCompoundShard(t *testing.T, dir string, ids []uint32, optFns ...func(
}

// create a compound shard.
tmpFn, dstFn, err := merge(t, dir, repoFns)
result, err := merge(t, dir, repoFns)
if err != nil {
t.Fatal(err)
}
if !result.HasOutput() {
t.Fatal("merge produced no output")
}
for _, old := range repoFns {
if err := os.Remove(old); err != nil {
t.Fatal(err)
}
}
if err := os.Rename(tmpFn, dstFn); err != nil {
if err := os.Rename(result.TempPath, result.FinalPath); err != nil {
t.Fatal(err)
}
return dstFn
return result.FinalPath
}

func mergeHelper(t *testing.T, fn string) error {
Expand All @@ -620,6 +635,22 @@ func mergeHelper(t *testing.T, fn string) error {
}
defer indexFile.Close()

_, _, err = index.Merge(filepath.Dir(fn), indexFile)
return err
result, err := index.Merge(filepath.Dir(fn), indexFile)
if err != nil {
return err
}

paths, err := index.IndexFilePaths(fn)
if err != nil {
return err
}
for _, path := range paths {
if err := os.Remove(path); err != nil {
return err
}
}
if result.HasOutput() {
return os.Rename(result.TempPath, result.FinalPath)
}
return nil
}
2 changes: 1 addition & 1 deletion cmd/zoekt-sourcegraph-indexserver/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1235,7 +1235,7 @@ func (s *Server) DeleteAllData(ctx context.Context, _ *indexserverv1.DeleteAllDa
}

func listIndexed(indexDir string) []uint32 {
index := getShards(indexDir)
index := getShards(indexDir, false)
metricNumIndexed.Set(float64(len(index)))
repoIDs := make([]uint32, 0, len(index))
for id := range index {
Expand Down
14 changes: 9 additions & 5 deletions cmd/zoekt-sourcegraph-indexserver/meta_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,17 @@ func TestMergeMeta(t *testing.T) {
// create a compound shard. Use a new indexdir to avoid the need to cleanup
// old shards.
dir = t.TempDir()
tmpFn, dstFn, err := merge(t, dir, repoFns)
result, err := merge(t, dir, repoFns)
if err != nil {
t.Fatal(err)
}
if err := os.Rename(tmpFn, dstFn); err != nil {
if !result.HasOutput() {
t.Fatal("merge produced no output")
}
if err := os.Rename(result.TempPath, result.FinalPath); err != nil {
t.Fatal(err)
}
dstFn := result.FinalPath

readPublic := func() []string {
var public []string
Expand Down Expand Up @@ -103,20 +107,20 @@ func TestMergeMeta(t *testing.T) {
}
}

func merge(t *testing.T, dstDir string, names []string) (string, string, error) {
func merge(t *testing.T, dstDir string, names []string) (index.MergeResult, error) {
t.Helper()

var files []index.IndexFile
for _, fn := range names {
f, err := os.Open(fn)
if err != nil {
return "", "", err
return index.MergeResult{}, err
}
defer f.Close()

indexFile, err := index.NewIndexFile(f)
if err != nil {
return "", "", err
return index.MergeResult{}, err
}
defer indexFile.Close()

Expand Down
7 changes: 5 additions & 2 deletions index/builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -959,11 +959,14 @@ func createTestCompoundShard(t testing.TB, indexDir string, repositories []zoekt
}

// merge all the simple shards into a compound shard
tmpName, dstName, err := Merge(indexDir, files...)
result, err := Merge(indexDir, files...)
if err != nil {
t.Fatalf("merging index files into compound shard: %s", err)
}
if err := os.Rename(tmpName, dstName); err != nil {
if !result.HasOutput() {
t.Fatal("merging index files produced no output")
}
if err := os.Rename(result.TempPath, result.FinalPath); err != nil {
t.Fatal(err)
}
}
Expand Down
Loading
Loading