Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

repo_indexer.go 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 addDelete(update.Filename, repo, batch)
  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. func isIndexable(entry *git.TreeEntry) bool {
  210. return entry.IsRegular() || entry.IsExecutable()
  211. }
  212. // parseGitLsTreeOutput parses the output of a `git ls-tree -r --full-name` command
  213. func parseGitLsTreeOutput(stdout []byte) ([]fileUpdate, error) {
  214. entries, err := git.ParseTreeEntries(stdout)
  215. if err != nil {
  216. return nil, err
  217. }
  218. var idxCount = 0
  219. updates := make([]fileUpdate, len(entries))
  220. for _, entry := range entries {
  221. if isIndexable(entry) {
  222. updates[idxCount] = fileUpdate{
  223. Filename: entry.Name(),
  224. BlobSha: entry.ID.String(),
  225. }
  226. idxCount++
  227. }
  228. }
  229. return updates[:idxCount], nil
  230. }
  231. // genesisChanges get changes to add repo to the indexer for the first time
  232. func genesisChanges(repo *Repository, revision string) (*repoChanges, error) {
  233. var changes repoChanges
  234. stdout, err := git.NewCommand("ls-tree", "--full-tree", "-r", revision).
  235. RunInDirBytes(repo.RepoPath())
  236. if err != nil {
  237. return nil, err
  238. }
  239. changes.Updates, err = parseGitLsTreeOutput(stdout)
  240. return &changes, err
  241. }
  242. // nonGenesisChanges get changes since the previous indexer update
  243. func nonGenesisChanges(repo *Repository, revision string) (*repoChanges, error) {
  244. diffCmd := git.NewCommand("diff", "--name-status",
  245. repo.IndexerStatus.CommitSha, revision)
  246. stdout, err := diffCmd.RunInDir(repo.RepoPath())
  247. if err != nil {
  248. // previous commit sha may have been removed by a force push, so
  249. // try rebuilding from scratch
  250. log.Warn("git diff: %v", err)
  251. if err = indexer.DeleteRepoFromIndexer(repo.ID); err != nil {
  252. return nil, err
  253. }
  254. return genesisChanges(repo, revision)
  255. }
  256. var changes repoChanges
  257. updatedFilenames := make([]string, 0, 10)
  258. for _, line := range strings.Split(stdout, "\n") {
  259. line = strings.TrimSpace(line)
  260. if len(line) == 0 {
  261. continue
  262. }
  263. filename := strings.TrimSpace(line[1:])
  264. if len(filename) == 0 {
  265. continue
  266. } else if filename[0] == '"' {
  267. filename, err = strconv.Unquote(filename)
  268. if err != nil {
  269. return nil, err
  270. }
  271. }
  272. switch status := line[0]; status {
  273. case 'M', 'A':
  274. updatedFilenames = append(updatedFilenames, filename)
  275. case 'D':
  276. changes.RemovedFilenames = append(changes.RemovedFilenames, filename)
  277. default:
  278. log.Warn("Unrecognized status: %c (line=%s)", status, line)
  279. }
  280. }
  281. cmd := git.NewCommand("ls-tree", "--full-tree", revision, "--")
  282. cmd.AddArguments(updatedFilenames...)
  283. lsTreeStdout, err := cmd.RunInDirBytes(repo.RepoPath())
  284. if err != nil {
  285. return nil, err
  286. }
  287. changes.Updates, err = parseGitLsTreeOutput(lsTreeStdout)
  288. return &changes, err
  289. }
  290. func processRepoIndexerOperationQueue() {
  291. for {
  292. op := <-repoIndexerOperationQueue
  293. var err error
  294. if op.deleted {
  295. if err = indexer.DeleteRepoFromIndexer(op.repo.ID); err != nil {
  296. log.Error("DeleteRepoFromIndexer: %v", err)
  297. }
  298. } else {
  299. if err = updateRepoIndexer(op.repo); err != nil {
  300. log.Error("updateRepoIndexer: %v", err)
  301. }
  302. }
  303. for _, watcher := range op.watchers {
  304. watcher <- err
  305. }
  306. }
  307. }
  308. // DeleteRepoFromIndexer remove all of a repository's entries from the indexer
  309. func DeleteRepoFromIndexer(repo *Repository, watchers ...chan<- error) {
  310. addOperationToQueue(repoIndexerOperation{repo: repo, deleted: true, watchers: watchers})
  311. }
  312. // UpdateRepoIndexer update a repository's entries in the indexer
  313. func UpdateRepoIndexer(repo *Repository, watchers ...chan<- error) {
  314. addOperationToQueue(repoIndexerOperation{repo: repo, deleted: false, watchers: watchers})
  315. }
  316. func addOperationToQueue(op repoIndexerOperation) {
  317. if !setting.Indexer.RepoIndexerEnabled {
  318. return
  319. }
  320. select {
  321. case repoIndexerOperationQueue <- op:
  322. break
  323. default:
  324. go func() {
  325. repoIndexerOperationQueue <- op
  326. }()
  327. }
  328. }