mirror.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. // findPasswordInMirrorAddress returns start (inclusive) and end index (exclusive)
  61. // of password portion of credentials in given mirror address.
  62. // It returns a boolean value to indicate whether password portion is found.
  63. func findPasswordInMirrorAddress(addr string) (start int, end int, found bool) {
  64. // Find end of credentials (start of path)
  65. end = strings.LastIndex(addr, "@")
  66. if end == -1 {
  67. return -1, -1, false
  68. }
  69. // Find delimiter of credentials (end of username)
  70. start = strings.Index(addr, "://")
  71. if start == -1 {
  72. return -1, -1, false
  73. }
  74. start += 3
  75. delim := strings.Index(addr[start:], ":")
  76. if delim == -1 {
  77. return -1, -1, false
  78. }
  79. delim += 1
  80. if start+delim >= end {
  81. return -1, -1, false // No password portion presented
  82. }
  83. return start + delim, end, true
  84. }
  85. // unescapeMirrorCredentials returns mirror address with unescaped credentials.
  86. func unescapeMirrorCredentials(addr string) string {
  87. start, end, found := findPasswordInMirrorAddress(addr)
  88. if !found {
  89. return addr
  90. }
  91. password, _ := url.QueryUnescape(addr[start:end])
  92. return addr[:start] + password + addr[end:]
  93. }
  94. func (m *Mirror) readAddress() {
  95. if len(m.address) > 0 {
  96. return
  97. }
  98. cfg, err := ini.Load(m.Repo.GitConfigPath())
  99. if err != nil {
  100. log.Error(2, "Load: %v", err)
  101. return
  102. }
  103. m.address = unescapeMirrorCredentials(cfg.Section("remote \"origin\"").Key("url").Value())
  104. }
  105. // HandleCloneUserCredentials replaces user credentials from HTTP/HTTPS URL
  106. // with placeholder <credentials>.
  107. // It will fail for any other forms of clone addresses.
  108. func HandleCloneUserCredentials(url string, mosaics bool) string {
  109. i := strings.Index(url, "@")
  110. if i == -1 {
  111. return url
  112. }
  113. start := strings.Index(url, "://")
  114. if start == -1 {
  115. return url
  116. }
  117. if mosaics {
  118. return url[:start+3] + "<credentials>" + url[i:]
  119. }
  120. return url[:start+3] + url[i+1:]
  121. }
  122. // Address returns mirror address from Git repository config without credentials.
  123. func (m *Mirror) Address() string {
  124. m.readAddress()
  125. return HandleCloneUserCredentials(m.address, false)
  126. }
  127. // MosaicsAddress returns mirror address from Git repository config with credentials under mosaics.
  128. func (m *Mirror) MosaicsAddress() string {
  129. m.readAddress()
  130. return HandleCloneUserCredentials(m.address, true)
  131. }
  132. // FullAddress returns mirror address from Git repository config.
  133. func (m *Mirror) FullAddress() string {
  134. m.readAddress()
  135. return m.address
  136. }
  137. // escapeCredentials returns mirror address with escaped credentials.
  138. func escapeMirrorCredentials(addr string) string {
  139. start, end, found := findPasswordInMirrorAddress(addr)
  140. if !found {
  141. return addr
  142. }
  143. return addr[:start] + url.QueryEscape(addr[start:end]) + addr[end:]
  144. }
  145. // SaveAddress writes new address to Git repository config.
  146. func (m *Mirror) SaveAddress(addr string) error {
  147. configPath := m.Repo.GitConfigPath()
  148. cfg, err := ini.Load(configPath)
  149. if err != nil {
  150. return fmt.Errorf("Load: %v", err)
  151. }
  152. cfg.Section("remote \"origin\"").Key("url").SetValue(escapeMirrorCredentials(addr))
  153. return cfg.SaveToIndent(configPath, "\t")
  154. }
  155. // runSync returns true if sync finished without error.
  156. func (m *Mirror) runSync() bool {
  157. repoPath := m.Repo.RepoPath()
  158. wikiPath := m.Repo.WikiPath()
  159. timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second
  160. // Do a fast-fail testing against on repository URL to ensure it is accessible under
  161. // good condition to prevent long blocking on URL resolution without syncing anything.
  162. if !git.IsRepoURLAccessible(git.NetworkOptions{
  163. URL: m.FullAddress(),
  164. Timeout: 10 * time.Second,
  165. }) {
  166. desc := fmt.Sprintf("Source URL of mirror repository '%s' is not accessible: %s", m.Repo.FullName(), m.MosaicsAddress())
  167. if err := CreateRepositoryNotice(desc); err != nil {
  168. log.Error(2, "CreateRepositoryNotice: %v", err)
  169. }
  170. return false
  171. }
  172. gitArgs := []string{"remote", "update"}
  173. if m.EnablePrune {
  174. gitArgs = append(gitArgs, "--prune")
  175. }
  176. if _, stderr, err := process.ExecDir(
  177. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  178. "git", gitArgs...); err != nil {
  179. desc := fmt.Sprintf("Fail to update mirror repository '%s': %s", repoPath, stderr)
  180. log.Error(2, desc)
  181. if err = CreateRepositoryNotice(desc); err != nil {
  182. log.Error(2, "CreateRepositoryNotice: %v", err)
  183. }
  184. return false
  185. }
  186. if err := m.Repo.UpdateSize(); err != nil {
  187. log.Error(2, "UpdateSize [repo_id: %d]: %v", m.Repo.ID, err)
  188. }
  189. if m.Repo.HasWiki() {
  190. if _, stderr, err := process.ExecDir(
  191. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  192. "git", "remote", "update", "--prune"); err != nil {
  193. desc := fmt.Sprintf("Fail to update mirror wiki repository '%s': %s", wikiPath, stderr)
  194. log.Error(2, desc)
  195. if err = CreateRepositoryNotice(desc); err != nil {
  196. log.Error(2, "CreateRepositoryNotice: %v", err)
  197. }
  198. return false
  199. }
  200. }
  201. return true
  202. }
  203. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  204. m := &Mirror{RepoID: repoID}
  205. has, err := e.Get(m)
  206. if err != nil {
  207. return nil, err
  208. } else if !has {
  209. return nil, errors.MirrorNotExist{repoID}
  210. }
  211. return m, nil
  212. }
  213. // GetMirrorByRepoID returns mirror information of a repository.
  214. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  215. return getMirrorByRepoID(x, repoID)
  216. }
  217. func updateMirror(e Engine, m *Mirror) error {
  218. _, err := e.Id(m.ID).AllCols().Update(m)
  219. return err
  220. }
  221. func UpdateMirror(m *Mirror) error {
  222. return updateMirror(x, m)
  223. }
  224. func DeleteMirrorByRepoID(repoID int64) error {
  225. _, err := x.Delete(&Mirror{RepoID: repoID})
  226. return err
  227. }
  228. // MirrorUpdate checks and updates mirror repositories.
  229. func MirrorUpdate() {
  230. if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
  231. return
  232. }
  233. taskStatusTable.Start(_MIRROR_UPDATE)
  234. defer taskStatusTable.Stop(_MIRROR_UPDATE)
  235. log.Trace("Doing: MirrorUpdate")
  236. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  237. m := bean.(*Mirror)
  238. if m.Repo == nil {
  239. log.Error(2, "Disconnected mirror repository found: %d", m.ID)
  240. return nil
  241. }
  242. MirrorQueue.Add(m.RepoID)
  243. return nil
  244. }); err != nil {
  245. log.Error(2, "MirrorUpdate: %v", err)
  246. }
  247. }
  248. // SyncMirrors checks and syncs mirrors.
  249. // TODO: sync more mirrors at same time.
  250. func SyncMirrors() {
  251. // Start listening on new sync requests.
  252. for repoID := range MirrorQueue.Queue() {
  253. log.Trace("SyncMirrors [repo_id: %v]", repoID)
  254. MirrorQueue.Remove(repoID)
  255. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  256. if err != nil {
  257. log.Error(2, "GetMirrorByRepoID [%s]: %v", m.RepoID, err)
  258. continue
  259. }
  260. if !m.runSync() {
  261. continue
  262. }
  263. m.ScheduleNextUpdate()
  264. if err = UpdateMirror(m); err != nil {
  265. log.Error(2, "UpdateMirror [%s]: %v", m.RepoID, err)
  266. continue
  267. }
  268. // Update repository last updated time
  269. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", time.Now().Unix(), m.RepoID); err != nil {
  270. log.Error(2, "Update repository 'updated_unix' [%s]: %v", m.RepoID, err)
  271. }
  272. }
  273. }
  274. func InitSyncMirrors() {
  275. go SyncMirrors()
  276. }