mirror.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. package models
  2. import (
  3. "container/list"
  4. "fmt"
  5. "gitote/gitote/models/errors"
  6. "gitote/gitote/pkg/process"
  7. "gitote/gitote/pkg/setting"
  8. "gitote/gitote/pkg/sync"
  9. "net/url"
  10. "strings"
  11. "time"
  12. "github.com/Unknwon/com"
  13. "github.com/go-xorm/xorm"
  14. "gitlab.com/gitote/git-module"
  15. log "gopkg.in/clog.v1"
  16. "gopkg.in/ini.v1"
  17. )
  18. var MirrorQueue = sync.NewUniqueQueue(setting.Repository.MirrorQueueLength)
  19. // Mirror represents mirror information of a repository.
  20. type Mirror struct {
  21. ID int64
  22. RepoID int64
  23. Repo *Repository `xorm:"-" json:"-"`
  24. Interval int // Hour.
  25. EnablePrune bool `xorm:"NOT NULL DEFAULT true"`
  26. // Last and next sync time of Git data from upstream
  27. LastSync time.Time `xorm:"-" json:"-"`
  28. LastSyncUnix int64 `xorm:"updated_unix"`
  29. NextSync time.Time `xorm:"-" json:"-"`
  30. NextSyncUnix int64 `xorm:"next_update_unix"`
  31. address string `xorm:"-" json:"-"`
  32. }
  33. func (m *Mirror) BeforeInsert() {
  34. m.NextSyncUnix = m.NextSync.Unix()
  35. }
  36. func (m *Mirror) BeforeUpdate() {
  37. m.LastSyncUnix = m.LastSync.Unix()
  38. m.NextSyncUnix = m.NextSync.Unix()
  39. }
  40. func (m *Mirror) AfterSet(colName string, _ xorm.Cell) {
  41. var err error
  42. switch colName {
  43. case "repo_id":
  44. m.Repo, err = GetRepositoryByID(m.RepoID)
  45. if err != nil {
  46. log.Error(3, "GetRepositoryByID [%d]: %v", m.ID, err)
  47. }
  48. case "updated_unix":
  49. m.LastSync = time.Unix(m.LastSyncUnix, 0).Local()
  50. case "next_update_unix":
  51. m.NextSync = time.Unix(m.NextSyncUnix, 0).Local()
  52. }
  53. }
  54. // ScheduleNextSync calculates and sets next sync time based on repostiroy mirror setting.
  55. func (m *Mirror) ScheduleNextSync() {
  56. m.NextSync = time.Now().Add(time.Duration(m.Interval) * time.Hour)
  57. }
  58. // findPasswordInMirrorAddress returns start (inclusive) and end index (exclusive)
  59. // of password portion of credentials in given mirror address.
  60. // It returns a boolean value to indicate whether password portion is found.
  61. func findPasswordInMirrorAddress(addr string) (start int, end int, found bool) {
  62. // Find end of credentials (start of path)
  63. end = strings.LastIndex(addr, "@")
  64. if end == -1 {
  65. return -1, -1, false
  66. }
  67. // Find delimiter of credentials (end of username)
  68. start = strings.Index(addr, "://")
  69. if start == -1 {
  70. return -1, -1, false
  71. }
  72. start += 3
  73. delim := strings.Index(addr[start:], ":")
  74. if delim == -1 {
  75. return -1, -1, false
  76. }
  77. delim += 1
  78. if start+delim >= end {
  79. return -1, -1, false // No password portion presented
  80. }
  81. return start + delim, end, true
  82. }
  83. // unescapeMirrorCredentials returns mirror address with unescaped credentials.
  84. func unescapeMirrorCredentials(addr string) string {
  85. start, end, found := findPasswordInMirrorAddress(addr)
  86. if !found {
  87. return addr
  88. }
  89. password, _ := url.QueryUnescape(addr[start:end])
  90. return addr[:start] + password + addr[end:]
  91. }
  92. func (m *Mirror) readAddress() {
  93. if len(m.address) > 0 {
  94. return
  95. }
  96. cfg, err := ini.Load(m.Repo.GitConfigPath())
  97. if err != nil {
  98. log.Error(2, "Load: %v", err)
  99. return
  100. }
  101. m.address = cfg.Section("remote \"origin\"").Key("url").Value()
  102. }
  103. // HandleMirrorCredentials replaces user credentials from HTTP/HTTPS URL
  104. // with placeholder <credentials>.
  105. // It returns original string if protocol is not HTTP/HTTPS.
  106. func HandleMirrorCredentials(url string, mosaics bool) string {
  107. i := strings.Index(url, "@")
  108. if i == -1 {
  109. return url
  110. }
  111. start := strings.Index(url, "://")
  112. if start == -1 {
  113. return url
  114. }
  115. if mosaics {
  116. return url[:start+3] + "<credentials>" + url[i:]
  117. }
  118. return url[:start+3] + url[i+1:]
  119. }
  120. // Address returns mirror address from Git repository config without credentials.
  121. func (m *Mirror) Address() string {
  122. m.readAddress()
  123. return HandleMirrorCredentials(m.address, false)
  124. }
  125. // MosaicsAddress returns mirror address from Git repository config with credentials under mosaics.
  126. func (m *Mirror) MosaicsAddress() string {
  127. m.readAddress()
  128. return HandleMirrorCredentials(m.address, true)
  129. }
  130. // RawAddress returns raw mirror address directly from Git repository config.
  131. func (m *Mirror) RawAddress() string {
  132. m.readAddress()
  133. return m.address
  134. }
  135. // FullAddress returns mirror address from Git repository config with unescaped credentials.
  136. func (m *Mirror) FullAddress() string {
  137. m.readAddress()
  138. return unescapeMirrorCredentials(m.address)
  139. }
  140. // escapeCredentials returns mirror address with escaped credentials.
  141. func escapeMirrorCredentials(addr string) string {
  142. start, end, found := findPasswordInMirrorAddress(addr)
  143. if !found {
  144. return addr
  145. }
  146. return addr[:start] + url.QueryEscape(addr[start:end]) + addr[end:]
  147. }
  148. // SaveAddress writes new address to Git repository config.
  149. func (m *Mirror) SaveAddress(addr string) error {
  150. configPath := m.Repo.GitConfigPath()
  151. cfg, err := ini.Load(configPath)
  152. if err != nil {
  153. return fmt.Errorf("Load: %v", err)
  154. }
  155. cfg.Section(`remote "origin"`).Key("url").SetValue(escapeMirrorCredentials(addr))
  156. return cfg.SaveToIndent(configPath, "\t")
  157. }
  158. const GIT_SHORT_EMPTY_SHA = "0000000"
  159. // mirrorSyncResult contains information of a updated reference.
  160. // If the oldCommitID is "0000000", it means a new reference, the value of newCommitID is empty.
  161. // If the newCommitID is "0000000", it means the reference is deleted, the value of oldCommitID is empty.
  162. type mirrorSyncResult struct {
  163. refName string
  164. oldCommitID string
  165. newCommitID string
  166. }
  167. // parseRemoteUpdateOutput detects create, update and delete operations of references from upstream.
  168. func parseRemoteUpdateOutput(output string) []*mirrorSyncResult {
  169. results := make([]*mirrorSyncResult, 0, 3)
  170. lines := strings.Split(output, "\n")
  171. for i := range lines {
  172. // Make sure reference name is presented before continue
  173. idx := strings.Index(lines[i], "-> ")
  174. if idx == -1 {
  175. continue
  176. }
  177. refName := lines[i][idx+3:]
  178. switch {
  179. case strings.HasPrefix(lines[i], " * "): // New reference
  180. results = append(results, &mirrorSyncResult{
  181. refName: refName,
  182. oldCommitID: GIT_SHORT_EMPTY_SHA,
  183. })
  184. case strings.HasPrefix(lines[i], " - "): // Delete reference
  185. results = append(results, &mirrorSyncResult{
  186. refName: refName,
  187. newCommitID: GIT_SHORT_EMPTY_SHA,
  188. })
  189. case strings.HasPrefix(lines[i], " "): // New commits of a reference
  190. delimIdx := strings.Index(lines[i][3:], " ")
  191. if delimIdx == -1 {
  192. log.Error(2, "SHA delimiter not found: %q", lines[i])
  193. continue
  194. }
  195. shas := strings.Split(lines[i][3:delimIdx+3], "..")
  196. if len(shas) != 2 {
  197. log.Error(2, "Expect two SHAs but not what found: %q", lines[i])
  198. continue
  199. }
  200. results = append(results, &mirrorSyncResult{
  201. refName: refName,
  202. oldCommitID: shas[0],
  203. newCommitID: shas[1],
  204. })
  205. default:
  206. log.Warn("parseRemoteUpdateOutput: unexpected update line %q", lines[i])
  207. }
  208. }
  209. return results
  210. }
  211. // runSync returns true if sync finished without error.
  212. func (m *Mirror) runSync() ([]*mirrorSyncResult, bool) {
  213. repoPath := m.Repo.RepoPath()
  214. wikiPath := m.Repo.WikiPath()
  215. timeout := time.Duration(setting.Git.Timeout.Mirror) * time.Second
  216. // Do a fast-fail testing against on repository URL to ensure it is accessible under
  217. // good condition to prevent long blocking on URL resolution without syncing anything.
  218. if !git.IsRepoURLAccessible(git.NetworkOptions{
  219. URL: m.RawAddress(),
  220. Timeout: 10 * time.Second,
  221. }) {
  222. desc := fmt.Sprintf("Source URL of mirror repository '%s' is not accessible: %s", m.Repo.FullName(), m.MosaicsAddress())
  223. if err := CreateRepositoryNotice(desc); err != nil {
  224. log.Error(2, "CreateRepositoryNotice: %v", err)
  225. }
  226. return nil, false
  227. }
  228. gitArgs := []string{"remote", "update"}
  229. if m.EnablePrune {
  230. gitArgs = append(gitArgs, "--prune")
  231. }
  232. _, stderr, err := process.ExecDir(
  233. timeout, repoPath, fmt.Sprintf("Mirror.runSync: %s", repoPath),
  234. "git", gitArgs...)
  235. if err != nil {
  236. desc := fmt.Sprintf("Fail to update mirror repository '%s': %s", repoPath, stderr)
  237. log.Error(2, desc)
  238. if err = CreateRepositoryNotice(desc); err != nil {
  239. log.Error(2, "CreateRepositoryNotice: %v", err)
  240. }
  241. return nil, false
  242. }
  243. output := stderr
  244. if err := m.Repo.UpdateSize(); err != nil {
  245. log.Error(2, "UpdateSize [repo_id: %d]: %v", m.Repo.ID, err)
  246. }
  247. if m.Repo.HasWiki() {
  248. // Even if wiki sync failed, we still want results from the main repository
  249. if _, stderr, err := process.ExecDir(
  250. timeout, wikiPath, fmt.Sprintf("Mirror.runSync: %s", wikiPath),
  251. "git", "remote", "update", "--prune"); err != nil {
  252. desc := fmt.Sprintf("Fail to update mirror wiki repository '%s': %s", wikiPath, stderr)
  253. log.Error(2, desc)
  254. if err = CreateRepositoryNotice(desc); err != nil {
  255. log.Error(2, "CreateRepositoryNotice: %v", err)
  256. }
  257. }
  258. }
  259. return parseRemoteUpdateOutput(output), true
  260. }
  261. func getMirrorByRepoID(e Engine, repoID int64) (*Mirror, error) {
  262. m := &Mirror{RepoID: repoID}
  263. has, err := e.Get(m)
  264. if err != nil {
  265. return nil, err
  266. } else if !has {
  267. return nil, errors.MirrorNotExist{repoID}
  268. }
  269. return m, nil
  270. }
  271. // GetMirrorByRepoID returns mirror information of a repository.
  272. func GetMirrorByRepoID(repoID int64) (*Mirror, error) {
  273. return getMirrorByRepoID(x, repoID)
  274. }
  275. func updateMirror(e Engine, m *Mirror) error {
  276. _, err := e.ID(m.ID).AllCols().Update(m)
  277. return err
  278. }
  279. func UpdateMirror(m *Mirror) error {
  280. return updateMirror(x, m)
  281. }
  282. func DeleteMirrorByRepoID(repoID int64) error {
  283. _, err := x.Delete(&Mirror{RepoID: repoID})
  284. return err
  285. }
  286. // MirrorUpdate checks and updates mirror repositories.
  287. func MirrorUpdate() {
  288. if taskStatusTable.IsRunning(_MIRROR_UPDATE) {
  289. return
  290. }
  291. taskStatusTable.Start(_MIRROR_UPDATE)
  292. defer taskStatusTable.Stop(_MIRROR_UPDATE)
  293. log.Trace("Doing: MirrorUpdate")
  294. if err := x.Where("next_update_unix<=?", time.Now().Unix()).Iterate(new(Mirror), func(idx int, bean interface{}) error {
  295. m := bean.(*Mirror)
  296. if m.Repo == nil {
  297. log.Error(2, "Disconnected mirror repository found: %d", m.ID)
  298. return nil
  299. }
  300. MirrorQueue.Add(m.RepoID)
  301. return nil
  302. }); err != nil {
  303. log.Error(2, "MirrorUpdate: %v", err)
  304. }
  305. }
  306. // SyncMirrors checks and syncs mirrors.
  307. // TODO: sync more mirrors at same time.
  308. func SyncMirrors() {
  309. // Start listening on new sync requests.
  310. for repoID := range MirrorQueue.Queue() {
  311. log.Trace("SyncMirrors [repo_id: %s]", repoID)
  312. MirrorQueue.Remove(repoID)
  313. m, err := GetMirrorByRepoID(com.StrTo(repoID).MustInt64())
  314. if err != nil {
  315. log.Error(2, "GetMirrorByRepoID [%d]: %v", m.RepoID, err)
  316. continue
  317. }
  318. results, ok := m.runSync()
  319. if !ok {
  320. continue
  321. }
  322. m.ScheduleNextSync()
  323. if err = UpdateMirror(m); err != nil {
  324. log.Error(2, "UpdateMirror [%d]: %v", m.RepoID, err)
  325. continue
  326. }
  327. // TODO:
  328. // - Create "Mirror Sync" webhook event
  329. // - Create mirror sync (create, push and delete) events and trigger the "mirror sync" webhooks
  330. var gitRepo *git.Repository
  331. if len(results) == 0 {
  332. log.Trace("SyncMirrors [repo_id: %d]: no commits fetched", m.RepoID)
  333. } else {
  334. gitRepo, err = git.OpenRepository(m.Repo.RepoPath())
  335. if err != nil {
  336. log.Error(2, "OpenRepository [%d]: %v", m.RepoID, err)
  337. continue
  338. }
  339. }
  340. for _, result := range results {
  341. // Discard GitHub pull requests, i.e. refs/pull/*
  342. if strings.HasPrefix(result.refName, "refs/pull/") {
  343. continue
  344. }
  345. // Delete reference
  346. if result.newCommitID == GIT_SHORT_EMPTY_SHA {
  347. if err = MirrorSyncDeleteAction(m.Repo, result.refName); err != nil {
  348. log.Error(2, "MirrorSyncDeleteAction [repo_id: %d]: %v", m.RepoID, err)
  349. }
  350. continue
  351. }
  352. // New reference
  353. isNewRef := false
  354. if result.oldCommitID == GIT_SHORT_EMPTY_SHA {
  355. if err = MirrorSyncCreateAction(m.Repo, result.refName); err != nil {
  356. log.Error(2, "MirrorSyncCreateAction [repo_id: %d]: %v", m.RepoID, err)
  357. continue
  358. }
  359. isNewRef = true
  360. }
  361. // Push commits
  362. var commits *list.List
  363. var oldCommitID string
  364. var newCommitID string
  365. if !isNewRef {
  366. oldCommitID, err = git.GetFullCommitID(gitRepo.Path, result.oldCommitID)
  367. if err != nil {
  368. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  369. continue
  370. }
  371. newCommitID, err = git.GetFullCommitID(gitRepo.Path, result.newCommitID)
  372. if err != nil {
  373. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  374. continue
  375. }
  376. commits, err = gitRepo.CommitsBetweenIDs(newCommitID, oldCommitID)
  377. if err != nil {
  378. log.Error(2, "CommitsBetweenIDs [repo_id: %d, new_commit_id: %s, old_commit_id: %s]: %v", m.RepoID, newCommitID, oldCommitID, err)
  379. continue
  380. }
  381. } else {
  382. refNewCommitID, err := gitRepo.GetBranchCommitID(result.refName)
  383. if err != nil {
  384. log.Error(2, "GetFullCommitID [%d]: %v", m.RepoID, err)
  385. continue
  386. }
  387. if newCommit, err := gitRepo.GetCommit(refNewCommitID); err != nil {
  388. log.Error(2, "GetCommit [repo_id: %d, commit_id: %s]: %v", m.RepoID, refNewCommitID, err)
  389. continue
  390. } else {
  391. // TODO: Get the commits for the new ref until the closest ancestor branch like Github does
  392. commits, err = newCommit.CommitsBeforeLimit(10)
  393. if err != nil {
  394. log.Error(2, "CommitsBeforeLimit [repo_id: %d, commit_id: %s]: %v", m.RepoID, refNewCommitID, err)
  395. }
  396. oldCommitID = git.EMPTY_SHA
  397. newCommitID = refNewCommitID
  398. }
  399. }
  400. if err = MirrorSyncPushAction(m.Repo, MirrorSyncPushActionOptions{
  401. RefName: result.refName,
  402. OldCommitID: oldCommitID,
  403. NewCommitID: newCommitID,
  404. Commits: ListToPushCommits(commits),
  405. }); err != nil {
  406. log.Error(2, "MirrorSyncPushAction [repo_id: %d]: %v", m.RepoID, err)
  407. continue
  408. }
  409. }
  410. if _, err = x.Exec("UPDATE mirror SET updated_unix = ? WHERE repo_id = ?", time.Now().Unix(), m.RepoID); err != nil {
  411. log.Error(2, "Update 'mirror.updated_unix' [%d]: %v", m.RepoID, err)
  412. continue
  413. }
  414. // Get latest commit date and compare to current repository updated time,
  415. // update if latest commit date is newer.
  416. commitDate, err := git.GetLatestCommitDate(m.Repo.RepoPath(), "")
  417. if err != nil {
  418. log.Error(2, "GetLatestCommitDate [%d]: %v", m.RepoID, err)
  419. continue
  420. } else if commitDate.Before(m.Repo.Updated) {
  421. continue
  422. }
  423. if _, err = x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", commitDate.Unix(), m.RepoID); err != nil {
  424. log.Error(2, "Update 'repository.updated_unix' [%d]: %v", m.RepoID, err)
  425. continue
  426. }
  427. }
  428. }
  429. func InitSyncMirrors() {
  430. go SyncMirrors()
  431. }