mirror.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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. "gopkg.in/ini.v1"
  13. log "unknwon.dev/clog/v2"
  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/conf"
  19. "gogs.io/gogs/internal/sync"
  20. )
  21. var MirrorQueue = sync.NewUniqueQueue(conf.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("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("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. repoPath := m.Repo.RepoPath()
  154. err := git.RemoveRemote(repoPath, "origin")
  155. if err != nil {
  156. return fmt.Errorf("remove remote 'origin': %v", err)
  157. }
  158. err = git.AddRemote(repoPath, "origin", addr, git.AddRemoteOptions{
  159. Mirror: true,
  160. })
  161. if err != nil {
  162. return fmt.Errorf("add remote 'origin': %v", err)
  163. }
  164. return nil
  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("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("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(conf.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. log.Error("CreateRepositoryNotice: %v", err)
  233. }
  234. return nil, false
  235. }
  236. gitArgs := []string{"remote", "update"}
  237. if m.EnablePrune {
  238. gitArgs = append(gitArgs, "--prune")
  239. }
  240. _, stderr, err := process.ExecDir(
  241. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  242. "git", gitArgs...)
  243. if err != nil {
  244. desc := fmt.Sprintf("Failed to update mirror repository '%s': %s", repoPath, stderr)
  245. log.Error(desc)
  246. if err = CreateRepositoryNotice(desc); err != nil {
  247. log.Error("CreateRepositoryNotice: %v", err)
  248. }
  249. return nil, false
  250. }
  251. output := stderr
  252. if err := m.Repo.UpdateSize(); err != nil {
  253. log.Error("UpdateSize [repo_id: %d]: %v", m.Repo.ID, err)
  254. }
  255. if m.Repo.HasWiki() {
  256. // Even if wiki sync failed, we still want results from the main repository
  257. if _, stderr, err := process.ExecDir(
  258. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  259. "git", "remote", "update", "--prune"); err != nil {
  260. desc := fmt.Sprintf("Failed to update mirror wiki repository '%s': %s", wikiPath, stderr)
  261. log.Error(desc)
  262. if err = CreateRepositoryNotice(desc); err != nil {
  263. log.Error("CreateRepositoryNotice: %v", err)
  264. }
  265. }
  266. }
  267. return parseRemoteUpdateOutput(output), true
  268. }
  269. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  270. m := &Mirror{RepoID: repoID}
  271. has, err := e.Get(m)
  272. if err != nil {
  273. return nil, err
  274. } else if !has {
  275. return nil, errors.MirrorNotExist{repoID}
  276. }
  277. return m, nil
  278. }
  279. // GetMirrorByRepoID returns mirror information of a repository.
  280. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  281. return getMirrorByRepoID(x, repoID)
  282. }
  283. func updateMirror(e Engine, m *Mirror) error {
  284. _, err := e.ID(m.ID).AllCols().Update(m)
  285. return err
  286. }
  287. func UpdateMirror(m *Mirror) error {
  288. return updateMirror(x, m)
  289. }
  290. func DeleteMirrorByRepoID(repoID int64) error {
  291. _, err := x.Delete(&Mirror{RepoID: repoID})
  292. return err
  293. }
  294. // MirrorUpdate checks and updates mirror repositories.
  295. func MirrorUpdate() {
  296. if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
  297. return
  298. }
  299. taskStatusTable.Start(_MIRROR_UPDATE)
  300. defer taskStatusTable.Stop(_MIRROR_UPDATE)
  301. log.Trace("Doing: MirrorUpdate")
  302. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  303. m := bean.(*Mirror)
  304. if m.Repo == nil {
  305. log.Error("Disconnected mirror repository found: %d", m.ID)
  306. return nil
  307. }
  308. MirrorQueue.Add(m.RepoID)
  309. return nil
  310. }); err != nil {
  311. log.Error("MirrorUpdate: %v", err)
  312. }
  313. }
  314. // SyncMirrors checks and syncs mirrors.
  315. // TODO: sync more mirrors at same time.
  316. func SyncMirrors() {
  317. // Start listening on new sync requests.
  318. for repoID := range MirrorQueue.Queue() {
  319. log.Trace("SyncMirrors [repo_id: %s]", repoID)
  320. MirrorQueue.Remove(repoID)
  321. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  322. if err != nil {
  323. log.Error("GetMirrorByRepoID [%d]: %v", m.RepoID, err)
  324. continue
  325. }
  326. results, ok := m.runSync()
  327. if !ok {
  328. continue
  329. }
  330. m.ScheduleNextSync()
  331. if err = UpdateMirror(m); err != nil {
  332. log.Error("UpdateMirror [%d]: %v", m.RepoID, err)
  333. continue
  334. }
  335. // TODO:
  336. // - Create "Mirror Sync" webhook event
  337. // - Create mirror sync (create, push and delete) events and trigger the "mirror sync" webhooks
  338. var gitRepo *git.Repository
  339. if len(results) == 0 {
  340. log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
  341. } else {
  342. gitRepo, err = git.OpenRepository(m.Repo.RepoPath())
  343. if err != nil {
  344. log.Error("OpenRepository [%d]: %v", m.RepoID, err)
  345. continue
  346. }
  347. }
  348. for _, result := range results {
  349. // Discard GitHub pull requests, i.e. refs/pull/*
  350. if strings.HasPrefix(result.refName, "refs/pull/") {
  351. continue
  352. }
  353. // Delete reference
  354. if result.newCommitID == GIT_SHORT_EMPTY_SHA {
  355. if err = MirrorSyncDeleteAction(m.Repo, result.refName); err != nil {
  356. log.Error("MirrorSyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
  357. }
  358. continue
  359. }
  360. // New reference
  361. isNewRef := false
  362. if result.oldCommitID == GIT_SHORT_EMPTY_SHA {
  363. if err = MirrorSyncCreateAction(m.Repo, result.refName); err != nil {
  364. log.Error("MirrorSyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
  365. continue
  366. }
  367. isNewRef = true
  368. }
  369. // Push commits
  370. var commits *list.List
  371. var oldCommitID string
  372. var newCommitID string
  373. if !isNewRef {
  374. oldCommitID, err = git.GetFullCommitID(gitRepo.Path, result.oldCommitID)
  375. if err != nil {
  376. log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
  377. continue
  378. }
  379. newCommitID, err = git.GetFullCommitID(gitRepo.Path, result.newCommitID)
  380. if err != nil {
  381. log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
  382. continue
  383. }
  384. commits, err = gitRepo.CommitsBetweenIDs(newCommitID, oldCommitID)
  385. if err != nil {
  386. log.Error("CommitsBetweenIDs [repo_id: %d, new_commit_id: %s, old_commit_id: %s]: %v", m.RepoID, newCommitID, oldCommitID, err)
  387. continue
  388. }
  389. } else {
  390. refNewCommitID, err := gitRepo.GetBranchCommitID(result.refName)
  391. if err != nil {
  392. log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
  393. continue
  394. }
  395. if newCommit, err := gitRepo.GetCommit(refNewCommitID); err != nil {
  396. log.Error("GetCommit [repo_id: %d, commit_id: %s]: %v", m.RepoID, refNewCommitID, err)
  397. continue
  398. } else {
  399. // TODO: Get the commits for the new ref until the closest ancestor branch like Github does
  400. commits, err = newCommit.CommitsBeforeLimit(10)
  401. if err != nil {
  402. log.Error("CommitsBeforeLimit [repo_id: %d, commit_id: %s]: %v", m.RepoID, refNewCommitID, err)
  403. }
  404. oldCommitID = git.EMPTY_SHA
  405. newCommitID = refNewCommitID
  406. }
  407. }
  408. if err = MirrorSyncPushAction(m.Repo, MirrorSyncPushActionOptions{
  409. RefName: result.refName,
  410. OldCommitID: oldCommitID,
  411. NewCommitID: newCommitID,
  412. Commits: ListToPushCommits(commits),
  413. }); err != nil {
  414. log.Error("MirrorSyncPushAction [repo_id: %d]: %v", m.RepoID, err)
  415. continue
  416. }
  417. }
  418. if _, err = x.Exec("UPDATE mirror SET updated_unix = ? WHERE repo_id = ?", time.Now().Unix(), m.RepoID); err != nil {
  419. log.Error("Update 'mirror.updated_unix' [%d]: %v", m.RepoID, err)
  420. continue
  421. }
  422. // Get latest commit date and compare to current repository updated time,
  423. // update if latest commit date is newer.
  424. commitDate, err := git.GetLatestCommitDate(m.Repo.RepoPath(), "")
  425. if err != nil {
  426. log.Error("GetLatestCommitDate [%d]: %v", m.RepoID, err)
  427. continue
  428. } else if commitDate.Before(m.Repo.Updated) {
  429. continue
  430. }
  431. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", commitDate.Unix(), m.RepoID); err != nil {
  432. log.Error("Update 'repository.updated_unix' [%d]: %v", m.RepoID, err)
  433. continue
  434. }
  435. }
  436. }
  437. func InitSyncMirrors() {
  438. go SyncMirrors()
  439. }