models.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. 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. logger, err := log.NewFileWriter(path.Join(setting.LogRootPath, "xorm.log"),
  178. log.FileRotationConfig{
  179. Rotate: sec.Key("ROTATE").MustBool(true),
  180. Daily: sec.Key("ROTATE_DAILY").MustBool(true),
  181. MaxSize: sec.Key("MAX_SIZE").MustInt64(100) * 1024 * 1024,
  182. MaxDays: sec.Key("MAX_DAYS").MustInt64(3),
  183. })
  184. if err != nil {
  185. return fmt.Errorf("Fail to create 'xorm.log': %v", err)
  186. }
  187. if setting.ProdMode {
  188. x.SetLogger(xorm.NewSimpleLogger3(logger, xorm.DEFAULT_LOG_PREFIX, xorm.DEFAULT_LOG_FLAG, core.LOG_WARNING))
  189. } else {
  190. x.SetLogger(xorm.NewSimpleLogger(logger))
  191. }
  192. x.ShowSQL(true)
  193. return nil
  194. }
  195. func NewEngine() (err error) {
  196. if err = SetEngine(); err != nil {
  197. return err
  198. }
  199. if err = migrations.Migrate(x); err != nil {
  200. return fmt.Errorf("migrate: %v", err)
  201. }
  202. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  203. return fmt.Errorf("sync database struct error: %v\n", err)
  204. }
  205. return nil
  206. }
  207. type Statistic struct {
  208. Counter struct {
  209. User, Org, PublicKey,
  210. Repo, Watch, Star, Action, Access,
  211. Issue, Comment, Oauth, Follow,
  212. Mirror, Release, LoginSource, Webhook,
  213. Milestone, Label, HookTask,
  214. Team, UpdateTask, Attachment int64
  215. }
  216. }
  217. func GetStatistic() (stats Statistic) {
  218. stats.Counter.User = CountUsers()
  219. stats.Counter.Org = CountOrganizations()
  220. stats.Counter.PublicKey, _ = x.Count(new(PublicKey))
  221. stats.Counter.Repo = CountRepositories(true)
  222. stats.Counter.Watch, _ = x.Count(new(Watch))
  223. stats.Counter.Star, _ = x.Count(new(Star))
  224. stats.Counter.Action, _ = x.Count(new(Action))
  225. stats.Counter.Access, _ = x.Count(new(Access))
  226. stats.Counter.Issue, _ = x.Count(new(Issue))
  227. stats.Counter.Comment, _ = x.Count(new(Comment))
  228. stats.Counter.Oauth = 0
  229. stats.Counter.Follow, _ = x.Count(new(Follow))
  230. stats.Counter.Mirror, _ = x.Count(new(Mirror))
  231. stats.Counter.Release, _ = x.Count(new(Release))
  232. stats.Counter.LoginSource = CountLoginSources()
  233. stats.Counter.Webhook, _ = x.Count(new(Webhook))
  234. stats.Counter.Milestone, _ = x.Count(new(Milestone))
  235. stats.Counter.Label, _ = x.Count(new(Label))
  236. stats.Counter.HookTask, _ = x.Count(new(HookTask))
  237. stats.Counter.Team, _ = x.Count(new(Team))
  238. stats.Counter.Attachment, _ = x.Count(new(Attachment))
  239. return
  240. }
  241. func Ping() error {
  242. return x.Ping()
  243. }
  244. // The version table. Should have only one row with id==1
  245. type Version struct {
  246. ID int64
  247. Version int64
  248. }
  249. // DumpDatabase dumps all data from database to file system in JSON format.
  250. func DumpDatabase(dirPath string) (err error) {
  251. os.MkdirAll(dirPath, os.ModePerm)
  252. // Purposely create a local variable to not modify global variable
  253. tables := append(tables, new(Version))
  254. for _, table := range tables {
  255. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*models.")
  256. tableFile := path.Join(dirPath, tableName+".json")
  257. f, err := os.Create(tableFile)
  258. if err != nil {
  259. return fmt.Errorf("fail to create JSON file: %v", err)
  260. }
  261. if err = x.Asc("id").Iterate(table, func(idx int, bean interface{}) (err error) {
  262. enc := json.NewEncoder(f)
  263. return enc.Encode(bean)
  264. }); err != nil {
  265. f.Close()
  266. return fmt.Errorf("fail to dump table '%s': %v", tableName, err)
  267. }
  268. f.Close()
  269. }
  270. return nil
  271. }
  272. // ImportDatabase imports data from backup archive.
  273. func ImportDatabase(dirPath string) (err error) {
  274. // Purposely create a local variable to not modify global variable
  275. tables := append(tables, new(Version))
  276. for _, table := range tables {
  277. tableName := strings.TrimPrefix(fmt.Sprintf("%T", table), "*models.")
  278. tableFile := path.Join(dirPath, tableName+".json")
  279. if !com.IsExist(tableFile) {
  280. continue
  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. }
  320. return nil
  321. }