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.

272 lines
6.9 KiB

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