models.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. // Copyright 2014 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 models
  5. import (
  6. "bufio"
  7. "database/sql"
  8. "errors"
  9. "fmt"
  10. "net/url"
  11. "os"
  12. "path"
  13. "strings"
  14. "github.com/Unknwon/com"
  15. _ "github.com/denisenkom/go-mssqldb"
  16. _ "github.com/go-sql-driver/mysql"
  17. "github.com/go-xorm/core"
  18. "github.com/go-xorm/xorm"
  19. "github.com/json-iterator/go"
  20. _ "github.com/lib/pq"
  21. log "gopkg.in/clog.v1"
  22. "github.com/gogs/gogs/models/migrations"
  23. "github.com/gogs/gogs/pkg/setting"
  24. )
  25. // Engine represents a XORM engine or session.
  26. type Engine interface {
  27. Delete(interface{}) (int64, error)
  28. Exec(string, ...interface{}) (sql.Result, error)
  29. Find(interface{}, ...interface{}) error
  30. Get(interface{}) (bool, error)
  31. ID(interface{}) *xorm.Session
  32. In(string, ...interface{}) *xorm.Session
  33. Insert(...interface{}) (int64, error)
  34. InsertOne(interface{}) (int64, error)
  35. Iterate(interface{}, xorm.IterFunc) error
  36. Sql(string, ...interface{}) *xorm.Session
  37. Table(interface{}) *xorm.Session
  38. Where(interface{}, ...interface{}) *xorm.Session
  39. }
  40. var (
  41. x *xorm.Engine
  42. tables []interface{}
  43. HasEngine bool
  44. DbCfg struct {
  45. Type, Host, Name, User, Passwd, Path, SSLMode string
  46. }
  47. EnableSQLite3 bool
  48. )
  49. func init() {
  50. tables = append(tables,
  51. new(User), new(PublicKey), new(AccessToken), new(TwoFactor), new(TwoFactorRecoveryCode),
  52. new(Repository), new(DeployKey), new(Collaboration), new(Access), new(Upload),
  53. new(Watch), new(Star), new(Follow), new(Action),
  54. new(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),
  55. new(Label), new(IssueLabel), new(Milestone),
  56. new(Mirror), new(Release), new(LoginSource), new(Webhook), new(HookTask),
  57. new(ProtectBranch), new(ProtectBranchWhitelist),
  58. new(Team), new(OrgUser), new(TeamUser), new(TeamRepo),
  59. new(Notice), new(EmailAddress))
  60. gonicNames := []string{"SSL"}
  61. for _, name := range gonicNames {
  62. core.LintGonicMapper[name] = true
  63. }
  64. }
  65. func LoadConfigs() {
  66. sec := setting.Cfg.Section("database")
  67. DbCfg.Type = sec.Key("DB_TYPE").String()
  68. switch DbCfg.Type {
  69. case "sqlite3":
  70. setting.UseSQLite3 = true
  71. case "mysql":
  72. setting.UseMySQL = true
  73. case "postgres":
  74. setting.UsePostgreSQL = true
  75. case "mssql":
  76. setting.UseMSSQL = true
  77. }
  78. DbCfg.Host = sec.Key("HOST").String()
  79. DbCfg.Name = sec.Key("NAME").String()
  80. DbCfg.User = sec.Key("USER").String()
  81. if len(DbCfg.Passwd) == 0 {
  82. DbCfg.Passwd = sec.Key("PASSWD").String()
  83. }
  84. DbCfg.SSLMode = sec.Key("SSL_MODE").String()
  85. DbCfg.Path = sec.Key("PATH").MustString("data/gogs.db")
  86. }
  87. // parsePostgreSQLHostPort parses given input in various forms defined in
  88. // https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING
  89. // and returns proper host and port number.
  90. func parsePostgreSQLHostPort(info string) (string, string) {
  91. host, port := "127.0.0.1", "5432"
  92. if strings.Contains(info, ":") && !strings.HasSuffix(info, "]") {
  93. idx := strings.LastIndex(info, ":")
  94. host = info[:idx]
  95. port = info[idx+1:]
  96. } else if len(info) > 0 {
  97. host = info
  98. }
  99. return host, port
  100. }
  101. func parseMSSQLHostPort(info string) (string, string) {
  102. host, port := "127.0.0.1", "1433"
  103. if strings.Contains(info, ":") {
  104. host = strings.Split(info, ":")[0]
  105. port = strings.Split(info, ":")[1]
  106. } else if strings.Contains(info, ",") {
  107. host = strings.Split(info, ",")[0]
  108. port = strings.TrimSpace(strings.Split(info, ",")[1])
  109. } else if len(info) > 0 {
  110. host = info
  111. }
  112. return host, port
  113. }
  114. func getEngine() (*xorm.Engine, error) {
  115. connStr := ""
  116. var Param string = "?"
  117. if strings.Contains(DbCfg.Name, Param) {
  118. Param = "&"
  119. }
  120. switch DbCfg.Type {
  121. case "mysql":
  122. if DbCfg.Host[0] == '/' { // looks like a unix socket
  123. connStr = fmt.Sprintf("%s:%s@unix(%s)/%s%scharset=utf8mb4&parseTime=true",
  124. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  125. } else {
  126. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8mb4&parseTime=true",
  127. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  128. }
  129. var engineParams = map[string]string{"rowFormat": "DYNAMIC"}
  130. return xorm.NewEngineWithParams(DbCfg.Type, connStr, engineParams)
  131. case "postgres":
  132. host, port := parsePostgreSQLHostPort(DbCfg.Host)
  133. if host[0] == '/' { // looks like a unix socket
  134. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  135. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  136. } else {
  137. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  138. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  139. }
  140. case "mssql":
  141. host, port := parseMSSQLHostPort(DbCfg.Host)
  142. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  143. case "sqlite3":
  144. if !EnableSQLite3 {
  145. return nil, errors.New("This binary version does not build support for SQLite3.")
  146. }
  147. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  148. return nil, fmt.Errorf("Fail to create directories: %v", err)
  149. }
  150. connStr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  151. default:
  152. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  153. }
  154. return xorm.NewEngine(DbCfg.Type, connStr)
  155. }
  156. func NewTestEngine(x *xorm.Engine) (err error) {
  157. x, err = getEngine()
  158. if err != nil {
  159. return fmt.Errorf("Connect to database: %v", err)
  160. }
  161. x.SetMapper(core.GonicMapper{})
  162. return x.StoreEngine("InnoDB").Sync2(tables...)
  163. }
  164. func SetEngine() (err error) {
  165. x, err = getEngine()
  166. if err != nil {
  167. return fmt.Errorf("Fail to connect to database: %v", err)
  168. }
  169. x.SetMapper(core.GonicMapper{})
  170. // WARNING: for serv command, MUST remove the output to os.stdout,
  171. // so use log file to instead print to stdout.
  172. sec := setting.Cfg.Section("log.xorm")
  173. logger, err := log.NewFileWriter(path.Join(setting.LogRootPath, "xorm.log"),
  174. log.FileRotationConfig{
  175. Rotate: sec.Key("ROTATE").MustBool(true),
  176. Daily: sec.Key("ROTATE_DAILY").MustBool(true),
  177. MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
  178. MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
  179. })
  180. if err != nil {
  181. return fmt.Errorf("Fail to create 'xorm.log': %v", err)
  182. }
  183. if setting.ProdMode {
  184. x.SetLogger(xorm.NewSimpleLogger3(logger, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_WARNING))
  185. } else {
  186. x.SetLogger(xorm.NewSimpleLogger(logger))
  187. }
  188. x.ShowSQL(true)
  189. return nil
  190. }
  191. func NewEngine() (err error) {
  192. if err = SetEngine(); err != nil {
  193. return err
  194. }
  195. if err = migrations.Migrate(x); err != nil {
  196. return fmt.Errorf("migrate: %v", err)
  197. }
  198. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  199. return fmt.Errorf("sync database struct error: %v\n", err)
  200. }
  201. return nil
  202. }
  203. type Statistic struct {
  204. Counter struct {
  205. User, Org, PublicKey,
  206. Repo, Watch, Star, Action, Access,
  207. Issue, Comment, Oauth, Follow,
  208. Mirror, Release, LoginSource, Webhook,
  209. Milestone, Label, HookTask,
  210. Team, UpdateTask, Attachment int64
  211. }
  212. }
  213. func GetStatistic() (stats Statistic) {
  214. stats.Counter.User = CountUsers()
  215. stats.Counter.Org = CountOrganizations()
  216. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  217. stats.Counter.Repo = CountRepositories(true)
  218. stats.Counter.Watch, _ = x.Count(new(Watch))
  219. stats.Counter.Star, _ = x.Count(new(Star))
  220. stats.Counter.Action, _ = x.Count(new(Action))
  221. stats.Counter.Access, _ = x.Count(new(Access))
  222. stats.Counter.Issue, _ = x.Count(new(Issue))
  223. stats.Counter.Comment, _ = x.Count(new(Comment))
  224. stats.Counter.Oauth = 0
  225. stats.Counter.Follow, _ = x.Count(new(Follow))
  226. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  227. stats.Counter.Release, _ = x.Count(new(Release))
  228. stats.Counter.LoginSource = CountLoginSources()
  229. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  230. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  231. stats.Counter.Label, _ = x.Count(new(Label))
  232. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  233. stats.Counter.Team, _ = x.Count(new(Team))
  234. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  235. return
  236. }
  237. func Ping() error {
  238. return x.Ping()
  239. }
  240. // The version table. Should have only one row with id==1
  241. type Version struct {
  242. ID int64
  243. Version int64
  244. }
  245. // DumpDatabase dumps all data from database to file system in JSON format.
  246. func DumpDatabase(dirPath string) (err error) {
  247. os.MkdirAll(dirPath, os.ModePerm)
  248. // Purposely create a local variable to not modify global variable
  249. tables := append(tables, new(Version))
  250. for _, table := range tables {
  251. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*models.")
  252. tableFile := path.Join(dirPath, tableName+".json")
  253. f, err := os.Create(tableFile)
  254. if err != nil {
  255. return fmt.Errorf("fail to create JSON file: %v", err)
  256. }
  257. if err = x.Asc("id").Iterate(table, func(idx int, bean interface{}) (err error) {
  258. return jsoniter.NewEncoder(f).Encode(bean)
  259. }); err != nil {
  260. f.Close()
  261. return fmt.Errorf("fail to dump table '%s': %v", tableName, err)
  262. }
  263. f.Close()
  264. }
  265. return nil
  266. }
  267. // ImportDatabase imports data from backup archive.
  268. func ImportDatabase(dirPath string, verbose bool) (err error) {
  269. snakeMapper := core.SnakeMapper{}
  270. skipInsertProcessors := map[string]bool{
  271. "mirror": true,
  272. "milestone": true,
  273. }
  274. // Purposely create a local variable to not modify global variable
  275. tables := append(tables, new(Version))
  276. for _, table := range tables {
  277. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*models.")
  278. tableFile := path.Join(dirPath, tableName+".json")
  279. if !com.IsExist(tableFile) {
  280. continue
  281. }
  282. if verbose {
  283. log.Trace("Importing table '%s'...", tableName)
  284. }
  285. if err = x.DropTables(table); err != nil {
  286. return fmt.Errorf("drop table '%s': %v", tableName, err)
  287. } else if err = x.Sync2(table); err != nil {
  288. return fmt.Errorf("sync table '%s': %v", tableName, err)
  289. }
  290. f, err := os.Open(tableFile)
  291. if err != nil {
  292. return fmt.Errorf("open JSON file: %v", err)
  293. }
  294. rawTableName := x.TableName(table)
  295. _, isInsertProcessor := table.(xorm.BeforeInsertProcessor)
  296. scanner := bufio.NewScanner(f)
  297. for scanner.Scan() {
  298. switch bean := table.(type) {
  299. case *LoginSource:
  300. meta := make(map[string]interface{})
  301. if err = jsoniter.Unmarshal(scanner.Bytes(), &meta); err != nil {
  302. return fmt.Errorf("unmarshal to map: %v", err)
  303. }
  304. tp := LoginType(com.StrTo(com.ToStr(meta["Type"])).MustInt64())
  305. switch tp {
  306. case LOGIN_LDAP, LOGIN_DLDAP:
  307. bean.Cfg = new(LDAPConfig)
  308. case LOGIN_SMTP:
  309. bean.Cfg = new(SMTPConfig)
  310. case LOGIN_PAM:
  311. bean.Cfg = new(PAMConfig)
  312. case LOGIN_GITHUB:
  313. bean.Cfg = new(GitHubConfig)
  314. default:
  315. return fmt.Errorf("unrecognized login source type:: %v", tp)
  316. }
  317. table = bean
  318. }
  319. if err = jsoniter.Unmarshal(scanner.Bytes(), table); err != nil {
  320. return fmt.Errorf("unmarshal to struct: %v", err)
  321. }
  322. if _, err = x.Insert(table); err != nil {
  323. return fmt.Errorf("insert strcut: %v", err)
  324. }
  325. meta := make(map[string]interface{})
  326. if err = jsoniter.Unmarshal(scanner.Bytes(), &meta); err != nil {
  327. log.Error(2, "Failed to unmarshal to map: %v", err)
  328. }
  329. // Reset created_unix back to the date save in archive because Insert method updates its value
  330. if isInsertProcessor && !skipInsertProcessors[rawTableName] {
  331. if _, err = x.Exec("UPDATE "+rawTableName+" SET created_unix=? WHERE id=?", meta["CreatedUnix"], meta["ID"]); err != nil {
  332. log.Error(2, "Failed to reset 'created_unix': %v", err)
  333. }
  334. }
  335. switch rawTableName {
  336. case "milestone":
  337. if _, err = x.Exec("UPDATE "+rawTableName+" SET deadline_unix=?, closed_date_unix=? WHERE id=?", meta["DeadlineUnix"], meta["ClosedDateUnix"], meta["ID"]); err != nil {
  338. log.Error(2, "Failed to reset 'milestone.deadline_unix', 'milestone.closed_date_unix': %v", err)
  339. }
  340. }
  341. }
  342. // PostgreSQL needs manually reset table sequence for auto increment keys
  343. if setting.UsePostgreSQL {
  344. rawTableName := snakeMapper.Obj2Table(tableName)
  345. seqName := rawTableName + "_id_seq"
  346. if _, err = x.Exec(fmt.Sprintf(`SELECT setval('%s', COALESCE((SELECT MAX(id)+1 FROM "%s"), 1), false);`, seqName, rawTableName)); err != nil {
  347. return fmt.Errorf("reset table '%s' sequence: %v", rawTableName, err)
  348. }
  349. }
  350. }
  351. return nil
  352. }