models.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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=utf8&parseTime=true",
  124. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  125. } else {
  126. connStr = fmt.Sprintf("%s:%s@tcp(%s)/%s%scharset=utf8&parseTime=true",
  127. DbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name, Param)
  128. }
  129. case "postgres":
  130. host, port := parsePostgreSQLHostPort(DbCfg.Host)
  131. if host[0] == '/' { // looks like a unix socket
  132. connStr = fmt.Sprintf("postgres://%s:%s@:%s/%s%ssslmode=%s&host=%s",
  133. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), port, DbCfg.Name, Param, DbCfg.SSLMode, host)
  134. } else {
  135. connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s%ssslmode=%s",
  136. url.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, Param, DbCfg.SSLMode)
  137. }
  138. case "mssql":
  139. host, port := parseMSSQLHostPort(DbCfg.Host)
  140. connStr = fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;", host, port, DbCfg.Name, DbCfg.User, DbCfg.Passwd)
  141. case "sqlite3":
  142. if !EnableSQLite3 {
  143. return nil, errors.New("This binary version does not build support for SQLite3.")
  144. }
  145. if err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {
  146. return nil, fmt.Errorf("Fail to create directories: %v", err)
  147. }
  148. connStr = "file:" + DbCfg.Path + "?cache=shared&mode=rwc"
  149. default:
  150. return nil, fmt.Errorf("Unknown database type: %s", DbCfg.Type)
  151. }
  152. return xorm.NewEngine(DbCfg.Type, connStr)
  153. }
  154. func NewTestEngine(x *xorm.Engine) (err error) {
  155. x, err = getEngine()
  156. if err != nil {
  157. return fmt.Errorf("Connect to database: %v", err)
  158. }
  159. x.SetMapper(core.GonicMapper{})
  160. return x.StoreEngine("InnoDB").Sync2(tables...)
  161. }
  162. func SetEngine() (err error) {
  163. x, err = getEngine()
  164. if err != nil {
  165. return fmt.Errorf("Fail to connect to database: %v", err)
  166. }
  167. x.SetMapper(core.GonicMapper{})
  168. // WARNING: for serv command, MUST remove the output to os.stdout,
  169. // so use log file to instead print to stdout.
  170. sec := setting.Cfg.Section("log.xorm")
  171. logger, err := log.NewFileWriter(path.Join(setting.LogRootPath, "xorm.log"),
  172. log.FileRotationConfig{
  173. Rotate: sec.Key("ROTATE").MustBool(true),
  174. Daily: sec.Key("ROTATE_DAILY").MustBool(true),
  175. MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
  176. MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
  177. })
  178. if err != nil {
  179. return fmt.Errorf("Fail to create 'xorm.log': %v", err)
  180. }
  181. if setting.ProdMode {
  182. x.SetLogger(xorm.NewSimpleLogger3(logger, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_WARNING))
  183. } else {
  184. x.SetLogger(xorm.NewSimpleLogger(logger))
  185. }
  186. x.ShowSQL(true)
  187. return nil
  188. }
  189. func NewEngine() (err error) {
  190. if err = SetEngine(); err != nil {
  191. return err
  192. }
  193. if err = migrations.Migrate(x); err != nil {
  194. return fmt.Errorf("migrate: %v", err)
  195. }
  196. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  197. return fmt.Errorf("sync database struct error: %v\n", err)
  198. }
  199. return nil
  200. }
  201. type Statistic struct {
  202. Counter struct {
  203. User, Org, PublicKey,
  204. Repo, Watch, Star, Action, Access,
  205. Issue, Comment, Oauth, Follow,
  206. Mirror, Release, LoginSource, Webhook,
  207. Milestone, Label, HookTask,
  208. Team, UpdateTask, Attachment int64
  209. }
  210. }
  211. func GetStatistic() (stats Statistic) {
  212. stats.Counter.User = CountUsers()
  213. stats.Counter.Org = CountOrganizations()
  214. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  215. stats.Counter.Repo = CountRepositories(true)
  216. stats.Counter.Watch, _ = x.Count(new(Watch))
  217. stats.Counter.Star, _ = x.Count(new(Star))
  218. stats.Counter.Action, _ = x.Count(new(Action))
  219. stats.Counter.Access, _ = x.Count(new(Access))
  220. stats.Counter.Issue, _ = x.Count(new(Issue))
  221. stats.Counter.Comment, _ = x.Count(new(Comment))
  222. stats.Counter.Oauth = 0
  223. stats.Counter.Follow, _ = x.Count(new(Follow))
  224. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  225. stats.Counter.Release, _ = x.Count(new(Release))
  226. stats.Counter.LoginSource = CountLoginSources()
  227. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  228. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  229. stats.Counter.Label, _ = x.Count(new(Label))
  230. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  231. stats.Counter.Team, _ = x.Count(new(Team))
  232. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  233. return
  234. }
  235. func Ping() error {
  236. return x.Ping()
  237. }
  238. // The version table. Should have only one row with id==1
  239. type Version struct {
  240. ID int64
  241. Version int64
  242. }
  243. // DumpDatabase dumps all data from database to file system in JSON format.
  244. func DumpDatabase(dirPath string) (err error) {
  245. os.MkdirAll(dirPath, os.ModePerm)
  246. // Purposely create a local variable to not modify global variable
  247. tables := append(tables, new(Version))
  248. for _, table := range tables {
  249. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*models.")
  250. tableFile := path.Join(dirPath, tableName+".json")
  251. f, err := os.Create(tableFile)
  252. if err != nil {
  253. return fmt.Errorf("fail to create JSON file: %v", err)
  254. }
  255. if err = x.Asc("id").Iterate(table, func(idx int, bean interface{}) (err error) {
  256. enc := json.NewEncoder(f)
  257. return enc.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. // Purposely create a local variable to not modify global variable
  270. tables := append(tables, new(Version))
  271. for _, table := range tables {
  272. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*models.")
  273. tableFile := path.Join(dirPath, tableName+".json")
  274. if !com.IsExist(tableFile) {
  275. continue
  276. }
  277. if verbose {
  278. log.Trace("Importing table '%s'...", tableName)
  279. }
  280. if err = x.DropTables(table); err != nil {
  281. return fmt.Errorf("fail to drop table '%s': %v", tableName, err)
  282. } else if err = x.Sync2(table); err != nil {
  283. return fmt.Errorf("fail to sync table '%s': %v", tableName, err)
  284. }
  285. f, err := os.Open(tableFile)
  286. if err != nil {
  287. return fmt.Errorf("fail to open JSON file: %v", err)
  288. }
  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 = json.Unmarshal(scanner.Bytes(), &meta); err != nil {
  295. return fmt.Errorf("fail to 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 = json.Unmarshal(scanner.Bytes(), table); err != nil {
  311. return fmt.Errorf("fail to unmarshal to struct: %v", err)
  312. }
  313. if _, err = x.Insert(table); err != nil {
  314. return fmt.Errorf("fail to insert strcut: %v", err)
  315. }
  316. }
  317. // PostgreSQL needs manually reset table sequence for auto increment keys
  318. if setting.UsePostgreSQL {
  319. rawTableName := snakeMapper.Obj2Table(tableName)
  320. seqName := rawTableName + "_id_seq"
  321. if _, err = x.Exec(fmt.Sprintf(`SELECT setval('%s', COALESCE((SELECT MAX(id)+1 FROM "%s"), 1), false);`, seqName, rawTableName)); err != nil {
  322. return fmt.Errorf("fail to reset table '%s' sequence: %v", rawTableName, err)
  323. }
  324. }
  325. }
  326. return nil
  327. }