models.go 10 KB

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