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 11 kB

Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. "time"
  10. "code.gitea.io/gitea/modules/base"
  11. "code.gitea.io/gitea/modules/charset"
  12. "code.gitea.io/gitea/modules/git"
  13. "code.gitea.io/gitea/modules/graceful"
  14. "code.gitea.io/gitea/modules/indexer"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "github.com/ethantkoenig/rupture"
  18. )
  19. // RepoIndexerStatus status of a repo's entry in the repo indexer
  20. // For now, implicitly refers to default branch
  21. type RepoIndexerStatus struct {
  22. ID int64 `xorm:"pk autoincr"`
  23. RepoID int64 `xorm:"INDEX"`
  24. CommitSha string `xorm:"VARCHAR(40)"`
  25. }
  26. func (repo *Repository) getIndexerStatus() error {
  27. if repo.IndexerStatus != nil {
  28. return nil
  29. }
  30. status := &RepoIndexerStatus{RepoID: repo.ID}
  31. has, err := x.Get(status)
  32. if err != nil {
  33. return err
  34. } else if !has {
  35. status.CommitSha = ""
  36. }
  37. repo.IndexerStatus = status
  38. return nil
  39. }
  40. func (repo *Repository) updateIndexerStatus(sha string) error {
  41. if err := repo.getIndexerStatus(); err != nil {
  42. return err
  43. }
  44. if len(repo.IndexerStatus.CommitSha) == 0 {
  45. repo.IndexerStatus.CommitSha = sha
  46. _, err := x.Insert(repo.IndexerStatus)
  47. return err
  48. }
  49. repo.IndexerStatus.CommitSha = sha
  50. _, err := x.ID(repo.IndexerStatus.ID).Cols("commit_sha").
  51. Update(repo.IndexerStatus)
  52. return err
  53. }
  54. type repoIndexerOperation struct {
  55. repoID int64
  56. deleted bool
  57. watchers []chan<- error
  58. }
  59. var repoIndexerOperationQueue chan repoIndexerOperation
  60. // InitRepoIndexer initialize the repo indexer
  61. func InitRepoIndexer() {
  62. if !setting.Indexer.RepoIndexerEnabled {
  63. return
  64. }
  65. waitChannel := make(chan time.Duration)
  66. repoIndexerOperationQueue = make(chan repoIndexerOperation, setting.Indexer.UpdateQueueLength)
  67. go func() {
  68. start := time.Now()
  69. log.Info("Initializing Repository Indexer")
  70. indexer.InitRepoIndexer(populateRepoIndexerAsynchronously)
  71. go processRepoIndexerOperationQueue()
  72. waitChannel <- time.Since(start)
  73. }()
  74. if setting.Indexer.StartupTimeout > 0 {
  75. go func() {
  76. timeout := setting.Indexer.StartupTimeout
  77. if graceful.Manager.IsChild() && setting.GracefulHammerTime > 0 {
  78. timeout += setting.GracefulHammerTime
  79. }
  80. select {
  81. case duration := <-waitChannel:
  82. log.Info("Repository Indexer Initialization took %v", duration)
  83. case <-time.After(timeout):
  84. log.Fatal("Repository Indexer Initialization Timed-Out after: %v", timeout)
  85. }
  86. }()
  87. }
  88. }
  89. // populateRepoIndexerAsynchronously asynchronously populates the repo indexer
  90. // with pre-existing data. This should only be run when the indexer is created
  91. // for the first time.
  92. func populateRepoIndexerAsynchronously() error {
  93. exist, err := x.Table("repository").Exist()
  94. if err != nil {
  95. return err
  96. } else if !exist {
  97. return nil
  98. }
  99. // if there is any existing repo indexer metadata in the DB, delete it
  100. // since we are starting afresh. Also, xorm requires deletes to have a
  101. // condition, and we want to delete everything, thus 1=1.
  102. if _, err := x.Where("1=1").Delete(new(RepoIndexerStatus)); err != nil {
  103. return err
  104. }
  105. var maxRepoID int64
  106. if _, err = x.Select("MAX(id)").Table("repository").Get(&maxRepoID); err != nil {
  107. return err
  108. }
  109. go populateRepoIndexer(maxRepoID)
  110. return nil
  111. }
  112. // populateRepoIndexer populate the repo indexer with pre-existing data. This
  113. // should only be run when the indexer is created for the first time.
  114. func populateRepoIndexer(maxRepoID int64) {
  115. log.Info("Populating the repo indexer with existing repositories")
  116. // start with the maximum existing repo ID and work backwards, so that we
  117. // don't include repos that are created after gitea starts; such repos will
  118. // already be added to the indexer, and we don't need to add them again.
  119. for maxRepoID > 0 {
  120. repos := make([]*Repository, 0, RepositoryListDefaultPageSize)
  121. err := x.Where("id <= ?", maxRepoID).
  122. OrderBy("id DESC").
  123. Limit(RepositoryListDefaultPageSize).
  124. Find(&repos)
  125. if err != nil {
  126. log.Error("populateRepoIndexer: %v", err)
  127. return
  128. } else if len(repos) == 0 {
  129. break
  130. }
  131. for _, repo := range repos {
  132. repoIndexerOperationQueue <- repoIndexerOperation{
  133. repoID: repo.ID,
  134. deleted: false,
  135. }
  136. maxRepoID = repo.ID - 1
  137. }
  138. }
  139. log.Info("Done populating the repo indexer with existing repositories")
  140. }
  141. func updateRepoIndexer(repoID int64) error {
  142. repo, err := getRepositoryByID(x, repoID)
  143. if err != nil {
  144. return err
  145. }
  146. sha, err := getDefaultBranchSha(repo)
  147. if err != nil {
  148. return err
  149. }
  150. changes, err := getRepoChanges(repo, sha)
  151. if err != nil {
  152. return err
  153. } else if changes == nil {
  154. return nil
  155. }
  156. batch := indexer.RepoIndexerBatch()
  157. for _, update := range changes.Updates {
  158. if err := addUpdate(update, repo, batch); err != nil {
  159. return err
  160. }
  161. }
  162. for _, filename := range changes.RemovedFilenames {
  163. if err := addDelete(filename, repo, batch); err != nil {
  164. return err
  165. }
  166. }
  167. if err = batch.Flush(); err != nil {
  168. return err
  169. }
  170. return repo.updateIndexerStatus(sha)
  171. }
  172. // repoChanges changes (file additions/updates/removals) to a repo
  173. type repoChanges struct {
  174. Updates []fileUpdate
  175. RemovedFilenames []string
  176. }
  177. type fileUpdate struct {
  178. Filename string
  179. BlobSha string
  180. }
  181. func getDefaultBranchSha(repo *Repository) (string, error) {
  182. stdout, err := git.NewCommand("show-ref", "-s", repo.DefaultBranch).RunInDir(repo.RepoPath())
  183. if err != nil {
  184. return "", err
  185. }
  186. return strings.TrimSpace(stdout), nil
  187. }
  188. // getRepoChanges returns changes to repo since last indexer update
  189. func getRepoChanges(repo *Repository, revision string) (*repoChanges, error) {
  190. if err := repo.getIndexerStatus(); err != nil {
  191. return nil, err
  192. }
  193. if len(repo.IndexerStatus.CommitSha) == 0 {
  194. return genesisChanges(repo, revision)
  195. }
  196. return nonGenesisChanges(repo, revision)
  197. }
  198. func addUpdate(update fileUpdate, repo *Repository, batch rupture.FlushingBatch) error {
  199. stdout, err := git.NewCommand("cat-file", "-s", update.BlobSha).
  200. RunInDir(repo.RepoPath())
  201. if err != nil {
  202. return err
  203. }
  204. if size, err := strconv.Atoi(strings.TrimSpace(stdout)); err != nil {
  205. return fmt.Errorf("Misformatted git cat-file output: %v", err)
  206. } else if int64(size) > setting.Indexer.MaxIndexerFileSize {
  207. return addDelete(update.Filename, repo, batch)
  208. }
  209. fileContents, err := git.NewCommand("cat-file", "blob", update.BlobSha).
  210. RunInDirBytes(repo.RepoPath())
  211. if err != nil {
  212. return err
  213. } else if !base.IsTextFile(fileContents) {
  214. // FIXME: UTF-16 files will probably fail here
  215. return nil
  216. }
  217. indexerUpdate := indexer.RepoIndexerUpdate{
  218. Filepath: update.Filename,
  219. Op: indexer.RepoIndexerOpUpdate,
  220. Data: &indexer.RepoIndexerData{
  221. RepoID: repo.ID,
  222. Content: string(charset.ToUTF8DropErrors(fileContents)),
  223. },
  224. }
  225. return indexerUpdate.AddToFlushingBatch(batch)
  226. }
  227. func addDelete(filename string, repo *Repository, batch rupture.FlushingBatch) error {
  228. indexerUpdate := indexer.RepoIndexerUpdate{
  229. Filepath: filename,
  230. Op: indexer.RepoIndexerOpDelete,
  231. Data: &indexer.RepoIndexerData{
  232. RepoID: repo.ID,
  233. },
  234. }
  235. return indexerUpdate.AddToFlushingBatch(batch)
  236. }
  237. func isIndexable(entry *git.TreeEntry) bool {
  238. if !entry.IsRegular() && !entry.IsExecutable() {
  239. return false
  240. }
  241. name := strings.ToLower(entry.Name())
  242. for _, g := range setting.Indexer.ExcludePatterns {
  243. if g.Match(name) {
  244. return false
  245. }
  246. }
  247. for _, g := range setting.Indexer.IncludePatterns {
  248. if g.Match(name) {
  249. return true
  250. }
  251. }
  252. return len(setting.Indexer.IncludePatterns) == 0
  253. }
  254. // parseGitLsTreeOutput parses the output of a `git ls-tree -r --full-name` command
  255. func parseGitLsTreeOutput(stdout []byte) ([]fileUpdate, error) {
  256. entries, err := git.ParseTreeEntries(stdout)
  257. if err != nil {
  258. return nil, err
  259. }
  260. var idxCount = 0
  261. updates := make([]fileUpdate, len(entries))
  262. for _, entry := range entries {
  263. if isIndexable(entry) {
  264. updates[idxCount] = fileUpdate{
  265. Filename: entry.Name(),
  266. BlobSha: entry.ID.String(),
  267. }
  268. idxCount++
  269. }
  270. }
  271. return updates[:idxCount], nil
  272. }
  273. // genesisChanges get changes to add repo to the indexer for the first time
  274. func genesisChanges(repo *Repository, revision string) (*repoChanges, error) {
  275. var changes repoChanges
  276. stdout, err := git.NewCommand("ls-tree", "--full-tree", "-r", revision).
  277. RunInDirBytes(repo.RepoPath())
  278. if err != nil {
  279. return nil, err
  280. }
  281. changes.Updates, err = parseGitLsTreeOutput(stdout)
  282. return &changes, err
  283. }
  284. // nonGenesisChanges get changes since the previous indexer update
  285. func nonGenesisChanges(repo *Repository, revision string) (*repoChanges, error) {
  286. diffCmd := git.NewCommand("diff", "--name-status",
  287. repo.IndexerStatus.CommitSha, revision)
  288. stdout, err := diffCmd.RunInDir(repo.RepoPath())
  289. if err != nil {
  290. // previous commit sha may have been removed by a force push, so
  291. // try rebuilding from scratch
  292. log.Warn("git diff: %v", err)
  293. if err = indexer.DeleteRepoFromIndexer(repo.ID); err != nil {
  294. return nil, err
  295. }
  296. return genesisChanges(repo, revision)
  297. }
  298. var changes repoChanges
  299. updatedFilenames := make([]string, 0, 10)
  300. for _, line := range strings.Split(stdout, "\n") {
  301. line = strings.TrimSpace(line)
  302. if len(line) == 0 {
  303. continue
  304. }
  305. filename := strings.TrimSpace(line[1:])
  306. if len(filename) == 0 {
  307. continue
  308. } else if filename[0] == '"' {
  309. filename, err = strconv.Unquote(filename)
  310. if err != nil {
  311. return nil, err
  312. }
  313. }
  314. switch status := line[0]; status {
  315. case 'M', 'A':
  316. updatedFilenames = append(updatedFilenames, filename)
  317. case 'D':
  318. changes.RemovedFilenames = append(changes.RemovedFilenames, filename)
  319. default:
  320. log.Warn("Unrecognized status: %c (line=%s)", status, line)
  321. }
  322. }
  323. cmd := git.NewCommand("ls-tree", "--full-tree", revision, "--")
  324. cmd.AddArguments(updatedFilenames...)
  325. lsTreeStdout, err := cmd.RunInDirBytes(repo.RepoPath())
  326. if err != nil {
  327. return nil, err
  328. }
  329. changes.Updates, err = parseGitLsTreeOutput(lsTreeStdout)
  330. return &changes, err
  331. }
  332. func processRepoIndexerOperationQueue() {
  333. for {
  334. op := <-repoIndexerOperationQueue
  335. var err error
  336. if op.deleted {
  337. if err = indexer.DeleteRepoFromIndexer(op.repoID); err != nil {
  338. log.Error("DeleteRepoFromIndexer: %v", err)
  339. }
  340. } else {
  341. if err = updateRepoIndexer(op.repoID); err != nil {
  342. log.Error("updateRepoIndexer: %v", err)
  343. }
  344. }
  345. for _, watcher := range op.watchers {
  346. watcher <- err
  347. }
  348. }
  349. }
  350. // DeleteRepoFromIndexer remove all of a repository's entries from the indexer
  351. func DeleteRepoFromIndexer(repo *Repository, watchers ...chan<- error) {
  352. addOperationToQueue(repoIndexerOperation{repoID: repo.ID, deleted: true, watchers: watchers})
  353. }
  354. // UpdateRepoIndexer update a repository's entries in the indexer
  355. func UpdateRepoIndexer(repo *Repository, watchers ...chan<- error) {
  356. addOperationToQueue(repoIndexerOperation{repoID: repo.ID, deleted: false, watchers: watchers})
  357. }
  358. func addOperationToQueue(op repoIndexerOperation) {
  359. if !setting.Indexer.RepoIndexerEnabled {
  360. return
  361. }
  362. select {
  363. case repoIndexerOperationQueue <- op:
  364. break
  365. default:
  366. go func() {
  367. repoIndexerOperationQueue <- op
  368. }()
  369. }
  370. }