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 doc.Language = "binary"
614 }
615
616 b.todo = append(b.todo, &doc)
617
618 if doc.SkipReason == "" {
619 b.size += len(doc.Name) + len(doc.Content)
620 } else {
621 b.size += len(doc.Name) + len(doc.SkipReason)
622 // Drop the content if we are skipping the document. Skipped content is not counted towards the
623 // shard size limit, so otherwise we might buffer too much data in memory before flushing.
624 doc.Content = nil
625 }
626
627 if b.size > b.opts.ShardMax {
628 return b.flush()
629 }
630
631 return nil
632}
633
634// MarkFileAsChangedOrRemoved indicates that the file specified by the given path
635// has been changed or removed since the last indexing job for this repository.
636//
637// If this build is a delta build, these files will be tombstoned in the older shards for this repository.
638func (b *Builder) MarkFileAsChangedOrRemoved(path string) {
639 b.opts.changedOrRemovedFiles = append(b.opts.changedOrRemovedFiles, path)
640}
641
642// Finish creates a last shard from the buffered documents, and clears
643// stale shards from previous runs. This should always be called, also
644// in failure cases, to ensure cleanup.
645//
646// It is safe to call Finish() multiple times.
647func (b *Builder) Finish() error {
648 if b.finishCalled {
649 return b.buildError
650 }
651
652 b.finishCalled = true
653
654 b.flush()
655 b.building.Wait()
656
657 if b.buildError != nil {
658 for tmp := range b.finishedShards {
659 log.Printf("Builder.Finish %s", tmp)
660 os.Remove(tmp)
661 }
662 b.finishedShards = map[string]string{}
663 return b.buildError
664 }
665
666 // map of temporary -> final names for all updated shards + shard metadata files
667 artifactPaths := make(map[string]string)
668 for tmp, final := range b.finishedShards {
669 artifactPaths[tmp] = final
670 }
671
672 oldShards := b.opts.FindAllShards()
673
674 if b.opts.IsDelta {
675 // Delta shard builds need to update FileTombstone and branch commit information for all
676 // existing shards
677 for _, shard := range oldShards {
678 repositories, _, err := ReadMetadataPathAlive(shard)
679 if err != nil {
680 return fmt.Errorf("reading metadata from shard %q: %w", shard, err)
681 }
682
683 if len(repositories) > 1 {
684 return fmt.Errorf("delta shard builds don't support repositories contained in compound shards (shard %q)", shard)
685 }
686
687 if len(repositories) == 0 {
688 return fmt.Errorf("failed to update repository metadata for shard %q - shard contains no repositories", shard)
689 }
690
691 repository := repositories[0]
692 if repository.ID != b.opts.RepositoryDescription.ID {
693 return fmt.Errorf("shard %q doesn't contain repository ID %d (%q)", shard, b.opts.RepositoryDescription.ID, b.opts.RepositoryDescription.Name)
694 }
695
696 if len(b.opts.changedOrRemovedFiles) > 0 && repository.FileTombstones == nil {
697 repository.FileTombstones = make(map[string]struct{}, len(b.opts.changedOrRemovedFiles))
698 }
699
700 for _, f := range b.opts.changedOrRemovedFiles {
701 repository.FileTombstones[f] = struct{}{}
702 }
703
704 if !BranchNamesEqual(repository.Branches, b.opts.RepositoryDescription.Branches) {
705 return deltaBranchSetError{
706 shardName: shard,
707 old: repository.Branches,
708 new: b.opts.RepositoryDescription.Branches,
709 }
710 }
711
712 if b.opts.GetHash() != repository.IndexOptions {
713 return &deltaIndexOptionsMismatchError{
714 shardName: shard,
715 newOptions: b.opts.HashOptions(),
716 }
717 }
718
719 repository.Branches = b.opts.RepositoryDescription.Branches
720
721 repository.LatestCommitDate = b.opts.RepositoryDescription.LatestCommitDate
722
723 tempPath, finalPath, err := JsonMarshalRepoMetaTemp(shard, repository)
724 if err != nil {
725 return fmt.Errorf("writing repository metadta for shard %q: %w", shard, err)
726 }
727
728 artifactPaths[tempPath] = finalPath
729 }
730 }
731
732 // We mark finished shards as empty when we successfully finish. Return now
733 // to allow call sites to call Finish idempotently.
734 if len(artifactPaths) == 0 {
735 return b.buildError
736 }
737
738 // Collect a map of the old shards on disk. For each new shard we replace we
739 // delete it from toDelete. Anything remaining in toDelete will be removed
740 // after we have renamed everything into place.
741
742 var toDelete map[string]struct{}
743 if !b.opts.IsDelta {
744 // Non-delta shard builds delete all existing shards before they write out
745 // new ones.
746 // By contrast, delta shard builds work by stacking changes on top of existing shards.
747 // So, we skip populating the toDelete map if we're building delta shards.
748
749 toDelete = make(map[string]struct{})
750 for _, name := range oldShards {
751 paths, err := IndexFilePaths(name)
752 if err != nil {
753 b.buildError = fmt.Errorf("failed to find old paths for %s: %w", name, err)
754 }
755 for _, p := range paths {
756 toDelete[p] = struct{}{}
757 }
758 }
759 }
760
761 for tmp, final := range artifactPaths {
762 if err := os.Rename(tmp, final); err != nil {
763 b.buildError = err
764 continue
765 }
766
767 delete(toDelete, final)
768 }
769
770 b.finishedShards = map[string]string{}
771
772 for p := range toDelete {
773 // Don't delete compound shards, set tombstones instead.
774 if b.opts.ShardMerging && strings.HasPrefix(filepath.Base(p), "compound-") {
775 if !strings.HasSuffix(p, ".zoekt") {
776 continue
777 }
778 err := SetTombstone(p, b.opts.RepositoryDescription.ID)
779 b.buildError = err
780 continue
781 }
782 log.Printf("removing old shard file: %s", p)
783 if err := os.Remove(p); err != nil {
784 b.buildError = err
785 }
786 }
787
788 return b.buildError
789}
790
791// BranchNamesEqual compares the given zoekt.RepositoryBranch slices, and returns true
792// iff both slices specify the same set of branch names in the same order.
793func BranchNamesEqual(a, b []zoekt.RepositoryBranch) bool {
794 if len(a) != len(b) {
795 return false
796 }
797
798 for i := range a {
799 x, y := a[i], b[i]
800 if x.Name != y.Name {
801 return false
802 }
803 }
804
805 return true
806}
807
808func (b *Builder) flush() error {
809 todo := b.todo
810 b.todo = nil
811 b.size = 0
812 b.errMu.Lock()
813 defer b.errMu.Unlock()
814 if b.buildError != nil {
815 return b.buildError
816 }
817
818 hasShard := b.nextShardNum > 0
819 if len(todo) == 0 && hasShard {
820 return nil
821 }
822
823 shard := b.nextShardNum
824 b.nextShardNum++
825
826 if b.opts.Parallelism > 1 {
827 b.building.Add(1)
828 b.throttle <- 1
829 go func() {
830 done, err := b.buildShard(todo, shard)
831 <-b.throttle
832
833 b.errMu.Lock()
834 defer b.errMu.Unlock()
835 if err != nil && b.buildError == nil {
836 b.buildError = err
837 }
838 if err == nil {
839 b.finishedShards[done.temp] = done.final
840 }
841 b.building.Done()
842 }()
843 } else {
844 // No goroutines when we're not parallel. This
845 // simplifies memory profiling.
846 done, err := b.buildShard(todo, shard)
847 b.buildError = err
848 if err == nil {
849 b.finishedShards[done.temp] = done.final
850 }
851
852 return b.buildError
853 }
854
855 return nil
856}
857
858// map [0,inf) to [0,1) monotonically
859func squashRange(j int) float64 {
860 x := float64(j)
861 return x / (1 + x)
862}
863
864// IsLowPriority takes a file name and makes an educated guess about its priority
865// in search results. A file is considered low priority if it looks like a test,
866// vendored, or generated file.
867//
868// These 'priority' criteria affects how documents are ordered within a shard. It's
869// also used to help guess a file's rank when we're missing ranking information.
870func IsLowPriority(path string, content []byte) bool {
871 return enry.IsTest(path) || enry.IsVendor(path) || enry.IsGenerated(path, content)
872}
873
874type rankedDoc struct {
875 *Document
876 rank []float64
877}
878
879// rank returns a vector of scores which is used at index-time to sort documents
880// before writing them to disk. The order of documents in the shard is important
881// at query time, because earlier documents receive a boost at query time and
882// have a higher chance of being searched before limits kick in.
883func rank(d *Document, origIdx int) []float64 {
884 skipped := 0.0
885 if d.SkipReason != "" {
886 skipped = 1.0
887 }
888
889 generated := 0.0
890 if enry.IsGenerated(d.Name, d.Content) {
891 generated = 1.0
892 }
893
894 vendor := 0.0
895 if enry.IsVendor(d.Name) {
896 vendor = 1.0
897 }
898
899 test := 0.0
900 if enry.IsTest(d.Name) {
901 test = 1.0
902 }
903
904 // Smaller is earlier (=better).
905 return []float64{
906 // Always place skipped docs last
907 skipped,
908
909 // Prefer docs that are not generated
910 generated,
911
912 // Prefer docs that are not vendored
913 vendor,
914
915 // Prefer docs that are not tests
916 test,
917
918 // With short names
919 squashRange(len(d.Name)),
920
921 // With many symbols
922 1.0 - squashRange(len(d.Symbols)),
923
924 // With short content
925 squashRange(len(d.Content)),
926
927 // That is present is as many branches as possible
928 1.0 - squashRange(len(d.Branches)),
929
930 // Preserve original ordering.
931 squashRange(origIdx),
932 }
933}
934
935func sortDocuments(todo []*Document) {
936 rs := make([]rankedDoc, 0, len(todo))
937 for i, t := range todo {
938 rd := rankedDoc{t, rank(t, i)}
939 rs = append(rs, rd)
940 }
941 sort.Slice(rs, func(i, j int) bool {
942 r1 := rs[i].rank
943 r2 := rs[j].rank
944 for i := range r1 {
945 if r1[i] < r2[i] {
946 return true
947 }
948 if r1[i] > r2[i] {
949 return false
950 }
951 }
952
953 return false
954 })
955 for i := range todo {
956 todo[i] = rs[i].Document
957 }
958}
959
960func (b *Builder) buildShard(todo []*Document, nextShardNum int) (*finishedShard, error) {
961 if !b.opts.DisableCTags && (b.opts.CTagsPath != "" || b.opts.ScipCTagsPath != "") {
962 err := parseSymbols(todo, b.opts.LanguageMap, b.parserBins)
963 if b.opts.CTagsMustSucceed && err != nil {
964 return nil, err
965 }
966 if err != nil {
967 log.Printf("ignoring universal:%s or scip:%s error: %v", b.opts.CTagsPath, b.opts.ScipCTagsPath, err)
968 }
969 }
970
971 name := b.opts.shardName(nextShardNum)
972
973 shardBuilder, err := b.newShardBuilder()
974 if err != nil {
975 return nil, err
976 }
977
978 sortDocuments(todo)
979
980 for idx, t := range todo {
981 if err := shardBuilder.Add(*t); err != nil {
982 return nil, err
983 }
984
985 if idx%10_000 == 0 {
986 b.CheckMemoryUsage()
987 }
988 }
989
990 return b.writeShard(name, shardBuilder)
991}
992
993// CheckMemoryUsage checks the memory usage of the process and writes a memory profile if the heap usage exceeds the
994// configured threshold. NOTE: this method is expensive and should only be used for debugging.
995func (b *Builder) CheckMemoryUsage() {
996 // Don't check memory if heap profiling is disabled, or we've already written 10 profiles
997 if b.opts.HeapProfileTriggerBytes <= 0 || b.heapProfileNum >= 10 {
998 return
999 }
1000
1001 var m runtime.MemStats
1002 runtime.ReadMemStats(&m)
1003
1004 if m.HeapAlloc > b.opts.HeapProfileTriggerBytes && b.heapProfileMu.TryLock() {
1005 defer b.heapProfileMu.Unlock()
1006
1007 log.Printf("writing memory profile, allocated heap: %s", humanize.Bytes(m.HeapAlloc))
1008 name := filepath.Join(b.opts.IndexDir, fmt.Sprintf("indexmemory.prof.%d", b.heapProfileNum))
1009 f, err := os.Create(name)
1010 if err != nil {
1011 log.Printf("failed to create memory profile file: %v", err)
1012 return
1013 }
1014
1015 err = pprof.WriteHeapProfile(f)
1016 if err != nil {
1017 log.Printf("failed to write memory profile: %v", err)
1018 }
1019
1020 b.heapProfileNum++
1021 }
1022}
1023
1024func (b *Builder) newShardBuilder() (*ShardBuilder, error) {
1025 desc := b.opts.RepositoryDescription
1026 desc.HasSymbols = !b.opts.DisableCTags && b.opts.CTagsPath != ""
1027 desc.SubRepoMap = b.opts.SubRepositories
1028 desc.IndexOptions = b.opts.GetHash()
1029
1030 shardBuilder, err := NewShardBuilder(&desc)
1031 if err != nil {
1032 return nil, err
1033 }
1034 shardBuilder.IndexTime = b.indexTime
1035 shardBuilder.ID = b.id
1036 return shardBuilder, nil
1037}
1038
1039func (b *Builder) writeShard(fn string, ib *ShardBuilder) (*finishedShard, error) {
1040 dir := filepath.Dir(fn)
1041 if err := os.MkdirAll(dir, 0o700); err != nil {
1042 return nil, err
1043 }
1044
1045 f, err := os.CreateTemp(dir, filepath.Base(fn)+".*.tmp")
1046 if err != nil {
1047 return nil, err
1048 }
1049 if runtime.GOOS != "windows" {
1050 if err := f.Chmod(0o666 &^ umask); err != nil {
1051 return nil, err
1052 }
1053 }
1054
1055 defer f.Close()
1056 if err := ib.Write(f); err != nil {
1057 return nil, err
1058 }
1059 fi, err := f.Stat()
1060 if err != nil {
1061 return nil, err
1062 }
1063 if err := f.Close(); err != nil {
1064 return nil, err
1065 }
1066
1067 log.Printf("finished shard %s: %d index bytes (overhead %3.1f), %d files processed \n",
1068 fn,
1069 fi.Size(),
1070 float64(fi.Size())/float64(ib.ContentSize()+1),
1071 ib.NumFiles())
1072
1073 return &finishedShard{f.Name(), fn}, nil
1074}
1075
1076type deltaBranchSetError struct {
1077 shardName string
1078 old, new []zoekt.RepositoryBranch
1079}
1080
1081func (e deltaBranchSetError) Error() string {
1082 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)
1083}
1084
1085type deltaIndexOptionsMismatchError struct {
1086 shardName string
1087 newOptions HashOptions
1088}
1089
1090func (e *deltaIndexOptionsMismatchError) Error() string {
1091 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)
1092}
1093
1094// Document holds a document (file) to index.
1095type Document struct {
1096 Name string
1097 Content []byte
1098 Branches []string
1099 SubRepositoryPath string
1100 Language string
1101
1102 // If set, something is wrong with the file contents, and this
1103 // is the reason it wasn't indexed.
1104 SkipReason string
1105
1106 // Document sections for symbols. Offsets should use bytes.
1107 Symbols []DocumentSection
1108 SymbolsMetaData []*zoekt.Symbol
1109}
1110
1111type DocumentSection struct {
1112 Start, End uint32
1113}
1114
1115// umask holds the Umask of the current process
1116var umask os.FileMode
1117
1118func init() {
1119 umask = os.FileMode(unix.Umask(0))
1120 unix.Umask(int(umask))
1121}