sqlstore.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package sqlstore
  2. import (
  3. "context"
  4. "fmt"
  5. "net/url"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/grafana/grafana/pkg/bus"
  13. "github.com/grafana/grafana/pkg/log"
  14. m "github.com/grafana/grafana/pkg/models"
  15. "github.com/grafana/grafana/pkg/registry"
  16. "github.com/grafana/grafana/pkg/services/annotations"
  17. "github.com/grafana/grafana/pkg/services/sqlstore/migrations"
  18. "github.com/grafana/grafana/pkg/services/sqlstore/migrator"
  19. "github.com/grafana/grafana/pkg/services/sqlstore/sqlutil"
  20. "github.com/grafana/grafana/pkg/setting"
  21. "github.com/go-sql-driver/mysql"
  22. "github.com/go-xorm/xorm"
  23. _ "github.com/grafana/grafana/pkg/tsdb/mssql"
  24. _ "github.com/lib/pq"
  25. sqlite3 "github.com/mattn/go-sqlite3"
  26. )
  27. var (
  28. x *xorm.Engine
  29. dialect migrator.Dialect
  30. sqlog log.Logger = log.New("sqlstore")
  31. )
  32. const ContextSessionName = "db-session"
  33. func init() {
  34. registry.Register(&registry.Descriptor{
  35. Name: "SqlStore",
  36. Instance: &SqlStore{},
  37. InitPriority: registry.High,
  38. })
  39. }
  40. type SqlStore struct {
  41. Cfg *setting.Cfg `inject:""`
  42. Bus bus.Bus `inject:""`
  43. dbCfg DatabaseConfig
  44. engine *xorm.Engine
  45. log log.Logger
  46. skipEnsureAdmin bool
  47. }
  48. // NewSession returns a new DBSession
  49. func (ss *SqlStore) NewSession() *DBSession {
  50. return &DBSession{Session: ss.engine.NewSession()}
  51. }
  52. // WithDbSession calls the callback with an session attached to the context.
  53. func (ss *SqlStore) WithDbSession(ctx context.Context, callback dbTransactionFunc) error {
  54. sess, err := startSession(ctx, ss.engine, false)
  55. if err != nil {
  56. return err
  57. }
  58. return callback(sess)
  59. }
  60. // WithTransactionalDbSession calls the callback with an session within a transaction
  61. func (ss *SqlStore) WithTransactionalDbSession(ctx context.Context, callback dbTransactionFunc) error {
  62. return ss.inTransactionWithRetryCtx(ctx, callback, 0)
  63. }
  64. func (ss *SqlStore) inTransactionWithRetryCtx(ctx context.Context, callback dbTransactionFunc, retry int) error {
  65. sess, err := startSession(ctx, ss.engine, true)
  66. if err != nil {
  67. return err
  68. }
  69. defer sess.Close()
  70. err = callback(sess)
  71. // special handling of database locked errors for sqlite, then we can retry 3 times
  72. if sqlError, ok := err.(sqlite3.Error); ok && retry < 5 {
  73. if sqlError.Code == sqlite3.ErrLocked {
  74. sess.Rollback()
  75. time.Sleep(time.Millisecond * time.Duration(10))
  76. sqlog.Info("Database table locked, sleeping then retrying", "retry", retry)
  77. return ss.inTransactionWithRetryCtx(ctx, callback, retry+1)
  78. }
  79. }
  80. if err != nil {
  81. sess.Rollback()
  82. return err
  83. } else if err = sess.Commit(); err != nil {
  84. return err
  85. }
  86. if len(sess.events) > 0 {
  87. for _, e := range sess.events {
  88. if err = bus.Publish(e); err != nil {
  89. log.Error(3, "Failed to publish event after commit. error: %v", err)
  90. }
  91. }
  92. }
  93. return nil
  94. }
  95. func (ss *SqlStore) Init() error {
  96. ss.log = log.New("sqlstore")
  97. ss.readConfig()
  98. engine, err := ss.getEngine()
  99. if err != nil {
  100. return fmt.Errorf("Fail to connect to database: %v", err)
  101. }
  102. ss.engine = engine
  103. // temporarily still set global var
  104. x = engine
  105. dialect = migrator.NewDialect(x)
  106. migrator := migrator.NewMigrator(x)
  107. migrations.AddMigrations(migrator)
  108. for _, descriptor := range registry.GetServices() {
  109. sc, ok := descriptor.Instance.(registry.DatabaseMigrator)
  110. if ok {
  111. sc.AddMigration(migrator)
  112. }
  113. }
  114. if err := migrator.Start(); err != nil {
  115. return fmt.Errorf("Migration failed err: %v", err)
  116. }
  117. // Init repo instances
  118. annotations.SetRepository(&SqlAnnotationRepo{})
  119. ss.Bus.SetTransactionManager(ss)
  120. // ensure admin user
  121. if ss.skipEnsureAdmin {
  122. return nil
  123. }
  124. return ss.ensureAdminUser()
  125. }
  126. func (ss *SqlStore) ensureAdminUser() error {
  127. systemUserCountQuery := m.GetSystemUserCountStatsQuery{}
  128. err := ss.InTransaction(context.Background(), func(ctx context.Context) error {
  129. err := bus.DispatchCtx(ctx, &systemUserCountQuery)
  130. if err != nil {
  131. return fmt.Errorf("Could not determine if admin user exists: %v", err)
  132. }
  133. if systemUserCountQuery.Result.Count > 0 {
  134. return nil
  135. }
  136. cmd := m.CreateUserCommand{}
  137. cmd.Login = setting.AdminUser
  138. cmd.Email = setting.AdminUser + "@localhost"
  139. cmd.Password = setting.AdminPassword
  140. cmd.IsAdmin = true
  141. if err := bus.DispatchCtx(ctx, &cmd); err != nil {
  142. return fmt.Errorf("Failed to create admin user: %v", err)
  143. }
  144. ss.log.Info("Created default admin", "user", setting.AdminUser)
  145. return nil
  146. })
  147. return err
  148. }
  149. func (ss *SqlStore) buildConnectionString() (string, error) {
  150. cnnstr := ss.dbCfg.ConnectionString
  151. // special case used by integration tests
  152. if cnnstr != "" {
  153. return cnnstr, nil
  154. }
  155. switch ss.dbCfg.Type {
  156. case migrator.MYSQL:
  157. protocol := "tcp"
  158. if strings.HasPrefix(ss.dbCfg.Host, "/") {
  159. protocol = "unix"
  160. }
  161. cnnstr = fmt.Sprintf("%s:%s@%s(%s)/%s?collation=utf8mb4_unicode_ci&allowNativePasswords=true",
  162. ss.dbCfg.User, ss.dbCfg.Pwd, protocol, ss.dbCfg.Host, ss.dbCfg.Name)
  163. if ss.dbCfg.SslMode == "true" || ss.dbCfg.SslMode == "skip-verify" {
  164. tlsCert, err := makeCert("custom", ss.dbCfg)
  165. if err != nil {
  166. return "", err
  167. }
  168. mysql.RegisterTLSConfig("custom", tlsCert)
  169. cnnstr += "&tls=custom"
  170. }
  171. case migrator.POSTGRES:
  172. var host, port = "127.0.0.1", "5432"
  173. fields := strings.Split(ss.dbCfg.Host, ":")
  174. if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
  175. host = fields[0]
  176. }
  177. if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
  178. port = fields[1]
  179. }
  180. if ss.dbCfg.Pwd == "" {
  181. ss.dbCfg.Pwd = "''"
  182. }
  183. if ss.dbCfg.User == "" {
  184. ss.dbCfg.User = "''"
  185. }
  186. cnnstr = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s sslcert=%s sslkey=%s sslrootcert=%s", ss.dbCfg.User, ss.dbCfg.Pwd, host, port, ss.dbCfg.Name, ss.dbCfg.SslMode, ss.dbCfg.ClientCertPath, ss.dbCfg.ClientKeyPath, ss.dbCfg.CaCertPath)
  187. case migrator.SQLITE:
  188. // special case for tests
  189. if !filepath.IsAbs(ss.dbCfg.Path) {
  190. ss.dbCfg.Path = filepath.Join(setting.DataPath, ss.dbCfg.Path)
  191. }
  192. os.MkdirAll(path.Dir(ss.dbCfg.Path), os.ModePerm)
  193. cnnstr = "file:" + ss.dbCfg.Path + "?cache=shared&mode=rwc"
  194. default:
  195. return "", fmt.Errorf("Unknown database type: %s", ss.dbCfg.Type)
  196. }
  197. return cnnstr, nil
  198. }
  199. func (ss *SqlStore) getEngine() (*xorm.Engine, error) {
  200. connectionString, err := ss.buildConnectionString()
  201. if err != nil {
  202. return nil, err
  203. }
  204. sqlog.Info("Connecting to DB", "dbtype", ss.dbCfg.Type)
  205. engine, err := xorm.NewEngine(ss.dbCfg.Type, connectionString)
  206. if err != nil {
  207. return nil, err
  208. }
  209. engine.SetMaxOpenConns(ss.dbCfg.MaxOpenConn)
  210. engine.SetMaxIdleConns(ss.dbCfg.MaxIdleConn)
  211. engine.SetConnMaxLifetime(time.Second * time.Duration(ss.dbCfg.ConnMaxLifetime))
  212. // configure sql logging
  213. debugSql := ss.Cfg.Raw.Section("database").Key("log_queries").MustBool(false)
  214. if !debugSql {
  215. engine.SetLogger(&xorm.DiscardLogger{})
  216. } else {
  217. engine.SetLogger(NewXormLogger(log.LvlInfo, log.New("sqlstore.xorm")))
  218. engine.ShowSQL(true)
  219. engine.ShowExecTime(true)
  220. }
  221. return engine, nil
  222. }
  223. func (ss *SqlStore) readConfig() {
  224. sec := ss.Cfg.Raw.Section("database")
  225. cfgURL := sec.Key("url").String()
  226. if len(cfgURL) != 0 {
  227. dbURL, _ := url.Parse(cfgURL)
  228. ss.dbCfg.Type = dbURL.Scheme
  229. ss.dbCfg.Host = dbURL.Host
  230. pathSplit := strings.Split(dbURL.Path, "/")
  231. if len(pathSplit) > 1 {
  232. ss.dbCfg.Name = pathSplit[1]
  233. }
  234. userInfo := dbURL.User
  235. if userInfo != nil {
  236. ss.dbCfg.User = userInfo.Username()
  237. ss.dbCfg.Pwd, _ = userInfo.Password()
  238. }
  239. } else {
  240. ss.dbCfg.Type = sec.Key("type").String()
  241. ss.dbCfg.Host = sec.Key("host").String()
  242. ss.dbCfg.Name = sec.Key("name").String()
  243. ss.dbCfg.User = sec.Key("user").String()
  244. ss.dbCfg.ConnectionString = sec.Key("connection_string").String()
  245. ss.dbCfg.Pwd = sec.Key("password").String()
  246. }
  247. ss.dbCfg.MaxOpenConn = sec.Key("max_open_conn").MustInt(0)
  248. ss.dbCfg.MaxIdleConn = sec.Key("max_idle_conn").MustInt(2)
  249. ss.dbCfg.ConnMaxLifetime = sec.Key("conn_max_lifetime").MustInt(14400)
  250. ss.dbCfg.SslMode = sec.Key("ssl_mode").String()
  251. ss.dbCfg.CaCertPath = sec.Key("ca_cert_path").String()
  252. ss.dbCfg.ClientKeyPath = sec.Key("client_key_path").String()
  253. ss.dbCfg.ClientCertPath = sec.Key("client_cert_path").String()
  254. ss.dbCfg.ServerCertName = sec.Key("server_cert_name").String()
  255. ss.dbCfg.Path = sec.Key("path").MustString("data/grafana.db")
  256. }
  257. func InitTestDB(t *testing.T) *SqlStore {
  258. t.Helper()
  259. sqlstore := &SqlStore{}
  260. sqlstore.skipEnsureAdmin = true
  261. sqlstore.Bus = bus.New()
  262. dbType := migrator.SQLITE
  263. // environment variable present for test db?
  264. if db, present := os.LookupEnv("GRAFANA_TEST_DB"); present {
  265. dbType = db
  266. }
  267. // set test db config
  268. sqlstore.Cfg = setting.NewCfg()
  269. sec, _ := sqlstore.Cfg.Raw.NewSection("database")
  270. sec.NewKey("type", dbType)
  271. switch dbType {
  272. case "mysql":
  273. sec.NewKey("connection_string", sqlutil.TestDB_Mysql.ConnStr)
  274. case "postgres":
  275. sec.NewKey("connection_string", sqlutil.TestDB_Postgres.ConnStr)
  276. default:
  277. sec.NewKey("connection_string", sqlutil.TestDB_Sqlite3.ConnStr)
  278. }
  279. // need to get engine to clean db before we init
  280. engine, err := xorm.NewEngine(dbType, sec.Key("connection_string").String())
  281. if err != nil {
  282. t.Fatalf("Failed to init test database: %v", err)
  283. }
  284. dialect = migrator.NewDialect(engine)
  285. if err := dialect.CleanDB(); err != nil {
  286. t.Fatalf("Failed to clean test db %v", err)
  287. }
  288. if err := sqlstore.Init(); err != nil {
  289. t.Fatalf("Failed to init test database: %v", err)
  290. }
  291. sqlstore.engine.DatabaseTZ = time.UTC
  292. sqlstore.engine.TZLocation = time.UTC
  293. return sqlstore
  294. }
  295. func IsTestDbMySql() bool {
  296. if db, present := os.LookupEnv("GRAFANA_TEST_DB"); present {
  297. return db == migrator.MYSQL
  298. }
  299. return false
  300. }
  301. func IsTestDbPostgres() bool {
  302. if db, present := os.LookupEnv("GRAFANA_TEST_DB"); present {
  303. return db == migrator.POSTGRES
  304. }
  305. return false
  306. }
  307. type DatabaseConfig struct {
  308. Type, Host, Name, User, Pwd, Path, SslMode string
  309. CaCertPath string
  310. ClientKeyPath string
  311. ClientCertPath string
  312. ServerCertName string
  313. ConnectionString string
  314. MaxOpenConn int
  315. MaxIdleConn int
  316. ConnMaxLifetime int
  317. }