fork of https://github.com/sourcegraph/zoekt
1package main
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha1"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "log"
12 "net/url"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "sort"
17 "strconv"
18 "strings"
19 "time"
20
21 "github.com/sourcegraph/zoekt"
22 "github.com/sourcegraph/zoekt/build"
23 "github.com/sourcegraph/zoekt/ctags"
24
25 sglog "github.com/sourcegraph/log"
26)
27
28const defaultIndexingTimeout = 1*time.Hour + 30*time.Minute
29
30// IndexOptions are the options that Sourcegraph can set via it's search
31// configuration endpoint.
32type IndexOptions struct {
33 // LargeFiles is a slice of glob patterns where matching file paths should
34 // be indexed regardless of their size. The pattern syntax can be found
35 // here: https://golang.org/pkg/path/filepath/#Match.
36 LargeFiles []string
37
38 // Symbols if true will make zoekt index the output of ctags.
39 Symbols bool
40
41 // Branches is a slice of branches to index.
42 Branches []zoekt.RepositoryBranch
43
44 // RepoID is the Sourcegraph Repository ID.
45 RepoID uint32
46
47 // Name is the Repository Name.
48 Name string
49
50 // CloneURL is the internal clone URL for Name.
51 CloneURL string
52
53 // Priority indicates ranking in results, higher first.
54 Priority float64
55
56 // DocumentRanksVersion when non-empty will lead to indexing using offline
57 // ranking. When the string changes this will also cause us to re-index with
58 // new ranks.
59 DocumentRanksVersion string
60
61 // Public is true if the repository is public.
62 Public bool
63
64 // Fork is true if the repository is a fork.
65 Fork bool
66
67 // Archived is true if the repository is archived.
68 Archived bool
69
70 // Map from language to scip-ctags, universal-ctags, or neither
71 LanguageMap ctags.LanguageMap
72
73 // The number of threads to use for indexing shards. Defaults to the number of available
74 // CPUs. If the server flag -cpu_fraction is set, then this value overrides it.
75 ShardConcurrency int32
76}
77
78// indexArgs represents the arguments we pass to zoekt-git-index
79type indexArgs struct {
80 IndexOptions
81
82 // Incremental indicates to skip indexing if already indexed.
83 Incremental bool
84
85 // IndexDir is the index directory to store the shards.
86 IndexDir string
87
88 // Parallelism is the number of shards to compute in parallel.
89 Parallelism int
90
91 // FileLimit is the maximum size of a file
92 FileLimit int
93
94 // UseDelta is true if we want to use the new delta indexer. This should
95 // only be true for repositories we explicitly enable.
96 UseDelta bool
97
98 // DeltaShardNumberFallbackThreshold is an upper limit on the number of preexisting shards that can exist
99 // before attempting a delta build.
100 DeltaShardNumberFallbackThreshold uint64
101
102 // ShardMerging is true if we want zoekt-git-index to respect compound shards.
103 ShardMerging bool
104}
105
106// BuildOptions returns a build.Options represented by indexArgs. Note: it
107// doesn't set fields like repository/branch.
108func (o *indexArgs) BuildOptions() *build.Options {
109 return &build.Options{
110 // It is important that this RepositoryDescription exactly matches what
111 // the indexer we call will produce. This is to ensure that
112 // IncrementalSkipIndexing and IndexState can correctly calculate if
113 // nothing needs to be done.
114 RepositoryDescription: zoekt.Repository{
115 ID: uint32(o.IndexOptions.RepoID),
116 Name: o.Name,
117 Branches: o.Branches,
118 RawConfig: map[string]string{
119 "repoid": strconv.Itoa(int(o.IndexOptions.RepoID)),
120 "priority": strconv.FormatFloat(o.Priority, 'g', -1, 64),
121 "public": marshalBool(o.Public),
122 "fork": marshalBool(o.Fork),
123 "archived": marshalBool(o.Archived),
124 },
125 },
126 IndexDir: o.IndexDir,
127 Parallelism: o.Parallelism,
128 SizeMax: o.FileLimit,
129 LargeFiles: o.LargeFiles,
130 CTagsMustSucceed: o.Symbols,
131 DisableCTags: !o.Symbols,
132 IsDelta: o.UseDelta,
133
134 DocumentRanksVersion: o.DocumentRanksVersion,
135
136 LanguageMap: o.LanguageMap,
137
138 ShardMerging: o.ShardMerging,
139 }
140}
141
142func marshalBool(b bool) string {
143 if b {
144 return "1"
145 }
146 return "0"
147}
148
149func (o *indexArgs) String() string {
150 s := fmt.Sprintf("%d %s", o.RepoID, o.Name)
151 for i, b := range o.Branches {
152 if i == 0 {
153 s = fmt.Sprintf("%s@%s=%s", s, b.Name, b.Version)
154 } else {
155 s = fmt.Sprintf("%s,%s=%s", s, b.Name, b.Version)
156 }
157 }
158 return s
159}
160
161type gitIndexConfig struct {
162 // runCmd is the function that's used to execute all external commands (such as calls to "git" or "zoekt-git-index")
163 // that gitIndex may construct.
164 runCmd func(*exec.Cmd) error
165
166 // findRepositoryMetadata is the function that returns the repository metadata for the
167 // repository specified in args. 'ok' is false if the repository's metadata
168 // couldn't be found or if an error occurred.
169 //
170 // The primary purpose of this configuration option is to be able to provide a stub
171 // implementation for this in our test suite. All other callers should use build.Options.FindRepositoryMetadata().
172 findRepositoryMetadata func(args *indexArgs) (repository *zoekt.Repository, metadata *zoekt.IndexMetadata, ok bool, err error)
173
174 // timeout defines how long the index server waits before killing an indexing job.
175 timeout time.Duration
176}
177
178func gitIndex(c gitIndexConfig, o *indexArgs, sourcegraph Sourcegraph, l sglog.Logger) error {
179 logger := l.Scoped("gitIndex")
180
181 if len(o.Branches) == 0 {
182 return errors.New("zoekt-git-index requires 1 or more branches")
183 }
184
185 if c.runCmd == nil {
186 return errors.New("runCmd in provided configuration was nil - a function must be provided")
187 }
188
189 if c.findRepositoryMetadata == nil {
190 return errors.New("findRepositoryMetadata in provided configuration was nil - a function must be provided")
191 }
192
193 ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
194 defer cancel()
195
196 gitDir, err := tmpGitDir(o.Name)
197 if err != nil {
198 return err
199 }
200 defer os.RemoveAll(gitDir) // best-effort cleanup
201
202 err = fetchRepo(ctx, gitDir, o, c, logger)
203 if err != nil {
204 return err
205 }
206
207 err = setZoektConfig(ctx, gitDir, o, c)
208 if err != nil {
209 return err
210 }
211
212 err = indexRepo(ctx, gitDir, sourcegraph, o, c, logger)
213 if err != nil {
214 return err
215 }
216
217 return nil
218}
219
220func fetchRepo(ctx context.Context, gitDir string, o *indexArgs, c gitIndexConfig, logger sglog.Logger) error {
221 // Create a repo to fetch into
222 cmd := exec.CommandContext(ctx, "git",
223 // use a random default branch. This is so that HEAD isn't a symref to a
224 // branch that is indexed. For example if you are indexing
225 // HEAD,master. Then HEAD would be pointing to master by default.
226 "-c", "init.defaultBranch=nonExistentBranchBB0FOFCH32",
227 "init",
228 // we don't need a working copy
229 "--bare",
230 gitDir)
231 cmd.Stdin = &bytes.Buffer{}
232 if err := c.runCmd(cmd); err != nil {
233 return err
234 }
235
236 var fetchDuration time.Duration
237 successfullyFetchedCommitsCount := 0
238 allFetchesSucceeded := true
239
240 defer func() {
241 success := strconv.FormatBool(allFetchesSucceeded)
242 name := repoNameForMetric(o.Name)
243 metricFetchDuration.WithLabelValues(success, name).Observe(fetchDuration.Seconds())
244 }()
245
246 runFetch := func(branches []zoekt.RepositoryBranch) error {
247 // We shallow fetch each commit specified in zoekt.Branches. This requires
248 // the server to have configured both uploadpack.allowAnySHA1InWant and
249 // uploadpack.allowFilter. (See gitservice.go in the Sourcegraph repository)
250 fetchArgs := []string{
251 "-C", gitDir,
252 "-c", "protocol.version=2",
253 "-c", "http.extraHeader=X-Sourcegraph-Actor-UID: internal",
254 "fetch", "--depth=1", "--no-tags",
255 }
256
257 // If there are no exceptions to MaxFileSize (1MB), we can avoid fetching these large files.
258 if len(o.LargeFiles) == 0 {
259 fetchArgs = append(fetchArgs, "--filter=blob:limit=1m")
260 }
261
262 fetchArgs = append(fetchArgs, o.CloneURL)
263
264 var commits []string
265 for _, b := range branches {
266 commits = append(commits, b.Version)
267 }
268
269 fetchArgs = append(fetchArgs, commits...)
270
271 cmd = exec.CommandContext(ctx, "git", fetchArgs...)
272 cmd.Stdin = &bytes.Buffer{}
273
274 start := time.Now()
275 err := c.runCmd(cmd)
276 fetchDuration += time.Since(start)
277
278 if err != nil {
279 allFetchesSucceeded = false
280 var bs []string
281 for _, b := range branches {
282 bs = append(bs, b.String())
283 }
284
285 formattedBranches := strings.Join(bs, ", ")
286 return fmt.Errorf("fetching %s: %w", formattedBranches, err)
287 }
288
289 successfullyFetchedCommitsCount += len(commits)
290 return nil
291 }
292
293 fetchPriorAndLatestCommits := func() error {
294 prior, err := priorBranches(c, o)
295 if err != nil {
296 return err
297 }
298
299 var allBranches []zoekt.RepositoryBranch
300 allBranches = append(allBranches, o.Branches...)
301 allBranches = append(allBranches, prior...)
302
303 return runFetch(allBranches)
304 }
305
306 fetchOnlyLatestCommits := func() error {
307 return runFetch(o.Branches)
308 }
309
310 if o.UseDelta {
311 err := fetchPriorAndLatestCommits()
312 if err != nil {
313 name := o.BuildOptions().RepositoryDescription.Name
314 id := o.BuildOptions().RepositoryDescription.ID
315
316 log.Printf("delta build: failed to prepare delta build for %q (ID %d): failed to fetch both latest and prior commits: %s", name, id, err)
317 err = fetchOnlyLatestCommits()
318 if err != nil {
319 return err
320 }
321 }
322 } else {
323 err := fetchOnlyLatestCommits()
324 if err != nil {
325 return err
326 }
327 }
328
329 // We then create the relevant refs for each fetched commit.
330 for _, b := range o.Branches {
331 ref := b.Name
332 if ref != "HEAD" {
333 ref = "refs/heads/" + ref
334 }
335 cmd := exec.CommandContext(ctx, "git", "-C", gitDir, "update-ref", ref, b.Version)
336 cmd.Stdin = &bytes.Buffer{}
337 if err := c.runCmd(cmd); err != nil {
338 return fmt.Errorf("failed update-ref %s to %s: %w", ref, b.Version, err)
339 }
340 }
341
342 logger.Debug("successfully fetched git data",
343 sglog.String("repo", o.Name),
344 sglog.Uint32("id", o.RepoID),
345 sglog.Int("commits_count", successfullyFetchedCommitsCount),
346 sglog.Duration("duration", fetchDuration),
347 )
348 return nil
349}
350
351func setZoektConfig(ctx context.Context, gitDir string, o *indexArgs, c gitIndexConfig) error {
352 // create git configuration with options
353 type configKV struct{ Key, Value string }
354 config := []configKV{{
355 // zoekt.name is used by zoekt-git-index to set the repository name.
356 Key: "name",
357 Value: o.Name,
358 }}
359 for k, v := range o.BuildOptions().RepositoryDescription.RawConfig {
360 config = append(config, configKV{Key: k, Value: v})
361 }
362 sort.Slice(config, func(i, j int) bool {
363 return config[i].Key < config[j].Key
364 })
365
366 // write git configuration to repo
367 for _, kv := range config {
368 cmd := exec.CommandContext(ctx, "git", "-C", gitDir, "config", "zoekt."+kv.Key, kv.Value)
369 cmd.Stdin = &bytes.Buffer{}
370 if err := c.runCmd(cmd); err != nil {
371 return err
372 }
373 }
374 return nil
375}
376
377func indexRepo(ctx context.Context, gitDir string, sourcegraph Sourcegraph, o *indexArgs, c gitIndexConfig, logger sglog.Logger) error {
378 args := []string{
379 "-submodules=false",
380 }
381
382 if o.DocumentRanksVersion != "" {
383 // We store the document ranks as JSON in gitDir and tell zoekt-git-index where
384 // to find the file.
385 documentsRankFile := filepath.Join(gitDir, "documents.rank")
386
387 saveDocumentRanks := func() error {
388 r, err := sourcegraph.GetDocumentRanks(context.Background(), o.Name)
389 if err != nil {
390 return fmt.Errorf("GetDocumentRanks: %w", err)
391 }
392
393 b, err := json.Marshal(r)
394 if err != nil {
395 return err
396 }
397
398 if err := os.WriteFile(documentsRankFile, b, 0o600); err != nil {
399 return fmt.Errorf("failed to write %s to disk: %w", documentsRankFile, err)
400 }
401
402 return nil
403 }
404
405 if err := saveDocumentRanks(); err != nil {
406 // log and fall back to online ranking
407 logger.Warn(
408 "error saving document ranks. Falling back to online ranking",
409 sglog.Error(err),
410 sglog.String("repo", o.Name),
411 sglog.Uint32("id", o.RepoID),
412 )
413 } else {
414 args = append(args,
415 "-offline_ranking", documentsRankFile,
416 "-offline_ranking_version", o.DocumentRanksVersion)
417 }
418 }
419
420 // Even though we check for incremental in this process, we still pass it
421 // in just in case we regress in how we check in process. We will still
422 // notice thanks to metrics and increased load on gitserver.
423 if o.Incremental {
424 args = append(args, "-incremental")
425 }
426
427 var branches []string
428 for _, b := range o.Branches {
429 branches = append(branches, b.Name)
430 }
431 args = append(args, "-branches", strings.Join(branches, ","))
432
433 if o.UseDelta {
434 args = append(args, "-delta")
435 args = append(args, "-delta_threshold", strconv.FormatUint(o.DeltaShardNumberFallbackThreshold, 10))
436 }
437
438 if len(o.LanguageMap) > 0 {
439 var languageMap []string
440 for language, parser := range o.LanguageMap {
441 languageMap = append(languageMap, language+":"+ctags.ParserToString(parser))
442 }
443 args = append(args, "-language_map", strings.Join(languageMap, ","))
444 }
445
446 args = append(args, o.BuildOptions().Args()...)
447 args = append(args, gitDir)
448
449 cmd := exec.CommandContext(ctx, "zoekt-git-index", args...)
450 cmd.Stdin = &bytes.Buffer{}
451 if err := c.runCmd(cmd); err != nil {
452 return err
453 }
454 return nil
455}
456
457func priorBranches(c gitIndexConfig, o *indexArgs) ([]zoekt.RepositoryBranch, error) {
458 existingRepository, _, found, err := c.findRepositoryMetadata(o)
459 if err != nil {
460 return nil, fmt.Errorf("loading repository metadata: %w", err)
461 }
462
463 if !found || len(existingRepository.Branches) == 0 {
464 return nil, fmt.Errorf("no prior shards found")
465 }
466
467 return existingRepository.Branches, nil
468}
469
470func tmpGitDir(name string) (string, error) {
471 abs := url.QueryEscape(name)
472 if len(abs) > 200 {
473 h := sha1.New()
474 _, _ = io.WriteString(h, abs)
475 abs = abs[:200] + fmt.Sprintf("%x", h.Sum(nil))[:8]
476 }
477 dir := filepath.Join(os.TempDir(), abs+".git")
478 if _, err := os.Stat(dir); err == nil {
479 if err := os.RemoveAll(dir); err != nil {
480 return "", err
481 }
482 }
483 return dir, nil
484}