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 // Calculate repo rank based on the latest commit date.
125 "latestCommitDate": "1",
126 },
127 },
128 IndexDir: o.IndexDir,
129 Parallelism: o.Parallelism,
130 SizeMax: o.FileLimit,
131 LargeFiles: o.LargeFiles,
132 CTagsMustSucceed: o.Symbols,
133 DisableCTags: !o.Symbols,
134 IsDelta: o.UseDelta,
135
136 DocumentRanksVersion: o.DocumentRanksVersion,
137
138 LanguageMap: o.LanguageMap,
139
140 ShardMerging: o.ShardMerging,
141 }
142}
143
144func marshalBool(b bool) string {
145 if b {
146 return "1"
147 }
148 return "0"
149}
150
151func (o *indexArgs) String() string {
152 s := fmt.Sprintf("%d %s", o.RepoID, o.Name)
153 for i, b := range o.Branches {
154 if i == 0 {
155 s = fmt.Sprintf("%s@%s=%s", s, b.Name, b.Version)
156 } else {
157 s = fmt.Sprintf("%s,%s=%s", s, b.Name, b.Version)
158 }
159 }
160 return s
161}
162
163type gitIndexConfig struct {
164 // runCmd is the function that's used to execute all external commands (such as calls to "git" or "zoekt-git-index")
165 // that gitIndex may construct.
166 runCmd func(*exec.Cmd) error
167
168 // findRepositoryMetadata is the function that returns the repository metadata for the
169 // repository specified in args. 'ok' is false if the repository's metadata
170 // couldn't be found or if an error occurred.
171 //
172 // The primary purpose of this configuration option is to be able to provide a stub
173 // implementation for this in our test suite. All other callers should use build.Options.FindRepositoryMetadata().
174 findRepositoryMetadata func(args *indexArgs) (repository *zoekt.Repository, metadata *zoekt.IndexMetadata, ok bool, err error)
175
176 // timeout defines how long the index server waits before killing an indexing job.
177 timeout time.Duration
178}
179
180func gitIndex(c gitIndexConfig, o *indexArgs, sourcegraph Sourcegraph, l sglog.Logger) error {
181 logger := l.Scoped("gitIndex")
182
183 if len(o.Branches) == 0 {
184 return errors.New("zoekt-git-index requires 1 or more branches")
185 }
186
187 if c.runCmd == nil {
188 return errors.New("runCmd in provided configuration was nil - a function must be provided")
189 }
190
191 if c.findRepositoryMetadata == nil {
192 return errors.New("findRepositoryMetadata in provided configuration was nil - a function must be provided")
193 }
194
195 ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
196 defer cancel()
197
198 gitDir, err := tmpGitDir(o.Name)
199 if err != nil {
200 return err
201 }
202 defer os.RemoveAll(gitDir) // best-effort cleanup
203
204 err = fetchRepo(ctx, gitDir, o, c, logger)
205 if err != nil {
206 return err
207 }
208
209 err = setZoektConfig(ctx, gitDir, o, c)
210 if err != nil {
211 return err
212 }
213
214 err = indexRepo(ctx, gitDir, sourcegraph, o, c, logger)
215 if err != nil {
216 return err
217 }
218
219 return nil
220}
221
222func fetchRepo(ctx context.Context, gitDir string, o *indexArgs, c gitIndexConfig, logger sglog.Logger) error {
223 // Create a repo to fetch into
224 cmd := exec.CommandContext(ctx, "git",
225 // use a random default branch. This is so that HEAD isn't a symref to a
226 // branch that is indexed. For example if you are indexing
227 // HEAD,master. Then HEAD would be pointing to master by default.
228 "-c", "init.defaultBranch=nonExistentBranchBB0FOFCH32",
229 "init",
230 // we don't need a working copy
231 "--bare",
232 gitDir)
233 cmd.Stdin = &bytes.Buffer{}
234 if err := c.runCmd(cmd); err != nil {
235 return err
236 }
237
238 var fetchDuration time.Duration
239 successfullyFetchedCommitsCount := 0
240 allFetchesSucceeded := true
241
242 defer func() {
243 success := strconv.FormatBool(allFetchesSucceeded)
244 name := repoNameForMetric(o.Name)
245 metricFetchDuration.WithLabelValues(success, name).Observe(fetchDuration.Seconds())
246 }()
247
248 runFetch := func(branches []zoekt.RepositoryBranch) error {
249 // We shallow fetch each commit specified in zoekt.Branches. This requires
250 // the server to have configured both uploadpack.allowAnySHA1InWant and
251 // uploadpack.allowFilter. (See gitservice.go in the Sourcegraph repository)
252 fetchArgs := []string{
253 "-C", gitDir,
254 "-c", "protocol.version=2",
255 "-c", "http.extraHeader=X-Sourcegraph-Actor-UID: internal",
256 "fetch", "--depth=1", "--no-tags",
257 }
258
259 // If there are no exceptions to MaxFileSize (1MB), we can avoid fetching these large files.
260 if len(o.LargeFiles) == 0 {
261 fetchArgs = append(fetchArgs, "--filter=blob:limit=1m")
262 }
263
264 fetchArgs = append(fetchArgs, o.CloneURL)
265
266 var commits []string
267 for _, b := range branches {
268 commits = append(commits, b.Version)
269 }
270
271 fetchArgs = append(fetchArgs, commits...)
272
273 cmd = exec.CommandContext(ctx, "git", fetchArgs...)
274 cmd.Stdin = &bytes.Buffer{}
275
276 start := time.Now()
277 err := c.runCmd(cmd)
278 fetchDuration += time.Since(start)
279
280 if err != nil {
281 allFetchesSucceeded = false
282 var bs []string
283 for _, b := range branches {
284 bs = append(bs, b.String())
285 }
286
287 formattedBranches := strings.Join(bs, ", ")
288 return fmt.Errorf("fetching %s: %w", formattedBranches, err)
289 }
290
291 successfullyFetchedCommitsCount += len(commits)
292 return nil
293 }
294
295 fetchPriorAndLatestCommits := func() error {
296 prior, err := priorBranches(c, o)
297 if err != nil {
298 return err
299 }
300
301 var allBranches []zoekt.RepositoryBranch
302 allBranches = append(allBranches, o.Branches...)
303 allBranches = append(allBranches, prior...)
304
305 return runFetch(allBranches)
306 }
307
308 fetchOnlyLatestCommits := func() error {
309 return runFetch(o.Branches)
310 }
311
312 if o.UseDelta {
313 err := fetchPriorAndLatestCommits()
314 if err != nil {
315 name := o.BuildOptions().RepositoryDescription.Name
316 id := o.BuildOptions().RepositoryDescription.ID
317
318 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)
319 err = fetchOnlyLatestCommits()
320 if err != nil {
321 return err
322 }
323 }
324 } else {
325 err := fetchOnlyLatestCommits()
326 if err != nil {
327 return err
328 }
329 }
330
331 // We then create the relevant refs for each fetched commit.
332 for _, b := range o.Branches {
333 ref := b.Name
334 if ref != "HEAD" {
335 ref = "refs/heads/" + ref
336 }
337 cmd := exec.CommandContext(ctx, "git", "-C", gitDir, "update-ref", ref, b.Version)
338 cmd.Stdin = &bytes.Buffer{}
339 if err := c.runCmd(cmd); err != nil {
340 return fmt.Errorf("failed update-ref %s to %s: %w", ref, b.Version, err)
341 }
342 }
343
344 logger.Debug("successfully fetched git data",
345 sglog.String("repo", o.Name),
346 sglog.Uint32("id", o.RepoID),
347 sglog.Int("commits_count", successfullyFetchedCommitsCount),
348 sglog.Duration("duration", fetchDuration),
349 )
350 return nil
351}
352
353func setZoektConfig(ctx context.Context, gitDir string, o *indexArgs, c gitIndexConfig) error {
354 // create git configuration with options
355 type configKV struct{ Key, Value string }
356 config := []configKV{{
357 // zoekt.name is used by zoekt-git-index to set the repository name.
358 Key: "name",
359 Value: o.Name,
360 }}
361 for k, v := range o.BuildOptions().RepositoryDescription.RawConfig {
362 config = append(config, configKV{Key: k, Value: v})
363 }
364 sort.Slice(config, func(i, j int) bool {
365 return config[i].Key < config[j].Key
366 })
367
368 // write git configuration to repo
369 for _, kv := range config {
370 cmd := exec.CommandContext(ctx, "git", "-C", gitDir, "config", "zoekt."+kv.Key, kv.Value)
371 cmd.Stdin = &bytes.Buffer{}
372 if err := c.runCmd(cmd); err != nil {
373 return err
374 }
375 }
376 return nil
377}
378
379func indexRepo(ctx context.Context, gitDir string, sourcegraph Sourcegraph, o *indexArgs, c gitIndexConfig, logger sglog.Logger) error {
380 args := []string{
381 "-submodules=false",
382 }
383
384 if o.DocumentRanksVersion != "" {
385 // We store the document ranks as JSON in gitDir and tell zoekt-git-index where
386 // to find the file.
387 documentsRankFile := filepath.Join(gitDir, "documents.rank")
388
389 saveDocumentRanks := func() error {
390 r, err := sourcegraph.GetDocumentRanks(context.Background(), o.Name)
391 if err != nil {
392 return fmt.Errorf("GetDocumentRanks: %w", err)
393 }
394
395 b, err := json.Marshal(r)
396 if err != nil {
397 return err
398 }
399
400 if err := os.WriteFile(documentsRankFile, b, 0o600); err != nil {
401 return fmt.Errorf("failed to write %s to disk: %w", documentsRankFile, err)
402 }
403
404 return nil
405 }
406
407 if err := saveDocumentRanks(); err != nil {
408 // log and fall back to online ranking
409 logger.Warn(
410 "error saving document ranks. Falling back to online ranking",
411 sglog.Error(err),
412 sglog.String("repo", o.Name),
413 sglog.Uint32("id", o.RepoID),
414 )
415 } else {
416 args = append(args,
417 "-offline_ranking", documentsRankFile,
418 "-offline_ranking_version", o.DocumentRanksVersion)
419 }
420 }
421
422 // Even though we check for incremental in this process, we still pass it
423 // in just in case we regress in how we check in process. We will still
424 // notice thanks to metrics and increased load on gitserver.
425 if o.Incremental {
426 args = append(args, "-incremental")
427 }
428
429 var branches []string
430 for _, b := range o.Branches {
431 branches = append(branches, b.Name)
432 }
433 args = append(args, "-branches", strings.Join(branches, ","))
434
435 if o.UseDelta {
436 args = append(args, "-delta")
437 args = append(args, "-delta_threshold", strconv.FormatUint(o.DeltaShardNumberFallbackThreshold, 10))
438 }
439
440 if len(o.LanguageMap) > 0 {
441 var languageMap []string
442 for language, parser := range o.LanguageMap {
443 languageMap = append(languageMap, language+":"+ctags.ParserToString(parser))
444 }
445 args = append(args, "-language_map", strings.Join(languageMap, ","))
446 }
447
448 args = append(args, o.BuildOptions().Args()...)
449 args = append(args, gitDir)
450
451 cmd := exec.CommandContext(ctx, "zoekt-git-index", args...)
452 cmd.Stdin = &bytes.Buffer{}
453 if err := c.runCmd(cmd); err != nil {
454 return err
455 }
456 return nil
457}
458
459func priorBranches(c gitIndexConfig, o *indexArgs) ([]zoekt.RepositoryBranch, error) {
460 existingRepository, _, found, err := c.findRepositoryMetadata(o)
461 if err != nil {
462 return nil, fmt.Errorf("loading repository metadata: %w", err)
463 }
464
465 if !found || len(existingRepository.Branches) == 0 {
466 return nil, fmt.Errorf("no prior shards found")
467 }
468
469 return existingRepository.Branches, nil
470}
471
472func tmpGitDir(name string) (string, error) {
473 abs := url.QueryEscape(name)
474 if len(abs) > 200 {
475 h := sha1.New()
476 _, _ = io.WriteString(h, abs)
477 abs = abs[:200] + fmt.Sprintf("%x", h.Sum(nil))[:8]
478 }
479 dir := filepath.Join(os.TempDir(), abs+".git")
480 if _, err := os.Stat(dir); err == nil {
481 if err := os.RemoveAll(dir); err != nil {
482 return "", err
483 }
484 }
485 return dir, nil
486}