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 13KB

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