mirror.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. "net/url"
  8. "strings"
  9. "time"
  10. "github.com/Unknwon/com"
  11. "github.com/go-xorm/xorm"
  12. log "gopkg.in/clog.v1"
  13. "gopkg.in/ini.v1"
  14. "github.com/gogits/git-module"
  15. "github.com/gogits/gogs/models/errors"
  16. "github.com/gogits/gogs/pkg/process"
  17. "github.com/gogits/gogs/pkg/setting"
  18. "github.com/gogits/gogs/pkg/sync"
  19. )
  20. var MirrorQueue = sync.NewUniqueQueue(setting.Repository.MirrorQueueLength)
  21. // Mirror represents mirror information of a repository.
  22. type Mirror struct {
  23. ID int64 `xorm:"pk autoincr"`
  24. RepoID int64
  25. Repo *Repository `xorm:"-"`
  26. Interval int // Hour.
  27. EnablePrune bool `xorm:"NOT NULL DEFAULT true"`
  28. Updated time.Time `xorm:"-"`
  29. UpdatedUnix int64
  30. NextUpdate time.Time `xorm:"-"`
  31. NextUpdateUnix int64
  32. address string `xorm:"-"`
  33. }
  34. func (m *Mirror) BeforeInsert() {
  35. m.UpdatedUnix = time.Now().Unix()
  36. m.NextUpdateUnix = m.NextUpdate.Unix()
  37. }
  38. func (m *Mirror) BeforeUpdate() {
  39. m.UpdatedUnix = time.Now().Unix()
  40. m.NextUpdateUnix = m.NextUpdate.Unix()
  41. }
  42. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
  43. var err error
  44. switch colName {
  45. case "repo_id":
  46. m.Repo, err = GetRepositoryByID(m.RepoID)
  47. if err != nil {
  48. log.Error(3, "GetRepositoryByID [%d]: %v", m.ID, err)
  49. }
  50. case "updated_unix":
  51. m.Updated = time.Unix(m.UpdatedUnix, 0).Local()
  52. case "next_update_unix":
  53. m.NextUpdate = time.Unix(m.NextUpdateUnix, 0).Local()
  54. }
  55. }
  56. // ScheduleNextUpdate calculates and sets next update time.
  57. func (m *Mirror) ScheduleNextUpdate() {
  58. m.NextUpdate = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  59. }
  60. func (m *Mirror) readAddress() {
  61. if len(m.address) > 0 {
  62. return
  63. }
  64. cfg, err := ini.Load(m.Repo.GitConfigPath())
  65. if err != nil {
  66. log.Error(2, "Load: %v", err)
  67. return
  68. }
  69. m.address = cfg.Section("remote \"origin\"").Key("url").Value()
  70. }
  71. // HandleCloneUserCredentials replaces user credentials from HTTP/HTTPS URL
  72. // with placeholder <credentials>.
  73. // It will fail for any other forms of clone addresses.
  74. func HandleCloneUserCredentials(url string, mosaics bool) string {
  75. i := strings.Index(url, "@")
  76. if i == -1 {
  77. return url
  78. }
  79. start := strings.Index(url, "://")
  80. if start == -1 {
  81. return url
  82. }
  83. if mosaics {
  84. return url[:start+3] + "<credentials>" + url[i:]
  85. }
  86. return url[:start+3] + url[i+1:]
  87. }
  88. // Address returns mirror address from Git repository config without credentials.
  89. func (m *Mirror) Address() string {
  90. m.readAddress()
  91. return HandleCloneUserCredentials(m.address, false)
  92. }
  93. // MosaicsAddress returns mirror address from Git repository config with credentials under mosaics.
  94. func (m *Mirror) MosaicsAddress() string {
  95. m.readAddress()
  96. return HandleCloneUserCredentials(m.address, true)
  97. }
  98. // FullAddress returns mirror address from Git repository config.
  99. func (m *Mirror) FullAddress() string {
  100. m.readAddress()
  101. return m.address
  102. }
  103. // escapeCredentials returns mirror address with escaped credentials.
  104. func escapeMirrorCredentials(addr string) string {
  105. // Find end of credentials (start of path)
  106. end := strings.LastIndex(addr, "@")
  107. if end == -1 {
  108. return addr
  109. }
  110. // Find delimiter of credentials (end of username)
  111. start := strings.Index(addr, "://")
  112. if start == -1 {
  113. return addr
  114. }
  115. start += 3
  116. delim := strings.Index(addr[:start], ":")
  117. if delim == -1 {
  118. return addr
  119. }
  120. delim += 1
  121. if start+delim > end {
  122. return addr // No password portion presented
  123. }
  124. return addr[:start+delim] + url.QueryEscape(addr[start+delim:end]) + addr[end:]
  125. }
  126. // SaveAddress writes new address to Git repository config.
  127. func (m *Mirror) SaveAddress(addr string) error {
  128. configPath := m.Repo.GitConfigPath()
  129. cfg, err := ini.Load(configPath)
  130. if err != nil {
  131. return fmt.Errorf("Load: %v", err)
  132. }
  133. cfg.Section("remote \"origin\"").Key("url").SetValue(escapeMirrorCredentials(addr))
  134. return cfg.SaveToIndent(configPath, "\t")
  135. }
  136. // runSync returns true if sync finished without error.
  137. func (m *Mirror) runSync() bool {
  138. repoPath := m.Repo.RepoPath()
  139. wikiPath := m.Repo.WikiPath()
  140. timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second
  141. // Do a fast-fail testing against on repository URL to ensure it is accessible under
  142. // good condition to prevent long blocking on URL resolution without syncing anything.
  143. if !git.IsRepoURLAccessible(git.NetworkOptions{
  144. URL: m.FullAddress(),
  145. Timeout: 10 * time.Second,
  146. }) {
  147. desc := fmt.Sprintf("Source URL of mirror repository '%s' is not accessible: %s", m.Repo.FullName(), m.MosaicsAddress())
  148. if err := CreateRepositoryNotice(desc); err != nil {
  149. log.Error(2, "CreateRepositoryNotice: %v", err)
  150. }
  151. return false
  152. }
  153. gitArgs := []string{"remote", "update"}
  154. if m.EnablePrune {
  155. gitArgs = append(gitArgs, "--prune")
  156. }
  157. if _, stderr, err := process.ExecDir(
  158. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  159. "git", gitArgs...); err != nil {
  160. desc := fmt.Sprintf("Fail to update mirror repository '%s': %s", repoPath, stderr)
  161. log.Error(2, desc)
  162. if err = CreateRepositoryNotice(desc); err != nil {
  163. log.Error(2, "CreateRepositoryNotice: %v", err)
  164. }
  165. return false
  166. }
  167. if err := m.Repo.UpdateSize(); err != nil {
  168. log.Error(2, "UpdateSize [repo_id: %d]: %v", m.Repo.ID, err)
  169. }
  170. if m.Repo.HasWiki() {
  171. if _, stderr, err := process.ExecDir(
  172. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  173. "git", "remote", "update", "--prune"); err != nil {
  174. desc := fmt.Sprintf("Fail to update mirror wiki repository '%s': %s", wikiPath, stderr)
  175. log.Error(2, desc)
  176. if err = CreateRepositoryNotice(desc); err != nil {
  177. log.Error(2, "CreateRepositoryNotice: %v", err)
  178. }
  179. return false
  180. }
  181. }
  182. return true
  183. }
  184. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  185. m := &Mirror{RepoID: repoID}
  186. has, err := e.Get(m)
  187. if err != nil {
  188. return nil, err
  189. } else if !has {
  190. return nil, errors.MirrorNotExist{repoID}
  191. }
  192. return m, nil
  193. }
  194. // GetMirrorByRepoID returns mirror information of a repository.
  195. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  196. return getMirrorByRepoID(x, repoID)
  197. }
  198. func updateMirror(e Engine, m *Mirror) error {
  199. _, err := e.Id(m.ID).AllCols().Update(m)
  200. return err
  201. }
  202. func UpdateMirror(m *Mirror) error {
  203. return updateMirror(x, m)
  204. }
  205. func DeleteMirrorByRepoID(repoID int64) error {
  206. _, err := x.Delete(&Mirror{RepoID: repoID})
  207. return err
  208. }
  209. // MirrorUpdate checks and updates mirror repositories.
  210. func MirrorUpdate() {
  211. if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
  212. return
  213. }
  214. taskStatusTable.Start(_MIRROR_UPDATE)
  215. defer taskStatusTable.Stop(_MIRROR_UPDATE)
  216. log.Trace("Doing: MirrorUpdate")
  217. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  218. m := bean.(*Mirror)
  219. if m.Repo == nil {
  220. log.Error(2, "Disconnected mirror repository found: %d", m.ID)
  221. return nil
  222. }
  223. MirrorQueue.Add(m.RepoID)
  224. return nil
  225. }); err != nil {
  226. log.Error(2, "MirrorUpdate: %v", err)
  227. }
  228. }
  229. // SyncMirrors checks and syncs mirrors.
  230. // TODO: sync more mirrors at same time.
  231. func SyncMirrors() {
  232. // Start listening on new sync requests.
  233. for repoID := range MirrorQueue.Queue() {
  234. log.Trace("SyncMirrors [repo_id: %v]", repoID)
  235. MirrorQueue.Remove(repoID)
  236. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  237. if err != nil {
  238. log.Error(2, "GetMirrorByRepoID [%s]: %v", m.RepoID, err)
  239. continue
  240. }
  241. if !m.runSync() {
  242. continue
  243. }
  244. m.ScheduleNextUpdate()
  245. if err = UpdateMirror(m); err != nil {
  246. log.Error(2, "UpdateMirror [%s]: %v", m.RepoID, err)
  247. continue
  248. }
  249. // Update repository last updated time
  250. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", time.Now().Unix(), m.RepoID); err != nil {
  251. log.Error(2, "Update repository 'updated_unix' [%s]: %v", m.RepoID, err)
  252. }
  253. }
  254. }
  255. func InitSyncMirrors() {
  256. go SyncMirrors()
  257. }