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.

681 lines
18 KiB

9 years ago
9 years ago
9 years ago
9 years ago
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package migrations
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. "github.com/go-xorm/xorm"
  17. gouuid "github.com/satori/go.uuid"
  18. "gopkg.in/ini.v1"
  19. "github.com/go-gitea/gitea/modules/base"
  20. "github.com/go-gitea/gitea/modules/log"
  21. "github.com/go-gitea/gitea/modules/setting"
  22. )
  23. const _MIN_DB_VER = 4
  24. type Migration interface {
  25. Description() string
  26. Migrate(*xorm.Engine) error
  27. }
  28. type migration struct {
  29. description string
  30. migrate func(*xorm.Engine) error
  31. }
  32. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  33. return &migration{desc, fn}
  34. }
  35. func (m *migration) Description() string {
  36. return m.description
  37. }
  38. func (m *migration) Migrate(x *xorm.Engine) error {
  39. return m.migrate(x)
  40. }
  41. // The version table. Should have only one row with id==1
  42. type Version struct {
  43. ID int64 `xorm:"pk autoincr"`
  44. Version int64
  45. }
  46. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  47. // If you want to "retire" a migration, remove it from the top of the list and
  48. // update _MIN_VER_DB accordingly
  49. var migrations = []Migration{
  50. // v0 -> v4: before 0.6.0 -> 0.7.33
  51. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  52. NewMigration("trim action compare URL prefix", trimCommitActionAppUrlPrefix), // V5 -> V6:v0.6.3
  53. NewMigration("generate issue-label from issue", issueToIssueLabel), // V6 -> V7:v0.6.4
  54. NewMigration("refactor attachment table", attachmentRefactor), // V7 -> V8:v0.6.4
  55. NewMigration("rename pull request fields", renamePullRequestFields), // V8 -> V9:v0.6.16
  56. NewMigration("clean up migrate repo info", cleanUpMigrateRepoInfo), // V9 -> V10:v0.6.20
  57. NewMigration("generate rands and salt for organizations", generateOrgRandsAndSalt), // V10 -> V11:v0.8.5
  58. NewMigration("convert date to unix timestamp", convertDateToUnix), // V11 -> V12:v0.9.2
  59. NewMigration("convert LDAP UseSSL option to SecurityProtocol", ldapUseSSLToSecurityProtocol), // V12 -> V13:v0.9.37
  60. // v13 -> v14:v0.9.87
  61. NewMigration("set comment updated with created", setCommentUpdatedWithCreated),
  62. }
  63. // Migrate database to current version
  64. func Migrate(x *xorm.Engine) error {
  65. if err := x.Sync(new(Version)); err != nil {
  66. return fmt.Errorf("sync: %v", err)
  67. }
  68. currentVersion := &Version{ID: 1}
  69. has, err := x.Get(currentVersion)
  70. if err != nil {
  71. return fmt.Errorf("get: %v", err)
  72. } else if !has {
  73. // If the version record does not exist we think
  74. // it is a fresh installation and we can skip all migrations.
  75. currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
  76. if _, err = x.InsertOne(currentVersion); err != nil {
  77. return fmt.Errorf("insert: %v", err)
  78. }
  79. }
  80. v := currentVersion.Version
  81. if _MIN_DB_VER > v {
  82. log.Fatal(4, `Gogs no longer supports auto-migration from your previously installed version.
  83. Please try to upgrade to a lower version (>= v0.6.0) first, then upgrade to current version.`)
  84. return nil
  85. }
  86. if int(v-_MIN_DB_VER) > len(migrations) {
  87. // User downgraded Gogs.
  88. currentVersion.Version = int64(len(migrations) + _MIN_DB_VER)
  89. _, err = x.Id(1).Update(currentVersion)
  90. return err
  91. }
  92. for i, m := range migrations[v-_MIN_DB_VER:] {
  93. log.Info("Migration: %s", m.Description())
  94. if err = m.Migrate(x); err != nil {
  95. return fmt.Errorf("do migrate: %v", err)
  96. }
  97. currentVersion.Version = v + int64(i) + 1
  98. if _, err = x.Id(1).Update(currentVersion); err != nil {
  99. return err
  100. }
  101. }
  102. return nil
  103. }
  104. func sessionRelease(sess *xorm.Session) {
  105. if !sess.IsCommitedOrRollbacked {
  106. sess.Rollback()
  107. }
  108. sess.Close()
  109. }
  110. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  111. cfg, err := ini.Load(setting.CustomConf)
  112. if err != nil {
  113. return fmt.Errorf("load custom config: %v", err)
  114. }
  115. cfg.DeleteSection("i18n")
  116. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  117. return fmt.Errorf("save custom config: %v", err)
  118. }
  119. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  120. return nil
  121. }
  122. func trimCommitActionAppUrlPrefix(x *xorm.Engine) error {
  123. type PushCommit struct {
  124. Sha1 string
  125. Message string
  126. AuthorEmail string
  127. AuthorName string
  128. }
  129. type PushCommits struct {
  130. Len int
  131. Commits []*PushCommit
  132. CompareUrl string
  133. }
  134. type Action struct {
  135. ID int64 `xorm:"pk autoincr"`
  136. Content string `xorm:"TEXT"`
  137. }
  138. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  139. if err != nil {
  140. return fmt.Errorf("select commit actions: %v", err)
  141. }
  142. sess := x.NewSession()
  143. defer sessionRelease(sess)
  144. if err = sess.Begin(); err != nil {
  145. return err
  146. }
  147. var pushCommits *PushCommits
  148. for _, action := range results {
  149. actID := com.StrTo(string(action["id"])).MustInt64()
  150. if actID == 0 {
  151. continue
  152. }
  153. pushCommits = new(PushCommits)
  154. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  155. return fmt.Errorf("unmarshal action content[%d]: %v", actID, err)
  156. }
  157. infos := strings.Split(pushCommits.CompareUrl, "/")
  158. if len(infos) <= 4 {
  159. continue
  160. }
  161. pushCommits.CompareUrl = strings.Join(infos[len(infos)-4:], "/")
  162. p, err := json.Marshal(pushCommits)
  163. if err != nil {
  164. return fmt.Errorf("marshal action content[%d]: %v", actID, err)
  165. }
  166. if _, err = sess.Id(actID).Update(&Action{
  167. Content: string(p),
  168. }); err != nil {
  169. return fmt.Errorf("update action[%d]: %v", actID, err)
  170. }
  171. }
  172. return sess.Commit()
  173. }
  174. func issueToIssueLabel(x *xorm.Engine) error {
  175. type IssueLabel struct {
  176. ID int64 `xorm:"pk autoincr"`
  177. IssueID int64 `xorm:"UNIQUE(s)"`
  178. LabelID int64 `xorm:"UNIQUE(s)"`
  179. }
  180. issueLabels := make([]*IssueLabel, 0, 50)
  181. results, err := x.Query("SELECT `id`,`label_ids` FROM `issue`")
  182. if err != nil {
  183. if strings.Contains(err.Error(), "no such column") ||
  184. strings.Contains(err.Error(), "Unknown column") {
  185. return nil
  186. }
  187. return fmt.Errorf("select issues: %v", err)
  188. }
  189. for _, issue := range results {
  190. issueID := com.StrTo(issue["id"]).MustInt64()
  191. // Just in case legacy code can have duplicated IDs for same label.
  192. mark := make(map[int64]bool)
  193. for _, idStr := range strings.Split(string(issue["label_ids"]), "|") {
  194. labelID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  195. if labelID == 0 || mark[labelID] {
  196. continue
  197. }
  198. mark[labelID] = true
  199. issueLabels = append(issueLabels, &IssueLabel{
  200. IssueID: issueID,
  201. LabelID: labelID,
  202. })
  203. }
  204. }
  205. sess := x.NewSession()
  206. defer sessionRelease(sess)
  207. if err = sess.Begin(); err != nil {
  208. return err
  209. }
  210. if err = sess.Sync2(new(IssueLabel)); err != nil {
  211. return fmt.Errorf("Sync2: %v", err)
  212. } else if _, err = sess.Insert(issueLabels); err != nil {
  213. return fmt.Errorf("insert issue-labels: %v", err)
  214. }
  215. return sess.Commit()
  216. }
  217. func attachmentRefactor(x *xorm.Engine) error {
  218. type Attachment struct {
  219. ID int64 `xorm:"pk autoincr"`
  220. UUID string `xorm:"uuid INDEX"`
  221. // For rename purpose.
  222. Path string `xorm:"-"`
  223. NewPath string `xorm:"-"`
  224. }
  225. results, err := x.Query("SELECT * FROM `attachment`")
  226. if err != nil {
  227. return fmt.Errorf("select attachments: %v", err)
  228. }
  229. attachments := make([]*Attachment, 0, len(results))
  230. for _, attach := range results {
  231. if !com.IsExist(string(attach["path"])) {
  232. // If the attachment is already missing, there is no point to update it.
  233. continue
  234. }
  235. attachments = append(attachments, &Attachment{
  236. ID: com.StrTo(attach["id"]).MustInt64(),
  237. UUID: gouuid.NewV4().String(),
  238. Path: string(attach["path"]),
  239. })
  240. }
  241. sess := x.NewSession()
  242. defer sessionRelease(sess)
  243. if err = sess.Begin(); err != nil {
  244. return err
  245. }
  246. if err = sess.Sync2(new(Attachment)); err != nil {
  247. return fmt.Errorf("Sync2: %v", err)
  248. }
  249. // Note: Roll back for rename can be a dead loop,
  250. // so produces a backup file.
  251. var buf bytes.Buffer
  252. buf.WriteString("# old path -> new path\n")
  253. // Update database first because this is where error happens the most often.
  254. for _, attach := range attachments {
  255. if _, err = sess.Id(attach.ID).Update(attach); err != nil {
  256. return err
  257. }
  258. attach.NewPath = path.Join(setting.AttachmentPath, attach.UUID[0:1], attach.UUID[1:2], attach.UUID)
  259. buf.WriteString(attach.Path)
  260. buf.WriteString("\t")
  261. buf.WriteString(attach.NewPath)
  262. buf.WriteString("\n")
  263. }
  264. // Then rename attachments.
  265. isSucceed := true
  266. defer func() {
  267. if isSucceed {
  268. return
  269. }
  270. dumpPath := path.Join(setting.LogRootPath, "attachment_path.dump")
  271. ioutil.WriteFile(dumpPath, buf.Bytes(), 0666)
  272. fmt.Println("Fail to rename some attachments, old and new paths are saved into:", dumpPath)
  273. }()
  274. for _, attach := range attachments {
  275. if err = os.MkdirAll(path.Dir(attach.NewPath), os.ModePerm); err != nil {
  276. isSucceed = false
  277. return err
  278. }
  279. if err = os.Rename(attach.Path, attach.NewPath); err != nil {
  280. isSucceed = false
  281. return err
  282. }
  283. }
  284. return sess.Commit()
  285. }
  286. func renamePullRequestFields(x *xorm.Engine) (err error) {
  287. type PullRequest struct {
  288. ID int64 `xorm:"pk autoincr"`
  289. PullID int64 `xorm:"INDEX"`
  290. PullIndex int64
  291. HeadBarcnh string
  292. IssueID int64 `xorm:"INDEX"`
  293. Index int64
  294. HeadBranch string
  295. }
  296. if err = x.Sync(new(PullRequest)); err != nil {
  297. return fmt.Errorf("sync: %v", err)
  298. }
  299. results, err := x.Query("SELECT `id`,`pull_id`,`pull_index`,`head_barcnh` FROM `pull_request`")
  300. if err != nil {
  301. if strings.Contains(err.Error(), "no such column") {
  302. return nil
  303. }
  304. return fmt.Errorf("select pull requests: %v", err)
  305. }
  306. sess := x.NewSession()
  307. defer sessionRelease(sess)
  308. if err = sess.Begin(); err != nil {
  309. return err
  310. }
  311. var pull *PullRequest
  312. for _, pr := range results {
  313. pull = &PullRequest{
  314. ID: com.StrTo(pr["id"]).MustInt64(),
  315. IssueID: com.StrTo(pr["pull_id"]).MustInt64(),
  316. Index: com.StrTo(pr["pull_index"]).MustInt64(),
  317. HeadBranch: string(pr["head_barcnh"]),
  318. }
  319. if pull.Index == 0 {
  320. continue
  321. }
  322. if _, err = sess.Id(pull.ID).Update(pull); err != nil {
  323. return err
  324. }
  325. }
  326. return sess.Commit()
  327. }
  328. func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) {
  329. type (
  330. User struct {
  331. ID int64 `xorm:"pk autoincr"`
  332. LowerName string
  333. }
  334. Repository struct {
  335. ID int64 `xorm:"pk autoincr"`
  336. OwnerID int64
  337. LowerName string
  338. }
  339. )
  340. repos := make([]*Repository, 0, 25)
  341. if err = x.Where("is_mirror=?", false).Find(&repos); err != nil {
  342. return fmt.Errorf("select all non-mirror repositories: %v", err)
  343. }
  344. var user *User
  345. for _, repo := range repos {
  346. user = &User{ID: repo.OwnerID}
  347. has, err := x.Get(user)
  348. if err != nil {
  349. return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err)
  350. } else if !has {
  351. continue
  352. }
  353. configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config")
  354. // In case repository file is somehow missing.
  355. if !com.IsFile(configPath) {
  356. continue
  357. }
  358. cfg, err := ini.Load(configPath)
  359. if err != nil {
  360. return fmt.Errorf("open config file: %v", err)
  361. }
  362. cfg.DeleteSection("remote \"origin\"")
  363. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  364. return fmt.Errorf("save config file: %v", err)
  365. }
  366. }
  367. return nil
  368. }
  369. func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
  370. type User struct {
  371. ID int64 `xorm:"pk autoincr"`
  372. Rands string `xorm:"VARCHAR(10)"`
  373. Salt string `xorm:"VARCHAR(10)"`
  374. }
  375. orgs := make([]*User, 0, 10)
  376. if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
  377. return fmt.Errorf("select all organizations: %v", err)
  378. }
  379. sess := x.NewSession()
  380. defer sessionRelease(sess)
  381. if err = sess.Begin(); err != nil {
  382. return err
  383. }
  384. for _, org := range orgs {
  385. org.Rands = base.GetRandomString(10)
  386. org.Salt = base.GetRandomString(10)
  387. if _, err = sess.Id(org.ID).Update(org); err != nil {
  388. return err
  389. }
  390. }
  391. return sess.Commit()
  392. }
  393. type TAction struct {
  394. ID int64 `xorm:"pk autoincr"`
  395. CreatedUnix int64
  396. }
  397. func (t *TAction) TableName() string { return "action" }
  398. type TNotice struct {
  399. ID int64 `xorm:"pk autoincr"`
  400. CreatedUnix int64
  401. }
  402. func (t *TNotice) TableName() string { return "notice" }
  403. type TComment struct {
  404. ID int64 `xorm:"pk autoincr"`
  405. CreatedUnix int64
  406. }
  407. func (t *TComment) TableName() string { return "comment" }
  408. type TIssue struct {
  409. ID int64 `xorm:"pk autoincr"`
  410. DeadlineUnix int64
  411. CreatedUnix int64
  412. UpdatedUnix int64
  413. }
  414. func (t *TIssue) TableName() string { return "issue" }
  415. type TMilestone struct {
  416. ID int64 `xorm:"pk autoincr"`
  417. DeadlineUnix int64
  418. ClosedDateUnix int64
  419. }
  420. func (t *TMilestone) TableName() string { return "milestone" }
  421. type TAttachment struct {
  422. ID int64 `xorm:"pk autoincr"`
  423. CreatedUnix int64
  424. }
  425. func (t *TAttachment) TableName() string { return "attachment" }
  426. type TLoginSource struct {
  427. ID int64 `xorm:"pk autoincr"`
  428. CreatedUnix int64
  429. UpdatedUnix int64
  430. }
  431. func (t *TLoginSource) TableName() string { return "login_source" }
  432. type TPull struct {
  433. ID int64 `xorm:"pk autoincr"`
  434. MergedUnix int64
  435. }
  436. func (t *TPull) TableName() string { return "pull_request" }
  437. type TRelease struct {
  438. ID int64 `xorm:"pk autoincr"`
  439. CreatedUnix int64
  440. }
  441. func (t *TRelease) TableName() string { return "release" }
  442. type TRepo struct {
  443. ID int64 `xorm:"pk autoincr"`
  444. CreatedUnix int64
  445. UpdatedUnix int64
  446. }
  447. func (t *TRepo) TableName() string { return "repository" }
  448. type TMirror struct {
  449. ID int64 `xorm:"pk autoincr"`
  450. UpdatedUnix int64
  451. NextUpdateUnix int64
  452. }
  453. func (t *TMirror) TableName() string { return "mirror" }
  454. type TPublicKey struct {
  455. ID int64 `xorm:"pk autoincr"`
  456. CreatedUnix int64
  457. UpdatedUnix int64
  458. }
  459. func (t *TPublicKey) TableName() string { return "public_key" }
  460. type TDeployKey struct {
  461. ID int64 `xorm:"pk autoincr"`
  462. CreatedUnix int64
  463. UpdatedUnix int64
  464. }
  465. func (t *TDeployKey) TableName() string { return "deploy_key" }
  466. type TAccessToken struct {
  467. ID int64 `xorm:"pk autoincr"`
  468. CreatedUnix int64
  469. UpdatedUnix int64
  470. }
  471. func (t *TAccessToken) TableName() string { return "access_token" }
  472. type TUser struct {
  473. ID int64 `xorm:"pk autoincr"`
  474. CreatedUnix int64
  475. UpdatedUnix int64
  476. }
  477. func (t *TUser) TableName() string { return "user" }
  478. type TWebhook struct {
  479. ID int64 `xorm:"pk autoincr"`
  480. CreatedUnix int64
  481. UpdatedUnix int64
  482. }
  483. func (t *TWebhook) TableName() string { return "webhook" }
  484. func convertDateToUnix(x *xorm.Engine) (err error) {
  485. log.Info("This migration could take up to minutes, please be patient.")
  486. type Bean struct {
  487. ID int64 `xorm:"pk autoincr"`
  488. Created time.Time
  489. Updated time.Time
  490. Merged time.Time
  491. Deadline time.Time
  492. ClosedDate time.Time
  493. NextUpdate time.Time
  494. }
  495. var tables = []struct {
  496. name string
  497. cols []string
  498. bean interface{}
  499. }{
  500. {"action", []string{"created"}, new(TAction)},
  501. {"notice", []string{"created"}, new(TNotice)},
  502. {"comment", []string{"created"}, new(TComment)},
  503. {"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
  504. {"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
  505. {"attachment", []string{"created"}, new(TAttachment)},
  506. {"login_source", []string{"created", "updated"}, new(TLoginSource)},
  507. {"pull_request", []string{"merged"}, new(TPull)},
  508. {"release", []string{"created"}, new(TRelease)},
  509. {"repository", []string{"created", "updated"}, new(TRepo)},
  510. {"mirror", []string{"updated", "next_update"}, new(TMirror)},
  511. {"public_key", []string{"created", "updated"}, new(TPublicKey)},
  512. {"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
  513. {"access_token", []string{"created", "updated"}, new(TAccessToken)},
  514. {"user", []string{"created", "updated"}, new(TUser)},
  515. {"webhook", []string{"created", "updated"}, new(TWebhook)},
  516. }
  517. for _, table := range tables {
  518. log.Info("Converting table: %s", table.name)
  519. if err = x.Sync2(table.bean); err != nil {
  520. return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
  521. }
  522. offset := 0
  523. for {
  524. beans := make([]*Bean, 0, 100)
  525. if err = x.Sql(fmt.Sprintf("SELECT * FROM `%s` ORDER BY id ASC LIMIT 100 OFFSET %d",
  526. table.name, offset)).Find(&beans); err != nil {
  527. return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
  528. }
  529. log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
  530. if len(beans) == 0 {
  531. break
  532. }
  533. offset += 100
  534. baseSQL := "UPDATE `" + table.name + "` SET "
  535. for _, bean := range beans {
  536. valSQLs := make([]string, 0, len(table.cols))
  537. for _, col := range table.cols {
  538. fieldSQL := ""
  539. fieldSQL += col + "_unix = "
  540. switch col {
  541. case "deadline":
  542. if bean.Deadline.IsZero() {
  543. continue
  544. }
  545. fieldSQL += com.ToStr(bean.Deadline.Unix())
  546. case "created":
  547. fieldSQL += com.ToStr(bean.Created.Unix())
  548. case "updated":
  549. fieldSQL += com.ToStr(bean.Updated.Unix())
  550. case "closed_date":
  551. fieldSQL += com.ToStr(bean.ClosedDate.Unix())
  552. case "merged":
  553. fieldSQL += com.ToStr(bean.Merged.Unix())
  554. case "next_update":
  555. fieldSQL += com.ToStr(bean.NextUpdate.Unix())
  556. }
  557. valSQLs = append(valSQLs, fieldSQL)
  558. }
  559. if len(valSQLs) == 0 {
  560. continue
  561. }
  562. if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
  563. return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
  564. }
  565. }
  566. }
  567. }
  568. return nil
  569. }