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

9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. "strings"
  8. "time"
  9. "github.com/Unknwon/com"
  10. "github.com/go-xorm/xorm"
  11. "gopkg.in/ini.v1"
  12. "code.gitea.io/git"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/process"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/sync"
  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. Updated time.Time `xorm:"-"`
  28. UpdatedUnix int64 `xorm:"INDEX"`
  29. NextUpdate time.Time `xorm:"-"`
  30. NextUpdateUnix int64 `xorm:"INDEX"`
  31. address string `xorm:"-"`
  32. }
  33. // BeforeInsert will be invoked by XORM before inserting a record
  34. func (m *Mirror) BeforeInsert() {
  35. if m != nil {
  36. m.UpdatedUnix = time.Now().Unix()
  37. m.NextUpdateUnix = m.NextUpdate.Unix()
  38. }
  39. }
  40. // BeforeUpdate is invoked from XORM before updating this object.
  41. func (m *Mirror) BeforeUpdate() {
  42. if m != nil {
  43. m.UpdatedUnix = time.Now().Unix()
  44. m.NextUpdateUnix = m.NextUpdate.Unix()
  45. }
  46. }
  47. // AfterSet is invoked from XORM after setting the value of a field of this object.
  48. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
  49. if m == nil {
  50. return
  51. }
  52. var err error
  53. switch colName {
  54. case "repo_id":
  55. m.Repo, err = GetRepositoryByID(m.RepoID)
  56. if err != nil {
  57. log.Error(3, "GetRepositoryByID[%d]: %v", m.ID, err)
  58. }
  59. case "updated_unix":
  60. m.Updated = time.Unix(m.UpdatedUnix, 0).Local()
  61. case "next_update_unix":
  62. m.NextUpdate = time.Unix(m.NextUpdateUnix, 0).Local()
  63. }
  64. }
  65. // ScheduleNextUpdate calculates and sets next update time.
  66. func (m *Mirror) ScheduleNextUpdate() {
  67. m.NextUpdate = time.Now().Add(m.Interval)
  68. }
  69. func (m *Mirror) readAddress() {
  70. if len(m.address) > 0 {
  71. return
  72. }
  73. cfg, err := ini.Load(m.Repo.GitConfigPath())
  74. if err != nil {
  75. log.Error(4, "Load: %v", err)
  76. return
  77. }
  78. m.address = cfg.Section("remote \"origin\"").Key("url").Value()
  79. }
  80. // HandleCloneUserCredentials replaces user credentials from HTTP/HTTPS URL
  81. // with placeholder <credentials>.
  82. // It will fail for any other forms of clone addresses.
  83. func HandleCloneUserCredentials(url string, mosaics bool) string {
  84. i := strings.Index(url, "@")
  85. if i == -1 {
  86. return url
  87. }
  88. start := strings.Index(url, "://")
  89. if start == -1 {
  90. return url
  91. }
  92. if mosaics {
  93. return url[:start+3] + "<credentials>" + url[i:]
  94. }
  95. return url[:start+3] + url[i+1:]
  96. }
  97. // Address returns mirror address from Git repository config without credentials.
  98. func (m *Mirror) Address() string {
  99. m.readAddress()
  100. return HandleCloneUserCredentials(m.address, false)
  101. }
  102. // FullAddress returns mirror address from Git repository config.
  103. func (m *Mirror) FullAddress() string {
  104. m.readAddress()
  105. return m.address
  106. }
  107. // SaveAddress writes new address to Git repository config.
  108. func (m *Mirror) SaveAddress(addr string) error {
  109. configPath := m.Repo.GitConfigPath()
  110. cfg, err := ini.Load(configPath)
  111. if err != nil {
  112. return fmt.Errorf("Load: %v", err)
  113. }
  114. cfg.Section("remote \"origin\"").Key("url").SetValue(addr)
  115. return cfg.SaveToIndent(configPath, "\t")
  116. }
  117. // runSync returns true if sync finished without error.
  118. func (m *Mirror) runSync() bool {
  119. repoPath := m.Repo.RepoPath()
  120. wikiPath := m.Repo.WikiPath()
  121. timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second
  122. gitArgs := []string{"remote", "update"}
  123. if m.EnablePrune {
  124. gitArgs = append(gitArgs, "--prune")
  125. }
  126. if _, stderr, err := process.GetManager().ExecDir(
  127. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  128. "git", gitArgs...); err != nil {
  129. desc := fmt.Sprintf("Failed to update mirror repository '%s': %s", repoPath, stderr)
  130. log.Error(4, desc)
  131. if err = CreateRepositoryNotice(desc); err != nil {
  132. log.Error(4, "CreateRepositoryNotice: %v", err)
  133. }
  134. return false
  135. }
  136. gitRepo, err := git.OpenRepository(repoPath)
  137. if err != nil {
  138. log.Error(4, "OpenRepository: %v", err)
  139. return false
  140. }
  141. if err = SyncReleasesWithTags(m.Repo, gitRepo); err != nil {
  142. log.Error(4, "Failed to synchronize tags to releases for repository: %v", err)
  143. }
  144. if err := m.Repo.UpdateSize(); err != nil {
  145. log.Error(4, "Failed to update size for mirror repository: %v", err)
  146. }
  147. if m.Repo.HasWiki() {
  148. if _, stderr, err := process.GetManager().ExecDir(
  149. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  150. "git", "remote", "update", "--prune"); err != nil {
  151. desc := fmt.Sprintf("Failed to update mirror wiki repository '%s': %s", wikiPath, stderr)
  152. log.Error(4, desc)
  153. if err = CreateRepositoryNotice(desc); err != nil {
  154. log.Error(4, "CreateRepositoryNotice: %v", err)
  155. }
  156. return false
  157. }
  158. }
  159. return true
  160. }
  161. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  162. m := &Mirror{RepoID: repoID}
  163. has, err := e.Get(m)
  164. if err != nil {
  165. return nil, err
  166. } else if !has {
  167. return nil, ErrMirrorNotExist
  168. }
  169. return m, nil
  170. }
  171. // GetMirrorByRepoID returns mirror information of a repository.
  172. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  173. return getMirrorByRepoID(x, repoID)
  174. }
  175. func updateMirror(e Engine, m *Mirror) error {
  176. _, err := e.Id(m.ID).AllCols().Update(m)
  177. return err
  178. }
  179. // UpdateMirror updates the mirror
  180. func UpdateMirror(m *Mirror) error {
  181. return updateMirror(x, m)
  182. }
  183. // DeleteMirrorByRepoID deletes a mirror by repoID
  184. func DeleteMirrorByRepoID(repoID int64) error {
  185. _, err := x.Delete(&Mirror{RepoID: repoID})
  186. return err
  187. }
  188. // MirrorUpdate checks and updates mirror repositories.
  189. func MirrorUpdate() {
  190. if !taskStatusTable.StartIfNotRunning(mirrorUpdate) {
  191. return
  192. }
  193. defer taskStatusTable.Stop(mirrorUpdate)
  194. log.Trace("Doing: MirrorUpdate")
  195. if err := x.
  196. Where("next_update_unix<=?", time.Now().Unix()).
  197. Iterate(new(Mirror), func(idx int, bean interface{}) error {
  198. m := bean.(*Mirror)
  199. if m.Repo == nil {
  200. log.Error(4, "Disconnected mirror repository found: %d", m.ID)
  201. return nil
  202. }
  203. MirrorQueue.Add(m.RepoID)
  204. return nil
  205. }); err != nil {
  206. log.Error(4, "MirrorUpdate: %v", err)
  207. }
  208. }
  209. // SyncMirrors checks and syncs mirrors.
  210. // TODO: sync more mirrors at same time.
  211. func SyncMirrors() {
  212. // Start listening on new sync requests.
  213. for repoID := range MirrorQueue.Queue() {
  214. log.Trace("SyncMirrors [repo_id: %v]", repoID)
  215. MirrorQueue.Remove(repoID)
  216. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  217. if err != nil {
  218. log.Error(4, "GetMirrorByRepoID [%s]: %v", repoID, err)
  219. continue
  220. }
  221. if !m.runSync() {
  222. continue
  223. }
  224. m.ScheduleNextUpdate()
  225. if err = UpdateMirror(m); err != nil {
  226. log.Error(4, "UpdateMirror [%s]: %v", repoID, err)
  227. continue
  228. }
  229. }
  230. }
  231. // InitSyncMirrors initializes a go routine to sync the mirrors
  232. func InitSyncMirrors() {
  233. go SyncMirrors()
  234. }