...

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  	"go.uber.org/fx"
    20  
    21  	"github.com/jinzhu/gorm"
    22  
    23  	"github.com/chaos-mesh/chaos-mesh/pkg/config"
    24  
    25  	ctrl "sigs.k8s.io/controller-runtime"
    26  )
    27  
    28  var (
    29  	sqliteDriver string = "sqlite3"
    30  	log                 = ctrl.Log.WithName("store/dbstore")
    31  )
    32  
    33  // DB defines a db storage.
    34  type DB struct {
    35  	*gorm.DB
    36  }
    37  
    38  // NewDBStore returns a new DB
    39  func NewDBStore(lc fx.Lifecycle, conf *config.ChaosDashboardConfig) (*DB, error) {
    40  	dsn := conf.Database.Datasource
    41  
    42  	// fix error `database is locked`, refer to https://github.com/mattn/go-sqlite3/blob/master/README.md#faq
    43  	if conf.Database.Driver == sqliteDriver {
    44  		dsn += "?cache=shared"
    45  	}
    46  
    47  	gormDB, err := gorm.Open(conf.Database.Driver, dsn)
    48  	if err != nil {
    49  		log.Error(err, "failed to open DB", "driver", conf.Database.Driver, "datasource", conf.Database.Datasource)
    50  		return nil, err
    51  	}
    52  
    53  	// fix error `database is locked`, refer to https://github.com/mattn/go-sqlite3/blob/master/README.md#faq
    54  	if conf.Database.Driver == sqliteDriver {
    55  		gormDB.DB().SetMaxOpenConns(1)
    56  	}
    57  
    58  	db := &DB{
    59  		gormDB,
    60  	}
    61  
    62  	lc.Append(fx.Hook{
    63  		OnStop: func(context.Context) error {
    64  			return db.Close()
    65  		},
    66  	})
    67  
    68  	return db, nil
    69  }
    70