models.go 13 KB

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