models.go 12 KB

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