fork of https://github.com/sourcegraph/zoekt
0

Configure Feed

Select the types of activity you want to include in your feed.

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 15package shards 16 17import ( 18 "context" 19 "fmt" 20 "log" 21 "math" 22 "os" 23 "runtime" 24 "runtime/debug" 25 "sort" 26 "strconv" 27 "sync" 28 "time" 29 30 "golang.org/x/sync/semaphore" 31 32 "github.com/prometheus/client_golang/prometheus" 33 "github.com/prometheus/client_golang/prometheus/promauto" 34 "go.uber.org/atomic" 35 36 "github.com/sourcegraph/zoekt" 37 "github.com/sourcegraph/zoekt/query" 38 "github.com/sourcegraph/zoekt/trace" 39) 40 41var ( 42 metricShardsLoaded = promauto.NewGauge(prometheus.GaugeOpts{ 43 Name: "zoekt_shards_loaded", 44 Help: "The number of shards currently loaded", 45 }) 46 metricShardsLoadedTotal = promauto.NewCounter(prometheus.CounterOpts{ 47 Name: "zoekt_shards_loaded_total", 48 Help: "The total number of shards loaded", 49 }) 50 metricShardsLoadFailedTotal = promauto.NewCounter(prometheus.CounterOpts{ 51 Name: "zoekt_shards_load_failed_total", 52 Help: "The total number of shard loads that failed", 53 }) 54 55 metricSearchRunning = promauto.NewGauge(prometheus.GaugeOpts{ 56 Name: "zoekt_search_running", 57 Help: "The number of concurrent search requests running", 58 }) 59 metricSearchShardRunning = promauto.NewGauge(prometheus.GaugeOpts{ 60 Name: "zoekt_search_shard_running", 61 Help: "The number of concurrent search requests in a shard running", 62 }) 63 metricSearchFailedTotal = promauto.NewCounter(prometheus.CounterOpts{ 64 Name: "zoekt_search_failed_total", 65 Help: "The total number of search requests that failed", 66 }) 67 metricSearchDuration = promauto.NewHistogram(prometheus.HistogramOpts{ 68 Name: "zoekt_search_duration_seconds", 69 Help: "The duration a search request took in seconds", 70 Buckets: prometheus.DefBuckets, // DefBuckets good for service timings 71 }) 72 73 // A Counter per Stat. Name should match field in zoekt.Stats. 74 metricSearchContentBytesLoadedTotal = promauto.NewCounter(prometheus.CounterOpts{ 75 Name: "zoekt_search_content_loaded_bytes_total", 76 Help: "Total amount of I/O for reading contents", 77 }) 78 metricSearchIndexBytesLoadedTotal = promauto.NewCounter(prometheus.CounterOpts{ 79 Name: "zoekt_search_index_loaded_bytes_total", 80 Help: "Total amount of I/O for reading from index", 81 }) 82 metricSearchCrashesTotal = promauto.NewCounter(prometheus.CounterOpts{ 83 Name: "zoekt_search_crashes_total", 84 Help: "Total number of search shards that had a crash", 85 }) 86 metricSearchFileCountTotal = promauto.NewCounter(prometheus.CounterOpts{ 87 Name: "zoekt_search_file_count_total", 88 Help: "Total number of files containing a match", 89 }) 90 metricSearchShardFilesConsideredTotal = promauto.NewCounter(prometheus.CounterOpts{ 91 Name: "zoekt_search_shard_files_considered_total", 92 Help: "Total number of files in shards that we considered", 93 }) 94 metricSearchFilesConsideredTotal = promauto.NewCounter(prometheus.CounterOpts{ 95 Name: "zoekt_search_files_considered_total", 96 Help: "Total files that we evaluated. Equivalent to files for which all atom matches (including negations) evaluated to true", 97 }) 98 metricSearchFilesLoadedTotal = promauto.NewCounter(prometheus.CounterOpts{ 99 Name: "zoekt_search_files_loaded_total", 100 Help: "Total files for which we loaded file content to verify substring matches", 101 }) 102 metricSearchFilesSkippedTotal = promauto.NewCounter(prometheus.CounterOpts{ 103 Name: "zoekt_search_files_skipped_total", 104 Help: "Total candidate files whose contents weren't examined because we gathered enough matches", 105 }) 106 metricSearchShardsSkippedTotal = promauto.NewCounter(prometheus.CounterOpts{ 107 Name: "zoekt_search_shards_skipped_total", 108 Help: "Total shards that we did not process because a query was canceled", 109 }) 110 metricSearchMatchCountTotal = promauto.NewCounter(prometheus.CounterOpts{ 111 Name: "zoekt_search_match_count_total", 112 Help: "Total number of non-overlapping matches", 113 }) 114 metricSearchNgramMatchesTotal = promauto.NewCounter(prometheus.CounterOpts{ 115 Name: "zoekt_search_ngram_matches_total", 116 Help: "Total number of candidate matches as a result of searching ngrams", 117 }) 118 metricSearchNgramLookupsTotal = promauto.NewCounter(prometheus.CounterOpts{ 119 Name: "zoekt_search_ngram_lookups_total", 120 Help: "Total number of times we accessed an ngram in the index", 121 }) 122 metricSearchRegexpsConsideredTotal = promauto.NewCounter(prometheus.CounterOpts{ 123 Name: "zoekt_search_regexps_considered_total", 124 Help: "Total number of times regexp was called on files that we evaluated", 125 }) 126 127 metricListRunning = promauto.NewGauge(prometheus.GaugeOpts{ 128 Name: "zoekt_list_running", 129 Help: "The number of concurrent list requests running", 130 }) 131 metricListShardRunning = promauto.NewGauge(prometheus.GaugeOpts{ 132 Name: "zoekt_list_shard_running", 133 Help: "The number of concurrent list requests in a shard running", 134 }) 135 metricShardsBatchReplaceDurationSeconds = promauto.NewHistogram(prometheus.HistogramOpts{ 136 Name: "zoekt_shards_batch_replace_duration_seconds", 137 Help: "The time it takes to replace a batch of Searchers.", 138 Buckets: []float64{0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30}, 139 }) 140 metricListAllRepos = promauto.NewGauge(prometheus.GaugeOpts{ 141 Name: "zoekt_list_all_stats_repos", 142 Help: "The last List(true) value for RepoStats.Repos. Repos is used for aggregrating the number of repositories.", 143 }) 144 metricListAllShards = promauto.NewGauge(prometheus.GaugeOpts{ 145 Name: "zoekt_list_all_stats_shards", 146 Help: "The last List(true) value for RepoStats.Shards. Shards is the total number of search shards.", 147 }) 148 metricListAllDocuments = promauto.NewGauge(prometheus.GaugeOpts{ 149 Name: "zoekt_list_all_stats_documents", 150 Help: "The last List(true) value for RepoStats.Documents. Documents holds the number of documents or files.", 151 }) 152 metricListAllIndexBytes = promauto.NewGauge(prometheus.GaugeOpts{ 153 Name: "zoekt_list_all_stats_index_bytes", 154 Help: "The last List(true) value for RepoStats.IndexBytes. IndexBytes is the amount of RAM used for index overhead.", 155 }) 156 metricListAllContentBytes = promauto.NewGauge(prometheus.GaugeOpts{ 157 Name: "zoekt_list_all_stats_content_bytes", 158 Help: "The last List(true) value for RepoStats.ContentBytes. ContentBytes is the amount of RAM used for raw content.", 159 }) 160 metricListAllNewLinesCount = promauto.NewGauge(prometheus.GaugeOpts{ 161 Name: "zoekt_list_all_stats_new_lines_count", 162 Help: "The last List(true) value for RepoStats.NewLinesCount.", 163 }) 164 metricListAllDefaultBranchNewLinesCount = promauto.NewGauge(prometheus.GaugeOpts{ 165 Name: "zoekt_list_all_stats_default_branch_new_lines_count", 166 Help: "The last List(true) value for RepoStats.DefaultBranchNewLinesCount.", 167 }) 168 metricListAllOtherBranchesNewLinesCount = promauto.NewGauge(prometheus.GaugeOpts{ 169 Name: "zoekt_list_all_stats_other_branches_new_lines_count", 170 Help: "The last List(true) value for RepoStats.OtherBranchesNewLinesCount.", 171 }) 172) 173 174type rankedShard struct { 175 zoekt.Searcher 176 177 priority float64 // maximum priority across all repos in the shard 178 179 // We have out of band ranking on compound shards which can change even if 180 // the shard file does not. So we compute a rank in getShards. We store 181 // repos here to avoid the cost of List in the search request path. 182 repos []*zoekt.Repository 183} 184 185// loaded stores the state we compute when updating the state of shards from 186// disk. 187type loaded struct { 188 // shards is the currently loaded shards sorted by decreasing rank and 189 // should not be mutated. 190 shards []*rankedShard 191 192 // ready is true if sharded searcher has finished loading all initial 193 // shards on startup. 194 ready bool 195} 196 197type shardedSearcher struct { 198 // Limit the number of parallel queries. Since searching is 199 // CPU bound, we can't do better than #CPU queries in 200 // parallel. If we do so, we just create more memory 201 // pressure. 202 sched scheduler 203 204 mu sync.Mutex // protects writes to shards 205 shards map[string]*rankedShard 206 207 ready atomic.Bool 208 ranked atomic.Value 209} 210 211func newShardedSearcher(n int64) *shardedSearcher { 212 ss := &shardedSearcher{ 213 shards: make(map[string]*rankedShard), 214 sched: newScheduler(n), 215 } 216 return ss 217} 218 219// NewDirectorySearcher returns a searcher instance that loads all 220// shards corresponding to a glob into memory. 221func NewDirectorySearcher(dir string) (zoekt.Streamer, error) { 222 return newDirectorySearcher(dir, true) 223} 224 225// NewDirectorySearcherFast is like NewDirectorySearcher, but does not block 226// on the initial loading of shards. 227// 228// This exists since in the case of zoekt-webserver we are happy with having 229// partial availability since that is better than no availability on large 230// instances. 231func NewDirectorySearcherFast(dir string) (zoekt.Streamer, error) { 232 return newDirectorySearcher(dir, false) 233} 234 235func newDirectorySearcher(dir string, waitUntilReady bool) (zoekt.Streamer, error) { 236 ss := newShardedSearcher(int64(runtime.GOMAXPROCS(0))) 237 tl := &loader{ 238 ss: ss, 239 } 240 dw, err := newDirectoryWatcher(dir, tl) 241 if err != nil { 242 return nil, err 243 } 244 245 if waitUntilReady { 246 if err := dw.WaitUntilReady(); err != nil { 247 return nil, err 248 } 249 } 250 251 ds := &directorySearcher{ 252 Streamer: ss, 253 directoryWatcher: dw, 254 } 255 256 return &typeRepoSearcher{Streamer: ds}, nil 257} 258 259type directorySearcher struct { 260 zoekt.Streamer 261 262 directoryWatcher *DirectoryWatcher 263} 264 265func (s *directorySearcher) Close() { 266 // We need to Stop directoryWatcher first since it calls load/unload on 267 // Searcher. 268 s.directoryWatcher.Stop() 269 s.Streamer.Close() 270} 271 272type loader struct { 273 ss *shardedSearcher 274} 275 276func (tl *loader) load(keys ...string) { 277 // This is called with all keys on startup, so once this function has 278 // finished running shardedSearcher will be ready. 279 defer tl.ss.markReady() 280 281 if len(keys) == 0 { 282 // If there's nothing to load, we exit early here, but we want to mark 283 // ourselves as ready. 284 return 285 } 286 287 var ( 288 mu sync.Mutex // synchronizes writes to the shards map 289 wg sync.WaitGroup // used to wait for all shards to load 290 sem = semaphore.NewWeighted(int64(runtime.GOMAXPROCS(0))) 291 loadedShards = make(map[string]zoekt.Searcher) 292 ) 293 294 publishLoaded := func() { 295 mu.Lock() 296 chunk := loadedShards 297 loadedShards = make(map[string]zoekt.Searcher) 298 mu.Unlock() 299 tl.ss.replace(chunk) 300 } 301 302 log.Printf("loading %d shard(s): %s", len(keys), humanTruncateList(keys, 5)) 303 304 lastProgress := time.Now() 305 for i, key := range keys { 306 // If taking a while to start-up occasionally give a progress message 307 if time.Since(lastProgress) > 5*time.Second { 308 log.Printf("still need to load %d shards...", len(keys)-i) 309 lastProgress = time.Now() 310 311 publishLoaded() 312 } 313 314 _ = sem.Acquire(context.Background(), 1) 315 wg.Add(1) 316 317 go func(key string) { 318 defer sem.Release(1) 319 defer wg.Done() 320 321 shard, err := loadShard(key) 322 if err != nil { 323 metricShardsLoadFailedTotal.Inc() 324 log.Printf("reloading: %s, err %v ", key, err) 325 return 326 } 327 metricShardsLoadedTotal.Inc() 328 329 mu.Lock() 330 loadedShards[key] = shard 331 mu.Unlock() 332 }(key) 333 } 334 335 wg.Wait() 336 337 publishLoaded() 338} 339 340func (tl *loader) drop(keys ...string) { 341 shards := make(map[string]zoekt.Searcher, len(keys)) 342 for _, key := range keys { 343 shards[key] = nil 344 } 345 tl.ss.replace(shards) 346} 347 348func (ss *shardedSearcher) String() string { 349 return "shardedSearcher" 350} 351 352// Close closes references to open files. It may be called only once. 353func (ss *shardedSearcher) Close() { 354 ss.mu.Lock() 355 shards := make(map[string]zoekt.Searcher, len(ss.shards)) 356 for k := range ss.shards { 357 shards[k] = nil 358 } 359 ss.mu.Unlock() 360 361 ss.replace(shards) 362} 363 364func selectRepoSet(shards []*rankedShard, q query.Q) ([]*rankedShard, query.Q) { 365 and, ok := q.(*query.And) 366 if !ok { 367 return shards, q 368 } 369 370 // (and (reposet ...) (q)) 371 // (and true (q)) with a filtered shards 372 // (and false) // noop 373 374 // (and (repobranches ...) (q)) 375 // (and (repobranches ...) (q)) 376 377 hasReposForPredicate := func(pred func(repo *zoekt.Repository) bool) func(repos []*zoekt.Repository) (any, all bool) { 378 return func(repos []*zoekt.Repository) (any, all bool) { 379 any = false 380 all = true 381 for _, repo := range repos { 382 b := pred(repo) 383 any = any || b 384 all = all && b 385 } 386 return any, all 387 } 388 } 389 390 for i, c := range and.Children { 391 var setSize int 392 var hasRepos func([]*zoekt.Repository) (bool, bool) 393 switch setQuery := c.(type) { 394 case *query.RepoSet: 395 setSize = len(setQuery.Set) 396 hasRepos = hasReposForPredicate(func(repo *zoekt.Repository) bool { 397 return setQuery.Set[repo.Name] 398 }) 399 case *query.RepoIDs: 400 setSize = int(setQuery.Repos.GetCardinality()) 401 hasRepos = hasReposForPredicate(func(repo *zoekt.Repository) bool { 402 return setQuery.Repos.Contains(repo.ID) 403 }) 404 case *query.BranchesRepos: 405 for _, br := range setQuery.List { 406 setSize += int(br.Repos.GetCardinality()) 407 } 408 409 hasRepos = hasReposForPredicate(func(repo *zoekt.Repository) bool { 410 for _, br := range setQuery.List { 411 if br.Repos.Contains(repo.ID) { 412 return true 413 } 414 } 415 return false 416 }) 417 default: 418 continue 419 } 420 421 // setSize may be larger than the number of shards we have. The size of 422 // filtered is bounded by min(len(set), len(shards)) 423 if setSize > len(shards) { 424 setSize = len(shards) 425 } 426 427 filtered := make([]*rankedShard, 0, setSize) 428 filteredAll := true 429 430 for _, s := range shards { 431 if any, all := hasRepos(s.repos); any { 432 filtered = append(filtered, s) 433 filteredAll = filteredAll && all 434 } 435 } 436 437 // We don't need to adjust the query since we are returning an empty set 438 // of shards to search. 439 if len(filtered) == 0 { 440 return filtered, and 441 } 442 443 // We can't simplify the query since we are searching shards which contain 444 // repos we aren't supposed to search. 445 if !filteredAll { 446 return filtered, and 447 } 448 449 // This optimization allows us to avoid the work done by 450 // indexData.simplify for each shard. 451 // 452 // For example if our query is (and (reposet foo bar) (content baz)) 453 // then at this point filtered is [foo bar] and q is the same. For each 454 // shard indexData.simplify will simplify to (and true (content baz)) -> 455 // (content baz). This work can be done now once, rather than per shard. 456 switch c := c.(type) { 457 case *query.RepoSet: 458 and.Children[i] = &query.Const{Value: true} 459 return filtered, query.Simplify(and) 460 461 case *query.RepoIDs: 462 and.Children[i] = &query.Const{Value: true} 463 return filtered, query.Simplify(and) 464 465 case *query.BranchesRepos: 466 // We can only replace if all the repos want the same branches. We 467 // simplify and just check that we are requesting 1 branch. The common 468 // case is just asking for HEAD, so this should be effective. 469 if len(c.List) != 1 { 470 return filtered, and 471 } 472 473 // Every repo wants the same branches, so we can replace RepoBranches 474 // with a list of branch queries. 475 and.Children[i] = &query.Branch{Pattern: c.List[0].Branch, Exact: true} 476 return filtered, query.Simplify(and) 477 } 478 479 // Stop after first RepoSet, otherwise we might append duplicate 480 // shards to `filtered` 481 return filtered, and 482 } 483 484 return shards, and 485} 486 487func (ss *shardedSearcher) Search(ctx context.Context, q query.Q, opts *zoekt.SearchOptions) (sr *zoekt.SearchResult, err error) { 488 tr, ctx := trace.New(ctx, "shardedSearcher.Search", "") 489 defer func() { 490 tr.Finish() 491 }() 492 ctx, cancel := context.WithCancel(ctx) 493 defer cancel() 494 495 collectSender := newCollectSender(opts) 496 497 start := time.Now() 498 proc, err := ss.sched.Acquire(ctx) 499 if err != nil { 500 return nil, err 501 } 502 defer proc.Release() 503 tr.LazyPrintf("acquired process") 504 505 wait := time.Since(start) 506 start = time.Now() 507 508 loaded := ss.getLoaded() 509 done, err := streamSearch(ctx, proc, q, opts, loaded.shards, collectSender) 510 defer done() 511 if err != nil { 512 return nil, err 513 } 514 515 aggregate, ok := collectSender.Done() 516 if !ok { 517 aggregate = &zoekt.SearchResult{ 518 RepoURLs: map[string]string{}, 519 LineFragments: map[string]string{}, 520 } 521 } 522 523 copyFiles(aggregate) 524 525 if !loaded.ready { 526 // We may have missed results due to not being fully loaded. 527 aggregate.Stats.Crashes++ 528 } 529 530 aggregate.Stats.Wait = wait 531 aggregate.Stats.Duration = time.Since(start) 532 533 return aggregate, nil 534} 535 536func (ss *shardedSearcher) StreamSearch(ctx context.Context, q query.Q, opts *zoekt.SearchOptions, sender zoekt.Sender) (err error) { 537 tr, ctx := trace.New(ctx, "shardedSearcher.StreamSearch", "") 538 defer func() { 539 if err != nil { 540 tr.LazyPrintf("error: %v", err) 541 tr.SetError(err) 542 } 543 tr.Finish() 544 }() 545 546 start := time.Now() 547 proc, err := ss.sched.Acquire(ctx) 548 if err != nil { 549 return err 550 } 551 defer proc.Release() 552 tr.LazyPrintf("acquired process") 553 554 loaded := ss.getLoaded() 555 shards := loaded.shards 556 557 maxPendingPriority := math.Inf(-1) 558 if len(shards) > 0 { 559 maxPendingPriority = shards[0].priority 560 } 561 562 stillLoadingCrashes := 0 563 if !loaded.ready { 564 // We may have missed results due to not being fully loaded. 565 stillLoadingCrashes++ 566 } 567 568 sender.Send(&zoekt.SearchResult{ 569 Stats: zoekt.Stats{ 570 Crashes: stillLoadingCrashes, 571 Wait: time.Since(start), 572 }, 573 Progress: zoekt.Progress{ 574 MaxPendingPriority: maxPendingPriority, 575 }, 576 }) 577 578 // Matches flow from the shards up the stack in the following order: 579 // 580 // 1. Search shards 581 // 2. flushCollectSender (aggregate) 582 // 3. limitSender (limit) 583 // 4. copyFileSender (copy) 584 // 585 // For streaming, the wrapping has to happen in the inverted order. 586 sender = copyFileSender(sender) 587 588 if truncator, hasLimits := zoekt.NewDisplayTruncator(opts); hasLimits { 589 var cancel context.CancelFunc 590 ctx, cancel = context.WithCancel(ctx) 591 defer cancel() 592 sender = limitSender(cancel, sender, truncator) 593 } 594 595 sender, flush := newFlushCollectSender(opts, sender) 596 597 done, err := streamSearch(ctx, proc, q, opts, shards, sender) 598 599 // Even though streaming is done, we may have results sitting in a buffer we 600 // need to flush. So we need to send those before calling done. 601 flush() 602 done() 603 604 return err 605} 606 607// streamSearch is an internal helper since both Search and StreamSearch are 608// largely similar. 609// 610// done must always be called, even if err is non-nil. The SearchResults sent 611// via sender contain references to the underlying mmap data that the garbage 612// collector can't see. Calling done informs the garbage collector it is free 613// to collect those shards. The caller must call copyFiles on any 614// SearchResults it returns/streams out before calling done. 615func streamSearch(ctx context.Context, proc *process, q query.Q, opts *zoekt.SearchOptions, shards []*rankedShard, sender zoekt.Sender) (done func(), err error) { 616 tr, ctx := trace.New(ctx, "shardedSearcher.streamSearch", "") 617 overallStart := time.Now() 618 metricSearchRunning.Inc() 619 defer func() { 620 metricSearchRunning.Dec() 621 metricSearchDuration.Observe(time.Since(overallStart).Seconds()) 622 if err != nil { 623 metricSearchFailedTotal.Inc() 624 625 tr.LazyPrintf("error: %v", err) 626 tr.SetError(err) 627 } 628 tr.Finish() 629 }() 630 631 tr.LazyPrintf("before selectRepoSet shards:%d", len(shards)) 632 // Select the subset of shards that we will search over for the given query. 633 shards, q = selectRepoSet(shards, q) 634 tr.LazyPrintf("after selectRepoSet shards:%d %s", len(shards), q) 635 636 if len(shards) == 0 { 637 return func() {}, nil 638 } 639 640 var cancel context.CancelFunc 641 if opts.MaxWallTime == 0 { 642 ctx, cancel = context.WithCancel(ctx) 643 } else { 644 ctx, cancel = context.WithTimeout(ctx, opts.MaxWallTime) 645 } 646 647 defer cancel() 648 649 // We set the number of workers to GOMAXPROCS, or the number of shards, 650 // whichever is smaller. 651 workers := runtime.GOMAXPROCS(0) 652 if workers > len(shards) { 653 workers = len(shards) 654 } 655 656 type result struct { 657 priority float64 658 *zoekt.SearchResult 659 err error 660 } 661 662 var ( 663 // buffered channels to continue searching when sending back results 664 // takes a while / blocks. The maximum pending result set is workers * 2. 665 results = make(chan *result, workers) 666 search = make(chan *rankedShard, workers) 667 wg sync.WaitGroup 668 ) 669 670 // Start workers that receive shards from the search channel, search them, 671 // and send the results to the results channel. This process is repeated 672 // until the search channel is closed. 673 // 674 // Note: Making "search" a buffered channel has the effect of limiting the number of parallel shard searches. 675 // Since searching is mostly CPU bound, limiting parallel shard searches also reduces the peak working set. 676 wg.Add(workers) 677 for i := 0; i < workers; i++ { 678 go func() { 679 defer wg.Done() 680 for s := range search { 681 sr, err := searchOneShard(ctx, s, q, opts) 682 r := &result{priority: s.priority, SearchResult: sr, err: err} 683 results <- r 684 } 685 }() 686 } 687 688 go func() { 689 wg.Wait() 690 close(results) 691 }() 692 693 var ( 694 pending = make(prioritySlice, 0, workers) 695 shard = 0 696 next = shards[shard] 697 698 // We need a separate nil-able reference to the same channel so we can close(search) for the worker 699 // go-routines to finish but also set work to nil in order for the select statement below to ignore 700 // that case when we want to stop a search. This is needed because sending on a closed channel panics. 701 work = search 702 ) 703 704 stop := func() { 705 if work != nil { 706 close(search) 707 work = nil 708 next = nil 709 } 710 } 711 712 // tracked so we can stop when we hit TotalMaxMatchCount 713 var totalMatchCount int 714 715search: 716 for { 717 // At the top of each iteration, have the proc associated with this search yield its won "timeslice" 718 // to possibly allow other searches to make progress 719 _ = proc.Yield(ctx) // Note: we let searchOneShard handle context errors 720 721 select { 722 case work <- next: // is there a worker available to search the next shard? 723 pending.append(next.priority) 724 725 shard++ 726 if shard == len(shards) { 727 stop() 728 } else { 729 next = shards[shard] 730 } 731 case r, ok := <-results: // is there a result to send back? 732 if !ok { 733 break search 734 } 735 736 // delete this result's priority from pending before computing the new max pending priority 737 pending.remove(r.priority) 738 739 if r.err != nil { 740 // Set final error and stop searching new shards, but consume any pending 741 // search results. 742 stop() 743 err = r.err 744 continue 745 } 746 747 // Update the match count statistics and stop searching new shards if we've 748 // reached the limit set in the options. 749 totalMatchCount += r.SearchResult.Stats.MatchCount 750 if opts.TotalMaxMatchCount > 0 && totalMatchCount > opts.TotalMaxMatchCount { 751 stop() 752 } 753 754 observeMetrics(r.SearchResult) 755 756 r.Priority = r.priority 757 r.MaxPendingPriority = pending.max() 758 759 sendByRepository(r.SearchResult, opts, sender) // send the result back to the client 760 } 761 } 762 763 return func() { runtime.KeepAlive(shards) }, err 764} 765 766// sendByRepository splits a zoekt.SearchResult by repository and calls 767// sender.Send for each batch. Ranking in Sourcegraph expects zoekt.SearchResult 768// to contain results with the same zoekt.SearchResult.Priority only. 769// 770// We split by repository instead of by priority because it is easier to set 771// RepoURLs and LineFragments in zoekt.SearchResult. 772func sendByRepository(result *zoekt.SearchResult, opts *zoekt.SearchOptions, sender zoekt.Sender) { 773 if len(result.RepoURLs) <= 1 || len(result.Files) == 0 { 774 zoekt.SortFiles(result.Files) 775 sender.Send(result) 776 return 777 } 778 779 send := func(repoName string, a, b int, stats zoekt.Stats) { 780 zoekt.SortFiles(result.Files[a:b]) 781 sender.Send(&zoekt.SearchResult{ 782 Stats: stats, 783 Progress: zoekt.Progress{ 784 Priority: result.Files[a].RepositoryPriority, 785 MaxPendingPriority: result.MaxPendingPriority, 786 }, 787 Files: result.Files[a:b], 788 RepoURLs: map[string]string{repoName: result.RepoURLs[repoName]}, 789 LineFragments: map[string]string{repoName: result.LineFragments[repoName]}, 790 }) 791 } 792 793 var startIndex, endIndex int 794 curRepoID := result.Files[0].RepositoryID 795 curRepoName := result.Files[0].Repository 796 797 fm := zoekt.FileMatch{} 798 for endIndex, fm = range result.Files { 799 if curRepoID != fm.RepositoryID { 800 // Stats must stay aggregate-able, hence we sent the aggregate stats with the 801 // last event. 802 send(curRepoName, startIndex, endIndex, zoekt.Stats{}) 803 804 startIndex = endIndex 805 curRepoID = fm.RepositoryID 806 curRepoName = fm.Repository 807 } 808 } 809 810 send(curRepoName, startIndex, endIndex+1, result.Stats) 811} 812 813func observeMetrics(sr *zoekt.SearchResult) { 814 metricSearchContentBytesLoadedTotal.Add(float64(sr.Stats.ContentBytesLoaded)) 815 metricSearchIndexBytesLoadedTotal.Add(float64(sr.Stats.IndexBytesLoaded)) 816 metricSearchCrashesTotal.Add(float64(sr.Stats.Crashes)) 817 metricSearchFileCountTotal.Add(float64(sr.Stats.FileCount)) 818 metricSearchShardFilesConsideredTotal.Add(float64(sr.Stats.ShardFilesConsidered)) 819 metricSearchFilesConsideredTotal.Add(float64(sr.Stats.FilesConsidered)) 820 metricSearchFilesLoadedTotal.Add(float64(sr.Stats.FilesLoaded)) 821 metricSearchFilesSkippedTotal.Add(float64(sr.Stats.FilesSkipped)) 822 metricSearchShardsSkippedTotal.Add(float64(sr.Stats.ShardsSkipped)) 823 metricSearchMatchCountTotal.Add(float64(sr.Stats.MatchCount)) 824 metricSearchNgramMatchesTotal.Add(float64(sr.Stats.NgramMatches)) 825 metricSearchNgramLookupsTotal.Add(float64(sr.Stats.NgramLookups)) 826 metricSearchRegexpsConsideredTotal.Add(float64(sr.Stats.RegexpsConsidered)) 827} 828 829func copySlice(src *[]byte) { 830 if *src == nil { 831 return 832 } 833 dst := make([]byte, len(*src)) 834 copy(dst, *src) 835 *src = dst 836} 837 838func copyFiles(sr *zoekt.SearchResult) { 839 for i := range sr.Files { 840 copySlice(&sr.Files[i].Content) 841 copySlice(&sr.Files[i].Checksum) 842 for l := range sr.Files[i].LineMatches { 843 copySlice(&sr.Files[i].LineMatches[l].Line) 844 copySlice(&sr.Files[i].LineMatches[l].Before) 845 copySlice(&sr.Files[i].LineMatches[l].After) 846 } 847 for c := range sr.Files[i].ChunkMatches { 848 copySlice(&sr.Files[i].ChunkMatches[c].Content) 849 } 850 } 851} 852 853func searchOneShard(ctx context.Context, s zoekt.Searcher, q query.Q, opts *zoekt.SearchOptions) (sr *zoekt.SearchResult, err error) { 854 metricSearchShardRunning.Inc() 855 defer func() { 856 metricSearchShardRunning.Dec() 857 if e := recover(); e != nil { 858 log.Printf("crashed shard: %s: %#v, %s", s, e, debug.Stack()) 859 860 if sr == nil { 861 sr = &zoekt.SearchResult{} 862 } 863 sr.Stats.Crashes = 1 864 } 865 }() 866 867 return s.Search(ctx, q, opts) 868} 869 870type shardListResult struct { 871 rl *zoekt.RepoList 872 err error 873} 874 875func listOneShard(ctx context.Context, s zoekt.Searcher, q query.Q, opts *zoekt.ListOptions, sink chan shardListResult) { 876 metricListShardRunning.Inc() 877 defer func() { 878 metricListShardRunning.Dec() 879 if r := recover(); r != nil { 880 log.Printf("crashed shard: %s: %s, %s", s.String(), r, debug.Stack()) 881 sink <- shardListResult{ 882 &zoekt.RepoList{Crashes: 1}, nil, 883 } 884 } 885 }() 886 887 ms, err := s.List(ctx, q, opts) 888 sink <- shardListResult{ms, err} 889} 890 891func (ss *shardedSearcher) List(ctx context.Context, r query.Q, opts *zoekt.ListOptions) (rl *zoekt.RepoList, err error) { 892 tr, ctx := trace.New(ctx, "shardedSearcher.List", "") 893 metricListRunning.Inc() 894 defer func() { 895 metricListRunning.Dec() 896 if rl != nil { 897 tr.LazyPrintf("repos size: %d", len(rl.Repos)) 898 tr.LazyPrintf("reposmap size: %d", len(rl.ReposMap)) 899 tr.LazyPrintf("crashes: %d", rl.Crashes) 900 } 901 if err != nil { 902 tr.LazyPrintf("error: %v", err) 903 tr.SetError(err) 904 } 905 tr.Finish() 906 }() 907 908 r = query.Simplify(r) 909 isAll := false 910 if c, ok := r.(*query.Const); ok { 911 isAll = c.Value 912 } 913 914 proc, err := ss.sched.Acquire(ctx) 915 if err != nil { 916 return nil, err 917 } 918 defer proc.Release() 919 tr.LazyPrintf("acquired process") 920 921 loaded := ss.getLoaded() 922 shards := loaded.shards 923 shardCount := len(shards) 924 all := make(chan shardListResult, shardCount) 925 tr.LazyPrintf("shardCount: %d", len(shards)) 926 927 feeder := make(chan zoekt.Searcher, len(shards)) 928 for _, s := range shards { 929 feeder <- s 930 } 931 close(feeder) 932 933 for i := 0; i < runtime.GOMAXPROCS(0); i++ { 934 go func() { 935 for s := range feeder { 936 listOneShard(ctx, s, r, opts, all) 937 } 938 }() 939 } 940 941 stillLoadingCrashes := 0 942 if !loaded.ready { 943 // We may have missed results due to not being fully loaded. 944 stillLoadingCrashes++ 945 } 946 947 agg := zoekt.RepoList{ 948 Crashes: stillLoadingCrashes, 949 ReposMap: zoekt.ReposMap{}, 950 } 951 952 uniq := map[string]*zoekt.RepoListEntry{} 953 954 for range shards { 955 r := <-all 956 if r.err != nil { 957 return nil, r.err 958 } 959 960 agg.Crashes += r.rl.Crashes 961 agg.Stats.Add(&r.rl.Stats) 962 963 for _, r := range r.rl.Repos { 964 prev, ok := uniq[r.Repository.Name] 965 if !ok { 966 cp := *r // We need to copy because we mutate r.Stats when merging duplicates 967 uniq[r.Repository.Name] = &cp 968 } else { 969 prev.Stats.Add(&r.Stats) 970 } 971 } 972 973 for id, r := range r.rl.ReposMap { 974 _, ok := agg.ReposMap[id] 975 if !ok { 976 agg.ReposMap[id] = r 977 } 978 } 979 } 980 981 agg.Repos = make([]*zoekt.RepoListEntry, 0, len(uniq)) 982 for _, r := range uniq { 983 agg.Repos = append(agg.Repos, r) 984 } 985 986 // Only one of these fields is populated and in all cases the size of that 987 // field is the number of Repos. 988 // 989 // Note: we don't just add individual Stats.Repos since a repository can 990 // have multiple shards. 991 agg.Stats.Repos = len(uniq) + len(agg.ReposMap) 992 993 if isAll && len(agg.Repos) > 0 { 994 reportListAllMetrics(agg.Repos) 995 } 996 997 return &agg, nil 998} 999 1000func reportListAllMetrics(repos []*zoekt.RepoListEntry) { 1001 var stats zoekt.RepoStats 1002 for _, r := range repos { 1003 stats.Add(&r.Stats) 1004 } 1005 1006 metricListAllRepos.Set(float64(stats.Repos)) 1007 metricListAllIndexBytes.Set(float64(stats.IndexBytes)) 1008 metricListAllContentBytes.Set(float64(stats.ContentBytes)) 1009 metricListAllDocuments.Set(float64(stats.Documents)) 1010 metricListAllShards.Set(float64(stats.Shards)) 1011 metricListAllNewLinesCount.Set(float64(stats.NewLinesCount)) 1012 metricListAllDefaultBranchNewLinesCount.Set(float64(stats.DefaultBranchNewLinesCount)) 1013 metricListAllOtherBranchesNewLinesCount.Set(float64(stats.OtherBranchesNewLinesCount)) 1014} 1015 1016// getLoaded returns the currently loaded shards. Shared so do not mutate. 1017func (s *shardedSearcher) getLoaded() loaded { 1018 // next commit will store the true value of this, for now we keep the 1019 // backwards compatible behaviour. 1020 ready := s.ready.Load() 1021 // ranked is loaded after ready to avoid a race were ready is true but 1022 // ranked is still not the final set of shards. 1023 ranked, _ := s.ranked.Load().([]*rankedShard) 1024 return loaded{ 1025 shards: ranked, 1026 ready: ready, 1027 } 1028} 1029 1030func mkRankedShard(s zoekt.Searcher) *rankedShard { 1031 q := query.Const{Value: true} 1032 result, err := s.List(context.Background(), &q, nil) 1033 if err != nil { 1034 return &rankedShard{Searcher: s} 1035 } 1036 if len(result.Repos) == 0 { 1037 return &rankedShard{Searcher: s} 1038 } 1039 1040 var ( 1041 maxPriority float64 1042 repos = make([]*zoekt.Repository, 0, len(result.Repos)) 1043 ) 1044 for i := range result.Repos { 1045 repo := &result.Repos[i].Repository 1046 repos = append(repos, repo) 1047 if repo.RawConfig != nil { 1048 priority, _ := strconv.ParseFloat(repo.RawConfig["priority"], 64) 1049 if priority > maxPriority { 1050 maxPriority = priority 1051 } 1052 } 1053 } 1054 1055 return &rankedShard{ 1056 Searcher: s, 1057 repos: repos, 1058 priority: maxPriority, 1059 } 1060} 1061 1062// markReady should be called once all shards have been passed into replace on 1063// startup. Once s is marked as ready it stops reporting a Crash in the 1064// response Stats. 1065func (s *shardedSearcher) markReady() { 1066 s.ready.CompareAndSwap(false, true) 1067} 1068 1069func (s *shardedSearcher) replace(shards map[string]zoekt.Searcher) { 1070 if len(shards) == 0 { 1071 return 1072 } 1073 1074 defer func(began time.Time) { 1075 metricShardsBatchReplaceDurationSeconds.Observe(time.Since(began).Seconds()) 1076 }(time.Now()) 1077 1078 s.mu.Lock() 1079 defer s.mu.Unlock() 1080 1081 for key, shard := range shards { 1082 var r *rankedShard 1083 if shard != nil { 1084 r = mkRankedShard(shard) 1085 } 1086 1087 old := s.shards[key] 1088 if shard == nil { 1089 delete(s.shards, key) 1090 } else { 1091 s.shards[key] = r 1092 } 1093 1094 if old != nil && old.Searcher != nil { 1095 // _ ___ /^^\ /^\ /^^\_ 1096 // _ _@)@) \ ,,/ '` ~ `'~~ ', `\. 1097 // _/o\_ _ _ _/~`.`...'~\ ./~~..,'`','',.,' ' ~: 1098 // / `,'.~,~.~ . , . , ~|, ,/ .,' , ,. .. ,,. `, ~\_ 1099 // ( ' _' _ '_` _ ' . , `\_/ .' ..' ' ` ` `.. `, \_ 1100 // ~V~ V~ V~ V~ ~\ ` ' . ' , ' .,.,''`.,.''`.,.``. ', \_ 1101 // _/\ /\ /\ /\_/, . ' , `_/~\_ .' .,. ,, , _/~\_ `. `. '., \_ 1102 // < ~ ~ '~`'~'`, ., . `_: ::: \_ ' `_/ ::: \_ `.,' . ', \_ 1103 // \ ' `_ '`_ _ ',/ _::_::_ \ _ _/ _::_::_ \ `.,'.,`., \-,-,-,_,_, 1104 // `'~~ `'~~ `'~~ `'~~ \(_)(_)(_)/ `~~' \(_)(_)(_)/ ~'`\_.._,._,'_;_;_;_;_; 1105 // 1106 // We can't just call Close now, because there may be ongoing searches 1107 // which have old in the shards list. Previously we used an exclusive 1108 // lock to guarantee there were no concurrent searches. However, that 1109 // led to blocking on the read path. 1110 // 1111 // We could introduce granular locking per rankedShard to know when 1112 // there are no more references. However, this becomes tricky in 1113 // practice. Instead we rely on the garbage collector noticing old is no 1114 // longer used. We take care in our searchers to runtime.KeepAlive until 1115 // we have stopped referencing the underling mmap data. 1116 runtime.SetFinalizer(old, func(r *rankedShard) { 1117 r.Close() 1118 }) 1119 } 1120 } 1121 1122 ranked := make([]*rankedShard, 0, len(s.shards)) 1123 for _, r := range s.shards { 1124 ranked = append(ranked, r) 1125 } 1126 1127 sort.Slice(ranked, func(i, j int) bool { 1128 priorityDiff := ranked[i].priority - ranked[j].priority 1129 if priorityDiff != 0 { 1130 return priorityDiff > 0 1131 } 1132 if len(ranked[i].repos) == 0 || len(ranked[j].repos) == 0 { 1133 // Protect against empty names which can happen if we fail to List or 1134 // the shard is full of tombstones. Prefer the shard which has names. 1135 return len(ranked[i].repos) >= len(ranked[j].repos) 1136 } 1137 return ranked[i].repos[0].Name < ranked[j].repos[0].Name 1138 }) 1139 1140 s.ranked.Store(ranked) 1141 1142 metricShardsLoaded.Set(float64(len(ranked))) 1143} 1144 1145func loadShard(fn string) (zoekt.Searcher, error) { 1146 f, err := os.Open(fn) 1147 if err != nil { 1148 return nil, err 1149 } 1150 1151 iFile, err := zoekt.NewIndexFile(f) 1152 if err != nil { 1153 return nil, err 1154 } 1155 s, err := zoekt.NewSearcher(iFile) 1156 if err != nil { 1157 iFile.Close() 1158 return nil, fmt.Errorf("NewSearcher(%s): %v", fn, err) 1159 } 1160 1161 return s, nil 1162} 1163 1164// prioritySlice is a trivial implementation of an array that provides three 1165// things: appending a value, removing a value, and getting the array's max. 1166// Operations take O(n) time, which is acceptable because N is restricted to 1167// GOMAXPROCS (i.e., number of cpu cores) by the shardedSearcher interface. 1168type prioritySlice []float64 1169 1170func (p *prioritySlice) append(pri float64) { 1171 *p = append(*p, pri) 1172} 1173 1174func (p *prioritySlice) remove(pri float64) { 1175 for i, opri := range *p { 1176 if opri == pri { 1177 if i != len(*p)-1 { 1178 // swap to make this element the tail 1179 (*p)[i] = (*p)[len(*p)-1] 1180 } 1181 // pop the end off 1182 *p = (*p)[:len(*p)-1] 1183 break 1184 } 1185 } 1186} 1187 1188func (p *prioritySlice) max() float64 { 1189 // remove() and max() could be combined, but this is easier to read and 1190 // the expected performance difference from the extra lock and loop is 1191 // almost certainly irrelevant. 1192 maxPri := math.Inf(-1) 1193 for _, pri := range *p { 1194 if pri > maxPri { 1195 maxPri = pri 1196 } 1197 } 1198 return maxPri 1199}