/
utils.go
117 lines (106 loc) · 2.64 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package auth
import (
"fmt"
"os"
"path/filepath"
"time"
"bitbucket.org/liamstask/goose/lib/goose"
machinery "github.com/RichardKnop/machinery/v1"
"github.com/RichardKnop/machinery/v1/config"
"github.com/RichardKnop/machinery/v1/logger"
log "github.com/Sirupsen/logrus"
"github.com/garyburd/redigo/redis"
"github.com/jinzhu/gorm"
"github.com/kapmahc/lotus/web"
"github.com/spf13/viper"
)
func migrationConf() *goose.DBConf {
root := filepath.Join("db", viper.GetString("database.driver"), "migrations")
os.MkdirAll(root, 0700)
var drv goose.DBDriver
drv.Name, drv.OpenStr = databaseURL()
switch drv.Name {
case "postgres":
drv.Import = "github.com/lib/pq"
drv.Dialect = &goose.PostgresDialect{}
case "mysql":
drv.Import = "github.com/go-sql-driver/mysql"
drv.Dialect = &goose.MySqlDialect{}
case "sqlite3":
drv.Import = "github.com/mattn/go-sqlite3"
drv.Dialect = &goose.Sqlite3Dialect{}
}
return &goose.DBConf{
MigrationsDir: root,
Env: viper.GetString("env"),
Driver: drv,
}
}
func databaseURL() (string, string) {
//postgresql: "user=%s password=%s host=%s port=%d dbname=%s sslmode=%s"
args := ""
for k, v := range viper.GetStringMapString("database.args") {
args += fmt.Sprintf(" %s=%s ", k, v)
}
return viper.GetString("database.driver"), args
}
func openCacheRedis() *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, e := redis.Dial(
"tcp",
fmt.Sprintf(
"%s:%d",
viper.GetString("cache.host"),
viper.GetInt("cache.port"),
),
)
if e != nil {
return nil, e
}
if _, e = c.Do("SELECT", viper.GetInt("cache.db")); e != nil {
c.Close()
return nil, e
}
return c, nil
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
func openDatabase() (*gorm.DB, error) {
drv, url := databaseURL()
db, err := gorm.Open(drv, url)
if err != nil {
return nil, err
}
if !web.IsProduction() {
db.LogMode(true)
}
if err := db.DB().Ping(); err != nil {
return nil, err
}
db.DB().SetMaxIdleConns(viper.GetInt("database.pool.max_idle"))
db.DB().SetMaxOpenConns(viper.GetInt("database.pool.max_open"))
return db, nil
}
func openJobServer() (*machinery.Server, error) {
logger.Set(log.New())
url := fmt.Sprintf(
"redis://%s:%d/%d",
viper.GetString("jobs.host"),
viper.GetInt("jobs.port"),
viper.GetInt("jobs.db"),
)
var cnf = config.Config{
Broker: url,
ResultBackend: url,
ResultsExpireIn: 60 * 60 * 24 * 7 * 10,
DefaultQueue: viper.GetString("app.name") + "-tasks",
}
return machinery.NewServer(&cnf)
}