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_mirror.go 7.7KB

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