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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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/git"
  11. "code.gitea.io/gitea/modules/cache"
  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. "gopkg.in/ini.v1"
  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(3, "getRepositoryByID[%d]: %v", m.ID, err)
  50. }
  51. }
  52. // ScheduleNextUpdate calculates and sets next update time.
  53. func (m *Mirror) ScheduleNextUpdate() {
  54. m.NextUpdateUnix = util.TimeStampNow().AddDuration(m.Interval)
  55. }
  56. func remoteAddress(repoPath string) (string, error) {
  57. cfg, err := ini.Load(GitConfigPath(repoPath))
  58. if err != nil {
  59. return "", err
  60. }
  61. return cfg.Section("remote \"origin\"").Key("url").Value(), nil
  62. }
  63. func (m *Mirror) readAddress() {
  64. if len(m.address) > 0 {
  65. return
  66. }
  67. var err error
  68. m.address, err = remoteAddress(m.Repo.RepoPath())
  69. if err != nil {
  70. log.Error(4, "remoteAddress: %v", err)
  71. }
  72. }
  73. // sanitizeOutput sanitizes output of a command, replacing occurrences of the
  74. // repository's remote address with a sanitized version.
  75. func sanitizeOutput(output, repoPath string) (string, error) {
  76. remoteAddr, err := remoteAddress(repoPath)
  77. if err != nil {
  78. // if we're unable to load the remote address, then we're unable to
  79. // sanitize.
  80. return "", err
  81. }
  82. return util.SanitizeMessage(output, remoteAddr), nil
  83. }
  84. // Address returns mirror address from Git repository config without credentials.
  85. func (m *Mirror) Address() string {
  86. m.readAddress()
  87. return util.SanitizeURLCredentials(m.address, false)
  88. }
  89. // FullAddress returns mirror address from Git repository config.
  90. func (m *Mirror) FullAddress() string {
  91. m.readAddress()
  92. return m.address
  93. }
  94. // SaveAddress writes new address to Git repository config.
  95. func (m *Mirror) SaveAddress(addr string) error {
  96. configPath := m.Repo.GitConfigPath()
  97. cfg, err := ini.Load(configPath)
  98. if err != nil {
  99. return fmt.Errorf("Load: %v", err)
  100. }
  101. cfg.Section("remote \"origin\"").Key("url").SetValue(addr)
  102. return cfg.SaveToIndent(configPath, "\t")
  103. }
  104. // gitShortEmptySha Git short empty SHA
  105. const gitShortEmptySha = "0000000"
  106. // mirrorSyncResult contains information of a updated reference.
  107. // If the oldCommitID is "0000000", it means a new reference, the value of newCommitID is empty.
  108. // If the newCommitID is "0000000", it means the reference is deleted, the value of oldCommitID is empty.
  109. type mirrorSyncResult struct {
  110. refName string
  111. oldCommitID string
  112. newCommitID string
  113. }
  114. // parseRemoteUpdateOutput detects create, update and delete operations of references from upstream.
  115. func parseRemoteUpdateOutput(output string) []*mirrorSyncResult {
  116. results := make([]*mirrorSyncResult, 0, 3)
  117. lines := strings.Split(output, "\n")
  118. for i := range lines {
  119. // Make sure reference name is presented before continue
  120. idx := strings.Index(lines[i], "-> ")
  121. if idx == -1 {
  122. continue
  123. }
  124. refName := lines[i][idx+3:]
  125. switch {
  126. case strings.HasPrefix(lines[i], " * "): // New reference
  127. results = append(results, &mirrorSyncResult{
  128. refName: refName,
  129. oldCommitID: gitShortEmptySha,
  130. })
  131. case strings.HasPrefix(lines[i], " - "): // Delete reference
  132. results = append(results, &mirrorSyncResult{
  133. refName: refName,
  134. newCommitID: gitShortEmptySha,
  135. })
  136. case strings.HasPrefix(lines[i], " "): // New commits of a reference
  137. delimIdx := strings.Index(lines[i][3:], " ")
  138. if delimIdx == -1 {
  139. log.Error(2, "SHA delimiter not found: %q", lines[i])
  140. continue
  141. }
  142. shas := strings.Split(lines[i][3:delimIdx+3], "..")
  143. if len(shas) != 2 {
  144. log.Error(2, "Expect two SHAs but not what found: %q", lines[i])
  145. continue
  146. }
  147. results = append(results, &mirrorSyncResult{
  148. refName: refName,
  149. oldCommitID: shas[0],
  150. newCommitID: shas[1],
  151. })
  152. default:
  153. log.Warn("parseRemoteUpdateOutput: unexpected update line %q", lines[i])
  154. }
  155. }
  156. return results
  157. }
  158. // runSync returns true if sync finished without error.
  159. func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
  160. repoPath := m.Repo.RepoPath()
  161. wikiPath := m.Repo.WikiPath()
  162. timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second
  163. gitArgs := []string{"remote", "update"}
  164. if m.EnablePrune {
  165. gitArgs = append(gitArgs, "--prune")
  166. }
  167. _, stderr, err := process.GetManager().ExecDir(
  168. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  169. "git", gitArgs...)
  170. if err != nil {
  171. // sanitize the output, since it may contain the remote address, which may
  172. // contain a password
  173. message, err := sanitizeOutput(stderr, repoPath)
  174. if err != nil {
  175. log.Error(4, "sanitizeOutput: %v", err)
  176. return nil, false
  177. }
  178. desc := fmt.Sprintf("Failed to update mirror repository '%s': %s", repoPath, message)
  179. log.Error(4, desc)
  180. if err = CreateRepositoryNotice(desc); err != nil {
  181. log.Error(4, "CreateRepositoryNotice: %v", err)
  182. }
  183. return nil, false
  184. }
  185. output := stderr
  186. gitRepo, err := git.OpenRepository(repoPath)
  187. if err != nil {
  188. log.Error(4, "OpenRepository: %v", err)
  189. return nil, false
  190. }
  191. if err = SyncReleasesWithTags(m.Repo, gitRepo); err != nil {
  192. log.Error(4, "Failed to synchronize tags to releases for repository: %v", err)
  193. }
  194. if err := m.Repo.UpdateSize(); err != nil {
  195. log.Error(4, "Failed to update size for mirror repository: %v", err)
  196. }
  197. if m.Repo.HasWiki() {
  198. if _, stderr, err := process.GetManager().ExecDir(
  199. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  200. "git", "remote", "update", "--prune"); err != nil {
  201. // sanitize the output, since it may contain the remote address, which may
  202. // contain a password
  203. message, err := sanitizeOutput(stderr, wikiPath)
  204. if err != nil {
  205. log.Error(4, "sanitizeOutput: %v", err)
  206. return nil, false
  207. }
  208. desc := fmt.Sprintf("Failed to update mirror wiki repository '%s': %s", wikiPath, message)
  209. log.Error(4, desc)
  210. if err = CreateRepositoryNotice(desc); err != nil {
  211. log.Error(4, "CreateRepositoryNotice: %v", err)
  212. }
  213. return nil, false
  214. }
  215. }
  216. branches, err := m.Repo.GetBranches()
  217. if err != nil {
  218. log.Error(4, "GetBranches: %v", err)
  219. return nil, false
  220. }
  221. for i := range branches {
  222. cache.Remove(m.Repo.GetCommitsCountCacheKey(branches[i].Name, true))
  223. }
  224. m.UpdatedUnix = util.TimeStampNow()
  225. return parseRemoteUpdateOutput(output), true
  226. }
  227. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  228. m := &Mirror{RepoID: repoID}
  229. has, err := e.Get(m)
  230. if err != nil {
  231. return nil, err
  232. } else if !has {
  233. return nil, ErrMirrorNotExist
  234. }
  235. return m, nil
  236. }
  237. // GetMirrorByRepoID returns mirror information of a repository.
  238. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  239. return getMirrorByRepoID(x, repoID)
  240. }
  241. func updateMirror(e Engine, m *Mirror) error {
  242. _, err := e.ID(m.ID).AllCols().Update(m)
  243. return err
  244. }
  245. // UpdateMirror updates the mirror
  246. func UpdateMirror(m *Mirror) error {
  247. return updateMirror(x, m)
  248. }
  249. // DeleteMirrorByRepoID deletes a mirror by repoID
  250. func DeleteMirrorByRepoID(repoID int64) error {
  251. _, err := x.Delete(&Mirror{RepoID: repoID})
  252. return err
  253. }
  254. // MirrorUpdate checks and updates mirror repositories.
  255. func MirrorUpdate() {
  256. if !taskStatusTable.StartIfNotRunning(mirrorUpdate) {
  257. return
  258. }
  259. defer taskStatusTable.Stop(mirrorUpdate)
  260. log.Trace("Doing: MirrorUpdate")
  261. if err := x.
  262. Where("next_update_unix<=?", time.Now().Unix()).
  263. Iterate(new(Mirror), func(idx int, bean interface{}) error {
  264. m := bean.(*Mirror)
  265. if m.Repo == nil {
  266. log.Error(4, "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(4, "MirrorUpdate: %v", err)
  273. }
  274. }
  275. // SyncMirrors checks and syncs mirrors.
  276. // TODO: sync more mirrors at same time.
  277. func SyncMirrors() {
  278. sess := x.NewSession()
  279. defer sess.Close()
  280. // Start listening on new sync requests.
  281. for repoID := range MirrorQueue.Queue() {
  282. log.Trace("SyncMirrors [repo_id: %v]", repoID)
  283. MirrorQueue.Remove(repoID)
  284. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  285. if err != nil {
  286. log.Error(4, "GetMirrorByRepoID [%s]: %v", repoID, err)
  287. continue
  288. }
  289. results, ok := m.runSync()
  290. if !ok {
  291. continue
  292. }
  293. m.ScheduleNextUpdate()
  294. if err = updateMirror(sess, m); err != nil {
  295. log.Error(4, "UpdateMirror [%s]: %v", repoID, err)
  296. continue
  297. }
  298. var gitRepo *git.Repository
  299. if len(results) == 0 {
  300. log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
  301. } else {
  302. gitRepo, err = git.OpenRepository(m.Repo.RepoPath())
  303. if err != nil {
  304. log.Error(2, "OpenRepository [%d]: %v", m.RepoID, err)
  305. continue
  306. }
  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. // Create reference
  314. if result.oldCommitID == gitShortEmptySha {
  315. if err = MirrorSyncCreateAction(m.Repo, result.refName); err != nil {
  316. log.Error(2, "MirrorSyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
  317. }
  318. continue
  319. }
  320. // Delete reference
  321. if result.newCommitID == gitShortEmptySha {
  322. if err = MirrorSyncDeleteAction(m.Repo, result.refName); err != nil {
  323. log.Error(2, "MirrorSyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
  324. }
  325. continue
  326. }
  327. // Push commits
  328. oldCommitID, err := git.GetFullCommitID(gitRepo.Path, result.oldCommitID)
  329. if err != nil {
  330. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  331. continue
  332. }
  333. newCommitID, err := git.GetFullCommitID(gitRepo.Path, result.newCommitID)
  334. if err != nil {
  335. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  336. continue
  337. }
  338. commits, err := gitRepo.CommitsBetweenIDs(newCommitID, oldCommitID)
  339. if err != nil {
  340. log.Error(2, "CommitsBetweenIDs [repo_id: %d, new_commit_id: %s, old_commit_id: %s]: %v", m.RepoID, newCommitID, oldCommitID, err)
  341. continue
  342. }
  343. if err = MirrorSyncPushAction(m.Repo, MirrorSyncPushActionOptions{
  344. RefName: result.refName,
  345. OldCommitID: oldCommitID,
  346. NewCommitID: newCommitID,
  347. Commits: ListToPushCommits(commits),
  348. }); err != nil {
  349. log.Error(2, "MirrorSyncPushAction [repo_id: %d]: %v", m.RepoID, err)
  350. continue
  351. }
  352. }
  353. // Get latest commit date and update to current repository updated time
  354. commitDate, err := git.GetLatestCommitTime(m.Repo.RepoPath())
  355. if err != nil {
  356. log.Error(2, "GetLatestCommitDate [%s]: %v", m.RepoID, err)
  357. continue
  358. }
  359. if _, err = sess.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", commitDate.Unix(), m.RepoID); err != nil {
  360. log.Error(2, "Update repository 'updated_unix' [%s]: %v", m.RepoID, err)
  361. continue
  362. }
  363. }
  364. }
  365. // InitSyncMirrors initializes a go routine to sync the mirrors
  366. func InitSyncMirrors() {
  367. go SyncMirrors()
  368. }