models.go 12 KB

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