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.

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