mirror.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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_updated_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 m.Repo.HasWiki() {
  144. if _, stderr, err := process.ExecDir(
  145. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  146. "git", "remote", "update", "--prune"); err != nil {
  147. desc := fmt.Sprintf("Fail to update mirror wiki repository '%s': %s", wikiPath, stderr)
  148. log.Error(2, desc)
  149. if err = CreateRepositoryNotice(desc); err != nil {
  150. log.Error(2, "CreateRepositoryNotice: %v", err)
  151. }
  152. return false
  153. }
  154. }
  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, errors.MirrorNotExist{repoID}
  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. func UpdateMirror(m *Mirror) error {
  176. return updateMirror(x, m)
  177. }
  178. func DeleteMirrorByRepoID(repoID int64) error {
  179. _, err := x.Delete(&Mirror{RepoID: repoID})
  180. return err
  181. }
  182. // MirrorUpdate checks and updates mirror repositories.
  183. func MirrorUpdate() {
  184. if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
  185. return
  186. }
  187. taskStatusTable.Start(_MIRROR_UPDATE)
  188. defer taskStatusTable.Stop(_MIRROR_UPDATE)
  189. log.Trace("Doing: MirrorUpdate")
  190. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  191. m := bean.(*Mirror)
  192. if m.Repo == nil {
  193. log.Error(2, "Disconnected mirror repository found: %d", m.ID)
  194. return nil
  195. }
  196. MirrorQueue.Add(m.RepoID)
  197. return nil
  198. }); err != nil {
  199. log.Error(2, "MirrorUpdate: %v", err)
  200. }
  201. }
  202. // SyncMirrors checks and syncs mirrors.
  203. // TODO: sync more mirrors at same time.
  204. func SyncMirrors() {
  205. // Start listening on new sync requests.
  206. for repoID := range MirrorQueue.Queue() {
  207. log.Trace("SyncMirrors [repo_id: %v]", repoID)
  208. MirrorQueue.Remove(repoID)
  209. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  210. if err != nil {
  211. log.Error(2, "GetMirrorByRepoID [%s]: %v", m.RepoID, err)
  212. continue
  213. }
  214. if !m.runSync() {
  215. continue
  216. }
  217. m.ScheduleNextUpdate()
  218. if err = UpdateMirror(m); err != nil {
  219. log.Error(2, "UpdateMirror [%s]: %v", m.RepoID, err)
  220. continue
  221. }
  222. // Update repository last updated time
  223. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", time.Now().Unix(), m.RepoID); err != nil {
  224. log.Error(2, "Update repository 'updated_unix' [%s]: %v", m.RepoID, err)
  225. }
  226. }
  227. }
  228. func InitSyncMirrors() {
  229. go SyncMirrors()
  230. }