mirror.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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
  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 = cfg.Section("remote \"origin\"").Key("url").Value()
  104. }
  105. // HandleMirrorCredentials replaces user credentials from HTTP/HTTPS URL
  106. // with placeholder <credentials>.
  107. // It returns original string if protocol is not HTTP/HTTPS.
  108. func HandleMirrorCredentials(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 HandleMirrorCredentials(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 HandleMirrorCredentials(m.address, true)
  131. }
  132. // RawAddress returns raw mirror address directly from Git repository config.
  133. func (m *Mirror) RawAddress() string {
  134. m.readAddress()
  135. return m.address
  136. }
  137. // FullAddress returns mirror address from Git repository config with unescaped credentials.
  138. func (m *Mirror) FullAddress() string {
  139. m.readAddress()
  140. return unescapeMirrorCredentials(m.address)
  141. }
  142. // escapeCredentials returns mirror address with escaped credentials.
  143. func escapeMirrorCredentials(addr string) string {
  144. start, end, found := findPasswordInMirrorAddress(addr)
  145. if !found {
  146. return addr
  147. }
  148. return addr[:start] + url.QueryEscape(addr[start:end]) + addr[end:]
  149. }
  150. // SaveAddress writes new address to Git repository config.
  151. func (m *Mirror) SaveAddress(addr string) error {
  152. configPath := m.Repo.GitConfigPath()
  153. cfg, err := ini.Load(configPath)
  154. if err != nil {
  155. return fmt.Errorf("Load: %v", err)
  156. }
  157. cfg.Section(`remote "origin"`).Key("url").SetValue(escapeMirrorCredentials(addr))
  158. return cfg.SaveToIndent(configPath, "\t")
  159. }
  160. // runSync returns true if sync finished without error.
  161. func (m *Mirror) runSync() bool {
  162. repoPath := m.Repo.RepoPath()
  163. wikiPath := m.Repo.WikiPath()
  164. timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second
  165. // Do a fast-fail testing against on repository URL to ensure it is accessible under
  166. // good condition to prevent long blocking on URL resolution without syncing anything.
  167. if !git.IsRepoURLAccessible(git.NetworkOptions{
  168. URL: m.RawAddress(),
  169. Timeout: 10 * time.Second,
  170. }) {
  171. desc := fmt.Sprintf("Source URL of mirror repository '%s' is not accessible: %s", m.Repo.FullName(), m.MosaicsAddress())
  172. if err := CreateRepositoryNotice(desc); err != nil {
  173. log.Error(2, "CreateRepositoryNotice: %v", err)
  174. }
  175. return false
  176. }
  177. gitArgs := []string{"remote", "update"}
  178. if m.EnablePrune {
  179. gitArgs = append(gitArgs, "--prune")
  180. }
  181. if _, stderr, err := process.ExecDir(
  182. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  183. "git", gitArgs...); err != nil {
  184. desc := fmt.Sprintf("Fail to update mirror repository '%s': %s", repoPath, stderr)
  185. log.Error(2, desc)
  186. if err = CreateRepositoryNotice(desc); err != nil {
  187. log.Error(2, "CreateRepositoryNotice: %v", err)
  188. }
  189. return false
  190. }
  191. if err := m.Repo.UpdateSize(); err != nil {
  192. log.Error(2, "UpdateSize [repo_id: %d]: %v", m.Repo.ID, err)
  193. }
  194. if m.Repo.HasWiki() {
  195. if _, stderr, err := process.ExecDir(
  196. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  197. "git", "remote", "update", "--prune"); err != nil {
  198. desc := fmt.Sprintf("Fail to update mirror wiki repository '%s': %s", wikiPath, stderr)
  199. log.Error(2, desc)
  200. if err = CreateRepositoryNotice(desc); err != nil {
  201. log.Error(2, "CreateRepositoryNotice: %v", err)
  202. }
  203. return false
  204. }
  205. }
  206. return true
  207. }
  208. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  209. m := &Mirror{RepoID: repoID}
  210. has, err := e.Get(m)
  211. if err != nil {
  212. return nil, err
  213. } else if !has {
  214. return nil, errors.MirrorNotExist{repoID}
  215. }
  216. return m, nil
  217. }
  218. // GetMirrorByRepoID returns mirror information of a repository.
  219. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  220. return getMirrorByRepoID(x, repoID)
  221. }
  222. func updateMirror(e Engine, m *Mirror) error {
  223. _, err := e.Id(m.ID).AllCols().Update(m)
  224. return err
  225. }
  226. func UpdateMirror(m *Mirror) error {
  227. return updateMirror(x, m)
  228. }
  229. func DeleteMirrorByRepoID(repoID int64) error {
  230. _, err := x.Delete(&Mirror{RepoID: repoID})
  231. return err
  232. }
  233. // MirrorUpdate checks and updates mirror repositories.
  234. func MirrorUpdate() {
  235. if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
  236. return
  237. }
  238. taskStatusTable.Start(_MIRROR_UPDATE)
  239. defer taskStatusTable.Stop(_MIRROR_UPDATE)
  240. log.Trace("Doing: MirrorUpdate")
  241. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  242. m := bean.(*Mirror)
  243. if m.Repo == nil {
  244. log.Error(2, "Disconnected mirror repository found: %d", m.ID)
  245. return nil
  246. }
  247. MirrorQueue.Add(m.RepoID)
  248. return nil
  249. }); err != nil {
  250. log.Error(2, "MirrorUpdate: %v", err)
  251. }
  252. }
  253. // SyncMirrors checks and syncs mirrors.
  254. // TODO: sync more mirrors at same time.
  255. func SyncMirrors() {
  256. // Start listening on new sync requests.
  257. for repoID := range MirrorQueue.Queue() {
  258. log.Trace("SyncMirrors [repo_id: %v]", repoID)
  259. MirrorQueue.Remove(repoID)
  260. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  261. if err != nil {
  262. log.Error(2, "GetMirrorByRepoID [%s]: %v", m.RepoID, err)
  263. continue
  264. }
  265. if !m.runSync() {
  266. continue
  267. }
  268. m.ScheduleNextUpdate()
  269. if err = UpdateMirror(m); err != nil {
  270. log.Error(2, "UpdateMirror [%s]: %v", m.RepoID, err)
  271. continue
  272. }
  273. // Get latest commit date and compare to current repository updated time,
  274. // update if latest commit date is newer.
  275. commitDate, err := git.GetLatestCommitDate(m.Repo.RepoPath(), "")
  276. if err != nil {
  277. log.Error(2, "GetLatestCommitDate [%s]: %v", m.RepoID, err)
  278. continue
  279. } else if commitDate.Before(m.Repo.Updated) {
  280. continue
  281. }
  282. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", commitDate.Unix(), m.RepoID); err != nil {
  283. log.Error(2, "Update repository 'updated_unix' [%s]: %v", m.RepoID, err)
  284. continue
  285. }
  286. }
  287. }
  288. func InitSyncMirrors() {
  289. go SyncMirrors()
  290. }