mirror.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package models
  7. import (
  8. "container/list"
  9. "fmt"
  10. "gitote/gitote/models/errors"
  11. "gitote/gitote/pkg/process"
  12. "gitote/gitote/pkg/setting"
  13. "gitote/gitote/pkg/sync"
  14. "net/url"
  15. "strings"
  16. "time"
  17. raven "github.com/getsentry/raven-go"
  18. "github.com/go-xorm/xorm"
  19. "gitlab.com/gitote/com"
  20. "gitlab.com/gitote/git-module"
  21. log "gopkg.in/clog.v1"
  22. "gopkg.in/ini.v1"
  23. )
  24. var MirrorQueue = sync.NewUniqueQueue(setting.Repository.MirrorQueueLength)
  25. // Mirror represents mirror information of a repository.
  26. type Mirror struct {
  27. ID int64
  28. RepoID int64
  29. Repo *Repository `xorm:"-" json:"-"`
  30. Interval int // Hour.
  31. EnablePrune bool `xorm:"NOT NULL DEFAULT true"`
  32. // Last and next sync time of Git data from upstream
  33. LastSync time.Time `xorm:"-" json:"-"`
  34. LastSyncUnix int64 `xorm:"updated_unix"`
  35. NextSync time.Time `xorm:"-" json:"-"`
  36. NextSyncUnix int64 `xorm:"next_update_unix"`
  37. address string `xorm:"-" json:"-"`
  38. }
  39. func (m *Mirror) BeforeInsert() {
  40. m.NextSyncUnix = m.NextSync.Unix()
  41. }
  42. func (m *Mirror) BeforeUpdate() {
  43. m.LastSyncUnix = m.LastSync.Unix()
  44. m.NextSyncUnix = m.NextSync.Unix()
  45. }
  46. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
  47. var err error
  48. switch colName {
  49. case "repo_id":
  50. m.Repo, err = GetRepositoryByID(m.RepoID)
  51. if err != nil {
  52. raven.CaptureErrorAndWait(err, nil)
  53. log.Error(3, "GetRepositoryByID [%d]: %v", m.ID, err)
  54. }
  55. case "updated_unix":
  56. m.LastSync = time.Unix(m.LastSyncUnix, 0).Local()
  57. case "next_update_unix":
  58. m.NextSync = time.Unix(m.NextSyncUnix, 0).Local()
  59. }
  60. }
  61. // ScheduleNextSync calculates and sets next sync time based on repostiroy mirror setting.
  62. func (m *Mirror) ScheduleNextSync() {
  63. m.NextSync = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  64. }
  65. // findPasswordInMirrorAddress returns start (inclusive) and end index (exclusive)
  66. // of password portion of credentials in given mirror address.
  67. // It returns a boolean value to indicate whether password portion is found.
  68. func findPasswordInMirrorAddress(addr string) (start int, end int, found bool) {
  69. // Find end of credentials (start of path)
  70. end = strings.LastIndex(addr, "@")
  71. if end == -1 {
  72. return -1, -1, false
  73. }
  74. // Find delimiter of credentials (end of username)
  75. start = strings.Index(addr, "://")
  76. if start == -1 {
  77. return -1, -1, false
  78. }
  79. start += 3
  80. delim := strings.Index(addr[start:], ":")
  81. if delim == -1 {
  82. return -1, -1, false
  83. }
  84. delim += 1
  85. if start+delim >= end {
  86. return -1, -1, false // No password portion presented
  87. }
  88. return start + delim, end, true
  89. }
  90. // unescapeMirrorCredentials returns mirror address with unescaped credentials.
  91. func unescapeMirrorCredentials(addr string) string {
  92. start, end, found := findPasswordInMirrorAddress(addr)
  93. if !found {
  94. return addr
  95. }
  96. password, _ := url.QueryUnescape(addr[start:end])
  97. return addr[:start] + password + addr[end:]
  98. }
  99. func (m *Mirror) readAddress() {
  100. if len(m.address) > 0 {
  101. return
  102. }
  103. cfg, err := ini.Load(m.Repo.GitConfigPath())
  104. if err != nil {
  105. raven.CaptureErrorAndWait(err, nil)
  106. log.Error(2, "Load: %v", err)
  107. return
  108. }
  109. m.address = cfg.Section("remote \"origin\"").Key("url").Value()
  110. }
  111. // HandleMirrorCredentials replaces user credentials from HTTP/HTTPS URL
  112. // with placeholder <credentials>.
  113. // It returns original string if protocol is not HTTP/HTTPS.
  114. func HandleMirrorCredentials(url string, mosaics bool) string {
  115. i := strings.Index(url, "@")
  116. if i == -1 {
  117. return url
  118. }
  119. start := strings.Index(url, "://")
  120. if start == -1 {
  121. return url
  122. }
  123. if mosaics {
  124. return url[:start+3] + "<credentials>" + url[i:]
  125. }
  126. return url[:start+3] + url[i+1:]
  127. }
  128. // Address returns mirror address from Git repository config without credentials.
  129. func (m *Mirror) Address() string {
  130. m.readAddress()
  131. return HandleMirrorCredentials(m.address, false)
  132. }
  133. // MosaicsAddress returns mirror address from Git repository config with credentials under mosaics.
  134. func (m *Mirror) MosaicsAddress() string {
  135. m.readAddress()
  136. return HandleMirrorCredentials(m.address, true)
  137. }
  138. // RawAddress returns raw mirror address directly from Git repository config.
  139. func (m *Mirror) RawAddress() string {
  140. m.readAddress()
  141. return m.address
  142. }
  143. // FullAddress returns mirror address from Git repository config with unescaped credentials.
  144. func (m *Mirror) FullAddress() string {
  145. m.readAddress()
  146. return unescapeMirrorCredentials(m.address)
  147. }
  148. // escapeCredentials returns mirror address with escaped credentials.
  149. func escapeMirrorCredentials(addr string) string {
  150. start, end, found := findPasswordInMirrorAddress(addr)
  151. if !found {
  152. return addr
  153. }
  154. return addr[:start] + url.QueryEscape(addr[start:end]) + addr[end:]
  155. }
  156. // SaveAddress writes new address to Git repository config.
  157. func (m *Mirror) SaveAddress(addr string) error {
  158. configPath := m.Repo.GitConfigPath()
  159. cfg, err := ini.Load(configPath)
  160. if err != nil {
  161. return fmt.Errorf("Load: %v", err)
  162. }
  163. cfg.Section(`remote "origin"`).Key("url").SetValue(escapeMirrorCredentials(addr))
  164. return cfg.SaveToIndent(configPath, "\t")
  165. }
  166. const GIT_SHORT_EMPTY_SHA = "0000000"
  167. // mirrorSyncResult contains information of a updated reference.
  168. // If the oldCommitID is "0000000", it means a new reference, the value of newCommitID is empty.
  169. // If the newCommitID is "0000000", it means the reference is deleted, the value of oldCommitID is empty.
  170. type mirrorSyncResult struct {
  171. refName string
  172. oldCommitID string
  173. newCommitID string
  174. }
  175. // parseRemoteUpdateOutput detects create, update and delete operations of references from upstream.
  176. func parseRemoteUpdateOutput(output string) []*mirrorSyncResult {
  177. results := make([]*mirrorSyncResult, 0, 3)
  178. lines := strings.Split(output, "\n")
  179. for i := range lines {
  180. // Make sure reference name is presented before continue
  181. idx := strings.Index(lines[i], "-> ")
  182. if idx == -1 {
  183. continue
  184. }
  185. refName := lines[i][idx+3:]
  186. switch {
  187. case strings.HasPrefix(lines[i], " * "): // New reference
  188. results = append(results, &mirrorSyncResult{
  189. refName: refName,
  190. oldCommitID: GIT_SHORT_EMPTY_SHA,
  191. })
  192. case strings.HasPrefix(lines[i], " - "): // Delete reference
  193. results = append(results, &mirrorSyncResult{
  194. refName: refName,
  195. newCommitID: GIT_SHORT_EMPTY_SHA,
  196. })
  197. case strings.HasPrefix(lines[i], " "): // New commits of a reference
  198. delimIdx := strings.Index(lines[i][3:], " ")
  199. if delimIdx == -1 {
  200. log.Error(2, "SHA delimiter not found: %q", lines[i])
  201. continue
  202. }
  203. shas := strings.Split(lines[i][3:delimIdx+3], "..")
  204. if len(shas) != 2 {
  205. log.Error(2, "Expect two SHAs but not what found: %q", lines[i])
  206. continue
  207. }
  208. results = append(results, &mirrorSyncResult{
  209. refName: refName,
  210. oldCommitID: shas[0],
  211. newCommitID: shas[1],
  212. })
  213. default:
  214. log.Warn("parseRemoteUpdateOutput: unexpected update line %q", lines[i])
  215. }
  216. }
  217. return results
  218. }
  219. // runSync returns true if sync finished without error.
  220. func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
  221. repoPath := m.Repo.RepoPath()
  222. wikiPath := m.Repo.WikiPath()
  223. timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second
  224. // Do a fast-fail testing against on repository URL to ensure it is accessible under
  225. // good condition to prevent long blocking on URL resolution without syncing anything.
  226. if !git.IsRepoURLAccessible(git.NetworkOptions{
  227. URL: m.RawAddress(),
  228. Timeout: 10 * time.Second,
  229. }) {
  230. desc := fmt.Sprintf("Source URL of mirror repository '%s' is not accessible: %s", m.Repo.FullName(), m.MosaicsAddress())
  231. if err := CreateRepositoryNotice(desc); err != nil {
  232. raven.CaptureErrorAndWait(err, nil)
  233. log.Error(2, "CreateRepositoryNotice: %v", err)
  234. }
  235. return nil, false
  236. }
  237. gitArgs := []string{"remote", "update"}
  238. if m.EnablePrune {
  239. gitArgs = append(gitArgs, "--prune")
  240. }
  241. _, stderr, err := process.ExecDir(
  242. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  243. "git", gitArgs...)
  244. if err != nil {
  245. desc := fmt.Sprintf("Fail to update mirror repository '%s': %s", repoPath, stderr)
  246. log.Error(2, desc)
  247. if err = CreateRepositoryNotice(desc); err != nil {
  248. raven.CaptureErrorAndWait(err, nil)
  249. log.Error(2, "CreateRepositoryNotice: %v", err)
  250. }
  251. return nil, false
  252. }
  253. output := stderr
  254. if err := m.Repo.UpdateSize(); err != nil {
  255. raven.CaptureErrorAndWait(err, nil)
  256. log.Error(2, "UpdateSize [repo_id: %d]: %v", m.Repo.ID, err)
  257. }
  258. if m.Repo.HasWiki() {
  259. // Even if wiki sync failed, we still want results from the main repository
  260. if _, stderr, err := process.ExecDir(
  261. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  262. "git", "remote", "update", "--prune"); err != nil {
  263. desc := fmt.Sprintf("Fail to update mirror wiki repository '%s': %s", wikiPath, stderr)
  264. raven.CaptureErrorAndWait(err, nil)
  265. log.Error(2, desc)
  266. if err = CreateRepositoryNotice(desc); err != nil {
  267. raven.CaptureErrorAndWait(err, nil)
  268. log.Error(2, "CreateRepositoryNotice: %v", err)
  269. }
  270. }
  271. }
  272. return parseRemoteUpdateOutput(output), true
  273. }
  274. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  275. m := &Mirror{RepoID: repoID}
  276. has, err := e.Get(m)
  277. if err != nil {
  278. return nil, err
  279. } else if !has {
  280. return nil, errors.MirrorNotExist{repoID}
  281. }
  282. return m, nil
  283. }
  284. // GetMirrorByRepoID returns mirror information of a repository.
  285. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  286. return getMirrorByRepoID(x, repoID)
  287. }
  288. func updateMirror(e Engine, m *Mirror) error {
  289. _, err := e.ID(m.ID).AllCols().Update(m)
  290. return err
  291. }
  292. func UpdateMirror(m *Mirror) error {
  293. return updateMirror(x, m)
  294. }
  295. func DeleteMirrorByRepoID(repoID int64) error {
  296. _, err := x.Delete(&Mirror{RepoID: repoID})
  297. return err
  298. }
  299. // MirrorUpdate checks and updates mirror repositories.
  300. func MirrorUpdate() {
  301. if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
  302. return
  303. }
  304. taskStatusTable.Start(_MIRROR_UPDATE)
  305. defer taskStatusTable.Stop(_MIRROR_UPDATE)
  306. log.Trace("Doing: MirrorUpdate")
  307. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  308. m := bean.(*Mirror)
  309. if m.Repo == nil {
  310. log.Error(2, "Disconnected mirror repository found: %d", m.ID)
  311. return nil
  312. }
  313. MirrorQueue.Add(m.RepoID)
  314. return nil
  315. }); err != nil {
  316. raven.CaptureErrorAndWait(err, nil)
  317. log.Error(2, "MirrorUpdate: %v", err)
  318. }
  319. }
  320. // SyncMirrors checks and syncs mirrors.
  321. // TODO: sync more mirrors at same time.
  322. func SyncMirrors() {
  323. // Start listening on new sync requests.
  324. for repoID := range MirrorQueue.Queue() {
  325. log.Trace("SyncMirrors [repo_id: %s]", repoID)
  326. MirrorQueue.Remove(repoID)
  327. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  328. if err != nil {
  329. raven.CaptureErrorAndWait(err, nil)
  330. log.Error(2, "GetMirrorByRepoID [%d]: %v", m.RepoID, err)
  331. continue
  332. }
  333. results, ok := m.runSync()
  334. if !ok {
  335. continue
  336. }
  337. m.ScheduleNextSync()
  338. if err = UpdateMirror(m); err != nil {
  339. raven.CaptureErrorAndWait(err, nil)
  340. log.Error(2, "UpdateMirror [%d]: %v", m.RepoID, err)
  341. continue
  342. }
  343. // TODO:
  344. // - Create "Mirror Sync" webhook event
  345. // - Create mirror sync (create, push and delete) events and trigger the "mirror sync" webhooks
  346. var gitRepo *git.Repository
  347. if len(results) == 0 {
  348. log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
  349. } else {
  350. gitRepo, err = git.OpenRepository(m.Repo.RepoPath())
  351. if err != nil {
  352. raven.CaptureErrorAndWait(err, nil)
  353. log.Error(2, "OpenRepository [%d]: %v", m.RepoID, err)
  354. continue
  355. }
  356. }
  357. for _, result := range results {
  358. // Discard GitHub pull requests, i.e. refs/pull/*
  359. if strings.HasPrefix(result.refName, "refs/pull/") {
  360. continue
  361. }
  362. // Delete reference
  363. if result.newCommitID == GIT_SHORT_EMPTY_SHA {
  364. if err = MirrorSyncDeleteAction(m.Repo, result.refName); err != nil {
  365. raven.CaptureErrorAndWait(err, nil)
  366. log.Error(2, "MirrorSyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
  367. }
  368. continue
  369. }
  370. // New reference
  371. isNewRef := false
  372. if result.oldCommitID == GIT_SHORT_EMPTY_SHA {
  373. if err = MirrorSyncCreateAction(m.Repo, result.refName); err != nil {
  374. raven.CaptureErrorAndWait(err, nil)
  375. log.Error(2, "MirrorSyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
  376. continue
  377. }
  378. isNewRef = true
  379. }
  380. // Push commits
  381. var commits *list.List
  382. var oldCommitID string
  383. var newCommitID string
  384. if !isNewRef {
  385. oldCommitID, err = git.GetFullCommitID(gitRepo.Path, result.oldCommitID)
  386. if err != nil {
  387. raven.CaptureErrorAndWait(err, nil)
  388. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  389. continue
  390. }
  391. newCommitID, err = git.GetFullCommitID(gitRepo.Path, result.newCommitID)
  392. if err != nil {
  393. raven.CaptureErrorAndWait(err, nil)
  394. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  395. continue
  396. }
  397. commits, err = gitRepo.CommitsBetweenIDs(newCommitID, oldCommitID)
  398. if err != nil {
  399. raven.CaptureErrorAndWait(err, nil)
  400. log.Error(2, "CommitsBetweenIDs [repo_id: %d, new_commit_id: %s, old_commit_id: %s]: %v", m.RepoID, newCommitID, oldCommitID, err)
  401. continue
  402. }
  403. } else {
  404. refNewCommitID, err := gitRepo.GetBranchCommitID(result.refName)
  405. if err != nil {
  406. raven.CaptureErrorAndWait(err, nil)
  407. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  408. continue
  409. }
  410. if newCommit, err := gitRepo.GetCommit(refNewCommitID); err != nil {
  411. raven.CaptureErrorAndWait(err, nil)
  412. log.Error(2, "GetCommit [repo_id: %d, commit_id: %s]: %v", m.RepoID, refNewCommitID, err)
  413. continue
  414. } else {
  415. // TODO: Get the commits for the new ref until the closest ancestor branch like Github does
  416. commits, err = newCommit.CommitsBeforeLimit(10)
  417. if err != nil {
  418. raven.CaptureErrorAndWait(err, nil)
  419. log.Error(2, "CommitsBeforeLimit [repo_id: %d, commit_id: %s]: %v", m.RepoID, refNewCommitID, err)
  420. }
  421. oldCommitID = git.EMPTY_SHA
  422. newCommitID = refNewCommitID
  423. }
  424. }
  425. if err = MirrorSyncPushAction(m.Repo, MirrorSyncPushActionOptions{
  426. RefName: result.refName,
  427. OldCommitID: oldCommitID,
  428. NewCommitID: newCommitID,
  429. Commits: ListToPushCommits(commits),
  430. }); err != nil {
  431. raven.CaptureErrorAndWait(err, nil)
  432. log.Error(2, "MirrorSyncPushAction [repo_id: %d]: %v", m.RepoID, err)
  433. continue
  434. }
  435. }
  436. if _, err = x.Exec("UPDATE mirror SET updated_unix = ? WHERE repo_id = ?", time.Now().Unix(), m.RepoID); err != nil {
  437. raven.CaptureErrorAndWait(err, nil)
  438. log.Error(2, "Update 'mirror.updated_unix' [%d]: %v", m.RepoID, err)
  439. continue
  440. }
  441. // Get latest commit date and compare to current repository updated time,
  442. // update if latest commit date is newer.
  443. commitDate, err := git.GetLatestCommitDate(m.Repo.RepoPath(), "")
  444. if err != nil {
  445. raven.CaptureErrorAndWait(err, nil)
  446. log.Error(2, "GetLatestCommitDate [%d]: %v", m.RepoID, err)
  447. continue
  448. } else if commitDate.Before(m.Repo.Updated) {
  449. continue
  450. }
  451. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", commitDate.Unix(), m.RepoID); err != nil {
  452. raven.CaptureErrorAndWait(err, nil)
  453. log.Error(2, "Update 'repository.updated_unix' [%d]: %v", m.RepoID, err)
  454. continue
  455. }
  456. }
  457. }
  458. func InitSyncMirrors() {
  459. go SyncMirrors()
  460. }