fork of https://github.com/sourcegraph/zoekt
1// Copyright 2016 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package web
16
17import (
18 "bytes"
19 "context"
20 "encoding/json"
21 "fmt"
22 "html/template"
23 "log"
24 "net"
25 "net/http"
26 "regexp/syntax"
27 "sort"
28 "strconv"
29 "strings"
30 "sync"
31 "time"
32
33 "github.com/grafana/regexp"
34 "github.com/sourcegraph/zoekt"
35 zjson "github.com/sourcegraph/zoekt/json"
36 "github.com/sourcegraph/zoekt/query"
37)
38
39var Funcmap = template.FuncMap{
40 "Inc": func(orig int) int {
41 return orig + 1
42 },
43 "More": func(orig int) int {
44 return orig * 3
45 },
46 "HumanUnit": func(orig int64) string {
47 b := orig
48 suffix := ""
49 if orig > 10*(1<<30) {
50 suffix = "G"
51 b = orig / (1 << 30)
52 } else if orig > 10*(1<<20) {
53 suffix = "M"
54 b = orig / (1 << 20)
55 } else if orig > 10*(1<<10) {
56 suffix = "K"
57 b = orig / (1 << 10)
58 }
59
60 return fmt.Sprintf("%d%s", b, suffix)
61 },
62 "LimitPre": func(limit int, pre string) string {
63 if len(pre) < limit {
64 return pre
65 }
66 return fmt.Sprintf("...(%d bytes skipped)...%s", len(pre)-limit, pre[len(pre)-limit:])
67 },
68 "LimitPost": func(limit int, post string) string {
69 if len(post) < limit {
70 return post
71 }
72 return fmt.Sprintf("%s...(%d bytes skipped)...", post[:limit], len(post)-limit)
73 },
74 "TrimTrailingNewline": func(s string) string {
75 return strings.TrimSuffix(s, "\n")
76 },
77}
78
79const defaultNumResults = 50
80
81type Server struct {
82 Searcher zoekt.Streamer
83
84 // Serve HTML interface
85 HTML bool
86
87 // Serve RPC
88 RPC bool
89
90 // If set, show files from the index.
91 Print bool
92
93 // Version string for this server.
94 Version string
95
96 // Depending on the Host header, add a query to the entry
97 // page. For example, when serving on "search.myproject.org"
98 // we could add "r:myproject" automatically. This allows a
99 // single instance to serve as search engine for multiple
100 // domains.
101 HostCustomQueries map[string]string
102
103 // This should contain the following templates: "repolist"
104 // (for the repo search result page), "result" for
105 // the search results, "search" (for the opening page),
106 // "box" for the search query input element and
107 // "print" for the show file functionality.
108 Top *template.Template
109
110 repolist *template.Template
111 search *template.Template
112 result *template.Template
113 print *template.Template
114 about *template.Template
115 robots *template.Template
116
117 startTime time.Time
118
119 templateMu sync.Mutex
120 templateCache map[string]*template.Template
121
122 lastStatsMu sync.Mutex
123 lastStats *zoekt.RepoStats
124 lastStatsTS time.Time
125}
126
127func (s *Server) getTemplate(str string) *template.Template {
128 s.templateMu.Lock()
129 defer s.templateMu.Unlock()
130 t := s.templateCache[str]
131 if t != nil {
132 return t
133 }
134
135 t, err := template.New("cache").Parse(str)
136 if err != nil {
137 log.Printf("template parse error: %v", err)
138 t = template.Must(template.New("empty").Parse(""))
139 }
140 s.templateCache[str] = t
141 return t
142}
143
144func NewMux(s *Server) (*http.ServeMux, error) {
145 s.print = s.Top.Lookup("print")
146 if s.print == nil {
147 return nil, fmt.Errorf("missing template 'print'")
148 }
149
150 for k, v := range map[string]**template.Template{
151 "results": &s.result,
152 "print": &s.print,
153 "search": &s.search,
154 "repolist": &s.repolist,
155 "about": &s.about,
156 "robots": &s.robots,
157 } {
158 *v = s.Top.Lookup(k)
159 if *v == nil {
160 return nil, fmt.Errorf("missing template %q", k)
161 }
162 }
163
164 s.templateCache = map[string]*template.Template{}
165 s.startTime = time.Now()
166
167 mux := http.NewServeMux()
168
169 if s.HTML {
170 mux.HandleFunc("/robots.txt", s.serveRobots)
171 mux.HandleFunc("/search", s.serveSearch)
172 mux.HandleFunc("/", s.serveSearchBox)
173 mux.HandleFunc("/about", s.serveAbout)
174 mux.HandleFunc("/print", s.servePrint)
175 }
176 if s.RPC {
177 mux.Handle("/api/", http.StripPrefix("/api", zjson.JSONServer(traceAwareSearcher{s.Searcher})))
178 }
179
180 mux.HandleFunc("/healthz", s.serveHealthz)
181
182 return mux, nil
183}
184
185func (s *Server) serveHealthz(w http.ResponseWriter, r *http.Request) {
186 q := &query.Const{Value: true}
187 opts := &zoekt.SearchOptions{ShardMaxMatchCount: 1, TotalMaxMatchCount: 1, MaxDocDisplayCount: 1}
188
189 result, err := s.Searcher.Search(r.Context(), q, opts)
190 if err != nil {
191 http.Error(w, fmt.Sprintf("not ready: %v", err), http.StatusInternalServerError)
192 return
193 }
194
195 w.Header().Set("Content-Type", "application/json")
196
197 _ = json.NewEncoder(w).Encode(result)
198}
199
200func (s *Server) serveSearch(w http.ResponseWriter, r *http.Request) {
201 result, err := s.serveSearchErr(r)
202 if err != nil {
203 http.Error(w, err.Error(), http.StatusTeapot)
204 return
205 }
206
207 qvals := r.URL.Query()
208 if qvals.Get("format") == "json" {
209 w.Header().Add("Content-Type", "application/json")
210 encoder := json.NewEncoder(w)
211 encoder.Encode(result)
212 return
213 }
214
215 var buf bytes.Buffer
216 if result.Repos != nil {
217 err = s.repolist.Execute(&buf, &result.Repos)
218 } else if result.Result != nil {
219 err = s.result.Execute(&buf, &result.Result)
220 }
221 if err != nil {
222 http.Error(w, err.Error(), http.StatusTeapot)
223 return
224 }
225 w.Write(buf.Bytes())
226}
227
228func (s *Server) serveSearchErr(r *http.Request) (*ApiSearchResult, error) {
229 qvals := r.URL.Query()
230
231 debugScore, _ := strconv.ParseBool(qvals.Get("debug"))
232
233 queryStr := qvals.Get("q")
234 if queryStr == "" {
235 return nil, fmt.Errorf("no query found")
236 }
237
238 q, err := query.Parse(queryStr)
239 if err != nil {
240 return nil, err
241 }
242
243 repoOnly := true
244 query.VisitAtoms(q, func(q query.Q) {
245 _, ok := q.(*query.Repo)
246 repoOnly = repoOnly && ok
247 })
248 if repoOnly {
249 repos, err := s.serveListReposErr(q, queryStr, r)
250 if err == nil {
251 return &ApiSearchResult{Repos: repos}, nil
252 }
253 return nil, err
254 }
255
256 if qt, ok := q.(*query.Type); ok && qt.Type == query.TypeRepo {
257 repos, err := s.serveListReposErr(q, queryStr, r)
258 if err == nil {
259 return &ApiSearchResult{Repos: repos}, nil
260 }
261 return nil, err
262 }
263
264 numStr := qvals.Get("num")
265
266 num, err := strconv.Atoi(numStr)
267 if err != nil || num <= 0 {
268 num = defaultNumResults
269 }
270
271 sOpts := zoekt.SearchOptions{
272 MaxWallTime: 10 * time.Second,
273 }
274
275 numCtxLines := 0
276 if ctxLinesStr := qvals.Get("ctx"); ctxLinesStr != "" {
277 numCtxLines, err = strconv.Atoi(ctxLinesStr)
278 if err != nil || numCtxLines < 0 || numCtxLines > 10 {
279 return nil, fmt.Errorf("Number of context lines must be between 0 and 10")
280 }
281 }
282 sOpts.NumContextLines = numCtxLines
283
284 sOpts.SetDefaults()
285 sOpts.MaxDocDisplayCount = num
286 sOpts.DebugScore = debugScore
287
288 ctx := r.Context()
289 if err := zjson.CalculateDefaultSearchLimits(ctx, q, s.Searcher, &sOpts); err != nil {
290 return nil, err
291 }
292
293 result, err := s.Searcher.Search(ctx, q, &sOpts)
294 if err != nil {
295 return nil, err
296 }
297
298 fileMatches, err := s.formatResults(result, queryStr, s.Print)
299 if err != nil {
300 return nil, err
301 }
302
303 res := ResultInput{
304 Last: LastInput{
305 Query: queryStr,
306 Num: num,
307 Ctx: numCtxLines,
308 AutoFocus: true,
309 },
310 Stats: result.Stats,
311 Query: q.String(),
312 QueryStr: queryStr,
313 FileMatches: fileMatches,
314 }
315 if res.Stats.Wait < res.Stats.Duration/10 {
316 // Suppress queueing stats if they are neglible.
317 res.Stats.Wait = 0
318 }
319
320 res.Last.Debug = debugScore
321 return &ApiSearchResult{Result: &res}, nil
322}
323
324func (s *Server) servePrint(w http.ResponseWriter, r *http.Request) {
325 err := s.servePrintErr(w, r)
326 if err != nil {
327 http.Error(w, err.Error(), http.StatusTeapot)
328 }
329}
330
331const statsStaleNess = 30 * time.Second
332
333func (s *Server) fetchStats(ctx context.Context) (*zoekt.RepoStats, error) {
334 s.lastStatsMu.Lock()
335 stats := s.lastStats
336 if time.Since(s.lastStatsTS) > statsStaleNess {
337 stats = nil
338 }
339 s.lastStatsMu.Unlock()
340
341 if stats != nil {
342 return stats, nil
343 }
344
345 repos, err := s.Searcher.List(ctx, &query.Const{Value: true}, nil)
346 if err != nil {
347 return nil, err
348 }
349
350 stats = &repos.Stats
351
352 s.lastStatsMu.Lock()
353 s.lastStatsTS = time.Now()
354 s.lastStats = stats
355 s.lastStatsMu.Unlock()
356
357 return stats, nil
358}
359
360func (s *Server) serveSearchBoxErr(w http.ResponseWriter, r *http.Request) error {
361 stats, err := s.fetchStats(r.Context())
362 if err != nil {
363 return err
364 }
365 d := SearchBoxInput{
366 Last: LastInput{
367 Num: defaultNumResults,
368 AutoFocus: true,
369 },
370 Stats: stats,
371 Version: s.Version,
372 Uptime: time.Since(s.startTime),
373 }
374
375 d.Last.Query = r.URL.Query().Get("q")
376 if d.Last.Query == "" {
377 custom := s.HostCustomQueries[r.Host]
378 if custom == "" {
379 host, _, _ := net.SplitHostPort(r.Host)
380 custom = s.HostCustomQueries[host]
381 }
382
383 if custom != "" {
384 d.Last.Query = custom + " "
385 }
386 }
387
388 var buf bytes.Buffer
389 if err := s.search.Execute(&buf, &d); err != nil {
390 return err
391 }
392 _, _ = w.Write(buf.Bytes())
393 return nil
394}
395
396func (s *Server) serveSearchBox(w http.ResponseWriter, r *http.Request) {
397 if err := s.serveSearchBoxErr(w, r); err != nil {
398 http.Error(w, err.Error(), http.StatusTeapot)
399 }
400}
401
402func (s *Server) serveAboutErr(w http.ResponseWriter, r *http.Request) error {
403 stats, err := s.fetchStats(r.Context())
404 if err != nil {
405 return err
406 }
407
408 d := SearchBoxInput{
409 Stats: stats,
410 Version: s.Version,
411 Uptime: time.Since(s.startTime),
412 }
413
414 var buf bytes.Buffer
415 if err := s.about.Execute(&buf, &d); err != nil {
416 return err
417 }
418 _, _ = w.Write(buf.Bytes())
419 return nil
420}
421
422func (s *Server) serveAbout(w http.ResponseWriter, r *http.Request) {
423 if err := s.serveAboutErr(w, r); err != nil {
424 http.Error(w, err.Error(), http.StatusTeapot)
425 }
426}
427
428func (s *Server) serveRobotsErr(w http.ResponseWriter, r *http.Request) error {
429 data := struct{}{}
430 var buf bytes.Buffer
431 if err := s.robots.Execute(&buf, &data); err != nil {
432 return err
433 }
434 _, _ = w.Write(buf.Bytes())
435 return nil
436}
437
438func (s *Server) serveRobots(w http.ResponseWriter, r *http.Request) {
439 if err := s.serveRobotsErr(w, r); err != nil {
440 http.Error(w, err.Error(), http.StatusTeapot)
441 }
442}
443
444func (s *Server) serveListReposErr(q query.Q, qStr string, r *http.Request) (*RepoListInput, error) {
445 ctx := r.Context()
446 repos, err := s.Searcher.List(ctx, q, nil)
447 if err != nil {
448 return nil, err
449 }
450
451 qvals := r.URL.Query()
452 order := qvals.Get("order")
453 switch order {
454 case "", "name", "revname":
455 sort.Slice(repos.Repos, func(i, j int) bool {
456 return strings.Compare(repos.Repos[i].Repository.Name, repos.Repos[j].Repository.Name) < 0
457 })
458 case "size", "revsize":
459 sort.Slice(repos.Repos, func(i, j int) bool {
460 return repos.Repos[i].Stats.ContentBytes < repos.Repos[j].Stats.ContentBytes
461 })
462 case "ram", "revram":
463 sort.Slice(repos.Repos, func(i, j int) bool {
464 return repos.Repos[i].Stats.IndexBytes < repos.Repos[j].Stats.IndexBytes
465 })
466 case "time", "revtime":
467 sort.Slice(repos.Repos, func(i, j int) bool {
468 return repos.Repos[i].IndexMetadata.IndexTime.Before(
469 repos.Repos[j].IndexMetadata.IndexTime)
470 })
471 default:
472 return nil, fmt.Errorf("got unknown sort key %q, allowed [rev]name, [rev]time, [rev]size", order)
473 }
474 if strings.HasPrefix(order, "rev") {
475 for i, j := 0, len(repos.Repos)-1; i < j; {
476 repos.Repos[i], repos.Repos[j] = repos.Repos[j], repos.Repos[i]
477 i++
478 j--
479
480 }
481 }
482
483 aggregate := zoekt.RepoStats{
484 Repos: len(repos.Repos),
485 }
486 for _, s := range repos.Repos {
487 aggregate.Add(&s.Stats)
488 }
489
490 numStr := qvals.Get("num")
491 num, err := strconv.Atoi(numStr)
492 if err != nil || num <= 0 {
493 num = 0
494 }
495 if num > 0 {
496 if num > len(repos.Repos) {
497 num = len(repos.Repos)
498 }
499
500 repos.Repos = repos.Repos[:num]
501 }
502
503 res := RepoListInput{
504 Last: LastInput{
505 Query: qStr,
506 Num: num,
507 AutoFocus: true,
508 },
509 Stats: aggregate,
510 }
511
512 for _, r := range repos.Repos {
513 t := s.getTemplate(r.Repository.CommitURLTemplate)
514
515 repo := Repository{
516 Name: r.Repository.Name,
517 URL: r.Repository.URL,
518 IndexTime: r.IndexMetadata.IndexTime,
519 Size: r.Stats.ContentBytes,
520 MemorySize: r.Stats.IndexBytes,
521 Files: int64(r.Stats.Documents),
522 }
523 for _, b := range r.Repository.Branches {
524 var buf bytes.Buffer
525 if err := t.Execute(&buf, b); err != nil {
526 return nil, err
527 }
528 repo.Branches = append(repo.Branches,
529 Branch{
530 Name: b.Name,
531 Version: b.Version,
532 URL: buf.String(),
533 })
534 }
535 res.Repos = append(res.Repos, repo)
536 }
537 return &res, nil
538}
539
540func (s *Server) servePrintErr(w http.ResponseWriter, r *http.Request) error {
541 qvals := r.URL.Query()
542 fileStr := qvals.Get("f")
543 repoStr := qvals.Get("r")
544 queryStr := qvals.Get("q")
545 numStr := qvals.Get("num")
546 num, err := strconv.Atoi(numStr)
547 if err != nil || num <= 0 {
548 num = defaultNumResults
549 }
550
551 re, err := syntax.Parse("^"+regexp.QuoteMeta(fileStr)+"$", 0)
552 if err != nil {
553 return err
554 }
555
556 repoRe, err := regexp.Compile("^" + regexp.QuoteMeta(repoStr) + "$")
557 if err != nil {
558 return err
559 }
560
561 qs := []query.Q{
562 &query.Regexp{Regexp: re, FileName: true, CaseSensitive: true},
563 &query.Repo{Regexp: repoRe},
564 }
565
566 if branchStr := qvals.Get("b"); branchStr != "" {
567 qs = append(qs, &query.Branch{Pattern: branchStr})
568 }
569
570 q := &query.And{Children: qs}
571
572 sOpts := zoekt.SearchOptions{
573 Whole: true,
574 }
575
576 ctx := r.Context()
577 result, err := s.Searcher.Search(ctx, q, &sOpts)
578 if err != nil {
579 return err
580 }
581
582 if len(result.Files) != 1 {
583 var ss []string
584 for _, n := range result.Files {
585 ss = append(ss, n.FileName)
586 }
587 return fmt.Errorf("ambiguous result: %v", ss)
588 }
589
590 f := result.Files[0]
591
592 byteLines := bytes.Split(f.Content, []byte{'\n'})
593 strLines := make([]string, 0, len(byteLines))
594 for _, l := range byteLines {
595 strLines = append(strLines, string(l))
596 }
597
598 d := PrintInput{
599 Name: f.FileName,
600 Repo: f.Repository,
601 Lines: strLines,
602 Last: LastInput{
603 Query: queryStr,
604 Num: num,
605 AutoFocus: false,
606 },
607 }
608
609 var buf bytes.Buffer
610 if err := s.print.Execute(&buf, &d); err != nil {
611 return err
612 }
613
614 _, _ = w.Write(buf.Bytes())
615 return nil
616}