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

bleve.go 10 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. "strconv"
  8. "strings"
  9. "time"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/charset"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/graceful"
  15. "code.gitea.io/gitea/modules/indexer"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. "github.com/ethantkoenig/rupture"
  19. )
  20. type repoIndexerOperation struct {
  21. repoID int64
  22. deleted bool
  23. watchers []chan<- error
  24. }
  25. var repoIndexerOperationQueue chan repoIndexerOperation
  26. // InitRepoIndexer initialize the repo indexer
  27. func InitRepoIndexer() {
  28. if !setting.Indexer.RepoIndexerEnabled {
  29. return
  30. }
  31. waitChannel := make(chan time.Duration)
  32. repoIndexerOperationQueue = make(chan repoIndexerOperation, setting.Indexer.UpdateQueueLength)
  33. go func() {
  34. start := time.Now()
  35. log.Info("Initializing Repository Indexer")
  36. indexer.InitRepoIndexer(populateRepoIndexerAsynchronously)
  37. go processRepoIndexerOperationQueue()
  38. waitChannel <- time.Since(start)
  39. }()
  40. if setting.Indexer.StartupTimeout > 0 {
  41. go func() {
  42. timeout := setting.Indexer.StartupTimeout
  43. if graceful.Manager.IsChild() && setting.GracefulHammerTime > 0 {
  44. timeout += setting.GracefulHammerTime
  45. }
  46. select {
  47. case duration := <-waitChannel:
  48. log.Info("Repository Indexer Initialization took %v", duration)
  49. case <-time.After(timeout):
  50. log.Fatal("Repository Indexer Initialization Timed-Out after: %v", timeout)
  51. }
  52. }()
  53. }
  54. }
  55. // populateRepoIndexerAsynchronously asynchronously populates the repo indexer
  56. // with pre-existing data. This should only be run when the indexer is created
  57. // for the first time.
  58. func populateRepoIndexerAsynchronously() error {
  59. exist, err := models.IsTableNotEmpty("repository")
  60. if err != nil {
  61. return err
  62. } else if !exist {
  63. return nil
  64. }
  65. // if there is any existing repo indexer metadata in the DB, delete it
  66. // since we are starting afresh. Also, xorm requires deletes to have a
  67. // condition, and we want to delete everything, thus 1=1.
  68. if err := models.DeleteAllRecords("repo_indexer_status"); err != nil {
  69. return err
  70. }
  71. var maxRepoID int64
  72. if maxRepoID, err = models.GetMaxID("repository"); err != nil {
  73. return err
  74. }
  75. go populateRepoIndexer(maxRepoID)
  76. return nil
  77. }
  78. // populateRepoIndexer populate the repo indexer with pre-existing data. This
  79. // should only be run when the indexer is created for the first time.
  80. func populateRepoIndexer(maxRepoID int64) {
  81. log.Info("Populating the repo indexer with existing repositories")
  82. // start with the maximum existing repo ID and work backwards, so that we
  83. // don't include repos that are created after gitea starts; such repos will
  84. // already be added to the indexer, and we don't need to add them again.
  85. for maxRepoID > 0 {
  86. repos := make([]*models.Repository, 0, models.RepositoryListDefaultPageSize)
  87. err := models.FindByMaxID(maxRepoID, models.RepositoryListDefaultPageSize, &repos)
  88. if err != nil {
  89. log.Error("populateRepoIndexer: %v", err)
  90. return
  91. } else if len(repos) == 0 {
  92. break
  93. }
  94. for _, repo := range repos {
  95. repoIndexerOperationQueue <- repoIndexerOperation{
  96. repoID: repo.ID,
  97. deleted: false,
  98. }
  99. maxRepoID = repo.ID - 1
  100. }
  101. }
  102. log.Info("Done populating the repo indexer with existing repositories")
  103. }
  104. func updateRepoIndexer(repoID int64) error {
  105. repo, err := models.GetRepositoryByID(repoID)
  106. if err != nil {
  107. return err
  108. }
  109. sha, err := getDefaultBranchSha(repo)
  110. if err != nil {
  111. return err
  112. }
  113. changes, err := getRepoChanges(repo, sha)
  114. if err != nil {
  115. return err
  116. } else if changes == nil {
  117. return nil
  118. }
  119. batch := indexer.RepoIndexerBatch()
  120. for _, update := range changes.Updates {
  121. if err := addUpdate(update, repo, batch); err != nil {
  122. return err
  123. }
  124. }
  125. for _, filename := range changes.RemovedFilenames {
  126. if err := addDelete(filename, repo, batch); err != nil {
  127. return err
  128. }
  129. }
  130. if err = batch.Flush(); err != nil {
  131. return err
  132. }
  133. return repo.UpdateIndexerStatus(sha)
  134. }
  135. // repoChanges changes (file additions/updates/removals) to a repo
  136. type repoChanges struct {
  137. Updates []fileUpdate
  138. RemovedFilenames []string
  139. }
  140. type fileUpdate struct {
  141. Filename string
  142. BlobSha string
  143. }
  144. func getDefaultBranchSha(repo *models.Repository) (string, error) {
  145. stdout, err := git.NewCommand("show-ref", "-s", repo.DefaultBranch).RunInDir(repo.RepoPath())
  146. if err != nil {
  147. return "", err
  148. }
  149. return strings.TrimSpace(stdout), nil
  150. }
  151. // getRepoChanges returns changes to repo since last indexer update
  152. func getRepoChanges(repo *models.Repository, revision string) (*repoChanges, error) {
  153. if err := repo.GetIndexerStatus(); err != nil {
  154. return nil, err
  155. }
  156. if len(repo.IndexerStatus.CommitSha) == 0 {
  157. return genesisChanges(repo, revision)
  158. }
  159. return nonGenesisChanges(repo, revision)
  160. }
  161. func addUpdate(update fileUpdate, repo *models.Repository, batch rupture.FlushingBatch) error {
  162. stdout, err := git.NewCommand("cat-file", "-s", update.BlobSha).
  163. RunInDir(repo.RepoPath())
  164. if err != nil {
  165. return err
  166. }
  167. if size, err := strconv.Atoi(strings.TrimSpace(stdout)); err != nil {
  168. return fmt.Errorf("Misformatted git cat-file output: %v", err)
  169. } else if int64(size) > setting.Indexer.MaxIndexerFileSize {
  170. return addDelete(update.Filename, repo, batch)
  171. }
  172. fileContents, err := git.NewCommand("cat-file", "blob", update.BlobSha).
  173. RunInDirBytes(repo.RepoPath())
  174. if err != nil {
  175. return err
  176. } else if !base.IsTextFile(fileContents) {
  177. // FIXME: UTF-16 files will probably fail here
  178. return nil
  179. }
  180. indexerUpdate := indexer.RepoIndexerUpdate{
  181. Filepath: update.Filename,
  182. Op: indexer.RepoIndexerOpUpdate,
  183. Data: &indexer.RepoIndexerData{
  184. RepoID: repo.ID,
  185. Content: string(charset.ToUTF8DropErrors(fileContents)),
  186. },
  187. }
  188. return indexerUpdate.AddToFlushingBatch(batch)
  189. }
  190. func addDelete(filename string, repo *models.Repository, batch rupture.FlushingBatch) error {
  191. indexerUpdate := indexer.RepoIndexerUpdate{
  192. Filepath: filename,
  193. Op: indexer.RepoIndexerOpDelete,
  194. Data: &indexer.RepoIndexerData{
  195. RepoID: repo.ID,
  196. },
  197. }
  198. return indexerUpdate.AddToFlushingBatch(batch)
  199. }
  200. func isIndexable(entry *git.TreeEntry) bool {
  201. if !entry.IsRegular() && !entry.IsExecutable() {
  202. return false
  203. }
  204. name := strings.ToLower(entry.Name())
  205. for _, g := range setting.Indexer.ExcludePatterns {
  206. if g.Match(name) {
  207. return false
  208. }
  209. }
  210. for _, g := range setting.Indexer.IncludePatterns {
  211. if g.Match(name) {
  212. return true
  213. }
  214. }
  215. return len(setting.Indexer.IncludePatterns) == 0
  216. }
  217. // parseGitLsTreeOutput parses the output of a `git ls-tree -r --full-name` command
  218. func parseGitLsTreeOutput(stdout []byte) ([]fileUpdate, error) {
  219. entries, err := git.ParseTreeEntries(stdout)
  220. if err != nil {
  221. return nil, err
  222. }
  223. var idxCount = 0
  224. updates := make([]fileUpdate, len(entries))
  225. for _, entry := range entries {
  226. if isIndexable(entry) {
  227. updates[idxCount] = fileUpdate{
  228. Filename: entry.Name(),
  229. BlobSha: entry.ID.String(),
  230. }
  231. idxCount++
  232. }
  233. }
  234. return updates[:idxCount], nil
  235. }
  236. // genesisChanges get changes to add repo to the indexer for the first time
  237. func genesisChanges(repo *models.Repository, revision string) (*repoChanges, error) {
  238. var changes repoChanges
  239. stdout, err := git.NewCommand("ls-tree", "--full-tree", "-r", revision).
  240. RunInDirBytes(repo.RepoPath())
  241. if err != nil {
  242. return nil, err
  243. }
  244. changes.Updates, err = parseGitLsTreeOutput(stdout)
  245. return &changes, err
  246. }
  247. // nonGenesisChanges get changes since the previous indexer update
  248. func nonGenesisChanges(repo *models.Repository, revision string) (*repoChanges, error) {
  249. diffCmd := git.NewCommand("diff", "--name-status",
  250. repo.IndexerStatus.CommitSha, revision)
  251. stdout, err := diffCmd.RunInDir(repo.RepoPath())
  252. if err != nil {
  253. // previous commit sha may have been removed by a force push, so
  254. // try rebuilding from scratch
  255. log.Warn("git diff: %v", err)
  256. if err = indexer.DeleteRepoFromIndexer(repo.ID); err != nil {
  257. return nil, err
  258. }
  259. return genesisChanges(repo, revision)
  260. }
  261. var changes repoChanges
  262. updatedFilenames := make([]string, 0, 10)
  263. for _, line := range strings.Split(stdout, "\n") {
  264. line = strings.TrimSpace(line)
  265. if len(line) == 0 {
  266. continue
  267. }
  268. filename := strings.TrimSpace(line[1:])
  269. if len(filename) == 0 {
  270. continue
  271. } else if filename[0] == '"' {
  272. filename, err = strconv.Unquote(filename)
  273. if err != nil {
  274. return nil, err
  275. }
  276. }
  277. switch status := line[0]; status {
  278. case 'M', 'A':
  279. updatedFilenames = append(updatedFilenames, filename)
  280. case 'D':
  281. changes.RemovedFilenames = append(changes.RemovedFilenames, filename)
  282. default:
  283. log.Warn("Unrecognized status: %c (line=%s)", status, line)
  284. }
  285. }
  286. cmd := git.NewCommand("ls-tree", "--full-tree", revision, "--")
  287. cmd.AddArguments(updatedFilenames...)
  288. lsTreeStdout, err := cmd.RunInDirBytes(repo.RepoPath())
  289. if err != nil {
  290. return nil, err
  291. }
  292. changes.Updates, err = parseGitLsTreeOutput(lsTreeStdout)
  293. return &changes, err
  294. }
  295. func processRepoIndexerOperationQueue() {
  296. for {
  297. op := <-repoIndexerOperationQueue
  298. var err error
  299. if op.deleted {
  300. if err = indexer.DeleteRepoFromIndexer(op.repoID); err != nil {
  301. log.Error("DeleteRepoFromIndexer: %v", err)
  302. }
  303. } else {
  304. if err = updateRepoIndexer(op.repoID); err != nil {
  305. log.Error("updateRepoIndexer: %v", err)
  306. }
  307. }
  308. for _, watcher := range op.watchers {
  309. watcher <- err
  310. }
  311. }
  312. }
  313. // DeleteRepoFromIndexer remove all of a repository's entries from the indexer
  314. func DeleteRepoFromIndexer(repo *models.Repository, watchers ...chan<- error) {
  315. addOperationToQueue(repoIndexerOperation{repoID: repo.ID, deleted: true, watchers: watchers})
  316. }
  317. // UpdateRepoIndexer update a repository's entries in the indexer
  318. func UpdateRepoIndexer(repo *models.Repository, watchers ...chan<- error) {
  319. addOperationToQueue(repoIndexerOperation{repoID: repo.ID, deleted: false, watchers: watchers})
  320. }
  321. func addOperationToQueue(op repoIndexerOperation) {
  322. if !setting.Indexer.RepoIndexerEnabled {
  323. return
  324. }
  325. select {
  326. case repoIndexerOperationQueue <- op:
  327. break
  328. default:
  329. go func() {
  330. repoIndexerOperationQueue <- op
  331. }()
  332. }
  333. }