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

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