fork of https://github.com/sourcegraph/zoekt
1package main
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha1"
7 "errors"
8 "fmt"
9 "io"
10 "net/url"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "sort"
15 "strconv"
16 "strings"
17 "time"
18
19 sglog "github.com/sourcegraph/log"
20
21 "github.com/sourcegraph/zoekt"
22 configv1 "github.com/sourcegraph/zoekt/cmd/zoekt-sourcegraph-indexserver/grpc/protos/sourcegraph/zoekt/configuration/v1"
23 "github.com/sourcegraph/zoekt/index"
24 "github.com/sourcegraph/zoekt/internal/ctags"
25)
26
27const defaultIndexingTimeout = 1*time.Hour + 30*time.Minute
28
29// IndexOptions are the options that Sourcegraph can set via it's search
30// configuration endpoint.
31type IndexOptions struct {
32 // LargeFiles is a slice of glob patterns where matching file paths should
33 // be indexed regardless of their size. The pattern syntax can be found
34 // here: https://golang.org/pkg/path/filepath/#Match.
35 LargeFiles []string
36
37 // Symbols if true will make zoekt index the output of ctags.
38 Symbols bool
39
40 // Branches is a slice of branches to index.
41 Branches []zoekt.RepositoryBranch
42
43 // RepoID is the Sourcegraph Repository ID.
44 RepoID uint32
45
46 // Name is the Repository Name.
47 Name string
48
49 // CloneURL is the internal clone URL for Name.
50 CloneURL string
51
52 // Priority indicates ranking in results, higher first.
53 Priority float64
54
55 // Public is true if the repository is public.
56 Public bool
57
58 // Fork is true if the repository is a fork.
59 Fork bool
60
61 // Archived is true if the repository is archived.
62 Archived bool
63
64 // Map from language to scip-ctags, universal-ctags, or neither
65 LanguageMap ctags.LanguageMap
66
67 // The number of threads to use for indexing shards. Defaults to the number of available
68 // CPUs. If the server flag -cpu_fraction is set, then this value overrides it.
69 ShardConcurrency int32
70
71 // TenantID is the tenant ID for the repository.
72 TenantID int
73}
74
75// indexArgs represents the arguments we pass to zoekt-git-index
76type indexArgs struct {
77 IndexOptions
78
79 // Incremental indicates to skip indexing if already indexed.
80 Incremental bool
81
82 // IndexDir is the index directory to store the shards.
83 IndexDir string
84
85 // Parallelism is the number of shards to compute in parallel.
86 Parallelism int
87
88 // FileLimit is the maximum size of a file
89 FileLimit int
90
91 // UseDelta is true if we want to use the new delta indexer. This should
92 // only be true for repositories we explicitly enable.
93 UseDelta bool
94
95 // DeltaShardNumberFallbackThreshold is an upper limit on the number of preexisting shards that can exist
96 // before attempting a delta build.
97 DeltaShardNumberFallbackThreshold uint64
98
99 // ShardMerging is true if we want zoekt-git-index to respect compound shards.
100 ShardMerging bool
101}
102
103// BuildOptions returns a index.Options represented by indexArgs. Note: it
104// doesn't set fields like repository/branch.
105func (o *indexArgs) BuildOptions() *index.Options {
106 return &index.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 TenantID: o.TenantID,
113 ID: o.RepoID,
114 Name: o.Name,
115 Branches: o.Branches,
116 RawConfig: map[string]string{
117 "repoid": strconv.Itoa(int(o.RepoID)),
118 "priority": strconv.FormatFloat(o.Priority, 'g', -1, 64),
119 "public": marshalBool(o.Public),
120 "fork": marshalBool(o.Fork),
121 "archived": marshalBool(o.Archived),
122 // Calculate repo rank based on the latest commit date.
123 "latestCommitDate": "1",
124 "tenantID": strconv.Itoa(o.TenantID),
125 },
126 },
127 IndexDir: o.IndexDir,
128 Parallelism: o.Parallelism,
129 SizeMax: o.FileLimit,
130 LargeFiles: o.LargeFiles,
131 CTagsMustSucceed: o.Symbols,
132 DisableCTags: !o.Symbols,
133 IsDelta: o.UseDelta,
134
135 LanguageMap: o.LanguageMap,
136
137 ShardMerging: o.ShardMerging,
138 }
139}
140
141func marshalBool(b bool) string {
142 if b {
143 return "1"
144 }
145 return "0"
146}
147
148func (o *indexArgs) String() string {
149 s := fmt.Sprintf("%d %s", o.RepoID, o.Name)
150 for i, b := range o.Branches {
151 if i == 0 {
152 s = fmt.Sprintf("%s@%s=%s", s, b.Name, b.Version)
153 } else {
154 s = fmt.Sprintf("%s,%s=%s", s, b.Name, b.Version)
155 }
156 }
157 return s
158}
159
160type gitIndexConfig struct {
161 // runCmd is the function that's used to execute all external commands (such as calls to "git" or "zoekt-git-index")
162 // that gitIndex may construct.
163 runCmd func(*exec.Cmd) error
164
165 // findRepositoryMetadata is the function that returns the repository metadata for the
166 // repository specified in args. 'ok' is false if the repository's metadata
167 // couldn't be found or if an error occurred.
168 //
169 // The primary purpose of this configuration option is to be able to provide a stub
170 // implementation for this in our test suite. All other callers should use build.Options.FindRepositoryMetadata().
171 findRepositoryMetadata func(args *indexArgs) (repository *zoekt.Repository, metadata *zoekt.IndexMetadata, ok bool, err error)
172
173 // timeout defines how long the index server waits before killing an indexing job.
174 timeout time.Duration
175}
176
177func gitIndex(ctx context.Context, c gitIndexConfig, o *indexArgs, sourcegraph Sourcegraph, l sglog.Logger) error {
178 logger := l.Scoped("gitIndex")
179
180 if len(o.Branches) == 0 {
181 return errors.New("zoekt-git-index requires 1 or more branches")
182 }
183
184 if c.runCmd == nil {
185 return errors.New("runCmd in provided configuration was nil - a function must be provided")
186 }
187
188 if c.findRepositoryMetadata == nil {
189 return errors.New("findRepositoryMetadata in provided configuration was nil - a function must be provided")
190 }
191
192 ctx, cancel := context.WithTimeout(ctx, c.timeout)
193 defer cancel()
194
195 gitDir, err := tmpGitDir(o.Name)
196 if err != nil {
197 return err
198 }
199 defer os.RemoveAll(gitDir) // best-effort cleanup
200
201 err = fetchRepo(ctx, gitDir, o, c, logger)
202 if err != nil {
203 return err
204 }
205
206 err = setZoektConfig(ctx, gitDir, o, c)
207 if err != nil {
208 return err
209 }
210
211 err = indexRepo(ctx, gitDir, sourcegraph, o, c, logger)
212 if err != nil {
213 return err
214 }
215
216 return nil
217}
218
219func fetchRepo(ctx context.Context, gitDir string, o *indexArgs, c gitIndexConfig, logger sglog.Logger) error {
220 // Create a repo to fetch into
221 cmd := exec.CommandContext(ctx, "git",
222 // use a random default branch. This is so that HEAD isn't a symref to a
223 // branch that is indexed. For example if you are indexing
224 // HEAD,master. Then HEAD would be pointing to master by default.
225 "-c", "init.defaultBranch=nonExistentBranchBB0FOFCH32",
226 "init",
227 // we don't need a working copy
228 "--bare",
229 gitDir)
230 cmd.Stdin = &bytes.Buffer{}
231 if err := c.runCmd(cmd); err != nil {
232 return err
233 }
234
235 var fetchDuration time.Duration
236 successfullyFetchedCommitsCount := 0
237 allFetchesSucceeded := true
238
239 defer func() {
240 success := strconv.FormatBool(allFetchesSucceeded)
241 name := repoNameForMetric(o.Name)
242 metricFetchDuration.WithLabelValues(success, name).Observe(fetchDuration.Seconds())
243 }()
244
245 runFetch := func(branches []zoekt.RepositoryBranch) error {
246 // We shallow fetch each commit specified in zoekt.Branches. This requires
247 // the server to have configured both uploadpack.allowAnySHA1InWant and
248 // uploadpack.allowFilter. (See gitservice.go in the Sourcegraph repository)
249 fetchArgs := []string{
250 "-C", gitDir,
251 "-c", "protocol.version=2",
252 "-c", "http.extraHeader=X-Sourcegraph-Actor-UID: internal",
253 "-c", "http.extraHeader=X-Sourcegraph-Tenant-ID: " + strconv.Itoa(o.TenantID),
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 errorLog.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 // Even though we check for incremental in this process, we still pass it
383 // in just in case we regress in how we check in process. We will still
384 // notice thanks to metrics and increased load on gitserver.
385 if o.Incremental {
386 args = append(args, "-incremental")
387 }
388
389 var branches []string
390 for _, b := range o.Branches {
391 branches = append(branches, b.Name)
392 }
393 args = append(args, "-branches", strings.Join(branches, ","))
394
395 if o.UseDelta {
396 args = append(args, "-delta")
397 args = append(args, "-delta_threshold", strconv.FormatUint(o.DeltaShardNumberFallbackThreshold, 10))
398 }
399
400 if len(o.LanguageMap) > 0 {
401 var languageMap []string
402 for language, parser := range o.LanguageMap {
403 languageMap = append(languageMap, language+":"+ctags.ParserToString(parser))
404 }
405 args = append(args, "-language_map", strings.Join(languageMap, ","))
406 }
407
408 args = append(args, o.BuildOptions().Args()...)
409 args = append(args, gitDir)
410
411 cmd := exec.CommandContext(ctx, "zoekt-git-index", args...)
412 cmd.Stdin = &bytes.Buffer{}
413 if err := c.runCmd(cmd); err != nil {
414 return err
415 }
416 return nil
417}
418
419func priorBranches(c gitIndexConfig, o *indexArgs) ([]zoekt.RepositoryBranch, error) {
420 existingRepository, _, found, err := c.findRepositoryMetadata(o)
421 if err != nil {
422 return nil, fmt.Errorf("loading repository metadata: %w", err)
423 }
424
425 if !found || len(existingRepository.Branches) == 0 {
426 return nil, fmt.Errorf("no prior shards found")
427 }
428
429 return existingRepository.Branches, nil
430}
431
432func tmpGitDir(name string) (string, error) {
433 abs := url.QueryEscape(name)
434 if len(abs) > 200 {
435 h := sha1.New()
436 _, _ = io.WriteString(h, abs)
437 abs = abs[:200] + fmt.Sprintf("%x", h.Sum(nil))[:8]
438 }
439 dir := filepath.Join(os.TempDir(), abs+".git")
440 if _, err := os.Stat(dir); err == nil {
441 if err := os.RemoveAll(dir); err != nil {
442 return "", err
443 }
444 }
445 return dir, nil
446}
447
448// FromProto converts a ZoektIndexOptions proto message into an IndexOptions struct.
449func (o *IndexOptions) FromProto(x *configv1.ZoektIndexOptions) {
450 branches := make([]zoekt.RepositoryBranch, 0, len(x.Branches))
451 for _, b := range x.GetBranches() {
452 branches = append(branches, zoekt.RepositoryBranch{
453 Name: b.GetName(),
454 Version: b.GetVersion(),
455 })
456 }
457
458 languageMap := make(map[string]ctags.CTagsParserType)
459 for _, lang := range x.GetLanguageMap() {
460 languageMap[lang.GetLanguage()] = ctags.CTagsParserType(lang.GetCtags().Number())
461 }
462
463 *o = IndexOptions{
464 RepoID: uint32(x.GetRepoId()),
465 LargeFiles: x.GetLargeFiles(),
466 Symbols: x.GetSymbols(),
467 Branches: branches,
468 Name: x.GetName(),
469
470 Priority: x.GetPriority(),
471
472 Public: x.GetPublic(),
473 Fork: x.GetFork(),
474 Archived: x.GetArchived(),
475
476 LanguageMap: languageMap,
477 ShardConcurrency: x.GetShardConcurrency(),
478
479 TenantID: int(x.TenantId),
480 }
481}