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