-
Notifications
You must be signed in to change notification settings - Fork 0
/
recreation.go
355 lines (289 loc) · 7.28 KB
/
recreation.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package main
import (
"bufio"
"crypto/rsa"
"errors"
"fmt"
"math/rand"
"net"
"os"
"strconv"
"time"
docker "github.com/fsouza/go-dockerclient"
"github.com/gocql/gocql"
"github.com/kelseyhightower/envconfig"
)
var conn *CassandraConnection
var dbConfig DBConfig
var privateKey *rsa.PrivateKey
type DBConfig struct {
Keyspace string `default:"recreation"`
Host string `default:"127.0.0.1"`
Port string `default:""`
Name string `default:"recreation"`
Timeout int `default:"30"`
}
type user struct {
FirstName string
LastName string
Age int
}
func getConfig(app_name string, s interface{}) error {
err := envconfig.Process(app_name, s)
return err
}
func getPort() int {
l, err := net.Listen("tcp", ":0")
if err != nil {
return 0
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port
}
func startCassandraDocker(name string, port string) error {
var err error
var container *docker.Container
var authConfig docker.AuthConfiguration
repo := "cassandra"
tag := "3.11.1"
endpoint := "unix:///var/run/docker.sock"
client, _ := docker.NewClient(endpoint)
exposedPort := map[docker.Port]struct{}{
"9042/tcp": {},
}
createContConf := docker.Config{
ExposedPorts: exposedPort,
Image: fmt.Sprintf("%s:%s", repo, tag),
Env: []string{"CASSANDRA_BROADCAST_ADDRESS=127.0.0.1"},
}
portBindings := map[docker.Port][]docker.PortBinding{
"9042/tcp": {{HostIP: "", HostPort: port}},
}
createContHostConfig := docker.HostConfig{
PortBindings: portBindings,
PublishAllPorts: false,
Privileged: false,
}
createContOps := docker.CreateContainerOptions{
Name: name,
Config: &createContConf,
HostConfig: &createContHostConfig,
}
pullImageOps := docker.PullImageOptions{
Repository: repo,
Tag: tag,
}
fmt.Println("Pulling Cassandra Docker image.")
if err = client.PullImage(pullImageOps, authConfig); err != nil {
return err
}
fmt.Println("Creating Cassandra container.")
container, err = client.CreateContainer(createContOps)
if err != nil {
return err
}
fmt.Println("Starting Cassandra container.")
if err = client.StartContainer(container.ID, nil); err != nil {
return err
}
return nil
}
func destroyDockerContainer(containerID string) error {
fmt.Println("Destroying Cassandra Docker container.")
endpoint := "unix:///var/run/docker.sock"
client, _ := docker.NewClient(endpoint)
err := client.StopContainer(containerID, 30)
err = client.RemoveContainer(docker.RemoveContainerOptions{
ID: containerID,
RemoveVolumes: true,
Force: true,
})
return err
}
func waitForConnection(host string, port string, timeout int) error {
fmt.Printf("Attempting to connect to DB %s:%s", host, port)
iter := 0
for iter < timeout {
c := gocql.NewCluster(host)
c.Timeout = 6 * time.Second
c.Consistency = gocql.Quorum
c.Keyspace = "system"
c.Port, _ = strconv.Atoi(port)
session, err := c.CreateSession()
if err == nil {
session.Close()
break
} else {
fmt.Print(".")
time.Sleep(1 * time.Second)
}
}
fmt.Println("\nConnected to DB.")
if iter >= timeout {
return errors.New("timeout while waiting for the DB")
}
return nil
}
func setupDB(host string, port string, name string, keyspace string) (*CassandraConnection, error) {
fmt.Println("Setting up the database.")
var conn *CassandraConnection
c := &CassandraConnection{}
c.Hosts = []string{host}
c.Port = port
c.DBName = name
c.Keyspace = keyspace
conn = c
if err := conn.Init(); err != nil {
return nil, err
}
if err := conn.Connect(); err != nil {
return nil, err
}
return conn, nil
}
func getContainer(name string) (*docker.APIContainers, error) {
endpoint := "unix:///var/run/docker.sock"
client, _ := docker.NewClient(endpoint)
containers, err := client.ListContainers(docker.ListContainersOptions{All: true})
if err != nil {
return nil, err
}
for _, i := range containers {
for _, n := range i.Names {
if n == fmt.Sprintf("/%s", name) {
return &i, nil
}
}
}
return nil, errors.New("no container found")
}
func tearDown() error {
if dbConfig == (DBConfig{}) {
err := getConfig("CASSANDRA_13991", &dbConfig)
if err != nil {
return err
}
}
if conn != nil {
conn.Close()
}
apiContainer, err := getContainer(dbConfig.Name)
if err != nil {
return err
}
if err = destroyDockerContainer(apiContainer.ID); err != nil {
fmt.Printf("Unable to stop container: %s\n", err)
return err
}
return nil
}
func scan(table string, pageSize int, pageState []byte) ([]user, []byte, error) {
q := conn.Session.Query
query := q(`SELECT first_name, last_name, age FROM users`)
if pageSize > 0 {
query.PageSize(pageSize)
}
if pageState != nil {
query.PageState(pageState)
}
iter := query.Iter()
u := user{}
users := make([]user, 0)
for iter.Scan(&u.FirstName, &u.LastName, &u.Age) {
users = append(users, u)
if pageSize > 0 {
if len(users) >= pageSize {
break
}
}
}
next := iter.PageState()
err := iter.Close()
return users, next, err
}
func performRecreation() error {
var err error
var next []byte
var users []user
names := []string{"bill", "mary", "bob", "june", "peter", "sally",
"rich", "patty", "henry", "nancy", "george", "allie"}
q := conn.Session.Query
for _, name := range names {
if err = q(`INSERT INTO users (
first_name, last_name, age)
VALUES (?, ?, ?)`,
name, "smith", rand.Intn(30)+20).Exec(); err != nil {
return err
}
}
//Query the whole table
fmt.Println("Query all:")
users, next, err = scan("users", 0, nil)
if err != nil {
return err
}
fmt.Println("\tResults:")
for _, u := range users {
fmt.Printf("\t\t%s %s, %d\n", u.FirstName, u.LastName, u.Age)
}
fmt.Println()
//Query the first row, saving the state in "next"
fmt.Println("Query one:")
users, next, err = scan("users", 1, nil)
if err != nil {
return err
}
fmt.Println("\tResults:")
for _, u := range users {
fmt.Printf("\t\t%s %s, %d\n", u.FirstName, u.LastName, u.Age)
}
fmt.Println()
//Query the whole table again.
scan("users", 0, nil)
//Query the next 5 using the state from the "Query one" query.
fmt.Println("Query next 5:")
users, next, err = scan("users", 5, next)
if err != nil {
if err.Error() == "java.lang.NullPointerException" {
fmt.Printf("Got a NullPointerException. Run 'docker logs %s' in another window to see the stacktrace.\n", dbConfig.Name)
fmt.Print("Press Enter to continue: ")
bufio.NewReader(os.Stdin).ReadBytes('\n')
} else {
return err
}
}
return nil
}
func main() {
var err error
err = getConfig("CASSANDRA_13991", &dbConfig)
if err != nil {
fmt.Printf("Error getting config values: %v\n", err)
return
}
dbConfig.Port = strconv.Itoa(getPort())
err = startCassandraDocker(dbConfig.Name, dbConfig.Port)
if err != nil {
fmt.Printf("Error starting container: %v\n", err)
tearDown()
return
}
err = waitForConnection(dbConfig.Host, dbConfig.Port, dbConfig.Timeout)
if err != nil {
fmt.Printf("Error waiting for connection: %v\n", err)
tearDown()
return
}
conn, err = setupDB(dbConfig.Host, dbConfig.Port, dbConfig.Name, dbConfig.Keyspace)
if err != nil {
fmt.Printf("Error setting up the DB: %v\n", err)
tearDown()
return
}
if err = performRecreation(); err != nil {
fmt.Printf("Error performing recreation: %v\n", err)
tearDown()
return
}
tearDown()
}