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 10KB

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