-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontext.go
85 lines (72 loc) · 2.25 KB
/
context.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
package getaredis
import (
"fmt"
"io/ioutil"
"math/rand"
"time"
"golang.org/x/oauth2"
"gopkg.in/yaml.v2"
"github.com/digitalocean/godo"
"github.com/garyburd/redigo/redis"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
type configuration struct {
Database map[string]string `yaml:"database"`
Docker map[string]string `yaml:"docker"`
RedisAddress string `yaml:"redisAddress"`
RedisPassword string `yaml:"redisPassword"`
DigitalOceanToken string `yaml:"digitalOceanToken"`
DropletSSHKeyID int `yaml:"dropletSSHKeyID"`
MaxInstanceSize int `yaml:"maxInstanceSize"`
MaxInstanceTime int `yaml:"maxInstanceTime"`
MaxInstancesPerIP int `yaml:"maxInstancesPerIP"`
MaxRedisConnections int `yaml:"maxRedisConnections"`
MaxContainersPerHost int `yaml:"maxContainersPerHost"`
}
type context struct {
db gorm.DB
redis redis.Conn
digitalocean godo.Client
config configuration
}
func Init(configPath string) (*context, error) {
rand.Seed(time.Now().UnixNano())
data, err := ioutil.ReadFile(configPath)
if err != nil {
return nil, err
}
config := new(configuration)
config.DropletSSHKeyID = -1 // Default Value
err = yaml.Unmarshal(data, config)
if err != nil {
return nil, err
}
// Starting mysql connection
databaseHost := fmt.Sprintf("%v:%v@tcp(%v)/%v?charset=utf8&parseTime=True&loc=Local", config.Database["user"], config.Database["password"], config.Database["host"], config.Database["dbname"])
tmp2, err := gorm.Open("mysql", databaseHost)
if err != nil {
return nil, err
}
tmp2.AutoMigrate(&Instance{})
// Starting redis connection
tmp3, err := redis.Dial("tcp", config.RedisAddress)
if err != nil {
return nil, err
}
tmp3.Do("AUTH", config.RedisPassword)
// Starting digital ocean client
oauthClient := oauth2.NewClient(oauth2.NoContext, &TokenSource{AccessToken: config.DigitalOceanToken})
tmp4 := godo.NewClient(oauthClient)
ctx := context{
config: *config,
db: tmp2,
redis: tmp3,
digitalocean: *tmp4,
}
return &ctx, nil
}
func (ctx *context) Close() {
ctx.db.Close()
ctx.redis.Close()
}