fork of https://github.com/sourcegraph/zoekt
1// Copyright 2016 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Package index contains logic for building Zoekt indexes. NOTE: this package is not considered
16// part of the public API, and it is not recommended to rely on it in external code.
17package index
18
19import (
20 "cmp"
21 "crypto/sha1"
22 "flag"
23 "fmt"
24 "log"
25 "net/url"
26 "os"
27 "os/exec"
28 "path"
29 "path/filepath"
30 "reflect"
31 "runtime"
32 "runtime/pprof"
33 "sort"
34 "strconv"
35 "strings"
36 "sync"
37 "time"
38
39 "github.com/bmatcuk/doublestar"
40 "github.com/dustin/go-humanize"
41 "github.com/go-enry/go-enry/v2"
42 "github.com/rs/xid"
43 "golang.org/x/sys/unix"
44
45 "github.com/sourcegraph/zoekt"
46 "github.com/sourcegraph/zoekt/internal/ctags"
47)
48
49var DefaultDir = filepath.Join(os.Getenv("HOME"), ".zoekt")
50
51// Branch describes a single branch version.
52type Branch struct {
53 Name string
54 Version string
55}
56
57// Options sets options for the index building.
58type Options struct {
59 // IndexDir is a directory that holds *.zoekt index files.
60 IndexDir string
61
62 // SizeMax is the maximum file size
63 SizeMax int
64
65 // Parallelism is the maximum number of shards to index in parallel
66 Parallelism int
67
68 // ShardMax sets the maximum corpus size for a single shard
69 ShardMax int
70
71 // TrigramMax sets the maximum number of distinct trigrams per document.
72 TrigramMax int
73
74 // RepositoryDescription holds names and URLs for the repository.
75 RepositoryDescription zoekt.Repository
76
77 // SubRepositories is a path => sub repository map.
78 SubRepositories map[string]*zoekt.Repository
79
80 // DisableCTags disables the generation of ctags metadata.
81 DisableCTags bool
82
83 // CtagsPath is the path to the ctags binary to run, or empty
84 // if a valid binary couldn't be found.
85 CTagsPath string
86
87 // Same as CTagsPath but for scip-ctags
88 ScipCTagsPath string
89
90 // If set, ctags must succeed.
91 CTagsMustSucceed bool
92
93 // LargeFiles is a slice of glob patterns, including ** for any number
94 // of directories, where matching file paths should be indexed
95 // regardless of their size. The full pattern syntax is here:
96 // https://github.com/bmatcuk/doublestar/tree/v1#patterns.
97 LargeFiles []string
98
99 // IsDelta is true if this run contains only the changed documents since the
100 // last run.
101 IsDelta bool
102
103 // changedOrRemovedFiles is a list of file paths that have been changed or removed
104 // since the last indexing job for this repository. These files will be tombstoned
105 // in the older shards for this repository.
106 changedOrRemovedFiles []string
107
108 LanguageMap ctags.LanguageMap
109
110 // ShardMerging is true if builder should respect compound shards. This is a
111 // Sourcegraph specific option.
112 ShardMerging bool
113
114 // HeapProfileTriggerBytes is the heap allocation in bytes that will trigger a memory profile. If 0, no memory profile
115 // will be triggered. Note this trigger looks at total heap allocation (which includes both inuse and garbage objects).
116 //
117 // Profiles will be written to files named `index-memory.prof.n` in the index directory. No more than 10 files are written.
118 //
119 // Note: heap checking is "best effort", and it's possible for the process to OOM without triggering the heap profile.
120 HeapProfileTriggerBytes uint64
121
122 // ShardPrefix is the prefix of the shard. It defaults to the repository name.
123 ShardPrefix string
124}
125
126// HashOptions contains only the options in Options that upon modification leads to IndexState of IndexStateMismatch during the next index building.
127type HashOptions struct {
128 sizeMax int
129 disableCTags bool
130 ctagsPath string
131 cTagsMustSucceed bool
132 largeFiles []string
133}
134
135func (o *Options) HashOptions() HashOptions {
136 return HashOptions{
137 sizeMax: o.SizeMax,
138 disableCTags: o.DisableCTags,
139 ctagsPath: o.CTagsPath,
140 cTagsMustSucceed: o.CTagsMustSucceed,
141 largeFiles: o.LargeFiles,
142 }
143}
144
145func (o *Options) GetHash() string {
146 h := o.HashOptions()
147 hasher := sha1.New()
148
149 hasher.Write([]byte(h.ctagsPath))
150 hasher.Write([]byte(fmt.Sprintf("%t", h.cTagsMustSucceed)))
151 hasher.Write([]byte(fmt.Sprintf("%d", h.sizeMax)))
152 hasher.Write([]byte(fmt.Sprintf("%q", h.largeFiles)))
153 hasher.Write([]byte(fmt.Sprintf("%t", h.disableCTags)))
154
155 return fmt.Sprintf("%x", hasher.Sum(nil))
156}
157
158type largeFilesFlag struct{ *Options }
159
160func (f largeFilesFlag) String() string {
161 // From flag.Value documentation:
162 //
163 // The flag package may call the String method with a zero-valued receiver,
164 // such as a nil pointer.
165 if f.Options == nil {
166 return ""
167 }
168 s := append([]string{""}, f.LargeFiles...)
169 return strings.Join(s, "-large_file ")
170}
171
172func (f largeFilesFlag) Set(value string) error {
173 f.LargeFiles = append(f.LargeFiles, value)
174 return nil
175}
176
177// Flags adds flags for build options to fs. It is the "inverse" of Args.
178func (o *Options) Flags(fs *flag.FlagSet) {
179 x := *o
180 x.SetDefaults()
181 fs.IntVar(&o.SizeMax, "file_limit", x.SizeMax, "maximum file size")
182 fs.IntVar(&o.TrigramMax, "max_trigram_count", x.TrigramMax, "maximum number of trigrams per document")
183 fs.IntVar(&o.ShardMax, "shard_limit", x.ShardMax, "maximum corpus size for a shard")
184 fs.IntVar(&o.Parallelism, "parallelism", x.Parallelism, "maximum number of parallel indexing processes.")
185 fs.StringVar(&o.IndexDir, "index", x.IndexDir, "directory for search indices")
186 fs.BoolVar(&o.CTagsMustSucceed, "require_ctags", x.CTagsMustSucceed, "If set, ctags calls must succeed.")
187 fs.Var(largeFilesFlag{o}, "large_file", "A glob pattern where matching files are to be index regardless of their size. You can add multiple patterns by setting this more than once.")
188 fs.StringVar(&o.ShardPrefix, "shard_prefix", x.ShardPrefix, "the prefix of the shard. Defaults to repository name")
189
190 // Sourcegraph specific
191 fs.BoolVar(&o.DisableCTags, "disable_ctags", x.DisableCTags, "If set, ctags will not be called.")
192 fs.BoolVar(&o.ShardMerging, "shard_merging", x.ShardMerging, "If set, builder will respect compound shards.")
193}
194
195// Args generates command line arguments for o. It is the "inverse" of Flags.
196func (o *Options) Args() []string {
197 var args []string
198
199 if o.SizeMax != 0 {
200 args = append(args, "-file_limit", strconv.Itoa(o.SizeMax))
201 }
202
203 if o.TrigramMax != 0 {
204 args = append(args, "-max_trigram_count", strconv.Itoa(o.TrigramMax))
205 }
206
207 if o.ShardMax != 0 {
208 args = append(args, "-shard_limit", strconv.Itoa(o.ShardMax))
209 }
210
211 if o.Parallelism != 0 {
212 args = append(args, "-parallelism", strconv.Itoa(o.Parallelism))
213 }
214
215 if o.IndexDir != "" {
216 args = append(args, "-index", o.IndexDir)
217 }
218
219 if o.CTagsMustSucceed {
220 args = append(args, "-require_ctags")
221 }
222
223 for _, a := range o.LargeFiles {
224 args = append(args, "-large_file", a)
225 }
226
227 // Sourcegraph specific
228 if o.DisableCTags {
229 args = append(args, "-disable_ctags")
230 }
231
232 if o.ShardMerging {
233 args = append(args, "-shard_merging")
234 }
235
236 if o.ShardPrefix != "" {
237 args = append(args, "-shard_prefix", o.ShardPrefix)
238 }
239
240 return args
241}
242
243// Builder manages (parallel) creation of uniformly sized shards. The
244// builder buffers up documents until it collects enough documents and
245// then builds a shard and writes.
246type Builder struct {
247 opts Options
248 throttle chan int
249
250 nextShardNum int
251 todo []*Document
252 docChecker DocChecker
253 size int
254
255 parserBins ctags.ParserBinMap
256 building sync.WaitGroup
257
258 errMu sync.Mutex
259 buildError error
260
261 // temp name => final name for finished shards. We only rename
262 // them once all shards succeed to avoid Frankstein corpuses.
263 finishedShards map[string]string
264
265 // indexTime is set by tests for doing reproducible builds.
266 indexTime time.Time
267
268 // heapProfileMu is used to ensure that only one memory profile is written at a time
269 heapProfileMu sync.Mutex
270 heapProfileNum int
271
272 // a sortable 20 chars long id.
273 id string
274
275 finishCalled bool
276}
277
278type finishedShard struct {
279 temp, final string
280}
281
282func checkCTags() string {
283 if ctags := os.Getenv("CTAGS_COMMAND"); ctags != "" {
284 return ctags
285 }
286
287 if ctags, err := exec.LookPath("universal-ctags"); err == nil {
288 return ctags
289 }
290
291 return ""
292}
293
294func checkScipCTags() string {
295 if ctags := os.Getenv("SCIP_CTAGS_COMMAND"); ctags != "" {
296 return ctags
297 }
298
299 if ctags, err := exec.LookPath("scip-ctags"); err == nil {
300 return ctags
301 }
302
303 return ""
304}
305
306// SetDefaults sets reasonable default options.
307func (o *Options) SetDefaults() {
308 if o.CTagsPath == "" && !o.DisableCTags {
309 o.CTagsPath = checkCTags()
310 }
311
312 if o.ScipCTagsPath == "" && !o.DisableCTags {
313 o.ScipCTagsPath = checkScipCTags()
314 }
315
316 if o.Parallelism == 0 {
317 o.Parallelism = 4
318 }
319 if o.SizeMax == 0 {
320 o.SizeMax = 2 << 20
321 }
322 if o.ShardMax == 0 {
323 o.ShardMax = 100 << 20
324 }
325 if o.TrigramMax == 0 {
326 o.TrigramMax = 20000
327 }
328
329 if o.RepositoryDescription.Name == "" && o.RepositoryDescription.URL != "" {
330 parsed, _ := url.Parse(o.RepositoryDescription.URL)
331 if parsed != nil {
332 o.RepositoryDescription.Name = filepath.Join(parsed.Host, parsed.Path)
333 }
334 }
335}
336
337// ShardName returns the name the given index shard.
338func (o *Options) shardName(n int) string {
339 return o.shardNameVersion(IndexFormatVersion, n)
340}
341
342func (o *Options) shardNameVersion(version, n int) string {
343 return ShardName(o.IndexDir, cmp.Or(o.ShardPrefix, o.RepositoryDescription.Name), version, n)
344}
345
346type IndexState string
347
348const (
349 IndexStateMissing IndexState = "missing"
350 IndexStateCorrupt IndexState = "corrupt"
351 IndexStateVersion IndexState = "version-mismatch"
352 IndexStateOption IndexState = "option-mismatch"
353 IndexStateMeta IndexState = "meta-mismatch"
354 IndexStateContent IndexState = "content-mismatch"
355 IndexStateEqual IndexState = "equal"
356)
357
358var readVersions = []struct {
359 IndexFormatVersion int
360 FeatureVersion int
361}{{
362 IndexFormatVersion: IndexFormatVersion,
363 FeatureVersion: FeatureVersion,
364}, {
365 IndexFormatVersion: NextIndexFormatVersion,
366 FeatureVersion: FeatureVersion,
367}}
368
369// IncrementalSkipIndexing returns true if the index present on disk matches
370// the build options.
371func (o *Options) IncrementalSkipIndexing() bool {
372 state, _ := o.IndexState()
373 return state == IndexStateEqual
374}
375
376// IndexState checks how the index present on disk compares to the build
377// options and returns the IndexState and the name of the first shard.
378func (o *Options) IndexState() (IndexState, string) {
379 // Open the latest version we support that is on disk.
380 fn := o.findShard()
381 if fn == "" {
382 return IndexStateMissing, fn
383 }
384
385 repos, index, err := ReadMetadataPathAlive(fn)
386 if os.IsNotExist(err) {
387 return IndexStateMissing, fn
388 } else if err != nil {
389 return IndexStateCorrupt, fn
390 }
391
392 for _, v := range readVersions {
393 if v.IndexFormatVersion == index.IndexFormatVersion && v.FeatureVersion != index.IndexFeatureVersion {
394 return IndexStateVersion, fn
395 }
396 }
397
398 var repo *zoekt.Repository
399 for _, cand := range repos {
400 if cand.Name == o.RepositoryDescription.Name {
401 repo = cand
402 break
403 }
404 }
405
406 if repo == nil {
407 return IndexStateCorrupt, fn
408 }
409
410 if repo.IndexOptions != o.GetHash() {
411 return IndexStateOption, fn
412 }
413
414 if !reflect.DeepEqual(repo.Branches, o.RepositoryDescription.Branches) {
415 return IndexStateContent, fn
416 }
417
418 // We can mutate repo since it lives in the scope of this function call.
419 if updated, err := repo.MergeMutable(&o.RepositoryDescription); err != nil {
420 // non-nil err means we are trying to update an immutable field =>
421 // reindex content.
422 log.Printf("warn: immutable field changed, requires re-index: %s", err)
423 return IndexStateContent, fn
424 } else if updated {
425 return IndexStateMeta, fn
426 }
427
428 return IndexStateEqual, fn
429}
430
431// FindRepositoryMetadata returns the index metadata for the repository
432// specified in the options. 'ok' is false if the repository's metadata
433// couldn't be found or if an error occurred.
434func (o *Options) FindRepositoryMetadata() (repository *zoekt.Repository, metadata *zoekt.IndexMetadata, ok bool, err error) {
435 shard := o.findShard()
436 if shard == "" {
437 return nil, nil, false, nil
438 }
439
440 repositories, metadata, err := ReadMetadataPathAlive(shard)
441 if err != nil {
442 return nil, nil, false, fmt.Errorf("reading metadata for shard %q: %w", shard, err)
443 }
444
445 ID := o.RepositoryDescription.ID
446 for _, r := range repositories {
447 // compound shards contain multiple repositories, so we
448 // have to pick only the one we're looking for
449 if r.ID == ID {
450 return r, metadata, true, nil
451 }
452 }
453
454 // If we're here, then we're somehow in a state where we found a matching
455 // shard that's missing the repository metadata we're looking for. This
456 // should never happen.
457 name := o.RepositoryDescription.Name
458 return nil, nil, false, fmt.Errorf("matching shard %q doesn't contain metadata for repo id %d (%q)", shard, ID, name)
459}
460
461func (o *Options) findShard() string {
462 for _, v := range readVersions {
463 fn := o.shardNameVersion(v.IndexFormatVersion, 0)
464 if _, err := os.Stat(fn); err == nil {
465 return fn
466 }
467 }
468
469 // Brute force finding the shard in compound shards. We should only hit this
470 // code path for repositories that are not already existing or are in
471 // compound shards.
472 //
473 // TODO add an oracle which can speed this up in the case of repositories
474 // already in compound shards.
475 compoundShards, err := filepath.Glob(path.Join(o.IndexDir, "compound-*.zoekt"))
476 if err != nil {
477 return ""
478 }
479 for _, fn := range compoundShards {
480 repos, _, err := ReadMetadataPathAlive(fn)
481 if err != nil {
482 continue
483 }
484 for _, repo := range repos {
485 if repo.ID == o.RepositoryDescription.ID {
486 return fn
487 }
488 }
489 }
490
491 return ""
492}
493
494func (o *Options) FindAllShards() []string {
495 for _, v := range readVersions {
496 fn := o.shardNameVersion(v.IndexFormatVersion, 0)
497 if _, err := os.Stat(fn); err == nil {
498 shards := []string{fn}
499 for i := 1; ; i++ {
500 fn := o.shardNameVersion(v.IndexFormatVersion, i)
501 if _, err := os.Stat(fn); err != nil {
502 return shards
503 }
504 shards = append(shards, fn)
505 }
506 }
507 }
508
509 // lazily fallback to findShard which will look for a compound shard.
510 if fn := o.findShard(); fn != "" {
511 return []string{fn}
512 }
513
514 return nil
515}
516
517// IgnoreSizeMax determines whether the max size should be ignored.
518func (o *Options) IgnoreSizeMax(name string) bool {
519 // A pattern match will override preceding pattern matches.
520 for i := len(o.LargeFiles) - 1; i >= 0; i-- {
521 pattern := strings.TrimSpace(o.LargeFiles[i])
522 negated, validatedPattern := checkIsNegatePattern(pattern)
523
524 if m, _ := doublestar.PathMatch(validatedPattern, name); m {
525 if negated {
526 return false
527 } else {
528 return true
529 }
530 }
531 }
532
533 return false
534}
535
536func checkIsNegatePattern(pattern string) (bool, string) {
537 negate := "!"
538
539 // if negated then strip prefix meta character which identifies negated filter pattern
540 if strings.HasPrefix(pattern, negate) {
541 return true, pattern[len(negate):]
542 }
543
544 return false, pattern
545}
546
547// NewBuilder creates a new Builder instance.
548func NewBuilder(opts Options) (*Builder, error) {
549 opts.SetDefaults()
550 if opts.RepositoryDescription.Name == "" {
551 return nil, fmt.Errorf("builder: must set Name")
552 }
553
554 b := &Builder{
555 opts: opts,
556 throttle: make(chan int, opts.Parallelism),
557 finishedShards: map[string]string{},
558 }
559
560 parserBins, err := ctags.NewParserBinMap(
561 b.opts.CTagsPath,
562 b.opts.ScipCTagsPath,
563 opts.LanguageMap,
564 b.opts.CTagsMustSucceed,
565 )
566 if err != nil {
567 return nil, err
568 }
569
570 b.parserBins = parserBins
571
572 if opts.IsDelta {
573 // Delta shards build on top of previously existing shards.
574 // As a consequence, the shardNum for delta shards starts from
575 // the number following the most recently generated shard - not 0.
576 //
577 // Using this numbering scheme allows all the shards to be
578 // discovered as a set.
579 shards := b.opts.FindAllShards()
580 b.nextShardNum = len(shards) // shards are zero indexed, so len() provides the next number after the last one
581 }
582
583 if _, err := b.newShardBuilder(); err != nil {
584 return nil, err
585 }
586
587 now := time.Now()
588 b.indexTime = now
589 b.id = xid.NewWithTime(now).String()
590
591 return b, nil
592}
593
594// AddFile is a convenience wrapper for the Add method
595func (b *Builder) AddFile(name string, content []byte) error {
596 return b.Add(Document{Name: name, Content: content})
597}
598
599func (b *Builder) Add(doc Document) error {
600 if b.finishCalled {
601 return nil
602 }
603
604 allowLargeFile := b.opts.IgnoreSizeMax(doc.Name)
605 if len(doc.Content) > b.opts.SizeMax && !allowLargeFile {
606 // We could pass the document on to the shardbuilder, but if
607 // we pass through a part of the source tree with binary/large
608 // files, the corresponding shard would be mostly empty, so
609 // insert a reason here too.
610 doc.SkipReason = fmt.Sprintf("document size %d larger than limit %d", len(doc.Content), b.opts.SizeMax)
611 } else if err := b.docChecker.Check(doc.Content, b.opts.TrigramMax, allowLargeFile); err != nil {
612 doc.SkipReason = err.Error()
613 }
614
615 b.todo = append(b.todo, &doc)
616
617 if doc.SkipReason == "" {
618 b.size += len(doc.Name) + len(doc.Content)
619 } else {
620 b.size += len(doc.Name) + len(doc.SkipReason)
621 // Drop the content if we are skipping the document. Skipped content is not counted towards the
622 // shard size limit, so otherwise we might buffer too much data in memory before flushing.
623 doc.Content = nil
624 }
625
626 if b.size > b.opts.ShardMax {
627 return b.flush()
628 }
629
630 return nil
631}
632
633// MarkFileAsChangedOrRemoved indicates that the file specified by the given path
634// has been changed or removed since the last indexing job for this repository.
635//
636// If this build is a delta build, these files will be tombstoned in the older shards for this repository.
637func (b *Builder) MarkFileAsChangedOrRemoved(path string) {
638 b.opts.changedOrRemovedFiles = append(b.opts.changedOrRemovedFiles, path)
639}
640
641// Finish creates a last shard from the buffered documents, and clears
642// stale shards from previous runs. This should always be called, also
643// in failure cases, to ensure cleanup.
644//
645// It is safe to call Finish() multiple times.
646func (b *Builder) Finish() error {
647 if b.finishCalled {
648 return b.buildError
649 }
650
651 b.finishCalled = true
652
653 b.flush()
654 b.building.Wait()
655
656 if b.buildError != nil {
657 for tmp := range b.finishedShards {
658 log.Printf("Builder.Finish %s", tmp)
659 os.Remove(tmp)
660 }
661 b.finishedShards = map[string]string{}
662 return b.buildError
663 }
664
665 // map of temporary -> final names for all updated shards + shard metadata files
666 artifactPaths := make(map[string]string)
667 for tmp, final := range b.finishedShards {
668 artifactPaths[tmp] = final
669 }
670
671 oldShards := b.opts.FindAllShards()
672
673 if b.opts.IsDelta {
674 // Delta shard builds need to update FileTombstone and branch commit information for all
675 // existing shards
676 for _, shard := range oldShards {
677 repositories, _, err := ReadMetadataPathAlive(shard)
678 if err != nil {
679 return fmt.Errorf("reading metadata from shard %q: %w", shard, err)
680 }
681
682 if len(repositories) > 1 {
683 return fmt.Errorf("delta shard builds don't support repositories contained in compound shards (shard %q)", shard)
684 }
685
686 if len(repositories) == 0 {
687 return fmt.Errorf("failed to update repository metadata for shard %q - shard contains no repositories", shard)
688 }
689
690 repository := repositories[0]
691 if repository.ID != b.opts.RepositoryDescription.ID {
692 return fmt.Errorf("shard %q doesn't contain repository ID %d (%q)", shard, b.opts.RepositoryDescription.ID, b.opts.RepositoryDescription.Name)
693 }
694
695 if len(b.opts.changedOrRemovedFiles) > 0 && repository.FileTombstones == nil {
696 repository.FileTombstones = make(map[string]struct{}, len(b.opts.changedOrRemovedFiles))
697 }
698
699 for _, f := range b.opts.changedOrRemovedFiles {
700 repository.FileTombstones[f] = struct{}{}
701 }
702
703 if !BranchNamesEqual(repository.Branches, b.opts.RepositoryDescription.Branches) {
704 return deltaBranchSetError{
705 shardName: shard,
706 old: repository.Branches,
707 new: b.opts.RepositoryDescription.Branches,
708 }
709 }
710
711 if b.opts.GetHash() != repository.IndexOptions {
712 return &deltaIndexOptionsMismatchError{
713 shardName: shard,
714 newOptions: b.opts.HashOptions(),
715 }
716 }
717
718 repository.Branches = b.opts.RepositoryDescription.Branches
719
720 repository.LatestCommitDate = b.opts.RepositoryDescription.LatestCommitDate
721
722 tempPath, finalPath, err := JsonMarshalRepoMetaTemp(shard, repository)
723 if err != nil {
724 return fmt.Errorf("writing repository metadta for shard %q: %w", shard, err)
725 }
726
727 artifactPaths[tempPath] = finalPath
728 }
729 }
730
731 // We mark finished shards as empty when we successfully finish. Return now
732 // to allow call sites to call Finish idempotently.
733 if len(artifactPaths) == 0 {
734 return b.buildError
735 }
736
737 // Collect a map of the old shards on disk. For each new shard we replace we
738 // delete it from toDelete. Anything remaining in toDelete will be removed
739 // after we have renamed everything into place.
740
741 var toDelete map[string]struct{}
742 if !b.opts.IsDelta {
743 // Non-delta shard builds delete all existing shards before they write out
744 // new ones.
745 // By contrast, delta shard builds work by stacking changes on top of existing shards.
746 // So, we skip populating the toDelete map if we're building delta shards.
747
748 toDelete = make(map[string]struct{})
749 for _, name := range oldShards {
750 paths, err := IndexFilePaths(name)
751 if err != nil {
752 b.buildError = fmt.Errorf("failed to find old paths for %s: %w", name, err)
753 }
754 for _, p := range paths {
755 toDelete[p] = struct{}{}
756 }
757 }
758 }
759
760 for tmp, final := range artifactPaths {
761 if err := os.Rename(tmp, final); err != nil {
762 b.buildError = err
763 continue
764 }
765
766 delete(toDelete, final)
767 }
768
769 b.finishedShards = map[string]string{}
770
771 for p := range toDelete {
772 // Don't delete compound shards, set tombstones instead.
773 if b.opts.ShardMerging && strings.HasPrefix(filepath.Base(p), "compound-") {
774 if !strings.HasSuffix(p, ".zoekt") {
775 continue
776 }
777 err := SetTombstone(p, b.opts.RepositoryDescription.ID)
778 b.buildError = err
779 continue
780 }
781 log.Printf("removing old shard file: %s", p)
782 if err := os.Remove(p); err != nil {
783 b.buildError = err
784 }
785 }
786
787 return b.buildError
788}
789
790// BranchNamesEqual compares the given zoekt.RepositoryBranch slices, and returns true
791// iff both slices specify the same set of branch names in the same order.
792func BranchNamesEqual(a, b []zoekt.RepositoryBranch) bool {
793 if len(a) != len(b) {
794 return false
795 }
796
797 for i := range a {
798 x, y := a[i], b[i]
799 if x.Name != y.Name {
800 return false
801 }
802 }
803
804 return true
805}
806
807func (b *Builder) flush() error {
808 todo := b.todo
809 b.todo = nil
810 b.size = 0
811 b.errMu.Lock()
812 defer b.errMu.Unlock()
813 if b.buildError != nil {
814 return b.buildError
815 }
816
817 hasShard := b.nextShardNum > 0
818 if len(todo) == 0 && hasShard {
819 return nil
820 }
821
822 shard := b.nextShardNum
823 b.nextShardNum++
824
825 if b.opts.Parallelism > 1 {
826 b.building.Add(1)
827 b.throttle <- 1
828 go func() {
829 done, err := b.buildShard(todo, shard)
830 <-b.throttle
831
832 b.errMu.Lock()
833 defer b.errMu.Unlock()
834 if err != nil && b.buildError == nil {
835 b.buildError = err
836 }
837 if err == nil {
838 b.finishedShards[done.temp] = done.final
839 }
840 b.building.Done()
841 }()
842 } else {
843 // No goroutines when we're not parallel. This
844 // simplifies memory profiling.
845 done, err := b.buildShard(todo, shard)
846 b.buildError = err
847 if err == nil {
848 b.finishedShards[done.temp] = done.final
849 }
850
851 return b.buildError
852 }
853
854 return nil
855}
856
857// map [0,inf) to [0,1) monotonically
858func squashRange(j int) float64 {
859 x := float64(j)
860 return x / (1 + x)
861}
862
863// IsLowPriority takes a file name and makes an educated guess about its priority
864// in search results. A file is considered low priority if it looks like a test,
865// vendored, or generated file.
866//
867// These 'priority' criteria affects how documents are ordered within a shard. It's
868// also used to help guess a file's rank when we're missing ranking information.
869func IsLowPriority(path string, content []byte) bool {
870 return enry.IsTest(path) || enry.IsVendor(path) || enry.IsGenerated(path, content)
871}
872
873type rankedDoc struct {
874 *Document
875 rank []float64
876}
877
878// rank returns a vector of scores which is used at index-time to sort documents
879// before writing them to disk. The order of documents in the shard is important
880// at query time, because earlier documents receive a boost at query time and
881// have a higher chance of being searched before limits kick in.
882func rank(d *Document, origIdx int) []float64 {
883 skipped := 0.0
884 if d.SkipReason != "" {
885 skipped = 1.0
886 }
887
888 generated := 0.0
889 if enry.IsGenerated(d.Name, d.Content) {
890 generated = 1.0
891 }
892
893 vendor := 0.0
894 if enry.IsVendor(d.Name) {
895 vendor = 1.0
896 }
897
898 test := 0.0
899 if enry.IsTest(d.Name) {
900 test = 1.0
901 }
902
903 // Smaller is earlier (=better).
904 return []float64{
905 // Always place skipped docs last
906 skipped,
907
908 // Prefer docs that are not generated
909 generated,
910
911 // Prefer docs that are not vendored
912 vendor,
913
914 // Prefer docs that are not tests
915 test,
916
917 // With short names
918 squashRange(len(d.Name)),
919
920 // With many symbols
921 1.0 - squashRange(len(d.Symbols)),
922
923 // With short content
924 squashRange(len(d.Content)),
925
926 // That is present is as many branches as possible
927 1.0 - squashRange(len(d.Branches)),
928
929 // Preserve original ordering.
930 squashRange(origIdx),
931 }
932}
933
934func sortDocuments(todo []*Document) {
935 rs := make([]rankedDoc, 0, len(todo))
936 for i, t := range todo {
937 rd := rankedDoc{t, rank(t, i)}
938 rs = append(rs, rd)
939 }
940 sort.Slice(rs, func(i, j int) bool {
941 r1 := rs[i].rank
942 r2 := rs[j].rank
943 for i := range r1 {
944 if r1[i] < r2[i] {
945 return true
946 }
947 if r1[i] > r2[i] {
948 return false
949 }
950 }
951
952 return false
953 })
954 for i := range todo {
955 todo[i] = rs[i].Document
956 }
957}
958
959func (b *Builder) buildShard(todo []*Document, nextShardNum int) (*finishedShard, error) {
960 if !b.opts.DisableCTags && (b.opts.CTagsPath != "" || b.opts.ScipCTagsPath != "") {
961 err := parseSymbols(todo, b.opts.LanguageMap, b.parserBins)
962 if b.opts.CTagsMustSucceed && err != nil {
963 return nil, err
964 }
965 if err != nil {
966 log.Printf("ignoring universal:%s or scip:%s error: %v", b.opts.CTagsPath, b.opts.ScipCTagsPath, err)
967 }
968 }
969
970 name := b.opts.shardName(nextShardNum)
971
972 shardBuilder, err := b.newShardBuilder()
973 if err != nil {
974 return nil, err
975 }
976
977 sortDocuments(todo)
978
979 for idx, t := range todo {
980 if err := shardBuilder.Add(*t); err != nil {
981 return nil, err
982 }
983
984 if idx%10_000 == 0 {
985 b.CheckMemoryUsage()
986 }
987 }
988
989 return b.writeShard(name, shardBuilder)
990}
991
992// CheckMemoryUsage checks the memory usage of the process and writes a memory profile if the heap usage exceeds the
993// configured threshold. NOTE: this method is expensive and should only be used for debugging.
994func (b *Builder) CheckMemoryUsage() {
995 // Don't check memory if heap profiling is disabled, or we've already written 10 profiles
996 if b.opts.HeapProfileTriggerBytes <= 0 || b.heapProfileNum >= 10 {
997 return
998 }
999
1000 var m runtime.MemStats
1001 runtime.ReadMemStats(&m)
1002
1003 if m.HeapAlloc > b.opts.HeapProfileTriggerBytes && b.heapProfileMu.TryLock() {
1004 defer b.heapProfileMu.Unlock()
1005
1006 log.Printf("writing memory profile, allocated heap: %s", humanize.Bytes(m.HeapAlloc))
1007 name := filepath.Join(b.opts.IndexDir, fmt.Sprintf("indexmemory.prof.%d", b.heapProfileNum))
1008 f, err := os.Create(name)
1009 if err != nil {
1010 log.Printf("failed to create memory profile file: %v", err)
1011 return
1012 }
1013
1014 err = pprof.WriteHeapProfile(f)
1015 if err != nil {
1016 log.Printf("failed to write memory profile: %v", err)
1017 }
1018
1019 b.heapProfileNum++
1020 }
1021}
1022
1023func (b *Builder) newShardBuilder() (*ShardBuilder, error) {
1024 desc := b.opts.RepositoryDescription
1025 desc.HasSymbols = !b.opts.DisableCTags && b.opts.CTagsPath != ""
1026 desc.SubRepoMap = b.opts.SubRepositories
1027 desc.IndexOptions = b.opts.GetHash()
1028
1029 shardBuilder, err := NewShardBuilder(&desc)
1030 if err != nil {
1031 return nil, err
1032 }
1033 shardBuilder.IndexTime = b.indexTime
1034 shardBuilder.ID = b.id
1035 return shardBuilder, nil
1036}
1037
1038func (b *Builder) writeShard(fn string, ib *ShardBuilder) (*finishedShard, error) {
1039 dir := filepath.Dir(fn)
1040 if err := os.MkdirAll(dir, 0o700); err != nil {
1041 return nil, err
1042 }
1043
1044 f, err := os.CreateTemp(dir, filepath.Base(fn)+".*.tmp")
1045 if err != nil {
1046 return nil, err
1047 }
1048 if runtime.GOOS != "windows" {
1049 if err := f.Chmod(0o666 &^ umask); err != nil {
1050 return nil, err
1051 }
1052 }
1053
1054 defer f.Close()
1055 if err := ib.Write(f); err != nil {
1056 return nil, err
1057 }
1058 fi, err := f.Stat()
1059 if err != nil {
1060 return nil, err
1061 }
1062 if err := f.Close(); err != nil {
1063 return nil, err
1064 }
1065
1066 log.Printf("finished shard %s: %d index bytes (overhead %3.1f), %d files processed \n",
1067 fn,
1068 fi.Size(),
1069 float64(fi.Size())/float64(ib.ContentSize()+1),
1070 ib.NumFiles())
1071
1072 return &finishedShard{f.Name(), fn}, nil
1073}
1074
1075type deltaBranchSetError struct {
1076 shardName string
1077 old, new []zoekt.RepositoryBranch
1078}
1079
1080func (e deltaBranchSetError) Error() string {
1081 return fmt.Sprintf("repository metadata in shard %q contains a different set of branch names than what was requested, which is unsupported in a delta shard build. old: %+v, new: %+v", e.shardName, e.old, e.new)
1082}
1083
1084type deltaIndexOptionsMismatchError struct {
1085 shardName string
1086 newOptions HashOptions
1087}
1088
1089func (e *deltaIndexOptionsMismatchError) Error() string {
1090 return fmt.Sprintf("one or more index options for shard %q do not match Builder's index options. These index option updates are incompatible with delta build. New index options: %+v", e.shardName, e.newOptions)
1091}
1092
1093// Document holds a document (file) to index.
1094type Document struct {
1095 Name string
1096 Content []byte
1097 Branches []string
1098 SubRepositoryPath string
1099 Language string
1100
1101 // If set, something is wrong with the file contents, and this
1102 // is the reason it wasn't indexed.
1103 SkipReason string
1104
1105 // Document sections for symbols. Offsets should use bytes.
1106 Symbols []DocumentSection
1107 SymbolsMetaData []*zoekt.Symbol
1108}
1109
1110type DocumentSection struct {
1111 Start, End uint32
1112}
1113
1114// umask holds the Umask of the current process
1115var umask os.FileMode
1116
1117func init() {
1118 umask = os.FileMode(unix.Umask(0))
1119 unix.Umask(int(umask))
1120}