mirror.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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/gogs/git-module"
  15. "github.com/gogs/gogs/models/errors"
  16. "github.com/gogs/gogs/pkg/process"
  17. "github.com/gogs/gogs/pkg/setting"
  18. "github.com/gogs/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:"-" json:"-"`
  26. Interval int // Hour.
  27. EnablePrune bool `xorm:"NOT NULL DEFAULT true"`
  28. // Last and next sync time of Git data from upstream
  29. LastSync time.Time `xorm:"-" json:"-"`
  30. LastSyncUnix int64 `xorm:"updated_unix"`
  31. NextSync time.Time `xorm:"-" json:"-"`
  32. NextSyncUnix int64 `xorm:"next_update_unix"`
  33. address string `xorm:"-" json:"-"`
  34. }
  35. func (m *Mirror) BeforeInsert() {
  36. m.NextSyncUnix = m.NextSync.Unix()
  37. }
  38. func (m *Mirror) BeforeUpdate() {
  39. m.LastSyncUnix = m.LastSync.Unix()
  40. m.NextSyncUnix = m.NextSync.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.LastSync = time.Unix(m.LastSyncUnix, 0).Local()
  52. case "next_update_unix":
  53. m.NextSync = time.Unix(m.NextSyncUnix, 0).Local()
  54. }
  55. }
  56. // ScheduleNextSync calculates and sets next sync time based on repostiroy mirror setting.
  57. func (m *Mirror) ScheduleNextSync() {
  58. m.NextSync = 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. const GIT_SHORT_EMPTY_SHA = "0000000"
  161. // mirrorSyncResult contains information of a updated reference.
  162. // If the oldCommitID is "0000000", it means a new reference, the value of newCommitID is empty.
  163. // If the newCommitID is "0000000", it means the reference is deleted, the value of oldCommitID is empty.
  164. type mirrorSyncResult struct {
  165. refName string
  166. oldCommitID string
  167. newCommitID string
  168. }
  169. // parseRemoteUpdateOutput detects create, update and delete operations of references from upstream.
  170. func parseRemoteUpdateOutput(output string) []*mirrorSyncResult {
  171. results := make([]*mirrorSyncResult, 0, 3)
  172. lines := strings.Split(output, "\n")
  173. for i := range lines {
  174. // Make sure reference name is presented before continue
  175. idx := strings.Index(lines[i], "-> ")
  176. if idx == -1 {
  177. continue
  178. }
  179. refName := lines[i][idx+3:]
  180. switch {
  181. case strings.HasPrefix(lines[i], " * "): // New reference
  182. results = append(results, &mirrorSyncResult{
  183. refName: refName,
  184. oldCommitID: GIT_SHORT_EMPTY_SHA,
  185. })
  186. case strings.HasPrefix(lines[i], " - "): // Delete reference
  187. results = append(results, &mirrorSyncResult{
  188. refName: refName,
  189. newCommitID: GIT_SHORT_EMPTY_SHA,
  190. })
  191. case strings.HasPrefix(lines[i], " "): // New commits of a reference
  192. delimIdx := strings.Index(lines[i][3:], " ")
  193. if delimIdx == -1 {
  194. log.Error(2, "SHA delimiter not found: %q", lines[i])
  195. continue
  196. }
  197. shas := strings.Split(lines[i][3:delimIdx+3], "..")
  198. if len(shas) != 2 {
  199. log.Error(2, "Expect two SHAs but not what found: %q", lines[i])
  200. continue
  201. }
  202. results = append(results, &mirrorSyncResult{
  203. refName: refName,
  204. oldCommitID: shas[0],
  205. newCommitID: shas[1],
  206. })
  207. default:
  208. log.Warn("parseRemoteUpdateOutput: unexpected update line %q", lines[i])
  209. }
  210. }
  211. return results
  212. }
  213. // runSync returns true if sync finished without error.
  214. func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
  215. repoPath := m.Repo.RepoPath()
  216. wikiPath := m.Repo.WikiPath()
  217. timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second
  218. // Do a fast-fail testing against on repository URL to ensure it is accessible under
  219. // good condition to prevent long blocking on URL resolution without syncing anything.
  220. if !git.IsRepoURLAccessible(git.NetworkOptions{
  221. URL: m.RawAddress(),
  222. Timeout: 10 * time.Second,
  223. }) {
  224. desc := fmt.Sprintf("Source URL of mirror repository '%s' is not accessible: %s", m.Repo.FullName(), m.MosaicsAddress())
  225. if err := CreateRepositoryNotice(desc); err != nil {
  226. log.Error(2, "CreateRepositoryNotice: %v", err)
  227. }
  228. return nil, false
  229. }
  230. gitArgs := []string{"remote", "update"}
  231. if m.EnablePrune {
  232. gitArgs = append(gitArgs, "--prune")
  233. }
  234. _, stderr, err := process.ExecDir(
  235. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  236. "git", gitArgs...)
  237. if err != nil {
  238. desc := fmt.Sprintf("Fail to update mirror repository '%s': %s", repoPath, stderr)
  239. log.Error(2, desc)
  240. if err = CreateRepositoryNotice(desc); err != nil {
  241. log.Error(2, "CreateRepositoryNotice: %v", err)
  242. }
  243. return nil, false
  244. }
  245. output := stderr
  246. if err := m.Repo.UpdateSize(); err != nil {
  247. log.Error(2, "UpdateSize [repo_id: %d]: %v", m.Repo.ID, err)
  248. }
  249. if m.Repo.HasWiki() {
  250. // Even if wiki sync failed, we still want results from the main repository
  251. if _, stderr, err := process.ExecDir(
  252. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  253. "git", "remote", "update", "--prune"); err != nil {
  254. desc := fmt.Sprintf("Fail to update mirror wiki repository '%s': %s", wikiPath, stderr)
  255. log.Error(2, desc)
  256. if err = CreateRepositoryNotice(desc); err != nil {
  257. log.Error(2, "CreateRepositoryNotice: %v", err)
  258. }
  259. }
  260. }
  261. return parseRemoteUpdateOutput(output), true
  262. }
  263. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  264. m := &Mirror{RepoID: repoID}
  265. has, err := e.Get(m)
  266. if err != nil {
  267. return nil, err
  268. } else if !has {
  269. return nil, errors.MirrorNotExist{repoID}
  270. }
  271. return m, nil
  272. }
  273. // GetMirrorByRepoID returns mirror information of a repository.
  274. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  275. return getMirrorByRepoID(x, repoID)
  276. }
  277. func updateMirror(e Engine, m *Mirror) error {
  278. _, err := e.ID(m.ID).AllCols().Update(m)
  279. return err
  280. }
  281. func UpdateMirror(m *Mirror) error {
  282. return updateMirror(x, m)
  283. }
  284. func DeleteMirrorByRepoID(repoID int64) error {
  285. _, err := x.Delete(&Mirror{RepoID: repoID})
  286. return err
  287. }
  288. // MirrorUpdate checks and updates mirror repositories.
  289. func MirrorUpdate() {
  290. if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
  291. return
  292. }
  293. taskStatusTable.Start(_MIRROR_UPDATE)
  294. defer taskStatusTable.Stop(_MIRROR_UPDATE)
  295. log.Trace("Doing: MirrorUpdate")
  296. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  297. m := bean.(*Mirror)
  298. if m.Repo == nil {
  299. log.Error(2, "Disconnected mirror repository found: %d", m.ID)
  300. return nil
  301. }
  302. MirrorQueue.Add(m.RepoID)
  303. return nil
  304. }); err != nil {
  305. log.Error(2, "MirrorUpdate: %v", err)
  306. }
  307. }
  308. // SyncMirrors checks and syncs mirrors.
  309. // TODO: sync more mirrors at same time.
  310. func SyncMirrors() {
  311. // Start listening on new sync requests.
  312. for repoID := range MirrorQueue.Queue() {
  313. log.Trace("SyncMirrors [repo_id: %s]", repoID)
  314. MirrorQueue.Remove(repoID)
  315. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  316. if err != nil {
  317. log.Error(2, "GetMirrorByRepoID [%d]: %v", m.RepoID, err)
  318. continue
  319. }
  320. results, ok := m.runSync()
  321. if !ok {
  322. continue
  323. }
  324. m.ScheduleNextSync()
  325. if err = UpdateMirror(m); err != nil {
  326. log.Error(2, "UpdateMirror [%d]: %v", m.RepoID, err)
  327. continue
  328. }
  329. // TODO:
  330. // - Create "Mirror Sync" webhook event
  331. // - Create mirror sync (create, push and delete) events and trigger the "mirror sync" webhooks
  332. var gitRepo *git.Repository
  333. if len(results) == 0 {
  334. log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
  335. } else {
  336. gitRepo, err = git.OpenRepository(m.Repo.RepoPath())
  337. if err != nil {
  338. log.Error(2, "OpenRepository [%d]: %v", m.RepoID, err)
  339. continue
  340. }
  341. }
  342. for _, result := range results {
  343. // Discard GitHub pull requests, i.e. refs/pull/*
  344. if strings.HasPrefix(result.refName, "refs/pull/") {
  345. continue
  346. }
  347. // Create reference
  348. if result.oldCommitID == GIT_SHORT_EMPTY_SHA {
  349. if err = MirrorSyncCreateAction(m.Repo, result.refName); err != nil {
  350. log.Error(2, "MirrorSyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
  351. }
  352. continue
  353. }
  354. // Delete reference
  355. if result.newCommitID == GIT_SHORT_EMPTY_SHA {
  356. if err = MirrorSyncDeleteAction(m.Repo, result.refName); err != nil {
  357. log.Error(2, "MirrorSyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
  358. }
  359. continue
  360. }
  361. // Push commits
  362. oldCommitID, err := git.GetFullCommitID(gitRepo.Path, result.oldCommitID)
  363. if err != nil {
  364. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  365. continue
  366. }
  367. newCommitID, err := git.GetFullCommitID(gitRepo.Path, result.newCommitID)
  368. if err != nil {
  369. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  370. continue
  371. }
  372. commits, err := gitRepo.CommitsBetweenIDs(newCommitID, oldCommitID)
  373. if err != nil {
  374. log.Error(2, "CommitsBetweenIDs [repo_id: %d, new_commit_id: %s, old_commit_id: %s]: %v", m.RepoID, newCommitID, oldCommitID, err)
  375. continue
  376. }
  377. if err = MirrorSyncPushAction(m.Repo, MirrorSyncPushActionOptions{
  378. RefName: result.refName,
  379. OldCommitID: oldCommitID,
  380. NewCommitID: newCommitID,
  381. Commits: ListToPushCommits(commits),
  382. }); err != nil {
  383. log.Error(2, "MirrorSyncPushAction [repo_id: %d]: %v", m.RepoID, err)
  384. continue
  385. }
  386. }
  387. if _, err = x.Exec("UPDATE mirror SET updated_unix = ? WHERE repo_id = ?", time.Now().Unix(), m.RepoID); err != nil {
  388. log.Error(2, "Update 'mirror.updated_unix' [%d]: %v", m.RepoID, err)
  389. continue
  390. }
  391. // Get latest commit date and compare to current repository updated time,
  392. // update if latest commit date is newer.
  393. commitDate, err := git.GetLatestCommitDate(m.Repo.RepoPath(), "")
  394. if err != nil {
  395. log.Error(2, "GetLatestCommitDate [%d]: %v", m.RepoID, err)
  396. continue
  397. } else if commitDate.Before(m.Repo.Updated) {
  398. continue
  399. }
  400. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", commitDate.Unix(), m.RepoID); err != nil {
  401. log.Error(2, "Update 'repository.updated_unix' [%d]: %v", m.RepoID, err)
  402. continue
  403. }
  404. }
  405. }
  406. func InitSyncMirrors() {
  407. go SyncMirrors()
  408. }