mirror.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 GitShortEmptySHA = "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: GitShortEmptySHA,
  191. })
  192. case strings.HasPrefix(lines[i], " - "): // Delete reference
  193. results = append(results, &mirrorSyncResult{
  194. refName: refName,
  195. newCommitID: GitShortEmptySHA,
  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. // UpdateMirror returns updateMirror
  293. func UpdateMirror(m *Mirror) error {
  294. return updateMirror(x, m)
  295. }
  296. // DeleteMirrorByRepoID delted repo by ID
  297. func DeleteMirrorByRepoID(repoID int64) error {
  298. _, err := x.Delete(&Mirror{RepoID: repoID})
  299. return err
  300. }
  301. // MirrorUpdate checks and updates mirror repositories.
  302. func MirrorUpdate() {
  303. if taskStatusTable.IsRunning(_MirrorUpdate) {
  304. return
  305. }
  306. taskStatusTable.Start(_MirrorUpdate)
  307. defer taskStatusTable.Stop(_MirrorUpdate)
  308. log.Trace("Doing: MirrorUpdate")
  309. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  310. m := bean.(*Mirror)
  311. if m.Repo == nil {
  312. log.Error(2, "Disconnected mirror repository found: %d", m.ID)
  313. return nil
  314. }
  315. MirrorQueue.Add(m.RepoID)
  316. return nil
  317. }); err != nil {
  318. raven.CaptureErrorAndWait(err, nil)
  319. log.Error(2, "MirrorUpdate: %v", err)
  320. }
  321. }
  322. // SyncMirrors checks and syncs mirrors.
  323. // TODO: sync more mirrors at same time.
  324. func SyncMirrors() {
  325. // Start listening on new sync requests.
  326. for repoID := range MirrorQueue.Queue() {
  327. log.Trace("SyncMirrors [repo_id: %s]", repoID)
  328. MirrorQueue.Remove(repoID)
  329. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  330. if err != nil {
  331. raven.CaptureErrorAndWait(err, nil)
  332. log.Error(2, "GetMirrorByRepoID [%d]: %v", m.RepoID, err)
  333. continue
  334. }
  335. results, ok := m.runSync()
  336. if !ok {
  337. continue
  338. }
  339. m.ScheduleNextSync()
  340. if err = UpdateMirror(m); err != nil {
  341. raven.CaptureErrorAndWait(err, nil)
  342. log.Error(2, "UpdateMirror [%d]: %v", m.RepoID, err)
  343. continue
  344. }
  345. // TODO:
  346. // - Create "Mirror Sync" webhook event
  347. // - Create mirror sync (create, push and delete) events and trigger the "mirror sync" webhooks
  348. var gitRepo *git.Repository
  349. if len(results) == 0 {
  350. log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
  351. } else {
  352. gitRepo, err = git.OpenRepository(m.Repo.RepoPath())
  353. if err != nil {
  354. raven.CaptureErrorAndWait(err, nil)
  355. log.Error(2, "OpenRepository [%d]: %v", m.RepoID, err)
  356. continue
  357. }
  358. }
  359. for _, result := range results {
  360. // Discard GitHub pull requests, i.e. refs/pull/*
  361. if strings.HasPrefix(result.refName, "refs/pull/") {
  362. continue
  363. }
  364. // Delete reference
  365. if result.newCommitID == GitShortEmptySHA {
  366. if err = MirrorSyncDeleteAction(m.Repo, result.refName); err != nil {
  367. raven.CaptureErrorAndWait(err, nil)
  368. log.Error(2, "MirrorSyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
  369. }
  370. continue
  371. }
  372. // New reference
  373. isNewRef := false
  374. if result.oldCommitID == GitShortEmptySHA {
  375. if err = MirrorSyncCreateAction(m.Repo, result.refName); err != nil {
  376. raven.CaptureErrorAndWait(err, nil)
  377. log.Error(2, "MirrorSyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
  378. continue
  379. }
  380. isNewRef = true
  381. }
  382. // Push commits
  383. var commits *list.List
  384. var oldCommitID string
  385. var newCommitID string
  386. if !isNewRef {
  387. oldCommitID, err = git.GetFullCommitID(gitRepo.Path, result.oldCommitID)
  388. if err != nil {
  389. raven.CaptureErrorAndWait(err, nil)
  390. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  391. continue
  392. }
  393. newCommitID, err = git.GetFullCommitID(gitRepo.Path, result.newCommitID)
  394. if err != nil {
  395. raven.CaptureErrorAndWait(err, nil)
  396. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  397. continue
  398. }
  399. commits, err = gitRepo.CommitsBetweenIDs(newCommitID, oldCommitID)
  400. if err != nil {
  401. raven.CaptureErrorAndWait(err, nil)
  402. log.Error(2, "CommitsBetweenIDs [repo_id: %d, new_commit_id: %s, old_commit_id: %s]: %v", m.RepoID, newCommitID, oldCommitID, err)
  403. continue
  404. }
  405. } else {
  406. refNewCommitID, err := gitRepo.GetBranchCommitID(result.refName)
  407. if err != nil {
  408. raven.CaptureErrorAndWait(err, nil)
  409. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  410. continue
  411. }
  412. if newCommit, err := gitRepo.GetCommit(refNewCommitID); err != nil {
  413. raven.CaptureErrorAndWait(err, nil)
  414. log.Error(2, "GetCommit [repo_id: %d, commit_id: %s]: %v", m.RepoID, refNewCommitID, err)
  415. continue
  416. } else {
  417. // TODO: Get the commits for the new ref until the closest ancestor branch like Github does
  418. commits, err = newCommit.CommitsBeforeLimit(10)
  419. if err != nil {
  420. raven.CaptureErrorAndWait(err, nil)
  421. log.Error(2, "CommitsBeforeLimit [repo_id: %d, commit_id: %s]: %v", m.RepoID, refNewCommitID, err)
  422. }
  423. oldCommitID = git.EMPTY_SHA
  424. newCommitID = refNewCommitID
  425. }
  426. }
  427. if err = MirrorSyncPushAction(m.Repo, MirrorSyncPushActionOptions{
  428. RefName: result.refName,
  429. OldCommitID: oldCommitID,
  430. NewCommitID: newCommitID,
  431. Commits: ListToPushCommits(commits),
  432. }); err != nil {
  433. raven.CaptureErrorAndWait(err, nil)
  434. log.Error(2, "MirrorSyncPushAction [repo_id: %d]: %v", m.RepoID, err)
  435. continue
  436. }
  437. }
  438. if _, err = x.Exec("UPDATE mirror SET updated_unix = ? WHERE repo_id = ?", time.Now().Unix(), m.RepoID); err != nil {
  439. raven.CaptureErrorAndWait(err, nil)
  440. log.Error(2, "Update 'mirror.updated_unix' [%d]: %v", m.RepoID, err)
  441. continue
  442. }
  443. // Get latest commit date and compare to current repository updated time,
  444. // update if latest commit date is newer.
  445. commitDate, err := git.GetLatestCommitDate(m.Repo.RepoPath(), "")
  446. if err != nil {
  447. raven.CaptureErrorAndWait(err, nil)
  448. log.Error(2, "GetLatestCommitDate [%d]: %v", m.RepoID, err)
  449. continue
  450. } else if commitDate.Before(m.Repo.Updated) {
  451. continue
  452. }
  453. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", commitDate.Unix(), m.RepoID); err != nil {
  454. raven.CaptureErrorAndWait(err, nil)
  455. log.Error(2, "Update 'repository.updated_unix' [%d]: %v", m.RepoID, err)
  456. continue
  457. }
  458. }
  459. }
  460. // InitSyncMirrors will init sync mirrors
  461. func InitSyncMirrors() {
  462. go SyncMirrors()
  463. }