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