sqlstore.go 10 KB

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