models.go 13 KB

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