mirror.go 7.2 KB

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. log "gopkg.in/clog.v1"
  12. "gopkg.in/ini.v1"
  13. "github.com/gogits/git-module"
  14. "github.com/gogits/gogs/models/errors"
  15. "github.com/gogits/gogs/modules/process"
  16. "github.com/gogits/gogs/modules/setting"
  17. "github.com/gogits/gogs/modules/sync"
  18. )
  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
  24. Repo *Repository `xorm:"-"`
  25. Interval int // Hour.
  26. EnablePrune bool `xorm:"NOT NULL DEFAULT true"`
  27. Updated time.Time `xorm:"-"`
  28. UpdatedUnix int64
  29. NextUpdate time.Time `xorm:"-"`
  30. NextUpdateUnix int64
  31. address string `xorm:"-"`
  32. }
  33. func (m *Mirror) BeforeInsert() {
  34. m.UpdatedUnix = time.Now().Unix()
  35. m.NextUpdateUnix = m.NextUpdate.Unix()
  36. }
  37. func (m *Mirror) BeforeUpdate() {
  38. m.UpdatedUnix = time.Now().Unix()
  39. m.NextUpdateUnix = m.NextUpdate.Unix()
  40. }
  41. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
  42. var err error
  43. switch colName {
  44. case "repo_id":
  45. m.Repo, err = GetRepositoryByID(m.RepoID)
  46. if err != nil {
  47. log.Error(3, "GetRepositoryByID [%d]: %v", m.ID, err)
  48. }
  49. case "updated_unix":
  50. m.Updated = time.Unix(m.UpdatedUnix, 0).Local()
  51. case "next_update_unix":
  52. m.NextUpdate = time.Unix(m.NextUpdateUnix, 0).Local()
  53. }
  54. }
  55. // ScheduleNextUpdate calculates and sets next update time.
  56. func (m *Mirror) ScheduleNextUpdate() {
  57. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  58. }
  59. func (m *Mirror) readAddress() {
  60. if len(m.address) > 0 {
  61. return
  62. }
  63. cfg, err := ini.Load(m.Repo.GitConfigPath())
  64. if err != nil {
  65. log.Error(2, "Load: %v", err)
  66. return
  67. }
  68. m.address = cfg.Section("remote \"origin\"").Key("url").Value()
  69. }
  70. // HandleCloneUserCredentials replaces user credentials from HTTP/HTTPS URL
  71. // with placeholder <credentials>.
  72. // It will fail for any other forms of clone addresses.
  73. func HandleCloneUserCredentials(url string, mosaics bool) string {
  74. i := strings.Index(url, "@")
  75. if i == -1 {
  76. return url
  77. }
  78. start := strings.Index(url, "://")
  79. if start == -1 {
  80. return url
  81. }
  82. if mosaics {
  83. return url[:start+3] + "<credentials>" + url[i:]
  84. }
  85. return url[:start+3] + url[i+1:]
  86. }
  87. // Address returns mirror address from Git repository config without credentials.
  88. func (m *Mirror) Address() string {
  89. m.readAddress()
  90. return HandleCloneUserCredentials(m.address, false)
  91. }
  92. // MosaicsAddress returns mirror address from Git repository config with credentials under mosaics.
  93. func (m *Mirror) MosaicsAddress() string {
  94. m.readAddress()
  95. return HandleCloneUserCredentials(m.address, true)
  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. // Do a fast-fail testing against on repository URL to ensure it is accessible under
  118. // good condition to prevent long blocking on URL resolution without syncing anything.
  119. if !git.IsRepoURLAccessible(git.NetworkOptions{
  120. URL: m.FullAddress(),
  121. Timeout: 10 * time.Second,
  122. }) {
  123. desc := fmt.Sprintf("Source URL of mirror repository '%s' is not accessible: %s", m.Repo.FullName(), m.MosaicsAddress())
  124. if err := CreateRepositoryNotice(desc); err != nil {
  125. log.Error(2, "CreateRepositoryNotice: %v", err)
  126. }
  127. return false
  128. }
  129. gitArgs := []string{"remote", "update"}
  130. if m.EnablePrune {
  131. gitArgs = append(gitArgs, "--prune")
  132. }
  133. if _, stderr, err := process.ExecDir(
  134. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  135. "git", gitArgs...); err != nil {
  136. desc := fmt.Sprintf("Fail to update mirror repository '%s': %s", repoPath, stderr)
  137. log.Error(2, desc)
  138. if err = CreateRepositoryNotice(desc); err != nil {
  139. log.Error(2, "CreateRepositoryNotice: %v", err)
  140. }
  141. return false
  142. }
  143. if err := m.Repo.UpdateSize(); err != nil {
  144. log.Error(2, "UpdateSize [repo_id: %d]: %v", m.Repo.ID, err)
  145. }
  146. if m.Repo.HasWiki() {
  147. if _, stderr, err := process.ExecDir(
  148. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  149. "git", "remote", "update", "--prune"); err != nil {
  150. desc := fmt.Sprintf("Fail to update mirror wiki repository '%s': %s", wikiPath, stderr)
  151. log.Error(2, desc)
  152. if err = CreateRepositoryNotice(desc); err != nil {
  153. log.Error(2, "CreateRepositoryNotice: %v", err)
  154. }
  155. return false
  156. }
  157. }
  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, errors.MirrorNotExist{repoID}
  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. func UpdateMirror(m *Mirror) error {
  179. return updateMirror(x, m)
  180. }
  181. func DeleteMirrorByRepoID(repoID int64) error {
  182. _, err := x.Delete(&Mirror{RepoID: repoID})
  183. return err
  184. }
  185. // MirrorUpdate checks and updates mirror repositories.
  186. func MirrorUpdate() {
  187. if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
  188. return
  189. }
  190. taskStatusTable.Start(_MIRROR_UPDATE)
  191. defer taskStatusTable.Stop(_MIRROR_UPDATE)
  192. log.Trace("Doing: MirrorUpdate")
  193. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  194. m := bean.(*Mirror)
  195. if m.Repo == nil {
  196. log.Error(2, "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(2, "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(2, "GetMirrorByRepoID [%s]: %v", m.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(2, "UpdateMirror [%s]: %v", m.RepoID, err)
  223. continue
  224. }
  225. // Update repository last updated time
  226. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", time.Now().Unix(), m.RepoID); err != nil {
  227. log.Error(2, "Update repository 'updated_unix' [%s]: %v", m.RepoID, err)
  228. }
  229. }
  230. }
  231. func InitSyncMirrors() {
  232. go SyncMirrors()
  233. }