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

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