forked from sourcegraph/zoekt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1632 lines (1378 loc) · 49.2 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Command zoekt-sourcegraph-indexserver periodically reindexes enabled
// repositories on sourcegraph
package main
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"io"
"io/fs"
"log"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"text/tabwriter"
"time"
grpcprom "github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/retry"
"github.com/peterbourgon/ff/v3/ffcli"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
sglog "github.com/sourcegraph/log"
"github.com/sourcegraph/mountinfo"
"go.uber.org/automaxprocs/maxprocs"
"golang.org/x/net/trace"
"golang.org/x/sys/unix"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"github.com/sourcegraph/zoekt"
"github.com/sourcegraph/zoekt/build"
proto "github.com/sourcegraph/zoekt/cmd/zoekt-sourcegraph-indexserver/protos/sourcegraph/zoekt/configuration/v1"
"github.com/sourcegraph/zoekt/debugserver"
"github.com/sourcegraph/zoekt/grpc/internalerrs"
"github.com/sourcegraph/zoekt/grpc/messagesize"
"github.com/sourcegraph/zoekt/internal/profiler"
)
var (
metricResolveRevisionsDuration = promauto.NewHistogram(prometheus.HistogramOpts{
Name: "resolve_revisions_seconds",
Help: "A histogram of latencies for resolving all repository revisions.",
Buckets: prometheus.ExponentialBuckets(1, 10, 6), // 1s -> 27min
})
metricResolveRevisionDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "resolve_revision_seconds",
Help: "A histogram of latencies for resolving a repository revision.",
Buckets: prometheus.ExponentialBuckets(.25, 2, 4), // 250ms -> 2s
}, []string{"success"}) // success=true|false
metricGetIndexOptions = promauto.NewCounter(prometheus.CounterOpts{
Name: "get_index_options_total",
Help: "The total number of times we tried to get index options for a repository. Includes errors.",
})
metricGetIndexOptionsError = promauto.NewCounter(prometheus.CounterOpts{
Name: "get_index_options_error_total",
Help: "The total number of times we failed to get index options for a repository.",
})
metricIndexDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "index_repo_seconds",
Help: "A histogram of latencies for indexing a repository.",
Buckets: prometheus.ExponentialBucketsRange(
(100 * time.Millisecond).Seconds(),
(40*time.Minute + defaultIndexingTimeout).Seconds(), // add an extra 40 minutes to account for the time it takes to clone the repo
20),
}, []string{
"state", // state is an indexState
"name", // name of the repository that was indexed
})
metricFetchDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "index_fetch_seconds",
Help: "A histogram of latencies for fetching a repository.",
Buckets: []float64{.05, .1, .25, .5, 1, 2.5, 5, 10, 20, 30, 60, 180, 300, 600}, // 50ms -> 10 minutes
}, []string{
"success", // true|false
"name", // the name of the repository that the commits were fetched from
})
metricIndexIncrementalIndexState = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "index_incremental_index_state",
Help: "A count of the state on disk vs what we want to build. See zoekt/build.IndexState.",
}, []string{"state"}) // state is build.IndexState
metricNumIndexed = promauto.NewGauge(prometheus.GaugeOpts{
Name: "index_num_indexed",
Help: "Number of indexed repos by code host",
})
metricFailingTotal = promauto.NewCounter(prometheus.CounterOpts{
Name: "index_failing_total",
Help: "Counts failures to index (indexing activity, should be used with rate())",
})
metricIndexingTotal = promauto.NewCounter(prometheus.CounterOpts{
Name: "index_indexing_total",
Help: "Counts indexings (indexing activity, should be used with rate())",
})
metricNumStoppedTrackingTotal = promauto.NewCounter(prometheus.CounterOpts{
Name: "index_num_stopped_tracking_total",
Help: "Counts the number of repos we stopped tracking.",
})
clientMetricsOnce sync.Once
clientMetrics *grpcprom.ClientMetrics
)
// set of repositories that we want to capture separate indexing metrics for
var reposWithSeparateIndexingMetrics = make(map[string]struct{})
type indexState string
const (
indexStateFail indexState = "fail"
indexStateSuccess indexState = "success"
indexStateSuccessMeta indexState = "success_meta" // We only updated metadata
indexStateNoop indexState = "noop" // We didn't need to update index
indexStateEmpty indexState = "empty" // index is empty (empty repo)
)
// Server is the main functionality of zoekt-sourcegraph-indexserver. It
// exists to conveniently use all the options passed in via func main.
type Server struct {
logger sglog.Logger
Sourcegraph Sourcegraph
BatchSize int
// IndexDir is the index directory to use.
IndexDir string
// IndexConcurrency is the number of repositories we index at once.
IndexConcurrency int
// Interval is how often we sync with Sourcegraph.
Interval time.Duration
// CPUCount is the number of CPUs to use for indexing shards.
CPUCount int
queue Queue
// muIndexDir protects the index directory from concurrent access.
muIndexDir indexMutex
// If true, shard merging is enabled.
shardMerging bool
// deltaBuildRepositoriesAllowList is an allowlist for repositories that we
// use delta-builds for instead of normal builds
deltaBuildRepositoriesAllowList map[string]struct{}
// deltaShardNumberFallbackThreshold is an upper limit on the number of preexisting shards that can exist
// before attempting a delta build.
deltaShardNumberFallbackThreshold uint64
// repositoriesSkipSymbolsCalculationAllowList is an allowlist for repositories that
// we skip calculating symbols metadata for during builds
repositoriesSkipSymbolsCalculationAllowList map[string]struct{}
hostname string
mergeOpts mergeOpts
// timeout defines how long the index server waits before killing an indexing job.
timeout time.Duration
}
var debug = log.New(io.Discard, "", log.LstdFlags)
// our index commands should output something every 100mb they process.
//
// 2020-11-24 Keegan. "This should be rather quick so 5m is more than enough
// time." famous last words. A client was indexing a monorepo with 42
// cores... 5m was not enough.
const noOutputTimeout = 30 * time.Minute
func (s *Server) loggedRun(tr trace.Trace, cmd *exec.Cmd) (err error) {
out := &synchronizedBuffer{}
cmd.Stdout = out
cmd.Stderr = out
tr.LazyPrintf("%s", cmd.Args)
defer func() {
if err != nil {
outS := out.String()
tr.LazyPrintf("failed: %v", err)
tr.LazyPrintf("output: %s", out)
tr.SetError()
err = fmt.Errorf("command %s failed: %v\nOUT: %s", cmd.Args, err, outS)
}
}()
s.logger.Debug("logged run", sglog.Strings("args", cmd.Args))
if err := cmd.Start(); err != nil {
return err
}
errC := make(chan error)
go func() {
errC <- cmd.Wait()
}()
// This channel is set after we have sent sigquit. It allows us to follow up
// with a sigkill if the process doesn't quit after sigquit.
kill := make(<-chan time.Time)
lastLen := 0
for {
select {
case <-time.After(noOutputTimeout):
// Periodically check if we have had output. If not kill the process.
if out.Len() != lastLen {
lastLen = out.Len()
log.Printf("still running %s", cmd.Args)
} else {
// Send quit (C-\) first so we get a stack dump.
log.Printf("no output for %s, quitting %s", noOutputTimeout, cmd.Args)
if err := cmd.Process.Signal(unix.SIGQUIT); err != nil {
log.Println("quit failed:", err)
}
// send sigkill if still running in 10s
kill = time.After(10 * time.Second)
}
case <-kill:
log.Printf("still running, killing %s", cmd.Args)
if err := cmd.Process.Kill(); err != nil {
log.Println("kill failed:", err)
}
case err := <-errC:
if err != nil {
return err
}
tr.LazyPrintf("success")
return nil
}
}
}
// synchronizedBuffer wraps a strings.Builder with a mutex. Used so we can
// monitor the buffer while it is being written to.
type synchronizedBuffer struct {
mu sync.Mutex
b bytes.Buffer
}
func (sb *synchronizedBuffer) Write(p []byte) (int, error) {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.b.Write(p)
}
func (sb *synchronizedBuffer) Len() int {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.b.Len()
}
func (sb *synchronizedBuffer) String() string {
sb.mu.Lock()
defer sb.mu.Unlock()
return sb.b.String()
}
// pauseFileName if present in IndexDir will stop index jobs from
// running. This is to make it possible to experiment with the content of the
// IndexDir without the indexserver writing to it.
const pauseFileName = "PAUSE"
// Run the sync loop. This blocks forever.
func (s *Server) Run() {
removeIncompleteShards(s.IndexDir)
// Start a goroutine which updates the queue with commits to index.
go func() {
// We update the list of indexed repos every Interval. To speed up manual
// testing we also listen for SIGUSR1 to trigger updates.
//
// "pkill -SIGUSR1 zoekt-sourcegra"
for range jitterTicker(s.Interval, unix.SIGUSR1) {
if b, err := os.ReadFile(filepath.Join(s.IndexDir, pauseFileName)); err == nil {
log.Printf("indexserver manually paused via PAUSE file: %s", string(bytes.TrimSpace(b)))
continue
}
repos, err := s.Sourcegraph.List(context.Background(), listIndexed(s.IndexDir))
if err != nil {
log.Printf("error listing repos: %s", err)
continue
}
debug.Printf("updating index queue with %d repositories", len(repos.IDs))
// Stop indexing repos we don't need to track anymore
removed := s.queue.MaybeRemoveMissing(repos.IDs)
metricNumStoppedTrackingTotal.Add(float64(len(removed)))
if len(removed) > 0 {
log.Printf("stopped tracking %d repositories: %s", len(removed), formatListUint32(removed, 5))
}
cleanupDone := make(chan struct{})
go func() {
defer close(cleanupDone)
s.muIndexDir.Global(func() {
cleanup(s.IndexDir, repos.IDs, time.Now(), s.shardMerging)
})
}()
repos.IterateIndexOptions(s.queue.AddOrUpdate)
// IterateIndexOptions will only iterate over repositories that have
// changed since we last called list. However, we want to add all IDs
// back onto the queue just to check that what is on disk is still
// correct. This will use the last IndexOptions we stored in the
// queue. The repositories not on the queue (missing) need a forced
// fetch of IndexOptions.
missing := s.queue.Bump(repos.IDs)
s.Sourcegraph.ForceIterateIndexOptions(s.queue.AddOrUpdate, func(uint32, error) {}, missing...)
setCompoundShardCounter(s.IndexDir)
<-cleanupDone
}
}()
go func() {
for range jitterTicker(s.mergeOpts.vacuumInterval, unix.SIGUSR1) {
if s.shardMerging {
s.vacuum()
}
}
}()
go func() {
for range jitterTicker(s.mergeOpts.mergeInterval, unix.SIGUSR1) {
if s.shardMerging {
s.doMerge()
}
}
}()
for i := 0; i < s.IndexConcurrency; i++ {
go s.processQueue()
}
// block forever
select {}
}
// formatList returns a comma-separated list of the first min(len(v), m) items.
func formatListUint32(v []uint32, m int) string {
if len(v) < m {
m = len(v)
}
sb := strings.Builder{}
for i := 0; i < m; i++ {
fmt.Fprintf(&sb, "%d, ", v[i])
}
if len(v) > m {
sb.WriteString("...")
}
return strings.TrimRight(sb.String(), ", ")
}
func (s *Server) processQueue() {
for {
if _, err := os.Stat(filepath.Join(s.IndexDir, pauseFileName)); err == nil {
time.Sleep(time.Second)
continue
}
opts, ok := s.queue.Pop()
if !ok {
time.Sleep(time.Second)
continue
}
args := s.indexArgs(opts)
ran := s.muIndexDir.With(opts.Name, func() {
// only record time taken once we hold the lock. This avoids us
// recording time taken while merging/cleanup runs.
start := time.Now()
state, err := s.Index(args)
elapsed := time.Since(start)
metricIndexDuration.WithLabelValues(string(state), repoNameForMetric(opts.Name)).Observe(elapsed.Seconds())
if err != nil {
log.Printf("error indexing %s: %s", args.String(), err)
}
switch state {
case indexStateSuccess:
var branches []string
for _, b := range args.Branches {
branches = append(branches, fmt.Sprintf("%s=%s", b.Name, b.Version))
}
s.logger.Info("updated index",
sglog.String("repo", args.Name),
sglog.Uint32("id", args.RepoID),
sglog.Strings("branches", branches),
sglog.Duration("duration", elapsed),
)
case indexStateSuccessMeta:
log.Printf("updated meta %s in %v", args.String(), elapsed)
}
s.queue.SetIndexed(opts, state)
})
if !ran {
// Someone else is processing the repository. We can just skip this job
// since the repository will be added back to the queue and we will
// converge to the correct behaviour.
debug.Printf("index job for repository already running: %s", args)
continue
}
}
}
// repoNameForMetric returns a normalized version of the given repository name that is
// suitable for use with Prometheus metrics.
func repoNameForMetric(repo string) string {
// Check to see if we want to be able to capture separate indexing metrics for this repository.
// If we don't, set to a default string to keep the cardinality for the Prometheus metric manageable.
if _, ok := reposWithSeparateIndexingMetrics[repo]; ok {
return repo
}
return ""
}
func batched(slice []uint32, size int) <-chan []uint32 {
c := make(chan []uint32)
go func() {
for len(slice) > 0 {
if size > len(slice) {
size = len(slice)
}
c <- slice[:size]
slice = slice[size:]
}
close(c)
}()
return c
}
// jitterTicker returns a ticker which ticks with a jitter. Each tick is
// uniformly selected from the range (d/2, d + d/2). It will tick on creation.
//
// sig is a list of signals which also cause the ticker to fire. This is a
// convenience to allow manually triggering of the ticker.
func jitterTicker(d time.Duration, sig ...os.Signal) <-chan struct{} {
ticker := make(chan struct{})
go func() {
for {
ticker <- struct{}{}
ns := int64(d)
jitter := rand.Int63n(ns)
time.Sleep(time.Duration(ns/2 + jitter))
}
}()
go func() {
if len(sig) == 0 {
return
}
c := make(chan os.Signal, 1)
signal.Notify(c, sig...)
for range c {
ticker <- struct{}{}
}
}()
return ticker
}
// Index starts an index job for repo name at commit.
func (s *Server) Index(args *indexArgs) (state indexState, err error) {
tr := trace.New("index", args.Name)
defer func() {
if err != nil {
tr.SetError()
tr.LazyPrintf("error: %v", err)
state = indexStateFail
metricFailingTotal.Inc()
}
tr.LazyPrintf("state: %s", state)
tr.Finish()
}()
tr.LazyPrintf("branches: %v", args.Branches)
if len(args.Branches) == 0 {
return indexStateEmpty, createEmptyShard(args)
}
repositoryName := args.Name
if _, ok := s.deltaBuildRepositoriesAllowList[repositoryName]; ok {
tr.LazyPrintf("marking this repository for delta build")
args.UseDelta = true
}
args.DeltaShardNumberFallbackThreshold = s.deltaShardNumberFallbackThreshold
if _, ok := s.repositoriesSkipSymbolsCalculationAllowList[repositoryName]; ok {
tr.LazyPrintf("skipping symbols calculation")
args.Symbols = false
}
reason := "forced"
if args.Incremental {
bo := args.BuildOptions()
bo.SetDefaults()
incrementalState, fn := bo.IndexState()
reason = string(incrementalState)
metricIndexIncrementalIndexState.WithLabelValues(string(incrementalState)).Inc()
switch incrementalState {
case build.IndexStateEqual:
debug.Printf("%s index already up to date. Shard=%s", args.String(), fn)
return indexStateNoop, nil
case build.IndexStateMeta:
log.Printf("updating index.meta %s", args.String())
if err := mergeMeta(bo); err != nil {
log.Printf("falling back to full update: failed to update index.meta %s: %s", args.String(), err)
} else {
return indexStateSuccessMeta, nil
}
case build.IndexStateCorrupt:
log.Printf("falling back to full update: corrupt index: %s", args.String())
}
}
log.Printf("updating index %s reason=%s", args.String(), reason)
metricIndexingTotal.Inc()
c := gitIndexConfig{
runCmd: func(cmd *exec.Cmd) error {
return s.loggedRun(tr, cmd)
},
findRepositoryMetadata: func(args *indexArgs) (repository *zoekt.Repository, metadata *zoekt.IndexMetadata, ok bool, err error) {
return args.BuildOptions().FindRepositoryMetadata()
},
timeout: s.timeout,
}
err = gitIndex(c, args, s.Sourcegraph, s.logger)
if err != nil {
return indexStateFail, err
}
if err := updateIndexStatusOnSourcegraph(c, args, s.Sourcegraph); err != nil {
s.logger.Error("failed to update index status",
sglog.String("repo", args.Name),
sglog.Uint32("id", args.RepoID),
sglogBranches("branches", args.Branches),
sglog.Error(err),
)
}
return indexStateSuccess, nil
}
// updateIndexStatusOnSourcegraph pushes the current state to sourcegraph so
// it can update the zoekt_repos table.
func updateIndexStatusOnSourcegraph(c gitIndexConfig, args *indexArgs, sg Sourcegraph) error {
// We need to read from disk for IndexTime.
_, metadata, ok, err := c.findRepositoryMetadata(args)
if err != nil {
return fmt.Errorf("failed to read metadata for new/updated index: %w", err)
}
if !ok {
return errors.New("failed to find metadata for new/updated index")
}
status := []indexStatus{{
RepoID: args.RepoID,
Branches: args.Branches,
IndexTimeUnix: metadata.IndexTime.Unix(),
}}
if err := sg.UpdateIndexStatus(status); err != nil {
return fmt.Errorf("failed to update sourcegraph with status: %w", err)
}
return nil
}
func sglogBranches(key string, branches []zoekt.RepositoryBranch) sglog.Field {
ss := make([]string, len(branches))
for i, b := range branches {
ss[i] = fmt.Sprintf("%s=%s", b.Name, b.Version)
}
return sglog.Strings(key, ss)
}
func (s *Server) indexArgs(opts IndexOptions) *indexArgs {
parallelism := s.parallelism(opts, runtime.GOMAXPROCS(0))
return &indexArgs{
IndexOptions: opts,
IndexDir: s.IndexDir,
Parallelism: parallelism,
Incremental: true,
// 1 MB; match https://sourcegraph.sgdev.org/github.com/sourcegraph/sourcegraph/-/blob/cmd/symbols/internal/symbols/search.go#L22
FileLimit: 1 << 20,
}
}
// parallelism consults both the server flags and index options to determine the number
// of shards to index in parallel. If the CPUCount index option is provided, it always
// overrides the server flag.
func (s *Server) parallelism(opts IndexOptions, maxProcs int) int {
var parallelism int
if opts.ShardConcurrency > 0 {
parallelism = int(opts.ShardConcurrency)
} else {
parallelism = s.CPUCount
}
// In case this was accidentally misconfigured, we cap the threads at 4 times the available CPUs
if parallelism > 4*maxProcs {
parallelism = 4 * maxProcs
}
// If index concurrency is set, then divide the parallelism by the number of
// repos we're indexing in parallel
if s.IndexConcurrency > 1 {
parallelism = int(math.Ceil(float64(parallelism) / float64(s.IndexConcurrency)))
}
return parallelism
}
func createEmptyShard(args *indexArgs) error {
bo := args.BuildOptions()
bo.SetDefaults()
bo.RepositoryDescription.Branches = []zoekt.RepositoryBranch{{Name: "HEAD", Version: "404aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}
if args.Incremental && bo.IncrementalSkipIndexing() {
return nil
}
builder, err := build.NewBuilder(*bo)
if err != nil {
return err
}
return builder.Finish()
}
// addDebugHandlers adds handlers specific to indexserver.
func (s *Server) addDebugHandlers(mux *http.ServeMux) {
// Sourcegraph's site admin view requires indexserver to serve it's admin view
// on "/".
mux.Handle("/", http.HandlerFunc(s.handleRoot))
mux.Handle("/debug/reindex", http.HandlerFunc(s.handleReindex))
mux.Handle("/debug/indexed", http.HandlerFunc(s.handleDebugIndexed))
mux.Handle("/debug/list", http.HandlerFunc(s.handleDebugList))
mux.Handle("/debug/merge", http.HandlerFunc(s.handleDebugMerge))
mux.Handle("/debug/queue", http.HandlerFunc(s.queue.handleDebugQueue))
mux.Handle("/debug/host", http.HandlerFunc(s.handleHost))
}
func (s *Server) handleHost(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.Header().Set("Allow", "GET")
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
response := struct {
Hostname string
}{
Hostname: s.hostname,
}
b, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Write(b)
}
var rootTmpl = template.Must(template.New("name").Parse(`
<html>
<body>
<a href="debug">Debug</a><br />
<a href="debug/requests">Traces</a><br />
{{.IndexMsg}}<br />
<br />
<h3>Reindex</h3>
{{if .Repos}}
<a href="?show_repos=false">hide repos</a><br />
<table style="margin-top: 20px">
<th style="text-align:left">Name</th>
<th style="text-align:left">ID</th>
{{range .Repos}}
<tr>
<td>{{.Name}}</td>
<td><a href="?id={{.ID}}&show_repos=true">{{.ID}}</a></id>
</tr>
{{end}}
</table>
{{else}}
<a href="?show_repos=true">show repos</a><br />
{{end}}
</body>
</html>
`))
func (s *Server) handleRoot(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.Header().Set("Allow", "GET")
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
values := r.URL.Query()
// ?id=
indexMsg := ""
if v := values.Get("id"); v != "" {
id, err := strconv.Atoi(v)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
indexMsg, _ = s.forceIndex(uint32(id))
}
// ?show_repos=
showRepos := false
if v := values.Get("show_repos"); v != "" {
showRepos, _ = strconv.ParseBool(v)
}
type Repo struct {
ID uint32
Name string
}
var data struct {
Repos []Repo
IndexMsg string
}
data.IndexMsg = indexMsg
if showRepos {
s.queue.Iterate(func(opts *IndexOptions) {
data.Repos = append(data.Repos, Repo{
ID: opts.RepoID,
Name: opts.Name,
})
})
sort.Slice(data.Repos, func(i, j int) bool { return data.Repos[i].Name < data.Repos[j].Name })
}
_ = rootTmpl.Execute(w, data)
}
// handleReindex triggers a reindex asynocronously. If a reindex was triggered
// the request returns with status 202. The caller can infer the new state of
// the index by calling List.
func (s *Server) handleReindex(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
id, err := strconv.Atoi(r.Form.Get("repo"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
go func() { s.forceIndex(uint32(id)) }()
// 202 Accepted
w.WriteHeader(http.StatusAccepted)
}
func (s *Server) handleDebugList(w http.ResponseWriter, r *http.Request) {
withIndexed := true
if b, err := strconv.ParseBool(r.URL.Query().Get("indexed")); err == nil {
withIndexed = b
}
var indexed []uint32
if withIndexed {
indexed = listIndexed(s.IndexDir)
}
repos, err := s.Sourcegraph.List(r.Context(), indexed)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
bw := bytes.Buffer{}
tw := tabwriter.NewWriter(&bw, 16, 8, 4, ' ', 0)
_, err = fmt.Fprintf(tw, "ID\tName\n")
if err != nil {
http.Error(w, fmt.Sprintf("writing column headers: %s", err), http.StatusInternalServerError)
return
}
s.queue.mu.Lock()
name := ""
for _, id := range repos.IDs {
if item := s.queue.get(id); item != nil {
name = item.opts.Name
} else {
name = ""
}
_, err = fmt.Fprintf(tw, "%d\t%s\n", id, name)
if err != nil {
debug.Printf("handleDebugList: %s\n", err.Error())
}
}
s.queue.mu.Unlock()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tw.Flush()
if err != nil {
http.Error(w, fmt.Sprintf("flushing tabwriter: %s", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Length", strconv.Itoa(bw.Len()))
if _, err := io.Copy(w, &bw); err != nil {
http.Error(w, fmt.Sprintf("copying output to response writer: %s", err), http.StatusInternalServerError)
return
}
}
// handleDebugMerge triggers a merge even if shard merging is not enabled. Users
// can run this command during periods of low usage (evenings, weekends) to
// trigger an initial merge run. In the steady-state, merges happen rarely, even
// on busy instances, and users can rely on automatic merging instead.
func (s *Server) handleDebugMerge(w http.ResponseWriter, _ *http.Request) {
// A merge operation can take very long, depending on the number merges and the
// target size of the compound shards. We run the merge in the background and
// return immediately to the user.
//
// We track the status of the merge with metricShardMergingRunning.
go func() {
s.doMerge()
}()
_, _ = w.Write([]byte("merging enqueued\n"))
}
func (s *Server) handleDebugIndexed(w http.ResponseWriter, r *http.Request) {
indexed := listIndexed(s.IndexDir)
bw := bytes.Buffer{}
tw := tabwriter.NewWriter(&bw, 16, 8, 4, ' ', 0)
_, err := fmt.Fprintf(tw, "ID\tName\n")
if err != nil {
http.Error(w, fmt.Sprintf("writing column headers: %s", err), http.StatusInternalServerError)
return
}
s.queue.mu.Lock()
name := ""
for _, id := range indexed {
if item := s.queue.get(id); item != nil {
name = item.opts.Name
} else {
name = ""
}
_, err = fmt.Fprintf(tw, "%d\t%s\n", id, name)
if err != nil {
debug.Printf("handleDebugIndexed: %s\n", err.Error())
}
}
s.queue.mu.Unlock()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tw.Flush()
if err != nil {
http.Error(w, fmt.Sprintf("flushing tabwriter: %s", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Length", strconv.Itoa(bw.Len()))
if _, err := io.Copy(w, &bw); err != nil {
http.Error(w, fmt.Sprintf("copying output to response writer: %s", err), http.StatusInternalServerError)
return
}
}
// forceIndex will run the index job for repo name now. It will return always
// return a string explaining what it did, even if it failed.
func (s *Server) forceIndex(id uint32) (string, error) {
var opts IndexOptions
var err error
s.Sourcegraph.ForceIterateIndexOptions(func(o IndexOptions) {
opts = o
}, func(_ uint32, e error) {
err = e
}, id)
if err != nil {
return fmt.Sprintf("Indexing %d failed: %v", id, err), err
}
args := s.indexArgs(opts)
args.Incremental = false // force re-index
var state indexState
ran := s.muIndexDir.With(opts.Name, func() {
state, err = s.Index(args)
})
if !ran {
return fmt.Sprintf("index job for repository already running: %s", args), nil
}
if err != nil {
return fmt.Sprintf("Indexing %s failed: %s", args.String(), err), err
}
return fmt.Sprintf("Indexed %s with state %s", args.String(), state), nil
}
func listIndexed(indexDir string) []uint32 {
index := getShards(indexDir)
metricNumIndexed.Set(float64(len(index)))
repoIDs := make([]uint32, 0, len(index))
for id := range index {
repoIDs = append(repoIDs, id)
}
sort.Slice(repoIDs, func(i, j int) bool {
return repoIDs[i] < repoIDs[j]
})
return repoIDs
}