Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

repo_mirror.go 12KB

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