/
init.go
106 lines (92 loc) · 2.63 KB
/
init.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
package db
import (
"github.com/k8guard/k8guard-action/db/stmts"
"fmt"
"time"
"github.com/gocql/gocql"
libs "github.com/k8guard/k8guardlibs"
)
// Here we'll store connection
var Sess *gocql.Session
var err error
// This is wrapper for gocql
func Connect(hosts []string) error {
libs.Log.Info("Connecting to db")
// Creating cluster for cassandra
cluster := gocql.NewCluster(hosts...)
cluster.Consistency = gocql.LocalQuorum
cluster.Timeout = time.Second * 15
// Auth if username is set
if libs.Cfg.CassandraUsername != "" {
libs.Log.Debug("Connecting with username ", libs.Cfg.CassandraUsername)
cluster.Authenticator = gocql.PasswordAuthenticator{
Username: libs.Cfg.CassandraUsername,
Password: libs.Cfg.CassandraPassword,
}
}
if libs.Cfg.CassandraCaPath != "" {
libs.Log.Debug("Using Ca")
cluster.SslOpts = &gocql.SslOptions{
CaPath: libs.Cfg.CassandraCaPath,
EnableHostVerification: libs.Cfg.CassandraSslHostValidation,
}
}
// Initializing session
session, err := cluster.CreateSession()
if err != nil {
return err
}
// Storring cassandra session
Sess = session
// Initializing database
err = initDB()
if err != nil {
return err
}
return nil
}
// This we need to initialize database scheme
func initDB() error {
libs.Log.Info("Initing DB")
// creating keyspace if configured true
if libs.Cfg.CassandraCreateKeyspace {
// Creating KEYSPACE (if not exists)
libs.Log.Info("Creating the keyspace ", libs.Cfg.CassandraKeyspace)
err = Sess.Query(fmt.Sprintf(stmts.CREATE_KEYSPACE, libs.Cfg.CassandraKeyspace)).Exec()
if err != nil {
return err
}
} else {
libs.Log.Info("Skipping creating the keyspace")
}
// creating tables if configured true
if libs.Cfg.CassandraCreateTables {
err = Sess.Query(fmt.Sprintf(stmts.CREATE_VACTION_TABLE, libs.Cfg.CassandraKeyspace)).Exec()
if err != nil {
return err
}
err = Sess.Query(fmt.Sprintf(stmts.CREATE_VIOLATION_LOG_TABLE, libs.Cfg.CassandraKeyspace)).Exec()
if err != nil {
return err
}
err = Sess.Query(fmt.Sprintf(stmts.CREATE_ACTION_LOG_NAMESPACE_TYPE_TABLE, libs.Cfg.CassandraKeyspace)).Exec()
if err != nil {
return err
}
err = Sess.Query(fmt.Sprintf(stmts.CREATE_ACTION_LOG_TYPE_TABLE, libs.Cfg.CassandraKeyspace)).Exec()
if err != nil {
return err
}
err = Sess.Query(fmt.Sprintf(stmts.CREATE_ACTION_LOG_VTYPE_TABLE, libs.Cfg.CassandraKeyspace)).Exec()
if err != nil {
return err
}
err = Sess.Query(fmt.Sprintf(stmts.CREATE_ACTION_LOG_ACTION_TABLE, libs.Cfg.CassandraKeyspace)).Exec()
if err != nil {
return err
}
} else {
libs.Log.Info("Skipping creating tables")
}
return nil
}