Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

repo_indexer.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. repoID int64
  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. repoID: repo.ID,
  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(repoID int64) error {
  120. repo, err := getRepositoryByID(x, repoID)
  121. if err != nil {
  122. return err
  123. }
  124. sha, err := getDefaultBranchSha(repo)
  125. if err != nil {
  126. return err
  127. }
  128. changes, err := getRepoChanges(repo, sha)
  129. if err != nil {
  130. return err
  131. } else if changes == nil {
  132. return nil
  133. }
  134. batch := indexer.RepoIndexerBatch()
  135. for _, update := range changes.Updates {
  136. if err := addUpdate(update, repo, batch); err != nil {
  137. return err
  138. }
  139. }
  140. for _, filename := range changes.RemovedFilenames {
  141. if err := addDelete(filename, repo, batch); err != nil {
  142. return err
  143. }
  144. }
  145. if err = batch.Flush(); err != nil {
  146. return err
  147. }
  148. return repo.updateIndexerStatus(sha)
  149. }
  150. // repoChanges changes (file additions/updates/removals) to a repo
  151. type repoChanges struct {
  152. Updates []fileUpdate
  153. RemovedFilenames []string
  154. }
  155. type fileUpdate struct {
  156. Filename string
  157. BlobSha string
  158. }
  159. func getDefaultBranchSha(repo *Repository) (string, error) {
  160. stdout, err := git.NewCommand("show-ref", "-s", repo.DefaultBranch).RunInDir(repo.RepoPath())
  161. if err != nil {
  162. return "", err
  163. }
  164. return strings.TrimSpace(stdout), nil
  165. }
  166. // getRepoChanges returns changes to repo since last indexer update
  167. func getRepoChanges(repo *Repository, revision string) (*repoChanges, error) {
  168. if err := repo.getIndexerStatus(); err != nil {
  169. return nil, err
  170. }
  171. if len(repo.IndexerStatus.CommitSha) == 0 {
  172. return genesisChanges(repo, revision)
  173. }
  174. return nonGenesisChanges(repo, revision)
  175. }
  176. func addUpdate(update fileUpdate, repo *Repository, batch rupture.FlushingBatch) error {
  177. stdout, err := git.NewCommand("cat-file", "-s", update.BlobSha).
  178. RunInDir(repo.RepoPath())
  179. if err != nil {
  180. return err
  181. }
  182. if size, err := strconv.Atoi(strings.TrimSpace(stdout)); err != nil {
  183. return fmt.Errorf("Misformatted git cat-file output: %v", err)
  184. } else if int64(size) > setting.Indexer.MaxIndexerFileSize {
  185. return addDelete(update.Filename, repo, batch)
  186. }
  187. fileContents, err := git.NewCommand("cat-file", "blob", update.BlobSha).
  188. RunInDirBytes(repo.RepoPath())
  189. if err != nil {
  190. return err
  191. } else if !base.IsTextFile(fileContents) {
  192. // FIXME: UTF-16 files will probably fail here
  193. return nil
  194. }
  195. indexerUpdate := indexer.RepoIndexerUpdate{
  196. Filepath: update.Filename,
  197. Op: indexer.RepoIndexerOpUpdate,
  198. Data: &indexer.RepoIndexerData{
  199. RepoID: repo.ID,
  200. Content: string(charset.ToUTF8DropErrors(fileContents)),
  201. },
  202. }
  203. return indexerUpdate.AddToFlushingBatch(batch)
  204. }
  205. func addDelete(filename string, repo *Repository, batch rupture.FlushingBatch) error {
  206. indexerUpdate := indexer.RepoIndexerUpdate{
  207. Filepath: filename,
  208. Op: indexer.RepoIndexerOpDelete,
  209. Data: &indexer.RepoIndexerData{
  210. RepoID: repo.ID,
  211. },
  212. }
  213. return indexerUpdate.AddToFlushingBatch(batch)
  214. }
  215. func isIndexable(entry *git.TreeEntry) bool {
  216. if !entry.IsRegular() && !entry.IsExecutable() {
  217. return false
  218. }
  219. name := strings.ToLower(entry.Name())
  220. for _, g := range setting.Indexer.ExcludePatterns {
  221. if g.Match(name) {
  222. return false
  223. }
  224. }
  225. for _, g := range setting.Indexer.IncludePatterns {
  226. if g.Match(name) {
  227. return true
  228. }
  229. }
  230. return len(setting.Indexer.IncludePatterns) == 0
  231. }
  232. // parseGitLsTreeOutput parses the output of a `git ls-tree -r --full-name` command
  233. func parseGitLsTreeOutput(stdout []byte) ([]fileUpdate, error) {
  234. entries, err := git.ParseTreeEntries(stdout)
  235. if err != nil {
  236. return nil, err
  237. }
  238. var idxCount = 0
  239. updates := make([]fileUpdate, len(entries))
  240. for _, entry := range entries {
  241. if isIndexable(entry) {
  242. updates[idxCount] = fileUpdate{
  243. Filename: entry.Name(),
  244. BlobSha: entry.ID.String(),
  245. }
  246. idxCount++
  247. }
  248. }
  249. return updates[:idxCount], nil
  250. }
  251. // genesisChanges get changes to add repo to the indexer for the first time
  252. func genesisChanges(repo *Repository, revision string) (*repoChanges, error) {
  253. var changes repoChanges
  254. stdout, err := git.NewCommand("ls-tree", "--full-tree", "-r", revision).
  255. RunInDirBytes(repo.RepoPath())
  256. if err != nil {
  257. return nil, err
  258. }
  259. changes.Updates, err = parseGitLsTreeOutput(stdout)
  260. return &changes, err
  261. }
  262. // nonGenesisChanges get changes since the previous indexer update
  263. func nonGenesisChanges(repo *Repository, revision string) (*repoChanges, error) {
  264. diffCmd := git.NewCommand("diff", "--name-status",
  265. repo.IndexerStatus.CommitSha, revision)
  266. stdout, err := diffCmd.RunInDir(repo.RepoPath())
  267. if err != nil {
  268. // previous commit sha may have been removed by a force push, so
  269. // try rebuilding from scratch
  270. log.Warn("git diff: %v", err)
  271. if err = indexer.DeleteRepoFromIndexer(repo.ID); err != nil {
  272. return nil, err
  273. }
  274. return genesisChanges(repo, revision)
  275. }
  276. var changes repoChanges
  277. updatedFilenames := make([]string, 0, 10)
  278. for _, line := range strings.Split(stdout, "\n") {
  279. line = strings.TrimSpace(line)
  280. if len(line) == 0 {
  281. continue
  282. }
  283. filename := strings.TrimSpace(line[1:])
  284. if len(filename) == 0 {
  285. continue
  286. } else if filename[0] == '"' {
  287. filename, err = strconv.Unquote(filename)
  288. if err != nil {
  289. return nil, err
  290. }
  291. }
  292. switch status := line[0]; status {
  293. case 'M', 'A':
  294. updatedFilenames = append(updatedFilenames, filename)
  295. case 'D':
  296. changes.RemovedFilenames = append(changes.RemovedFilenames, filename)
  297. default:
  298. log.Warn("Unrecognized status: %c (line=%s)", status, line)
  299. }
  300. }
  301. cmd := git.NewCommand("ls-tree", "--full-tree", revision, "--")
  302. cmd.AddArguments(updatedFilenames...)
  303. lsTreeStdout, err := cmd.RunInDirBytes(repo.RepoPath())
  304. if err != nil {
  305. return nil, err
  306. }
  307. changes.Updates, err = parseGitLsTreeOutput(lsTreeStdout)
  308. return &changes, err
  309. }
  310. func processRepoIndexerOperationQueue() {
  311. for {
  312. op := <-repoIndexerOperationQueue
  313. var err error
  314. if op.deleted {
  315. if err = indexer.DeleteRepoFromIndexer(op.repoID); err != nil {
  316. log.Error("DeleteRepoFromIndexer: %v", err)
  317. }
  318. } else {
  319. if err = updateRepoIndexer(op.repoID); err != nil {
  320. log.Error("updateRepoIndexer: %v", err)
  321. }
  322. }
  323. for _, watcher := range op.watchers {
  324. watcher <- err
  325. }
  326. }
  327. }
  328. // DeleteRepoFromIndexer remove all of a repository's entries from the indexer
  329. func DeleteRepoFromIndexer(repo *Repository, watchers ...chan<- error) {
  330. addOperationToQueue(repoIndexerOperation{repoID: repo.ID, deleted: true, watchers: watchers})
  331. }
  332. // UpdateRepoIndexer update a repository's entries in the indexer
  333. func UpdateRepoIndexer(repo *Repository, watchers ...chan<- error) {
  334. addOperationToQueue(repoIndexerOperation{repoID: repo.ID, deleted: false, watchers: watchers})
  335. }
  336. func addOperationToQueue(op repoIndexerOperation) {
  337. if !setting.Indexer.RepoIndexerEnabled {
  338. return
  339. }
  340. select {
  341. case repoIndexerOperationQueue <- op:
  342. break
  343. default:
  344. go func() {
  345. repoIndexerOperationQueue <- op
  346. }()
  347. }
  348. }