You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bleve.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package code
  5. import (
  6. "fmt"
  7. "os"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/analyze"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/charset"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "code.gitea.io/gitea/modules/timeutil"
  19. "github.com/blevesearch/bleve"
  20. analyzer_custom "github.com/blevesearch/bleve/analysis/analyzer/custom"
  21. analyzer_keyword "github.com/blevesearch/bleve/analysis/analyzer/keyword"
  22. "github.com/blevesearch/bleve/analysis/token/lowercase"
  23. "github.com/blevesearch/bleve/analysis/token/unicodenorm"
  24. "github.com/blevesearch/bleve/analysis/tokenizer/unicode"
  25. "github.com/blevesearch/bleve/index/upsidedown"
  26. "github.com/blevesearch/bleve/mapping"
  27. "github.com/blevesearch/bleve/search/query"
  28. "github.com/ethantkoenig/rupture"
  29. "github.com/src-d/enry/v2"
  30. )
  31. const unicodeNormalizeName = "unicodeNormalize"
  32. const maxBatchSize = 16
  33. // indexerID a bleve-compatible unique identifier for an integer id
  34. func indexerID(id int64) string {
  35. return strconv.FormatInt(id, 36)
  36. }
  37. // numericEqualityQuery a numeric equality query for the given value and field
  38. func numericEqualityQuery(value int64, field string) *query.NumericRangeQuery {
  39. f := float64(value)
  40. tru := true
  41. q := bleve.NewNumericRangeInclusiveQuery(&f, &f, &tru, &tru)
  42. q.SetField(field)
  43. return q
  44. }
  45. func addUnicodeNormalizeTokenFilter(m *mapping.IndexMappingImpl) error {
  46. return m.AddCustomTokenFilter(unicodeNormalizeName, map[string]interface{}{
  47. "type": unicodenorm.Name,
  48. "form": unicodenorm.NFC,
  49. })
  50. }
  51. // openIndexer open the index at the specified path, checking for metadata
  52. // updates and bleve version updates. If index needs to be created (or
  53. // re-created), returns (nil, nil)
  54. func openIndexer(path string, latestVersion int) (bleve.Index, error) {
  55. _, err := os.Stat(path)
  56. if err != nil && os.IsNotExist(err) {
  57. return nil, nil
  58. } else if err != nil {
  59. return nil, err
  60. }
  61. metadata, err := rupture.ReadIndexMetadata(path)
  62. if err != nil {
  63. return nil, err
  64. }
  65. if metadata.Version < latestVersion {
  66. // the indexer is using a previous version, so we should delete it and
  67. // re-populate
  68. return nil, os.RemoveAll(path)
  69. }
  70. index, err := bleve.Open(path)
  71. if err != nil && err == upsidedown.IncompatibleVersion {
  72. // the indexer was built with a previous version of bleve, so we should
  73. // delete it and re-populate
  74. return nil, os.RemoveAll(path)
  75. } else if err != nil {
  76. return nil, err
  77. }
  78. return index, nil
  79. }
  80. // RepoIndexerData data stored in the repo indexer
  81. type RepoIndexerData struct {
  82. RepoID int64
  83. CommitID string
  84. Content string
  85. Language string
  86. UpdatedAt time.Time
  87. }
  88. // Type returns the document type, for bleve's mapping.Classifier interface.
  89. func (d *RepoIndexerData) Type() string {
  90. return repoIndexerDocType
  91. }
  92. func addUpdate(commitSha string, update fileUpdate, repo *models.Repository, batch rupture.FlushingBatch) error {
  93. // Ignore vendored files in code search
  94. if setting.Indexer.ExcludeVendored && enry.IsVendor(update.Filename) {
  95. return nil
  96. }
  97. stdout, err := git.NewCommand("cat-file", "-s", update.BlobSha).
  98. RunInDir(repo.RepoPath())
  99. if err != nil {
  100. return err
  101. }
  102. if size, err := strconv.Atoi(strings.TrimSpace(stdout)); err != nil {
  103. return fmt.Errorf("Misformatted git cat-file output: %v", err)
  104. } else if int64(size) > setting.Indexer.MaxIndexerFileSize {
  105. return addDelete(update.Filename, repo, batch)
  106. }
  107. fileContents, err := git.NewCommand("cat-file", "blob", update.BlobSha).
  108. RunInDirBytes(repo.RepoPath())
  109. if err != nil {
  110. return err
  111. } else if !base.IsTextFile(fileContents) {
  112. // FIXME: UTF-16 files will probably fail here
  113. return nil
  114. }
  115. id := filenameIndexerID(repo.ID, update.Filename)
  116. return batch.Index(id, &RepoIndexerData{
  117. RepoID: repo.ID,
  118. CommitID: commitSha,
  119. Content: string(charset.ToUTF8DropErrors(fileContents)),
  120. Language: analyze.GetCodeLanguage(update.Filename, fileContents),
  121. UpdatedAt: time.Now().UTC(),
  122. })
  123. }
  124. func addDelete(filename string, repo *models.Repository, batch rupture.FlushingBatch) error {
  125. id := filenameIndexerID(repo.ID, filename)
  126. return batch.Delete(id)
  127. }
  128. const (
  129. repoIndexerAnalyzer = "repoIndexerAnalyzer"
  130. repoIndexerDocType = "repoIndexerDocType"
  131. repoIndexerLatestVersion = 5
  132. )
  133. // createRepoIndexer create a repo indexer if one does not already exist
  134. func createRepoIndexer(path string, latestVersion int) (bleve.Index, error) {
  135. docMapping := bleve.NewDocumentMapping()
  136. numericFieldMapping := bleve.NewNumericFieldMapping()
  137. numericFieldMapping.IncludeInAll = false
  138. docMapping.AddFieldMappingsAt("RepoID", numericFieldMapping)
  139. textFieldMapping := bleve.NewTextFieldMapping()
  140. textFieldMapping.IncludeInAll = false
  141. docMapping.AddFieldMappingsAt("Content", textFieldMapping)
  142. termFieldMapping := bleve.NewTextFieldMapping()
  143. termFieldMapping.IncludeInAll = false
  144. termFieldMapping.Analyzer = analyzer_keyword.Name
  145. docMapping.AddFieldMappingsAt("Language", termFieldMapping)
  146. docMapping.AddFieldMappingsAt("CommitID", termFieldMapping)
  147. timeFieldMapping := bleve.NewDateTimeFieldMapping()
  148. timeFieldMapping.IncludeInAll = false
  149. docMapping.AddFieldMappingsAt("UpdatedAt", timeFieldMapping)
  150. mapping := bleve.NewIndexMapping()
  151. if err := addUnicodeNormalizeTokenFilter(mapping); err != nil {
  152. return nil, err
  153. } else if err := mapping.AddCustomAnalyzer(repoIndexerAnalyzer, map[string]interface{}{
  154. "type": analyzer_custom.Name,
  155. "char_filters": []string{},
  156. "tokenizer": unicode.Name,
  157. "token_filters": []string{unicodeNormalizeName, lowercase.Name},
  158. }); err != nil {
  159. return nil, err
  160. }
  161. mapping.DefaultAnalyzer = repoIndexerAnalyzer
  162. mapping.AddDocumentMapping(repoIndexerDocType, docMapping)
  163. mapping.AddDocumentMapping("_all", bleve.NewDocumentDisabledMapping())
  164. indexer, err := bleve.New(path, mapping)
  165. if err != nil {
  166. return nil, err
  167. }
  168. if err = rupture.WriteIndexMetadata(path, &rupture.IndexMetadata{
  169. Version: latestVersion,
  170. }); err != nil {
  171. return nil, err
  172. }
  173. return indexer, nil
  174. }
  175. func filenameIndexerID(repoID int64, filename string) string {
  176. return indexerID(repoID) + "_" + filename
  177. }
  178. func filenameOfIndexerID(indexerID string) string {
  179. index := strings.IndexByte(indexerID, '_')
  180. if index == -1 {
  181. log.Error("Unexpected ID in repo indexer: %s", indexerID)
  182. }
  183. return indexerID[index+1:]
  184. }
  185. var (
  186. _ Indexer = &BleveIndexer{}
  187. )
  188. // BleveIndexer represents a bleve indexer implementation
  189. type BleveIndexer struct {
  190. indexDir string
  191. indexer bleve.Index
  192. }
  193. // NewBleveIndexer creates a new bleve local indexer
  194. func NewBleveIndexer(indexDir string) (*BleveIndexer, bool, error) {
  195. indexer := &BleveIndexer{
  196. indexDir: indexDir,
  197. }
  198. created, err := indexer.init()
  199. return indexer, created, err
  200. }
  201. // init init the indexer
  202. func (b *BleveIndexer) init() (bool, error) {
  203. var err error
  204. b.indexer, err = openIndexer(b.indexDir, repoIndexerLatestVersion)
  205. if err != nil {
  206. return false, err
  207. }
  208. if b.indexer != nil {
  209. return false, nil
  210. }
  211. b.indexer, err = createRepoIndexer(b.indexDir, repoIndexerLatestVersion)
  212. if err != nil {
  213. return false, err
  214. }
  215. return true, nil
  216. }
  217. // Close close the indexer
  218. func (b *BleveIndexer) Close() {
  219. log.Debug("Closing repo indexer")
  220. if b.indexer != nil {
  221. err := b.indexer.Close()
  222. if err != nil {
  223. log.Error("Error whilst closing the repository indexer: %v", err)
  224. }
  225. }
  226. log.Info("PID: %d Repository Indexer closed", os.Getpid())
  227. }
  228. // Index indexes the data
  229. func (b *BleveIndexer) Index(repoID int64) error {
  230. repo, err := models.GetRepositoryByID(repoID)
  231. if err != nil {
  232. return err
  233. }
  234. sha, err := getDefaultBranchSha(repo)
  235. if err != nil {
  236. return err
  237. }
  238. changes, err := getRepoChanges(repo, sha)
  239. if err != nil {
  240. return err
  241. } else if changes == nil {
  242. return nil
  243. }
  244. batch := rupture.NewFlushingBatch(b.indexer, maxBatchSize)
  245. for _, update := range changes.Updates {
  246. if err := addUpdate(sha, update, repo, batch); err != nil {
  247. return err
  248. }
  249. }
  250. for _, filename := range changes.RemovedFilenames {
  251. if err := addDelete(filename, repo, batch); err != nil {
  252. return err
  253. }
  254. }
  255. if err = batch.Flush(); err != nil {
  256. return err
  257. }
  258. return repo.UpdateIndexerStatus(models.RepoIndexerTypeCode, sha)
  259. }
  260. // Delete deletes indexes by ids
  261. func (b *BleveIndexer) Delete(repoID int64) error {
  262. query := numericEqualityQuery(repoID, "RepoID")
  263. searchRequest := bleve.NewSearchRequestOptions(query, 2147483647, 0, false)
  264. result, err := b.indexer.Search(searchRequest)
  265. if err != nil {
  266. return err
  267. }
  268. batch := rupture.NewFlushingBatch(b.indexer, maxBatchSize)
  269. for _, hit := range result.Hits {
  270. if err = batch.Delete(hit.ID); err != nil {
  271. return err
  272. }
  273. }
  274. return batch.Flush()
  275. }
  276. // Search searches for files in the specified repo.
  277. // Returns the matching file-paths
  278. func (b *BleveIndexer) Search(repoIDs []int64, language, keyword string, page, pageSize int) (int64, []*SearchResult, []*SearchResultLanguages, error) {
  279. phraseQuery := bleve.NewMatchPhraseQuery(keyword)
  280. phraseQuery.FieldVal = "Content"
  281. phraseQuery.Analyzer = repoIndexerAnalyzer
  282. var indexerQuery query.Query
  283. if len(repoIDs) > 0 {
  284. var repoQueries = make([]query.Query, 0, len(repoIDs))
  285. for _, repoID := range repoIDs {
  286. repoQueries = append(repoQueries, numericEqualityQuery(repoID, "RepoID"))
  287. }
  288. indexerQuery = bleve.NewConjunctionQuery(
  289. bleve.NewDisjunctionQuery(repoQueries...),
  290. phraseQuery,
  291. )
  292. } else {
  293. indexerQuery = phraseQuery
  294. }
  295. // Save for reuse without language filter
  296. facetQuery := indexerQuery
  297. if len(language) > 0 {
  298. languageQuery := bleve.NewMatchQuery(language)
  299. languageQuery.FieldVal = "Language"
  300. languageQuery.Analyzer = analyzer_keyword.Name
  301. indexerQuery = bleve.NewConjunctionQuery(
  302. indexerQuery,
  303. languageQuery,
  304. )
  305. }
  306. from := (page - 1) * pageSize
  307. searchRequest := bleve.NewSearchRequestOptions(indexerQuery, pageSize, from, false)
  308. searchRequest.Fields = []string{"Content", "RepoID", "Language", "CommitID", "UpdatedAt"}
  309. searchRequest.IncludeLocations = true
  310. if len(language) == 0 {
  311. searchRequest.AddFacet("languages", bleve.NewFacetRequest("Language", 10))
  312. }
  313. result, err := b.indexer.Search(searchRequest)
  314. if err != nil {
  315. return 0, nil, nil, err
  316. }
  317. total := int64(result.Total)
  318. searchResults := make([]*SearchResult, len(result.Hits))
  319. for i, hit := range result.Hits {
  320. var startIndex, endIndex int = -1, -1
  321. for _, locations := range hit.Locations["Content"] {
  322. location := locations[0]
  323. locationStart := int(location.Start)
  324. locationEnd := int(location.End)
  325. if startIndex < 0 || locationStart < startIndex {
  326. startIndex = locationStart
  327. }
  328. if endIndex < 0 || locationEnd > endIndex {
  329. endIndex = locationEnd
  330. }
  331. }
  332. language := hit.Fields["Language"].(string)
  333. var updatedUnix timeutil.TimeStamp
  334. if t, err := time.Parse(time.RFC3339, hit.Fields["UpdatedAt"].(string)); err == nil {
  335. updatedUnix = timeutil.TimeStamp(t.Unix())
  336. }
  337. searchResults[i] = &SearchResult{
  338. RepoID: int64(hit.Fields["RepoID"].(float64)),
  339. StartIndex: startIndex,
  340. EndIndex: endIndex,
  341. Filename: filenameOfIndexerID(hit.ID),
  342. Content: hit.Fields["Content"].(string),
  343. CommitID: hit.Fields["CommitID"].(string),
  344. UpdatedUnix: updatedUnix,
  345. Language: language,
  346. Color: enry.GetColor(language),
  347. }
  348. }
  349. searchResultLanguages := make([]*SearchResultLanguages, 0, 10)
  350. if len(language) > 0 {
  351. // Use separate query to go get all language counts
  352. facetRequest := bleve.NewSearchRequestOptions(facetQuery, 1, 0, false)
  353. facetRequest.Fields = []string{"Content", "RepoID", "Language", "CommitID", "UpdatedAt"}
  354. facetRequest.IncludeLocations = true
  355. facetRequest.AddFacet("languages", bleve.NewFacetRequest("Language", 10))
  356. if result, err = b.indexer.Search(facetRequest); err != nil {
  357. return 0, nil, nil, err
  358. }
  359. }
  360. languagesFacet := result.Facets["languages"]
  361. for _, term := range languagesFacet.Terms {
  362. if len(term.Term) == 0 {
  363. continue
  364. }
  365. searchResultLanguages = append(searchResultLanguages, &SearchResultLanguages{
  366. Language: term.Term,
  367. Color: enry.GetColor(term.Term),
  368. Count: term.Count,
  369. })
  370. }
  371. return total, searchResults, searchResultLanguages, nil
  372. }