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_mirror.go 8.1 kB

8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // Copyright 2016 The Gogs 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. "time"
  8. "code.gitea.io/git"
  9. "code.gitea.io/gitea/modules/cache"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/process"
  12. "code.gitea.io/gitea/modules/setting"
  13. "code.gitea.io/gitea/modules/sync"
  14. "code.gitea.io/gitea/modules/util"
  15. "github.com/Unknwon/com"
  16. "github.com/go-xorm/xorm"
  17. "gopkg.in/ini.v1"
  18. )
  19. // MirrorQueue holds an UniqueQueue object of the mirror
  20. var MirrorQueue = sync.NewUniqueQueue(setting.Repository.MirrorQueueLength)
  21. // Mirror represents mirror information of a repository.
  22. type Mirror struct {
  23. ID int64 `xorm:"pk autoincr"`
  24. RepoID int64 `xorm:"INDEX"`
  25. Repo *Repository `xorm:"-"`
  26. Interval time.Duration
  27. EnablePrune bool `xorm:"NOT NULL DEFAULT true"`
  28. UpdatedUnix util.TimeStamp `xorm:"INDEX"`
  29. NextUpdateUnix util.TimeStamp `xorm:"INDEX"`
  30. address string `xorm:"-"`
  31. }
  32. // BeforeInsert will be invoked by XORM before inserting a record
  33. func (m *Mirror) BeforeInsert() {
  34. if m != nil {
  35. m.UpdatedUnix = util.TimeStampNow()
  36. m.NextUpdateUnix = util.TimeStampNow()
  37. }
  38. }
  39. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  40. func (m *Mirror) AfterLoad(session *xorm.Session) {
  41. if m == nil {
  42. return
  43. }
  44. var err error
  45. m.Repo, err = getRepositoryByID(session, m.RepoID)
  46. if err != nil {
  47. log.Error(3, "getRepositoryByID[%d]: %v", m.ID, err)
  48. }
  49. }
  50. // ScheduleNextUpdate calculates and sets next update time.
  51. func (m *Mirror) ScheduleNextUpdate() {
  52. m.NextUpdateUnix = util.TimeStampNow().AddDuration(m.Interval)
  53. }
  54. func remoteAddress(repoPath string) (string, error) {
  55. cfg, err := ini.Load(GitConfigPath(repoPath))
  56. if err != nil {
  57. return "", err
  58. }
  59. return cfg.Section("remote \"origin\"").Key("url").Value(), nil
  60. }
  61. func (m *Mirror) readAddress() {
  62. if len(m.address) > 0 {
  63. return
  64. }
  65. var err error
  66. m.address, err = remoteAddress(m.Repo.RepoPath())
  67. if err != nil {
  68. log.Error(4, "remoteAddress: %v", err)
  69. }
  70. }
  71. // sanitizeOutput sanitizes output of a command, replacing occurrences of the
  72. // repository's remote address with a sanitized version.
  73. func sanitizeOutput(output, repoPath string) (string, error) {
  74. remoteAddr, err := remoteAddress(repoPath)
  75. if err != nil {
  76. // if we're unable to load the remote address, then we're unable to
  77. // sanitize.
  78. return "", err
  79. }
  80. return util.SanitizeMessage(output, remoteAddr), nil
  81. }
  82. // Address returns mirror address from Git repository config without credentials.
  83. func (m *Mirror) Address() string {
  84. m.readAddress()
  85. return util.SanitizeURLCredentials(m.address, false)
  86. }
  87. // FullAddress returns mirror address from Git repository config.
  88. func (m *Mirror) FullAddress() string {
  89. m.readAddress()
  90. return m.address
  91. }
  92. // SaveAddress writes new address to Git repository config.
  93. func (m *Mirror) SaveAddress(addr string) error {
  94. configPath := m.Repo.GitConfigPath()
  95. cfg, err := ini.Load(configPath)
  96. if err != nil {
  97. return fmt.Errorf("Load: %v", err)
  98. }
  99. cfg.Section("remote \"origin\"").Key("url").SetValue(addr)
  100. return cfg.SaveToIndent(configPath, "\t")
  101. }
  102. // runSync returns true if sync finished without error.
  103. func (m *Mirror) runSync() bool {
  104. repoPath := m.Repo.RepoPath()
  105. wikiPath := m.Repo.WikiPath()
  106. timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second
  107. gitArgs := []string{"remote", "update"}
  108. if m.EnablePrune {
  109. gitArgs = append(gitArgs, "--prune")
  110. }
  111. if _, stderr, err := process.GetManager().ExecDir(
  112. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  113. "git", gitArgs...); err != nil {
  114. // sanitize the output, since it may contain the remote address, which may
  115. // contain a password
  116. message, err := sanitizeOutput(stderr, repoPath)
  117. if err != nil {
  118. log.Error(4, "sanitizeOutput: %v", err)
  119. return false
  120. }
  121. desc := fmt.Sprintf("Failed to update mirror repository '%s': %s", repoPath, message)
  122. log.Error(4, desc)
  123. if err = CreateRepositoryNotice(desc); err != nil {
  124. log.Error(4, "CreateRepositoryNotice: %v", err)
  125. }
  126. return false
  127. }
  128. gitRepo, err := git.OpenRepository(repoPath)
  129. if err != nil {
  130. log.Error(4, "OpenRepository: %v", err)
  131. return false
  132. }
  133. if err = SyncReleasesWithTags(m.Repo, gitRepo); err != nil {
  134. log.Error(4, "Failed to synchronize tags to releases for repository: %v", err)
  135. }
  136. if err := m.Repo.UpdateSize(); err != nil {
  137. log.Error(4, "Failed to update size for mirror repository: %v", err)
  138. }
  139. if m.Repo.HasWiki() {
  140. if _, stderr, err := process.GetManager().ExecDir(
  141. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  142. "git", "remote", "update", "--prune"); err != nil {
  143. // sanitize the output, since it may contain the remote address, which may
  144. // contain a password
  145. message, err := sanitizeOutput(stderr, wikiPath)
  146. if err != nil {
  147. log.Error(4, "sanitizeOutput: %v", err)
  148. return false
  149. }
  150. desc := fmt.Sprintf("Failed to update mirror wiki repository '%s': %s", wikiPath, message)
  151. log.Error(4, desc)
  152. if err = CreateRepositoryNotice(desc); err != nil {
  153. log.Error(4, "CreateRepositoryNotice: %v", err)
  154. }
  155. return false
  156. }
  157. }
  158. branches, err := m.Repo.GetBranches()
  159. if err != nil {
  160. log.Error(4, "GetBranches: %v", err)
  161. return false
  162. }
  163. for i := range branches {
  164. cache.Remove(m.Repo.GetCommitsCountCacheKey(branches[i].Name, true))
  165. }
  166. m.UpdatedUnix = util.TimeStampNow()
  167. return true
  168. }
  169. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  170. m := &Mirror{RepoID: repoID}
  171. has, err := e.Get(m)
  172. if err != nil {
  173. return nil, err
  174. } else if !has {
  175. return nil, ErrMirrorNotExist
  176. }
  177. return m, nil
  178. }
  179. // GetMirrorByRepoID returns mirror information of a repository.
  180. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  181. return getMirrorByRepoID(x, repoID)
  182. }
  183. func updateMirror(e Engine, m *Mirror) error {
  184. _, err := e.ID(m.ID).AllCols().Update(m)
  185. return err
  186. }
  187. // UpdateMirror updates the mirror
  188. func UpdateMirror(m *Mirror) error {
  189. return updateMirror(x, m)
  190. }
  191. // DeleteMirrorByRepoID deletes a mirror by repoID
  192. func DeleteMirrorByRepoID(repoID int64) error {
  193. _, err := x.Delete(&Mirror{RepoID: repoID})
  194. return err
  195. }
  196. // MirrorUpdate checks and updates mirror repositories.
  197. func MirrorUpdate() {
  198. if !taskStatusTable.StartIfNotRunning(mirrorUpdate) {
  199. return
  200. }
  201. defer taskStatusTable.Stop(mirrorUpdate)
  202. log.Trace("Doing: MirrorUpdate")
  203. if err := x.
  204. Where("next_update_unix<=?", time.Now().Unix()).
  205. Iterate(new(Mirror), func(idx int, bean interface{}) error {
  206. m := bean.(*Mirror)
  207. if m.Repo == nil {
  208. log.Error(4, "Disconnected mirror repository found: %d", m.ID)
  209. return nil
  210. }
  211. MirrorQueue.Add(m.RepoID)
  212. return nil
  213. }); err != nil {
  214. log.Error(4, "MirrorUpdate: %v", err)
  215. }
  216. }
  217. // SyncMirrors checks and syncs mirrors.
  218. // TODO: sync more mirrors at same time.
  219. func SyncMirrors() {
  220. sess := x.NewSession()
  221. defer sess.Close()
  222. // Start listening on new sync requests.
  223. for repoID := range MirrorQueue.Queue() {
  224. log.Trace("SyncMirrors [repo_id: %v]", repoID)
  225. MirrorQueue.Remove(repoID)
  226. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  227. if err != nil {
  228. log.Error(4, "GetMirrorByRepoID [%s]: %v", repoID, err)
  229. continue
  230. }
  231. if !m.runSync() {
  232. continue
  233. }
  234. m.ScheduleNextUpdate()
  235. if err = updateMirror(sess, m); err != nil {
  236. log.Error(4, "UpdateMirror [%s]: %v", repoID, err)
  237. continue
  238. }
  239. // Get latest commit date and update to current repository updated time
  240. commitDate, err := git.GetLatestCommitTime(m.Repo.RepoPath())
  241. if err != nil {
  242. log.Error(2, "GetLatestCommitDate [%s]: %v", m.RepoID, err)
  243. continue
  244. }
  245. if _, err = sess.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", commitDate.Unix(), m.RepoID); err != nil {
  246. log.Error(2, "Update repository 'updated_unix' [%s]: %v", m.RepoID, err)
  247. continue
  248. }
  249. }
  250. }
  251. // InitSyncMirrors initializes a go routine to sync the mirrors
  252. func InitSyncMirrors() {
  253. go SyncMirrors()
  254. }