mirror.go 13 KB

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