You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo_mirror.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "fmt"
  8. "strings"
  9. "time"
  10. "code.gitea.io/gitea/modules/cache"
  11. "code.gitea.io/gitea/modules/git"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/process"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/sync"
  16. "code.gitea.io/gitea/modules/util"
  17. "github.com/Unknwon/com"
  18. "github.com/go-xorm/xorm"
  19. "github.com/mcuadros/go-version"
  20. )
  21. // MirrorQueue holds an UniqueQueue object of the mirror
  22. var MirrorQueue = sync.NewUniqueQueue(setting.Repository.MirrorQueueLength)
  23. // Mirror represents mirror information of a repository.
  24. type Mirror struct {
  25. ID int64 `xorm:"pk autoincr"`
  26. RepoID int64 `xorm:"INDEX"`
  27. Repo *Repository `xorm:"-"`
  28. Interval time.Duration
  29. EnablePrune bool `xorm:"NOT NULL DEFAULT true"`
  30. UpdatedUnix util.TimeStamp `xorm:"INDEX"`
  31. NextUpdateUnix util.TimeStamp `xorm:"INDEX"`
  32. address string `xorm:"-"`
  33. }
  34. // BeforeInsert will be invoked by XORM before inserting a record
  35. func (m *Mirror) BeforeInsert() {
  36. if m != nil {
  37. m.UpdatedUnix = util.TimeStampNow()
  38. m.NextUpdateUnix = util.TimeStampNow()
  39. }
  40. }
  41. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  42. func (m *Mirror) AfterLoad(session *xorm.Session) {
  43. if m == nil {
  44. return
  45. }
  46. var err error
  47. m.Repo, err = getRepositoryByID(session, m.RepoID)
  48. if err != nil {
  49. log.Error("getRepositoryByID[%d]: %v", m.ID, err)
  50. }
  51. }
  52. // ScheduleNextUpdate calculates and sets next update time.
  53. func (m *Mirror) ScheduleNextUpdate() {
  54. if m.Interval != 0 {
  55. m.NextUpdateUnix = util.TimeStampNow().AddDuration(m.Interval)
  56. } else {
  57. m.NextUpdateUnix = 0
  58. }
  59. }
  60. func remoteAddress(repoPath string) (string, error) {
  61. var cmd *git.Command
  62. binVersion, err := git.BinVersion()
  63. if err != nil {
  64. return "", err
  65. }
  66. if version.Compare(binVersion, "2.7", ">=") {
  67. cmd = git.NewCommand("remote", "get-url", "origin")
  68. } else {
  69. cmd = git.NewCommand("config", "--get", "remote.origin.url")
  70. }
  71. result, err := cmd.RunInDir(repoPath)
  72. if err != nil {
  73. if strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
  74. return "", nil
  75. }
  76. return "", err
  77. }
  78. if len(result) > 0 {
  79. return result[:len(result)-1], nil
  80. }
  81. return "", nil
  82. }
  83. func (m *Mirror) readAddress() {
  84. if len(m.address) > 0 {
  85. return
  86. }
  87. var err error
  88. m.address, err = remoteAddress(m.Repo.RepoPath())
  89. if err != nil {
  90. log.Error("remoteAddress: %v", err)
  91. }
  92. }
  93. // sanitizeOutput sanitizes output of a command, replacing occurrences of the
  94. // repository's remote address with a sanitized version.
  95. func sanitizeOutput(output, repoPath string) (string, error) {
  96. remoteAddr, err := remoteAddress(repoPath)
  97. if err != nil {
  98. // if we're unable to load the remote address, then we're unable to
  99. // sanitize.
  100. return "", err
  101. }
  102. return util.SanitizeMessage(output, remoteAddr), nil
  103. }
  104. // Address returns mirror address from Git repository config without credentials.
  105. func (m *Mirror) Address() string {
  106. m.readAddress()
  107. return util.SanitizeURLCredentials(m.address, false)
  108. }
  109. // FullAddress returns mirror address from Git repository config.
  110. func (m *Mirror) FullAddress() string {
  111. m.readAddress()
  112. return m.address
  113. }
  114. // SaveAddress writes new address to Git repository config.
  115. func (m *Mirror) SaveAddress(addr string) error {
  116. repoPath := m.Repo.RepoPath()
  117. // Remove old origin
  118. _, err := git.NewCommand("remote", "remove", "origin").RunInDir(repoPath)
  119. if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
  120. return err
  121. }
  122. _, err = git.NewCommand("remote", "add", "origin", "--mirror=fetch", addr).RunInDir(repoPath)
  123. return err
  124. }
  125. // gitShortEmptySha Git short empty SHA
  126. const gitShortEmptySha = "0000000"
  127. // mirrorSyncResult contains information of a updated reference.
  128. // If the oldCommitID is "0000000", it means a new reference, the value of newCommitID is empty.
  129. // If the newCommitID is "0000000", it means the reference is deleted, the value of oldCommitID is empty.
  130. type mirrorSyncResult struct {
  131. refName string
  132. oldCommitID string
  133. newCommitID string
  134. }
  135. // parseRemoteUpdateOutput detects create, update and delete operations of references from upstream.
  136. func parseRemoteUpdateOutput(output string) []*mirrorSyncResult {
  137. results := make([]*mirrorSyncResult, 0, 3)
  138. lines := strings.Split(output, "\n")
  139. for i := range lines {
  140. // Make sure reference name is presented before continue
  141. idx := strings.Index(lines[i], "-> ")
  142. if idx == -1 {
  143. continue
  144. }
  145. refName := lines[i][idx+3:]
  146. switch {
  147. case strings.HasPrefix(lines[i], " * "): // New reference
  148. results = append(results, &mirrorSyncResult{
  149. refName: refName,
  150. oldCommitID: gitShortEmptySha,
  151. })
  152. case strings.HasPrefix(lines[i], " - "): // Delete reference
  153. results = append(results, &mirrorSyncResult{
  154. refName: refName,
  155. newCommitID: gitShortEmptySha,
  156. })
  157. case strings.HasPrefix(lines[i], " "): // New commits of a reference
  158. delimIdx := strings.Index(lines[i][3:], " ")
  159. if delimIdx == -1 {
  160. log.Error("SHA delimiter not found: %q", lines[i])
  161. continue
  162. }
  163. shas := strings.Split(lines[i][3:delimIdx+3], "..")
  164. if len(shas) != 2 {
  165. log.Error("Expect two SHAs but not what found: %q", lines[i])
  166. continue
  167. }
  168. results = append(results, &mirrorSyncResult{
  169. refName: refName,
  170. oldCommitID: shas[0],
  171. newCommitID: shas[1],
  172. })
  173. default:
  174. log.Warn("parseRemoteUpdateOutput: unexpected update line %q", lines[i])
  175. }
  176. }
  177. return results
  178. }
  179. // runSync returns true if sync finished without error.
  180. func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
  181. repoPath := m.Repo.RepoPath()
  182. wikiPath := m.Repo.WikiPath()
  183. timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second
  184. gitArgs := []string{"remote", "update"}
  185. if m.EnablePrune {
  186. gitArgs = append(gitArgs, "--prune")
  187. }
  188. _, stderr, err := process.GetManager().ExecDir(
  189. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  190. git.GitExecutable, gitArgs...)
  191. if err != nil {
  192. // sanitize the output, since it may contain the remote address, which may
  193. // contain a password
  194. message, err := sanitizeOutput(stderr, repoPath)
  195. if err != nil {
  196. log.Error("sanitizeOutput: %v", err)
  197. return nil, false
  198. }
  199. desc := fmt.Sprintf("Failed to update mirror repository '%s': %s", repoPath, message)
  200. log.Error(desc)
  201. if err = CreateRepositoryNotice(desc); err != nil {
  202. log.Error("CreateRepositoryNotice: %v", err)
  203. }
  204. return nil, false
  205. }
  206. output := stderr
  207. gitRepo, err := git.OpenRepository(repoPath)
  208. if err != nil {
  209. log.Error("OpenRepository: %v", err)
  210. return nil, false
  211. }
  212. if err = SyncReleasesWithTags(m.Repo, gitRepo); err != nil {
  213. log.Error("Failed to synchronize tags to releases for repository: %v", err)
  214. }
  215. if err := m.Repo.UpdateSize(); err != nil {
  216. log.Error("Failed to update size for mirror repository: %v", err)
  217. }
  218. if m.Repo.HasWiki() {
  219. if _, stderr, err := process.GetManager().ExecDir(
  220. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  221. git.GitExecutable, "remote", "update", "--prune"); err != nil {
  222. // sanitize the output, since it may contain the remote address, which may
  223. // contain a password
  224. message, err := sanitizeOutput(stderr, wikiPath)
  225. if err != nil {
  226. log.Error("sanitizeOutput: %v", err)
  227. return nil, false
  228. }
  229. desc := fmt.Sprintf("Failed to update mirror wiki repository '%s': %s", wikiPath, message)
  230. log.Error(desc)
  231. if err = CreateRepositoryNotice(desc); err != nil {
  232. log.Error("CreateRepositoryNotice: %v", err)
  233. }
  234. return nil, false
  235. }
  236. }
  237. branches, err := m.Repo.GetBranches()
  238. if err != nil {
  239. log.Error("GetBranches: %v", err)
  240. return nil, false
  241. }
  242. for i := range branches {
  243. cache.Remove(m.Repo.GetCommitsCountCacheKey(branches[i].Name, true))
  244. }
  245. m.UpdatedUnix = util.TimeStampNow()
  246. return parseRemoteUpdateOutput(output), true
  247. }
  248. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  249. m := &Mirror{RepoID: repoID}
  250. has, err := e.Get(m)
  251. if err != nil {
  252. return nil, err
  253. } else if !has {
  254. return nil, ErrMirrorNotExist
  255. }
  256. return m, nil
  257. }
  258. // GetMirrorByRepoID returns mirror information of a repository.
  259. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  260. return getMirrorByRepoID(x, repoID)
  261. }
  262. func updateMirror(e Engine, m *Mirror) error {
  263. _, err := e.ID(m.ID).AllCols().Update(m)
  264. return err
  265. }
  266. // UpdateMirror updates the mirror
  267. func UpdateMirror(m *Mirror) error {
  268. return updateMirror(x, m)
  269. }
  270. // DeleteMirrorByRepoID deletes a mirror by repoID
  271. func DeleteMirrorByRepoID(repoID int64) error {
  272. _, err := x.Delete(&Mirror{RepoID: repoID})
  273. return err
  274. }
  275. // MirrorUpdate checks and updates mirror repositories.
  276. func MirrorUpdate() {
  277. if !taskStatusTable.StartIfNotRunning(mirrorUpdate) {
  278. return
  279. }
  280. defer taskStatusTable.Stop(mirrorUpdate)
  281. log.Trace("Doing: MirrorUpdate")
  282. if err := x.
  283. Where("next_update_unix<=?", time.Now().Unix()).
  284. And("next_update_unix!=0").
  285. Iterate(new(Mirror), func(idx int, bean interface{}) error {
  286. m := bean.(*Mirror)
  287. if m.Repo == nil {
  288. log.Error("Disconnected mirror repository found: %d", m.ID)
  289. return nil
  290. }
  291. MirrorQueue.Add(m.RepoID)
  292. return nil
  293. }); err != nil {
  294. log.Error("MirrorUpdate: %v", err)
  295. }
  296. }
  297. // SyncMirrors checks and syncs mirrors.
  298. // TODO: sync more mirrors at same time.
  299. func SyncMirrors() {
  300. sess := x.NewSession()
  301. defer sess.Close()
  302. // Start listening on new sync requests.
  303. for repoID := range MirrorQueue.Queue() {
  304. log.Trace("SyncMirrors [repo_id: %v]", repoID)
  305. MirrorQueue.Remove(repoID)
  306. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  307. if err != nil {
  308. log.Error("GetMirrorByRepoID [%s]: %v", repoID, err)
  309. continue
  310. }
  311. results, ok := m.runSync()
  312. if !ok {
  313. continue
  314. }
  315. m.ScheduleNextUpdate()
  316. if err = updateMirror(sess, m); err != nil {
  317. log.Error("UpdateMirror [%s]: %v", repoID, err)
  318. continue
  319. }
  320. var gitRepo *git.Repository
  321. if len(results) == 0 {
  322. log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
  323. } else {
  324. gitRepo, err = git.OpenRepository(m.Repo.RepoPath())
  325. if err != nil {
  326. log.Error("OpenRepository [%d]: %v", m.RepoID, err)
  327. continue
  328. }
  329. }
  330. for _, result := range results {
  331. // Discard GitHub pull requests, i.e. refs/pull/*
  332. if strings.HasPrefix(result.refName, "refs/pull/") {
  333. continue
  334. }
  335. // Create reference
  336. if result.oldCommitID == gitShortEmptySha {
  337. if err = MirrorSyncCreateAction(m.Repo, result.refName); err != nil {
  338. log.Error("MirrorSyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
  339. }
  340. continue
  341. }
  342. // Delete reference
  343. if result.newCommitID == gitShortEmptySha {
  344. if err = MirrorSyncDeleteAction(m.Repo, result.refName); err != nil {
  345. log.Error("MirrorSyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
  346. }
  347. continue
  348. }
  349. // Push commits
  350. oldCommitID, err := git.GetFullCommitID(gitRepo.Path, result.oldCommitID)
  351. if err != nil {
  352. log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
  353. continue
  354. }
  355. newCommitID, err := git.GetFullCommitID(gitRepo.Path, result.newCommitID)
  356. if err != nil {
  357. log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
  358. continue
  359. }
  360. commits, err := gitRepo.CommitsBetweenIDs(newCommitID, oldCommitID)
  361. if err != nil {
  362. log.Error("CommitsBetweenIDs [repo_id: %d, new_commit_id: %s, old_commit_id: %s]: %v", m.RepoID, newCommitID, oldCommitID, err)
  363. continue
  364. }
  365. if err = MirrorSyncPushAction(m.Repo, MirrorSyncPushActionOptions{
  366. RefName: result.refName,
  367. OldCommitID: oldCommitID,
  368. NewCommitID: newCommitID,
  369. Commits: ListToPushCommits(commits),
  370. }); err != nil {
  371. log.Error("MirrorSyncPushAction [repo_id: %d]: %v", m.RepoID, err)
  372. continue
  373. }
  374. }
  375. // Get latest commit date and update to current repository updated time
  376. commitDate, err := git.GetLatestCommitTime(m.Repo.RepoPath())
  377. if err != nil {
  378. log.Error("GetLatestCommitDate [%d]: %v", m.RepoID, err)
  379. continue
  380. }
  381. if _, err = sess.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", commitDate.Unix(), m.RepoID); err != nil {
  382. log.Error("Update repository 'updated_unix' [%d]: %v", m.RepoID, err)
  383. continue
  384. }
  385. }
  386. }
  387. // InitSyncMirrors initializes a go routine to sync the mirrors
  388. func InitSyncMirrors() {
  389. go SyncMirrors()
  390. }