models.go 12 KB

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