mirror.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. "context"
  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/conf"
  17. "gogs.io/gogs/internal/db/errors"
  18. "gogs.io/gogs/internal/process"
  19. "gogs.io/gogs/internal/sync"
  20. )
  21. var MirrorQueue = sync.NewUniqueQueue(1000)
  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:"-"`
  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 repository mirror setting.
  58. func (m *Mirror) ScheduleNextSync() {
  59. m.NextSync = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  60. }
  61. func (m *Mirror) readAddress() {
  62. if len(m.address) > 0 {
  63. return
  64. }
  65. cfg, err := ini.LoadSources(
  66. ini.LoadOptions{IgnoreInlineComment: true},
  67. m.Repo.GitConfigPath(),
  68. )
  69. if err != nil {
  70. log.Error("load config: %v", err)
  71. return
  72. }
  73. m.address = cfg.Section("remote \"origin\"").Key("url").Value()
  74. }
  75. // HandleMirrorCredentials replaces user credentials from HTTP/HTTPS URL
  76. // with placeholder <credentials>.
  77. // It returns original string if protocol is not HTTP/HTTPS.
  78. // TODO(unknwon): Use url.Parse.
  79. func HandleMirrorCredentials(url string, mosaics bool) string {
  80. i := strings.Index(url, "@")
  81. if i == -1 {
  82. return url
  83. }
  84. start := strings.Index(url, "://")
  85. if start == -1 {
  86. return url
  87. }
  88. if mosaics {
  89. return url[:start+3] + "<credentials>" + url[i:]
  90. }
  91. return url[:start+3] + url[i+1:]
  92. }
  93. // Address returns mirror address from Git repository config without credentials.
  94. func (m *Mirror) Address() string {
  95. m.readAddress()
  96. return HandleMirrorCredentials(m.address, false)
  97. }
  98. // MosaicsAddress returns mirror address from Git repository config with credentials under mosaics.
  99. func (m *Mirror) MosaicsAddress() string {
  100. m.readAddress()
  101. return HandleMirrorCredentials(m.address, true)
  102. }
  103. // RawAddress returns raw mirror address directly from Git repository config.
  104. func (m *Mirror) RawAddress() string {
  105. m.readAddress()
  106. return m.address
  107. }
  108. // SaveAddress writes new address to Git repository config.
  109. func (m *Mirror) SaveAddress(addr string) error {
  110. repoPath := m.Repo.RepoPath()
  111. err := git.RemoteRemove(repoPath, "origin")
  112. if err != nil {
  113. return fmt.Errorf("remove remote 'origin': %v", err)
  114. }
  115. addrURL, err := url.Parse(addr)
  116. if err != nil {
  117. return err
  118. }
  119. err = git.RemoteAdd(repoPath, "origin", addrURL.String(), git.RemoteAddOptions{MirrorFetch: true})
  120. if err != nil {
  121. return fmt.Errorf("add remote 'origin': %v", err)
  122. }
  123. return nil
  124. }
  125. const gitShortEmptyID = "0000000"
  126. // mirrorSyncResult contains information of a updated reference.
  127. // If the oldCommitID is "0000000", it means a new reference, the value of newCommitID is empty.
  128. // If the newCommitID is "0000000", it means the reference is deleted, the value of oldCommitID is empty.
  129. type mirrorSyncResult struct {
  130. refName string
  131. oldCommitID string
  132. newCommitID string
  133. }
  134. // parseRemoteUpdateOutput detects create, update and delete operations of references from upstream.
  135. func parseRemoteUpdateOutput(output string) []*mirrorSyncResult {
  136. results := make([]*mirrorSyncResult, 0, 3)
  137. lines := strings.Split(output, "\n")
  138. for i := range lines {
  139. // Make sure reference name is presented before continue
  140. idx := strings.Index(lines[i], "-> ")
  141. if idx == -1 {
  142. continue
  143. }
  144. refName := lines[i][idx+3:]
  145. switch {
  146. case strings.HasPrefix(lines[i], " * "): // New reference
  147. results = append(results, &mirrorSyncResult{
  148. refName: refName,
  149. oldCommitID: gitShortEmptyID,
  150. })
  151. case strings.HasPrefix(lines[i], " - "): // Delete reference
  152. results = append(results, &mirrorSyncResult{
  153. refName: refName,
  154. newCommitID: gitShortEmptyID,
  155. })
  156. case strings.HasPrefix(lines[i], " "): // New commits of a reference
  157. delimIdx := strings.Index(lines[i][3:], " ")
  158. if delimIdx == -1 {
  159. log.Error("SHA delimiter not found: %q", lines[i])
  160. continue
  161. }
  162. shas := strings.Split(lines[i][3:delimIdx+3], "..")
  163. if len(shas) != 2 {
  164. log.Error("Expect two SHAs but not what found: %q", lines[i])
  165. continue
  166. }
  167. results = append(results, &mirrorSyncResult{
  168. refName: refName,
  169. oldCommitID: shas[0],
  170. newCommitID: shas[1],
  171. })
  172. default:
  173. log.Warn("parseRemoteUpdateOutput: unexpected update line %q", lines[i])
  174. }
  175. }
  176. return results
  177. }
  178. // runSync returns true if sync finished without error.
  179. func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
  180. repoPath := m.Repo.RepoPath()
  181. wikiPath := m.Repo.WikiPath()
  182. timeout := time.Duration(conf.Git.Timeout.Mirror) * time.Second
  183. // Do a fast-fail testing against on repository URL to ensure it is accessible under
  184. // good condition to prevent long blocking on URL resolution without syncing anything.
  185. if !git.IsURLAccessible(time.Minute, m.RawAddress()) {
  186. desc := fmt.Sprintf("Source URL of mirror repository '%s' is not accessible: %s", m.Repo.FullName(), m.MosaicsAddress())
  187. if err := Notices.Create(context.TODO(), NoticeTypeRepository, desc); err != nil {
  188. log.Error("CreateRepositoryNotice: %v", err)
  189. }
  190. return nil, false
  191. }
  192. gitArgs := []string{"remote", "update"}
  193. if m.EnablePrune {
  194. gitArgs = append(gitArgs, "--prune")
  195. }
  196. _, stderr, err := process.ExecDir(
  197. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  198. "git", gitArgs...)
  199. if err != nil {
  200. desc := fmt.Sprintf("Failed to update mirror repository '%s': %s", repoPath, stderr)
  201. log.Error(desc)
  202. if err = Notices.Create(context.TODO(), NoticeTypeRepository, desc); err != nil {
  203. log.Error("CreateRepositoryNotice: %v", err)
  204. }
  205. return nil, false
  206. }
  207. output := stderr
  208. if err := m.Repo.UpdateSize(); err != nil {
  209. log.Error("UpdateSize [repo_id: %d]: %v", m.Repo.ID, err)
  210. }
  211. if m.Repo.HasWiki() {
  212. // Even if wiki sync failed, we still want results from the main repository
  213. if _, stderr, err := process.ExecDir(
  214. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  215. "git", "remote", "update", "--prune"); err != nil {
  216. desc := fmt.Sprintf("Failed to update mirror wiki repository '%s': %s", wikiPath, stderr)
  217. log.Error(desc)
  218. if err = Notices.Create(context.TODO(), NoticeTypeRepository, desc); err != nil {
  219. log.Error("CreateRepositoryNotice: %v", err)
  220. }
  221. }
  222. }
  223. return parseRemoteUpdateOutput(output), true
  224. }
  225. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  226. m := &Mirror{RepoID: repoID}
  227. has, err := e.Get(m)
  228. if err != nil {
  229. return nil, err
  230. } else if !has {
  231. return nil, errors.MirrorNotExist{RepoID: repoID}
  232. }
  233. return m, nil
  234. }
  235. // GetMirrorByRepoID returns mirror information of a repository.
  236. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  237. return getMirrorByRepoID(x, repoID)
  238. }
  239. func updateMirror(e Engine, m *Mirror) error {
  240. _, err := e.ID(m.ID).AllCols().Update(m)
  241. return err
  242. }
  243. func UpdateMirror(m *Mirror) error {
  244. return updateMirror(x, m)
  245. }
  246. func DeleteMirrorByRepoID(repoID int64) error {
  247. _, err := x.Delete(&Mirror{RepoID: repoID})
  248. return err
  249. }
  250. // MirrorUpdate checks and updates mirror repositories.
  251. func MirrorUpdate() {
  252. if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
  253. return
  254. }
  255. taskStatusTable.Start(_MIRROR_UPDATE)
  256. defer taskStatusTable.Stop(_MIRROR_UPDATE)
  257. log.Trace("Doing: MirrorUpdate")
  258. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean any) error {
  259. m := bean.(*Mirror)
  260. if m.Repo == nil {
  261. log.Error("Disconnected mirror repository found: %d", m.ID)
  262. return nil
  263. }
  264. MirrorQueue.Add(m.RepoID)
  265. return nil
  266. }); err != nil {
  267. log.Error("MirrorUpdate: %v", err)
  268. }
  269. }
  270. // SyncMirrors checks and syncs mirrors.
  271. // TODO: sync more mirrors at same time.
  272. func SyncMirrors() {
  273. ctx := context.Background()
  274. // Start listening on new sync requests.
  275. for repoID := range MirrorQueue.Queue() {
  276. log.Trace("SyncMirrors [repo_id: %s]", repoID)
  277. MirrorQueue.Remove(repoID)
  278. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  279. if err != nil {
  280. log.Error("GetMirrorByRepoID [%d]: %v", m.RepoID, err)
  281. continue
  282. }
  283. results, ok := m.runSync()
  284. if !ok {
  285. continue
  286. }
  287. m.ScheduleNextSync()
  288. if err = UpdateMirror(m); err != nil {
  289. log.Error("UpdateMirror [%d]: %v", m.RepoID, err)
  290. continue
  291. }
  292. // TODO:
  293. // - Create "Mirror Sync" webhook event
  294. // - Create mirror sync (create, push and delete) events and trigger the "mirror sync" webhooks
  295. if len(results) == 0 {
  296. log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
  297. }
  298. gitRepo, err := git.Open(m.Repo.RepoPath())
  299. if err != nil {
  300. log.Error("Failed to open repository [repo_id: %d]: %v", m.RepoID, err)
  301. continue
  302. }
  303. for _, result := range results {
  304. // Discard GitHub pull requests, i.e. refs/pull/*
  305. if strings.HasPrefix(result.refName, "refs/pull/") {
  306. continue
  307. }
  308. // Delete reference
  309. if result.newCommitID == gitShortEmptyID {
  310. if err = Actions.MirrorSyncDelete(ctx, m.Repo.MustOwner(), m.Repo, result.refName); err != nil {
  311. log.Error("Failed to create action for mirror sync delete [repo_id: %d]: %v", m.RepoID, err)
  312. }
  313. continue
  314. }
  315. // New reference
  316. isNewRef := false
  317. if result.oldCommitID == gitShortEmptyID {
  318. if err = Actions.MirrorSyncCreate(ctx, m.Repo.MustOwner(), m.Repo, result.refName); err != nil {
  319. log.Error("Failed to create action for mirror sync create [repo_id: %d]: %v", m.RepoID, err)
  320. continue
  321. }
  322. isNewRef = true
  323. }
  324. // Push commits
  325. var commits []*git.Commit
  326. var oldCommitID string
  327. var newCommitID string
  328. if !isNewRef {
  329. oldCommitID, err = gitRepo.RevParse(result.oldCommitID)
  330. if err != nil {
  331. log.Error("Failed to parse revision [repo_id: %d, old_commit_id: %s]: %v", m.RepoID, result.oldCommitID, err)
  332. continue
  333. }
  334. newCommitID, err = gitRepo.RevParse(result.newCommitID)
  335. if err != nil {
  336. log.Error("Failed to parse revision [repo_id: %d, new_commit_id: %s]: %v", m.RepoID, result.newCommitID, err)
  337. continue
  338. }
  339. commits, err = gitRepo.RevList([]string{oldCommitID + "..." + newCommitID})
  340. if err != nil {
  341. log.Error("Failed to list commits [repo_id: %d, old_commit_id: %s, new_commit_id: %s]: %v", m.RepoID, oldCommitID, newCommitID, err)
  342. continue
  343. }
  344. } else if gitRepo.HasBranch(result.refName) {
  345. refNewCommit, err := gitRepo.BranchCommit(result.refName)
  346. if err != nil {
  347. log.Error("Failed to get branch commit [repo_id: %d, branch: %s]: %v", m.RepoID, result.refName, err)
  348. continue
  349. }
  350. // TODO(unknwon): Get the commits for the new ref until the closest ancestor branch like GitHub does.
  351. commits, err = refNewCommit.Ancestors(git.LogOptions{MaxCount: 9})
  352. if err != nil {
  353. log.Error("Failed to get ancestors [repo_id: %d, commit_id: %s]: %v", m.RepoID, refNewCommit.ID, err)
  354. continue
  355. }
  356. // Put the latest commit in front of ancestors
  357. commits = append([]*git.Commit{refNewCommit}, commits...)
  358. oldCommitID = git.EmptyID
  359. newCommitID = refNewCommit.ID.String()
  360. }
  361. err = Actions.MirrorSyncPush(ctx,
  362. MirrorSyncPushOptions{
  363. Owner: m.Repo.MustOwner(),
  364. Repo: m.Repo,
  365. RefName: result.refName,
  366. OldCommitID: oldCommitID,
  367. NewCommitID: newCommitID,
  368. Commits: CommitsToPushCommits(commits),
  369. },
  370. )
  371. if err != nil {
  372. log.Error("Failed to create action for mirror sync push [repo_id: %d]: %v", m.RepoID, err)
  373. continue
  374. }
  375. }
  376. if _, err = x.Exec("UPDATE mirror SET updated_unix = ? WHERE repo_id = ?", time.Now().Unix(), m.RepoID); err != nil {
  377. log.Error("Update 'mirror.updated_unix' [%d]: %v", m.RepoID, err)
  378. continue
  379. }
  380. // Get latest commit date and compare to current repository updated time,
  381. // update if latest commit date is newer.
  382. latestCommitTime, err := gitRepo.LatestCommitTime()
  383. if err != nil {
  384. log.Error("GetLatestCommitDate [%d]: %v", m.RepoID, err)
  385. continue
  386. } else if !latestCommitTime.After(m.Repo.Updated) {
  387. continue
  388. }
  389. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", latestCommitTime.Unix(), m.RepoID); err != nil {
  390. log.Error("Update 'repository.updated_unix' [%d]: %v", m.RepoID, err)
  391. continue
  392. }
  393. }
  394. }
  395. func InitSyncMirrors() {
  396. go SyncMirrors()
  397. }