1
0

mirror.go 13 KB

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