123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- package tick
- import "log"
- import "database/sql"
- import _ "github.com/go-sql-driver/mysql"
- import "fmt"
- import "time"
- import "errors"
- var db *sql.DB
- var tserver *TickServer
- var serverconf *ServerConf
- type newDs func(conf *DsConf) (DataSource, error)
- var drivers = make(map[string]newDs)
- //设置数据库连接
- func initdb(dbconf *DBConf) {
- var err error
- db, err = sql.Open(dbconf.DBDriver, dbconf.DSN)
- if err != nil {
- panic(err)
- }
- }
- func getDriver(name string) (newDs, error) {
- if ret, ok := drivers[name]; ok {
- return ret, nil
- }
- return nil, errors.New("getDriver " + name + " error.")
- }
- func SetConf(conf *ServerConf) {
- serverconf = conf
- }
- func InitDb() {
- initdb(&serverconf.DBConf)
- }
- func Init() {
- //parse
- //log.Println("initdb")
- initdb(&serverconf.DBConf)
- var err error
- //getdblock,global 获取一个数据库的锁,这个锁可以证明没有其他的实例运行,操作数据库
- tserver, err = NewTickServer()
- if err != nil {
- panic(err)
- }
- //log.Println("run datasource...")
- runDataSource(serverconf)
- }
- func getFilePath(ty string) (string, error) {
- if conf, ok := serverconf.DsMap[ty]; ok {
- return conf.SaveDir, nil
- }
- return "", ErrDataSourceType
- }
- func runDataSource(conf *ServerConf) {
- for name, dsConf := range conf.DsMap {
- if dsConf.Run {
- ds := NewDataSource(name, dsConf)
- if ds != nil {
- tserver.AddDataSource(ds, dsConf.Download)
- go ds.Run()
- }
- //log.Println("run", name)
- }
- }
- }
- func NewDataSource(name string, conf *DsConf) DataSource {
- driver, err := getDriver(name)
- if err != nil {
- log.Fatal(err)
- }
- ds, err := driver(conf)
- if err != nil {
- log.Fatal(err)
- }
- return ds
- }
- func lockDb(name string) bool {
- //setLock
- q := "UPDATE system_lock SET flag=1 WHERE name='%s' AND flag <> 1"
- q = fmt.Sprintf(q, name)
- result, err := db.Exec(q)
- if err != nil {
- //log.Println("[lockdb]", err)
- return false
- }
- n, err := result.RowsAffected()
- if err != nil {
- //log.Println("[lockdb]", err)
- return false
- }
- if n == 1 {
- return true
- }
- //log.Println("[lockdb]", "lock an locked lock")
- return false
- }
- func LockDb(name string, wait bool) bool {
- for {
- ok := lockDb(name)
- if !ok && wait {
- time.Sleep(time.Millisecond * 100)
- continue
- }
- return ok
- }
- }
- func UnlockDb(name string) bool {
- q := "UPDATE system_lock SET flag=0 WHERE name='%s' AND flag <> 0"
- q = fmt.Sprintf(q, name)
- result, err := db.Exec(q)
- if err != nil {
- //log.Println("[unlockdb]", err)
- return false
- }
- n, err := result.RowsAffected()
- if err != nil {
- //log.Println("[unlockdb]", err)
- return false
- }
- if n == 1 {
- return true
- }
- panic("unlock a unlocked lock")
- }
|