You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo_indexer.go 9.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. "io/ioutil"
  7. "os"
  8. "path"
  9. "strconv"
  10. "strings"
  11. "code.gitea.io/git"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/indexer"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "github.com/Unknwon/com"
  17. )
  18. // RepoIndexerStatus status of a repo's entry in the repo indexer
  19. // For now, implicitly refers to default branch
  20. type RepoIndexerStatus struct {
  21. ID int64 `xorm:"pk autoincr"`
  22. RepoID int64 `xorm:"INDEX"`
  23. CommitSha string `xorm:"VARCHAR(40)"`
  24. }
  25. func (repo *Repository) getIndexerStatus() error {
  26. if repo.IndexerStatus != nil {
  27. return nil
  28. }
  29. status := &RepoIndexerStatus{RepoID: repo.ID}
  30. has, err := x.Get(status)
  31. if err != nil {
  32. return err
  33. } else if !has {
  34. status.CommitSha = ""
  35. }
  36. repo.IndexerStatus = status
  37. return nil
  38. }
  39. func (repo *Repository) updateIndexerStatus(sha string) error {
  40. if err := repo.getIndexerStatus(); err != nil {
  41. return err
  42. }
  43. if len(repo.IndexerStatus.CommitSha) == 0 {
  44. repo.IndexerStatus.CommitSha = sha
  45. _, err := x.Insert(repo.IndexerStatus)
  46. return err
  47. }
  48. repo.IndexerStatus.CommitSha = sha
  49. _, err := x.ID(repo.IndexerStatus.ID).Cols("commit_sha").
  50. Update(repo.IndexerStatus)
  51. return err
  52. }
  53. type repoIndexerOperation struct {
  54. repo *Repository
  55. deleted bool
  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(4, "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. changes, err := getRepoChanges(repo)
  121. if err != nil {
  122. return err
  123. } else if changes == nil {
  124. return nil
  125. }
  126. batch := indexer.RepoIndexerBatch()
  127. for _, filename := range changes.UpdatedFiles {
  128. if err := addUpdate(filename, repo, batch); err != nil {
  129. return err
  130. }
  131. }
  132. for _, filename := range changes.RemovedFiles {
  133. if err := addDelete(filename, repo, batch); err != nil {
  134. return err
  135. }
  136. }
  137. if err = batch.Flush(); err != nil {
  138. return err
  139. }
  140. return updateLastIndexSync(repo)
  141. }
  142. // repoChanges changes (file additions/updates/removals) to a repo
  143. type repoChanges struct {
  144. UpdatedFiles []string
  145. RemovedFiles []string
  146. }
  147. // getRepoChanges returns changes to repo since last indexer update
  148. func getRepoChanges(repo *Repository) (*repoChanges, error) {
  149. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  150. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  151. if err := repo.UpdateLocalCopyBranch(""); err != nil {
  152. return nil, err
  153. } else if !git.IsBranchExist(repo.LocalCopyPath(), repo.DefaultBranch) {
  154. // repo does not have any commits yet, so nothing to update
  155. return nil, nil
  156. } else if err = repo.UpdateLocalCopyBranch(repo.DefaultBranch); err != nil {
  157. return nil, err
  158. } else if err = repo.getIndexerStatus(); err != nil {
  159. return nil, err
  160. }
  161. if len(repo.IndexerStatus.CommitSha) == 0 {
  162. return genesisChanges(repo)
  163. }
  164. return nonGenesisChanges(repo)
  165. }
  166. func addUpdate(filename string, repo *Repository, batch *indexer.Batch) error {
  167. filepath := path.Join(repo.LocalCopyPath(), filename)
  168. if stat, err := os.Stat(filepath); err != nil {
  169. return err
  170. } else if stat.Size() > setting.Indexer.MaxIndexerFileSize {
  171. return nil
  172. } else if stat.IsDir() {
  173. // file could actually be a directory, if it is the root of a submodule.
  174. // We do not index submodule contents, so don't do anything.
  175. return nil
  176. }
  177. fileContents, err := ioutil.ReadFile(filepath)
  178. if err != nil {
  179. return err
  180. } else if !base.IsTextFile(fileContents) {
  181. return nil
  182. }
  183. return batch.Add(indexer.RepoIndexerUpdate{
  184. Filepath: filename,
  185. Op: indexer.RepoIndexerOpUpdate,
  186. Data: &indexer.RepoIndexerData{
  187. RepoID: repo.ID,
  188. Content: string(fileContents),
  189. },
  190. })
  191. }
  192. func addDelete(filename string, repo *Repository, batch *indexer.Batch) error {
  193. return batch.Add(indexer.RepoIndexerUpdate{
  194. Filepath: filename,
  195. Op: indexer.RepoIndexerOpDelete,
  196. Data: &indexer.RepoIndexerData{
  197. RepoID: repo.ID,
  198. },
  199. })
  200. }
  201. // genesisChanges get changes to add repo to the indexer for the first time
  202. func genesisChanges(repo *Repository) (*repoChanges, error) {
  203. var changes repoChanges
  204. stdout, err := git.NewCommand("ls-files").RunInDir(repo.LocalCopyPath())
  205. if err != nil {
  206. return nil, err
  207. }
  208. for _, line := range strings.Split(stdout, "\n") {
  209. filename := strings.TrimSpace(line)
  210. if len(filename) == 0 {
  211. continue
  212. } else if filename[0] == '"' {
  213. filename, err = strconv.Unquote(filename)
  214. if err != nil {
  215. return nil, err
  216. }
  217. }
  218. changes.UpdatedFiles = append(changes.UpdatedFiles, filename)
  219. }
  220. return &changes, nil
  221. }
  222. // nonGenesisChanges get changes since the previous indexer update
  223. func nonGenesisChanges(repo *Repository) (*repoChanges, error) {
  224. diffCmd := git.NewCommand("diff", "--name-status",
  225. repo.IndexerStatus.CommitSha, "HEAD")
  226. stdout, err := diffCmd.RunInDir(repo.LocalCopyPath())
  227. if err != nil {
  228. // previous commit sha may have been removed by a force push, so
  229. // try rebuilding from scratch
  230. if err = indexer.DeleteRepoFromIndexer(repo.ID); err != nil {
  231. return nil, err
  232. }
  233. return genesisChanges(repo)
  234. }
  235. var changes repoChanges
  236. for _, line := range strings.Split(stdout, "\n") {
  237. line = strings.TrimSpace(line)
  238. if len(line) == 0 {
  239. continue
  240. }
  241. filename := strings.TrimSpace(line[1:])
  242. if len(filename) == 0 {
  243. continue
  244. } else if filename[0] == '"' {
  245. filename, err = strconv.Unquote(filename)
  246. if err != nil {
  247. return nil, err
  248. }
  249. }
  250. switch status := line[0]; status {
  251. case 'M', 'A':
  252. changes.UpdatedFiles = append(changes.UpdatedFiles, filename)
  253. case 'D':
  254. changes.RemovedFiles = append(changes.RemovedFiles, filename)
  255. default:
  256. log.Warn("Unrecognized status: %c (line=%s)", status, line)
  257. }
  258. }
  259. return &changes, nil
  260. }
  261. func updateLastIndexSync(repo *Repository) error {
  262. stdout, err := git.NewCommand("rev-parse", "HEAD").RunInDir(repo.LocalCopyPath())
  263. if err != nil {
  264. return err
  265. }
  266. sha := strings.TrimSpace(stdout)
  267. return repo.updateIndexerStatus(sha)
  268. }
  269. func processRepoIndexerOperationQueue() {
  270. for {
  271. op := <-repoIndexerOperationQueue
  272. if op.deleted {
  273. if err := indexer.DeleteRepoFromIndexer(op.repo.ID); err != nil {
  274. log.Error(4, "DeleteRepoFromIndexer: %v", err)
  275. }
  276. } else {
  277. if err := updateRepoIndexer(op.repo); err != nil {
  278. log.Error(4, "updateRepoIndexer: %v", err)
  279. }
  280. }
  281. }
  282. }
  283. // DeleteRepoFromIndexer remove all of a repository's entries from the indexer
  284. func DeleteRepoFromIndexer(repo *Repository) {
  285. addOperationToQueue(repoIndexerOperation{repo: repo, deleted: true})
  286. }
  287. // UpdateRepoIndexer update a repository's entries in the indexer
  288. func UpdateRepoIndexer(repo *Repository) {
  289. addOperationToQueue(repoIndexerOperation{repo: repo, deleted: false})
  290. }
  291. func addOperationToQueue(op repoIndexerOperation) {
  292. if !setting.Indexer.RepoIndexerEnabled {
  293. return
  294. }
  295. select {
  296. case repoIndexerOperationQueue <- op:
  297. break
  298. default:
  299. go func() {
  300. repoIndexerOperationQueue <- op
  301. }()
  302. }
  303. }