mirror.go 16 KB

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