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

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