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.

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