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

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