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 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
235 var commits []string
236 for _, b := range branches {
237 commits = append(commits, b.Version)
238 }
239
240 fetchArgs = append(fetchArgs, commits...)
241
242 cmd = exec.CommandContext(ctx, "git", fetchArgs...)
243 cmd.Stdin = &bytes.Buffer{}
244
245 start := time.Now()
246 err := runCmd(cmd)
247 fetchDuration += time.Since(start)
248
249 if err != nil {
250 allFetchesSucceeded = false
251 var bs []string
252 for _, b := range branches {
253 bs = append(bs, b.String())
254 }
255
256 formattedBranches := strings.Join(bs, ", ")
257 return fmt.Errorf("fetching %s: %w", formattedBranches, err)
258 }
259
260 successfullyFetchedCommitsCount += len(commits)
261 return nil
262 }
263
264 fetchPriorAndLatestCommits := func() error {
265 prior, err := priorBranches(c, o)
266 if err != nil {
267 return err
268 }
269
270 var allBranches []zoekt.RepositoryBranch
271 allBranches = append(allBranches, o.Branches...)
272 allBranches = append(allBranches, prior...)
273
274 return runFetch(allBranches)
275 }
276
277 fetchOnlyLatestCommits := func() error {
278 return runFetch(o.Branches)
279 }
280
281 if o.UseDelta {
282 err := fetchPriorAndLatestCommits()
283 if err != nil {
284 name := buildOptions.RepositoryDescription.Name
285 id := buildOptions.RepositoryDescription.ID
286
287 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)
288 err = fetchOnlyLatestCommits()
289 if err != nil {
290 return err
291 }
292 }
293 } else {
294 err := fetchOnlyLatestCommits()
295 if err != nil {
296 return err
297 }
298 }
299
300 logger.Debug("successfully fetched git data",
301 sglog.String("repo", o.Name),
302 sglog.Uint32("id", o.RepoID),
303 sglog.Int("commits_count", successfullyFetchedCommitsCount),
304 sglog.Duration("duration", fetchDuration),
305 )
306
307 // We then create the relevant refs for each fetched commit.
308 for _, b := range o.Branches {
309 ref := b.Name
310 if ref != "HEAD" {
311 ref = "refs/heads/" + ref
312 }
313 cmd = exec.CommandContext(ctx, "git", "-C", gitDir, "update-ref", ref, b.Version)
314 cmd.Stdin = &bytes.Buffer{}
315 if err := runCmd(cmd); err != nil {
316 return fmt.Errorf("failed update-ref %s to %s: %w", ref, b.Version, err)
317 }
318 }
319
320 // create git configuration with options
321 type configKV struct{ Key, Value string }
322 config := []configKV{{
323 // zoekt.name is used by zoekt-git-index to set the repository name.
324 Key: "name",
325 Value: o.Name,
326 }}
327 for k, v := range buildOptions.RepositoryDescription.RawConfig {
328 config = append(config, configKV{Key: k, Value: v})
329 }
330 sort.Slice(config, func(i, j int) bool {
331 return config[i].Key < config[j].Key
332 })
333
334 // write git configuration to repo
335 for _, kv := range config {
336 cmd = exec.CommandContext(ctx, "git", "-C", gitDir, "config", "zoekt."+kv.Key, kv.Value)
337 cmd.Stdin = &bytes.Buffer{}
338 if err := runCmd(cmd); err != nil {
339 return err
340 }
341 }
342
343 args := []string{
344 "-submodules=false",
345 }
346
347 if o.DocumentRanksVersion != "" {
348 // We store the document ranks as JSON in gitDir and tell zoekt-git-index where
349 // to find the file.
350 documentsRankFile := filepath.Join(gitDir, "documents.rank")
351
352 saveDocumentRanks := func() error {
353 r, err := sourcegraph.GetDocumentRanks(context.Background(), o.Name)
354 if err != nil {
355 return fmt.Errorf("GetDocumentRanks: %w", err)
356 }
357
358 b, err := json.Marshal(r)
359 if err != nil {
360 return err
361 }
362
363 if err := os.WriteFile(documentsRankFile, b, 0o600); err != nil {
364 return fmt.Errorf("failed to write %s to disk: %w", documentsRankFile, err)
365 }
366
367 return nil
368 }
369
370 if err := saveDocumentRanks(); err != nil {
371 // log and fall back to online ranking
372 logger.Warn(
373 "error saving document ranks. Falling back to online ranking",
374 sglog.Error(err),
375 sglog.String("repo", o.Name),
376 sglog.Uint32("id", o.RepoID),
377 )
378 } else {
379 args = append(args,
380 "-offline_ranking", documentsRankFile,
381 "-offline_ranking_version", o.DocumentRanksVersion)
382 }
383 }
384
385 // Even though we check for incremental in this process, we still pass it
386 // in just in case we regress in how we check in process. We will still
387 // notice thanks to metrics and increased load on gitserver.
388 if o.Incremental {
389 args = append(args, "-incremental")
390 }
391
392 var branches []string
393 for _, b := range o.Branches {
394 branches = append(branches, b.Name)
395 }
396 args = append(args, "-branches", strings.Join(branches, ","))
397
398 if o.UseDelta {
399 args = append(args, "-delta")
400 args = append(args, "-delta_threshold", strconv.FormatUint(o.DeltaShardNumberFallbackThreshold, 10))
401 }
402
403 if len(o.LanguageMap) > 0 {
404 var languageMap []string
405 for language, parser := range o.LanguageMap {
406 languageMap = append(languageMap, language+":"+ctags.ParserToString(parser))
407 }
408 args = append(args, "-language_map", strings.Join(languageMap, ","))
409 }
410
411 args = append(args, buildOptions.Args()...)
412 args = append(args, gitDir)
413
414 cmd = exec.CommandContext(ctx, "zoekt-git-index", args...)
415 cmd.Stdin = &bytes.Buffer{}
416 if err := runCmd(cmd); err != nil {
417 return err
418 }
419
420 return nil
421}
422
423func priorBranches(c gitIndexConfig, o *indexArgs) ([]zoekt.RepositoryBranch, error) {
424 existingRepository, _, found, err := c.findRepositoryMetadata(o)
425 if err != nil {
426 return nil, fmt.Errorf("loading repository metadata: %w", err)
427 }
428
429 if !found || len(existingRepository.Branches) == 0 {
430 return nil, fmt.Errorf("no prior shards found")
431 }
432
433 return existingRepository.Branches, nil
434}
435
436func tmpGitDir(name string) (string, error) {
437 abs := url.QueryEscape(name)
438 if len(abs) > 200 {
439 h := sha1.New()
440 _, _ = io.WriteString(h, abs)
441 abs = abs[:200] + fmt.Sprintf("%x", h.Sum(nil))[:8]
442 }
443 dir := filepath.Join(os.TempDir(), abs+".git")
444 if _, err := os.Stat(dir); err == nil {
445 if err := os.RemoveAll(dir); err != nil {
446 return "", err
447 }
448 }
449 return dir, nil
450}