models.go 11 KB

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