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.

455 lines
12 KiB

  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. "encoding/json"
  7. "fmt"
  8. "strings"
  9. "time"
  10. "github.com/Unknwon/com"
  11. "github.com/go-xorm/xorm"
  12. "gopkg.in/ini.v1"
  13. "github.com/gogits/gogs/modules/log"
  14. "github.com/gogits/gogs/modules/setting"
  15. )
  16. const _MIN_DB_VER = 0
  17. type Migration interface {
  18. Description() string
  19. Migrate(*xorm.Engine) error
  20. }
  21. type migration struct {
  22. description string
  23. migrate func(*xorm.Engine) error
  24. }
  25. func NewMigration(desc string, fn func(*xorm.Engine) error) Migration {
  26. return &migration{desc, fn}
  27. }
  28. func (m *migration) Description() string {
  29. return m.description
  30. }
  31. func (m *migration) Migrate(x *xorm.Engine) error {
  32. return m.migrate(x)
  33. }
  34. // The version table. Should have only one row with id==1
  35. type Version struct {
  36. Id int64
  37. Version int64
  38. }
  39. // This is a sequence of migrations. Add new migrations to the bottom of the list.
  40. // If you want to "retire" a migration, remove it from the top of the list and
  41. // update _MIN_VER_DB accordingly
  42. var migrations = []Migration{
  43. NewMigration("generate collaboration from access", accessToCollaboration), // V0 -> V1:v0.5.13
  44. NewMigration("make authorize 4 if team is owners", ownerTeamUpdate), // V1 -> V2:v0.5.13
  45. NewMigration("refactor access table to use id's", accessRefactor), // V2 -> V3:v0.5.13
  46. NewMigration("generate team-repo from team", teamToTeamRepo), // V3 -> V4:v0.5.13
  47. NewMigration("fix locale file load panic", fixLocaleFileLoadPanic), // V4 -> V5:v0.6.0
  48. NewMigration("trim action compare URL prefix", trimCommitActionAppUrlPrefix), // V5 -> V6:v0.6.3 // V4 -> V5:v0.6.0
  49. }
  50. // Migrate database to current version
  51. func Migrate(x *xorm.Engine) error {
  52. if err := x.Sync(new(Version)); err != nil {
  53. return fmt.Errorf("sync: %v", err)
  54. }
  55. currentVersion := &Version{Id: 1}
  56. has, err := x.Get(currentVersion)
  57. if err != nil {
  58. return fmt.Errorf("get: %v", err)
  59. } else if !has {
  60. // If the user table does not exist it is a fresh installation and we
  61. // can skip all migrations.
  62. needsMigration, err := x.IsTableExist("user")
  63. if err != nil {
  64. return err
  65. }
  66. if needsMigration {
  67. isEmpty, err := x.IsTableEmpty("user")
  68. if err != nil {
  69. return err
  70. }
  71. // If the user table is empty it is a fresh installation and we can
  72. // skip all migrations.
  73. needsMigration = !isEmpty
  74. }
  75. if !needsMigration {
  76. currentVersion.Version = int64(_MIN_DB_VER + len(migrations))
  77. }
  78. if _, err = x.InsertOne(currentVersion); err != nil {
  79. return fmt.Errorf("insert: %v", err)
  80. }
  81. }
  82. v := currentVersion.Version
  83. for i, m := range migrations[v-_MIN_DB_VER:] {
  84. log.Info("Migration: %s", m.Description())
  85. if err = m.Migrate(x); err != nil {
  86. return fmt.Errorf("do migrate: %v", err)
  87. }
  88. currentVersion.Version = v + int64(i) + 1
  89. if _, err = x.Id(1).Update(currentVersion); err != nil {
  90. return err
  91. }
  92. }
  93. return nil
  94. }
  95. func sessionRelease(sess *xorm.Session) {
  96. if !sess.IsCommitedOrRollbacked {
  97. sess.Rollback()
  98. }
  99. sess.Close()
  100. }
  101. func accessToCollaboration(x *xorm.Engine) (err error) {
  102. type Collaboration struct {
  103. ID int64 `xorm:"pk autoincr"`
  104. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  105. UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  106. Created time.Time
  107. }
  108. if err = x.Sync(new(Collaboration)); err != nil {
  109. return fmt.Errorf("sync: %v", err)
  110. }
  111. results, err := x.Query("SELECT u.id AS `uid`, a.repo_name AS `repo`, a.mode AS `mode`, a.created as `created` FROM `access` a JOIN `user` u ON a.user_name=u.lower_name")
  112. if err != nil {
  113. return err
  114. }
  115. sess := x.NewSession()
  116. defer sessionRelease(sess)
  117. if err = sess.Begin(); err != nil {
  118. return err
  119. }
  120. offset := strings.Split(time.Now().String(), " ")[2]
  121. for _, result := range results {
  122. mode := com.StrTo(result["mode"]).MustInt64()
  123. // Collaborators must have write access.
  124. if mode < 2 {
  125. continue
  126. }
  127. userID := com.StrTo(result["uid"]).MustInt64()
  128. repoRefName := string(result["repo"])
  129. var created time.Time
  130. switch {
  131. case setting.UseSQLite3:
  132. created, _ = time.Parse(time.RFC3339, string(result["created"]))
  133. case setting.UseMySQL:
  134. created, _ = time.Parse("2006-01-02 15:04:05-0700", string(result["created"])+offset)
  135. case setting.UsePostgreSQL:
  136. created, _ = time.Parse("2006-01-02T15:04:05Z-0700", string(result["created"])+offset)
  137. }
  138. // find owner of repository
  139. parts := strings.SplitN(repoRefName, "/", 2)
  140. ownerName := parts[0]
  141. repoName := parts[1]
  142. results, err := sess.Query("SELECT u.id as `uid`, ou.uid as `memberid` FROM `user` u LEFT JOIN org_user ou ON ou.org_id=u.id WHERE u.lower_name=?", ownerName)
  143. if err != nil {
  144. return err
  145. }
  146. if len(results) < 1 {
  147. continue
  148. }
  149. ownerID := com.StrTo(results[0]["uid"]).MustInt64()
  150. if ownerID == userID {
  151. continue
  152. }
  153. // test if user is member of owning organization
  154. isMember := false
  155. for _, member := range results {
  156. memberID := com.StrTo(member["memberid"]).MustInt64()
  157. // We can skip all cases that a user is member of the owning organization
  158. if memberID == userID {
  159. isMember = true
  160. }
  161. }
  162. if isMember {
  163. continue
  164. }
  165. results, err = sess.Query("SELECT id FROM `repository` WHERE owner_id=? AND lower_name=?", ownerID, repoName)
  166. if err != nil {
  167. return err
  168. } else if len(results) < 1 {
  169. continue
  170. }
  171. collaboration := &Collaboration{
  172. UserID: userID,
  173. RepoID: com.StrTo(results[0]["id"]).MustInt64(),
  174. }
  175. has, err := sess.Get(collaboration)
  176. if err != nil {
  177. return err
  178. } else if has {
  179. continue
  180. }
  181. collaboration.Created = created
  182. if _, err = sess.InsertOne(collaboration); err != nil {
  183. return err
  184. }
  185. }
  186. return sess.Commit()
  187. }
  188. func ownerTeamUpdate(x *xorm.Engine) (err error) {
  189. if _, err := x.Exec("UPDATE `team` SET authorize=4 WHERE lower_name=?", "owners"); err != nil {
  190. return fmt.Errorf("update owner team table: %v", err)
  191. }
  192. return nil
  193. }
  194. func accessRefactor(x *xorm.Engine) (err error) {
  195. type (
  196. AccessMode int
  197. Access struct {
  198. ID int64 `xorm:"pk autoincr"`
  199. UserID int64 `xorm:"UNIQUE(s)"`
  200. RepoID int64 `xorm:"UNIQUE(s)"`
  201. Mode AccessMode
  202. }
  203. UserRepo struct {
  204. UserID int64
  205. RepoID int64
  206. }
  207. )
  208. // We consiously don't start a session yet as we make only reads for now, no writes
  209. accessMap := make(map[UserRepo]AccessMode, 50)
  210. results, err := x.Query("SELECT r.id AS `repo_id`, r.is_private AS `is_private`, r.owner_id AS `owner_id`, u.type AS `owner_type` FROM `repository` r LEFT JOIN `user` u ON r.owner_id=u.id")
  211. if err != nil {
  212. return fmt.Errorf("select repositories: %v", err)
  213. }
  214. for _, repo := range results {
  215. repoID := com.StrTo(repo["repo_id"]).MustInt64()
  216. isPrivate := com.StrTo(repo["is_private"]).MustInt() > 0
  217. ownerID := com.StrTo(repo["owner_id"]).MustInt64()
  218. ownerIsOrganization := com.StrTo(repo["owner_type"]).MustInt() > 0
  219. results, err := x.Query("SELECT `user_id` FROM `collaboration` WHERE repo_id=?", repoID)
  220. if err != nil {
  221. return fmt.Errorf("select collaborators: %v", err)
  222. }
  223. for _, user := range results {
  224. userID := com.StrTo(user["user_id"]).MustInt64()
  225. accessMap[UserRepo{userID, repoID}] = 2 // WRITE ACCESS
  226. }
  227. if !ownerIsOrganization {
  228. continue
  229. }
  230. // The minimum level to add a new access record,
  231. // because public repository has implicit open access.
  232. minAccessLevel := AccessMode(0)
  233. if !isPrivate {
  234. minAccessLevel = 1
  235. }
  236. repoString := "$" + string(repo["repo_id"]) + "|"
  237. results, err = x.Query("SELECT `id`,`authorize`,`repo_ids` FROM `team` WHERE org_id=? AND authorize>? ORDER BY `authorize` ASC", ownerID, int(minAccessLevel))
  238. if err != nil {
  239. return fmt.Errorf("select teams from org: %v", err)
  240. }
  241. for _, team := range results {
  242. if !strings.Contains(string(team["repo_ids"]), repoString) {
  243. continue
  244. }
  245. teamID := com.StrTo(team["id"]).MustInt64()
  246. mode := AccessMode(com.StrTo(team["authorize"]).MustInt())
  247. results, err := x.Query("SELECT `uid` FROM `team_user` WHERE team_id=?", teamID)
  248. if err != nil {
  249. return fmt.Errorf("select users from team: %v", err)
  250. }
  251. for _, user := range results {
  252. userID := com.StrTo(user["uid"]).MustInt64()
  253. accessMap[UserRepo{userID, repoID}] = mode
  254. }
  255. }
  256. }
  257. // Drop table can't be in a session (at least not in sqlite)
  258. if _, err = x.Exec("DROP TABLE `access`"); err != nil {
  259. return fmt.Errorf("drop access table: %v", err)
  260. }
  261. // Now we start writing so we make a session
  262. sess := x.NewSession()
  263. defer sessionRelease(sess)
  264. if err = sess.Begin(); err != nil {
  265. return err
  266. }
  267. if err = sess.Sync2(new(Access)); err != nil {
  268. return fmt.Errorf("sync: %v", err)
  269. }
  270. accesses := make([]*Access, 0, len(accessMap))
  271. for ur, mode := range accessMap {
  272. accesses = append(accesses, &Access{UserID: ur.UserID, RepoID: ur.RepoID, Mode: mode})
  273. }
  274. if _, err = sess.Insert(accesses); err != nil {
  275. return fmt.Errorf("insert accesses: %v", err)
  276. }
  277. return sess.Commit()
  278. }
  279. func teamToTeamRepo(x *xorm.Engine) error {
  280. type TeamRepo struct {
  281. ID int64 `xorm:"pk autoincr"`
  282. OrgID int64 `xorm:"INDEX"`
  283. TeamID int64 `xorm:"UNIQUE(s)"`
  284. RepoID int64 `xorm:"UNIQUE(s)"`
  285. }
  286. teamRepos := make([]*TeamRepo, 0, 50)
  287. results, err := x.Query("SELECT `id`,`org_id`,`repo_ids` FROM `team`")
  288. if err != nil {
  289. return fmt.Errorf("select teams: %v", err)
  290. }
  291. for _, team := range results {
  292. orgID := com.StrTo(team["org_id"]).MustInt64()
  293. teamID := com.StrTo(team["id"]).MustInt64()
  294. // #1032: legacy code can have duplicated IDs for same repository.
  295. mark := make(map[int64]bool)
  296. for _, idStr := range strings.Split(string(team["repo_ids"]), "|") {
  297. repoID := com.StrTo(strings.TrimPrefix(idStr, "$")).MustInt64()
  298. if repoID == 0 || mark[repoID] {
  299. continue
  300. }
  301. mark[repoID] = true
  302. teamRepos = append(teamRepos, &TeamRepo{
  303. OrgID: orgID,
  304. TeamID: teamID,
  305. RepoID: repoID,
  306. })
  307. }
  308. }
  309. sess := x.NewSession()
  310. defer sessionRelease(sess)
  311. if err = sess.Begin(); err != nil {
  312. return err
  313. }
  314. if err = sess.Sync2(new(TeamRepo)); err != nil {
  315. return fmt.Errorf("sync: %v", err)
  316. } else if _, err = sess.Insert(teamRepos); err != nil {
  317. return fmt.Errorf("insert team-repos: %v", err)
  318. }
  319. return sess.Commit()
  320. }
  321. func fixLocaleFileLoadPanic(_ *xorm.Engine) error {
  322. cfg, err := ini.Load(setting.CustomConf)
  323. if err != nil {
  324. return fmt.Errorf("load custom config: %v", err)
  325. }
  326. cfg.DeleteSection("i18n")
  327. if err = cfg.SaveTo(setting.CustomConf); err != nil {
  328. return fmt.Errorf("save custom config: %v", err)
  329. }
  330. setting.Langs = strings.Split(strings.Replace(strings.Join(setting.Langs, ","), "fr-CA", "fr-FR", 1), ",")
  331. return nil
  332. }
  333. func trimCommitActionAppUrlPrefix(x *xorm.Engine) error {
  334. type PushCommit struct {
  335. Sha1 string
  336. Message string
  337. AuthorEmail string
  338. AuthorName string
  339. }
  340. type PushCommits struct {
  341. Len int
  342. Commits []*PushCommit
  343. CompareUrl string
  344. }
  345. type Action struct {
  346. ID int64 `xorm:"pk autoincr"`
  347. Content string `xorm:"TEXT"`
  348. }
  349. results, err := x.Query("SELECT `id`,`content` FROM `action` WHERE `op_type`=?", 5)
  350. if err != nil {
  351. return fmt.Errorf("select commit actions: %v", err)
  352. }
  353. sess := x.NewSession()
  354. defer sessionRelease(sess)
  355. if err = sess.Begin(); err != nil {
  356. return err
  357. }
  358. var pushCommits *PushCommits
  359. for _, action := range results {
  360. actID := com.StrTo(string(action["id"])).MustInt64()
  361. if actID == 0 {
  362. continue
  363. }
  364. pushCommits = new(PushCommits)
  365. if err = json.Unmarshal(action["content"], pushCommits); err != nil {
  366. return fmt.Errorf("unmarshal action content[%s]: %v", actID, err)
  367. }
  368. infos := strings.Split(pushCommits.CompareUrl, "/")
  369. if len(infos) <= 4 {
  370. continue
  371. }
  372. pushCommits.CompareUrl = strings.Join(infos[len(infos)-4:], "/")
  373. p, err := json.Marshal(pushCommits)
  374. if err != nil {
  375. return fmt.Errorf("marshal action content[%s]: %v", actID, err)
  376. }
  377. if _, err = sess.Id(actID).Update(&Action{
  378. Content: string(p),
  379. }); err != nil {
  380. return fmt.Errorf("update action[%s]: %v", actID, err)
  381. }
  382. }
  383. return sess.Commit()
  384. }