mirror.go 14 KB

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