models.go 12 KB

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