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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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", "rm", "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. gitRepo.Close()
  216. if err := m.Repo.UpdateSize(); err != nil {
  217. log.Error("Failed to update size for mirror repository: %v", err)
  218. }
  219. if m.Repo.HasWiki() {
  220. if _, stderr, err := process.GetManager().ExecDir(
  221. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  222. git.GitExecutable, "remote", "update", "--prune"); err != nil {
  223. // sanitize the output, since it may contain the remote address, which may
  224. // contain a password
  225. message, err := sanitizeOutput(stderr, wikiPath)
  226. if err != nil {
  227. log.Error("sanitizeOutput: %v", err)
  228. return nil, false
  229. }
  230. desc := fmt.Sprintf("Failed to update mirror wiki repository '%s': %s", wikiPath, message)
  231. log.Error(desc)
  232. if err = CreateRepositoryNotice(desc); err != nil {
  233. log.Error("CreateRepositoryNotice: %v", err)
  234. }
  235. return nil, false
  236. }
  237. }
  238. branches, err := m.Repo.GetBranches()
  239. if err != nil {
  240. log.Error("GetBranches: %v", err)
  241. return nil, false
  242. }
  243. for i := range branches {
  244. cache.Remove(m.Repo.GetCommitsCountCacheKey(branches[i].Name, true))
  245. }
  246. m.UpdatedUnix = util.TimeStampNow()
  247. return parseRemoteUpdateOutput(output), true
  248. }
  249. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  250. m := &Mirror{RepoID: repoID}
  251. has, err := e.Get(m)
  252. if err != nil {
  253. return nil, err
  254. } else if !has {
  255. return nil, ErrMirrorNotExist
  256. }
  257. return m, nil
  258. }
  259. // GetMirrorByRepoID returns mirror information of a repository.
  260. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  261. return getMirrorByRepoID(x, repoID)
  262. }
  263. func updateMirror(e Engine, m *Mirror) error {
  264. _, err := e.ID(m.ID).AllCols().Update(m)
  265. return err
  266. }
  267. // UpdateMirror updates the mirror
  268. func UpdateMirror(m *Mirror) error {
  269. return updateMirror(x, m)
  270. }
  271. // DeleteMirrorByRepoID deletes a mirror by repoID
  272. func DeleteMirrorByRepoID(repoID int64) error {
  273. _, err := x.Delete(&Mirror{RepoID: repoID})
  274. return err
  275. }
  276. // MirrorUpdate checks and updates mirror repositories.
  277. func MirrorUpdate() {
  278. if !taskStatusTable.StartIfNotRunning(mirrorUpdate) {
  279. return
  280. }
  281. defer taskStatusTable.Stop(mirrorUpdate)
  282. log.Trace("Doing: MirrorUpdate")
  283. if err := x.
  284. Where("next_update_unix<=?", time.Now().Unix()).
  285. And("next_update_unix!=0").
  286. Iterate(new(Mirror), func(idx int, bean interface{}) error {
  287. m := bean.(*Mirror)
  288. if m.Repo == nil {
  289. log.Error("Disconnected mirror repository found: %d", m.ID)
  290. return nil
  291. }
  292. MirrorQueue.Add(m.RepoID)
  293. return nil
  294. }); err != nil {
  295. log.Error("MirrorUpdate: %v", err)
  296. }
  297. }
  298. // SyncMirrors checks and syncs mirrors.
  299. // TODO: sync more mirrors at same time.
  300. func SyncMirrors() {
  301. sess := x.NewSession()
  302. defer sess.Close()
  303. // Start listening on new sync requests.
  304. for repoID := range MirrorQueue.Queue() {
  305. log.Trace("SyncMirrors [repo_id: %v]", repoID)
  306. MirrorQueue.Remove(repoID)
  307. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  308. if err != nil {
  309. log.Error("GetMirrorByRepoID [%s]: %v", repoID, err)
  310. continue
  311. }
  312. results, ok := m.runSync()
  313. if !ok {
  314. continue
  315. }
  316. m.ScheduleNextUpdate()
  317. if err = updateMirror(sess, m); err != nil {
  318. log.Error("UpdateMirror [%s]: %v", repoID, err)
  319. continue
  320. }
  321. var gitRepo *git.Repository
  322. if len(results) == 0 {
  323. log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
  324. } else {
  325. gitRepo, err = git.OpenRepository(m.Repo.RepoPath())
  326. if err != nil {
  327. log.Error("OpenRepository [%d]: %v", m.RepoID, err)
  328. continue
  329. }
  330. }
  331. for _, result := range results {
  332. // Discard GitHub pull requests, i.e. refs/pull/*
  333. if strings.HasPrefix(result.refName, "refs/pull/") {
  334. continue
  335. }
  336. // Create reference
  337. if result.oldCommitID == gitShortEmptySha {
  338. if err = MirrorSyncCreateAction(m.Repo, result.refName); err != nil {
  339. log.Error("MirrorSyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
  340. }
  341. continue
  342. }
  343. // Delete reference
  344. if result.newCommitID == gitShortEmptySha {
  345. if err = MirrorSyncDeleteAction(m.Repo, result.refName); err != nil {
  346. log.Error("MirrorSyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
  347. }
  348. continue
  349. }
  350. // Push commits
  351. oldCommitID, err := git.GetFullCommitID(gitRepo.Path, result.oldCommitID)
  352. if err != nil {
  353. log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
  354. continue
  355. }
  356. newCommitID, err := git.GetFullCommitID(gitRepo.Path, result.newCommitID)
  357. if err != nil {
  358. log.Error("GetFullCommitID [%d]: %v", m.RepoID, err)
  359. continue
  360. }
  361. commits, err := gitRepo.CommitsBetweenIDs(newCommitID, oldCommitID)
  362. if err != nil {
  363. log.Error("CommitsBetweenIDs [repo_id: %d, new_commit_id: %s, old_commit_id: %s]: %v", m.RepoID, newCommitID, oldCommitID, err)
  364. continue
  365. }
  366. if err = MirrorSyncPushAction(m.Repo, MirrorSyncPushActionOptions{
  367. RefName: result.refName,
  368. OldCommitID: oldCommitID,
  369. NewCommitID: newCommitID,
  370. Commits: ListToPushCommits(commits),
  371. }); err != nil {
  372. log.Error("MirrorSyncPushAction [repo_id: %d]: %v", m.RepoID, err)
  373. continue
  374. }
  375. }
  376. gitRepo.Close()
  377. // Get latest commit date and update to current repository updated time
  378. commitDate, err := git.GetLatestCommitTime(m.Repo.RepoPath())
  379. if err != nil {
  380. log.Error("GetLatestCommitDate [%d]: %v", m.RepoID, err)
  381. continue
  382. }
  383. if _, err = sess.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", commitDate.Unix(), m.RepoID); err != nil {
  384. log.Error("Update repository 'updated_unix' [%d]: %v", m.RepoID, err)
  385. continue
  386. }
  387. }
  388. }
  389. // InitSyncMirrors initializes a go routine to sync the mirrors
  390. func InitSyncMirrors() {
  391. go SyncMirrors()
  392. }