...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/store/dbstore/store.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/store/dbstore

     1  // Copyright 2020 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package dbstore
    15  
    16  import (
    17  	"context"
    18  
    19  	"github.com/jinzhu/gorm"
    20  	"go.uber.org/fx"
    21  	ctrl "sigs.k8s.io/controller-runtime"
    22  
    23  	config "github.com/chaos-mesh/chaos-mesh/pkg/config/dashboard"
    24  )
    25  
    26  var (
    27  	sqliteDriver string = "sqlite3"
    28  	log                 = ctrl.Log.WithName("store/dbstore")
    29  )
    30  
    31  // DB defines a db storage.
    32  type DB struct {
    33  	*gorm.DB
    34  }
    35  
    36  // NewDBStore returns a new DB
    37  func NewDBStore(lc fx.Lifecycle, conf *config.ChaosDashboardConfig) (*DB, error) {
    38  	dsn := conf.Database.Datasource
    39  
    40  	// fix error `database is locked`, refer to https://github.com/mattn/go-sqlite3/blob/master/README.md#faq
    41  	if conf.Database.Driver == sqliteDriver {
    42  		dsn += "?cache=shared"
    43  	}
    44  
    45  	gormDB, err := gorm.Open(conf.Database.Driver, dsn)
    46  	if err != nil {
    47  		log.Error(err, "failed to open DB", "driver", conf.Database.Driver, "datasource", conf.Database.Datasource)
    48  		return nil, err
    49  	}
    50  
    51  	// fix error `database is locked`, refer to https://github.com/mattn/go-sqlite3/blob/master/README.md#faq
    52  	if conf.Database.Driver == sqliteDriver {
    53  		gormDB.DB().SetMaxOpenConns(1)
    54  	}
    55  
    56  	db := &DB{
    57  		gormDB,
    58  	}
    59  
    60  	lc.Append(fx.Hook{
    61  		OnStop: func(context.Context) error {
    62  			return db.Close()
    63  		},
    64  	})
    65  
    66  	return db, nil
    67  }
    68