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.

repo_indexer.go 9.6KB

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