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.9KB

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