forked from uber/cadence
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cqlclient.go
319 lines (285 loc) · 9.9 KB
/
cqlclient.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
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package cassandra
import (
"bufio"
"errors"
"io"
"os"
"strings"
"time"
"fmt"
"github.com/gocql/gocql"
"log"
)
type (
// CQLClient is the interface for implementations
// that provide a way to talk to cassandra through CQL
CQLClient interface {
// Exec executes a cql statement
Exec(stmt string) error
// ListTables lists the table names in a keyspace
ListTables() ([]string, error)
// ListTypes lists the user defined types in a keyspace
ListTypes() ([]string, error)
// CreateKeyspace creates a keyspace, if it doesn't exist
// it uses SimpleStrategy by default
CreateKeyspace(name string, replicas int) error
// DropTable drops the given table
DropTable(name string) error
// DropType drops a user defined type from keyspace
DropType(name string) error
// DropKeyspace drops a keyspace
DropKeyspace(keyspace string) error
// CreateSchemaVersionTables sets up the schema version tables
CreateSchemaVersionTables() error
// ReadSchemaVersion returns the current schema version for the keyspace
ReadSchemaVersion() (string, error)
// UpdateSchemaVersion updates the schema version for the keyspace
UpdateSchemaVersion(newVersion string, minCompatibleVersion string) error
// WriteSchemaUpdateLog adds an entry to the schema update history table
WriteSchemaUpdateLog(oldVersion string, newVersion string, manifestMD5 string, desc string) error
// Close gracefully closes the client object
Close()
}
cqlClient struct {
session *gocql.Session
clusterConfig *gocql.ClusterConfig
}
)
var errNoHosts = errors.New("Cassandra hosts list is empty or malformed")
var errGetSchemaVersion = errors.New("Failed to get current schema version from cassandra")
const (
newLineDelim = '\n'
defaultTimeout = 30 * time.Second
cqlProtoVersion = 4 // default CQL protocol version
defaultConsistency = "QUORUM" // schema updates must always be QUORUM
defaultCassandraPort = 9042
)
const (
readSchemaVersionCQL = `SELECT curr_version from schema_version where keyspace_name=?`
listTablesCQL = `SELECT table_name from system_schema.tables where keyspace_name=?`
listTypesCQL = `SELECT type_name from system_schema.types where keyspace_name=?`
writeSchemaVersionCQL = `INSERT into schema_version(keyspace_name, creation_time, curr_version, min_compatible_version) VALUES (?,?,?,?)`
writeSchemaUpdateHistoryCQL = `INSERT into schema_update_history(year, month, update_time, old_version, new_version, manifest_md5, description) VALUES(?,?,?,?,?,?,?)`
createSchemaVersionTableCQL = `CREATE TABLE schema_version(keyspace_name text PRIMARY KEY, ` +
`creation_time timestamp, ` +
`curr_version text, ` +
`min_compatible_version text);`
createSchemaUpdateHistoryTableCQL = `CREATE TABLE schema_update_history(` +
`year int, ` +
`month int, ` +
`update_time timestamp, ` +
`description text, ` +
`manifest_md5 text, ` +
`new_version text, ` +
`old_version text, ` +
`PRIMARY KEY ((year, month), update_time));`
createKeyspaceCQL = `CREATE KEYSPACE IF NOT EXISTS %v ` +
`WITH replication = { 'class' : 'SimpleStrategy', 'replication_factor' : %v};`
)
// newCQLClient returns a new instance of CQLClient
func newCQLClient(hostsCsv string, port int, user, password, keyspace string) (CQLClient, error) {
hosts := parseHosts(hostsCsv)
if len(hosts) == 0 {
return nil, errNoHosts
}
clusterCfg := gocql.NewCluster(hosts...)
clusterCfg.Port = port
if user != "" && password != "" {
clusterCfg.Authenticator = gocql.PasswordAuthenticator{
Username: user,
Password: password,
}
}
clusterCfg.Keyspace = keyspace
clusterCfg.Timeout = defaultTimeout
clusterCfg.ProtoVersion = cqlProtoVersion
clusterCfg.Consistency = gocql.ParseConsistency(defaultConsistency)
cqlClient := new(cqlClient)
cqlClient.clusterConfig = clusterCfg
var err error
cqlClient.session, err = clusterCfg.CreateSession()
if err != nil {
return nil, err
}
return cqlClient, nil
}
// Createkeyspace creates a keyspace if it doesn't exist
func (client *cqlClient) CreateKeyspace(name string, replicas int) error {
return client.Exec(fmt.Sprintf(createKeyspaceCQL, name, replicas))
}
// ListTables lists the table names in a keyspace
func (client *cqlClient) ListTables() ([]string, error) {
query := client.session.Query(listTablesCQL, client.clusterConfig.Keyspace)
iter := query.Iter()
var names []string
var name string
for iter.Scan(&name) {
names = append(names, name)
}
if err := iter.Close(); err != nil {
return nil, err
}
return names, nil
}
// ListTypes lists the user defined types in a keyspace
func (client *cqlClient) ListTypes() ([]string, error) {
qry := client.session.Query(listTypesCQL, client.clusterConfig.Keyspace)
iter := qry.Iter()
var names []string
var name string
for iter.Scan(&name) {
names = append(names, name)
}
if err := iter.Close(); err != nil {
return nil, err
}
return names, nil
}
// DropTable drops a given table from the keyspace
func (client *cqlClient) DropTable(name string) error {
return client.Exec(fmt.Sprintf("DROP TABLE %v", name))
}
// DropType drops a given type from the keyspace
func (client *cqlClient) DropType(name string) error {
return client.Exec(fmt.Sprintf("DROP TYPE %v", name))
}
// DropKeyspace drops a keyspace
func (client *cqlClient) DropKeyspace(keyspace string) error {
return client.Exec(fmt.Sprintf("DROP KEYSPACE %v", keyspace))
}
// CreateSchemaVersionTables sets up the schema version tables
func (client *cqlClient) CreateSchemaVersionTables() error {
if err := client.Exec(createSchemaVersionTableCQL); err != nil {
return err
}
if err := client.Exec(createSchemaUpdateHistoryTableCQL); err != nil {
return err
}
return nil
}
// ReadSchemaVersion returns the current schema version for the keyspace
func (client *cqlClient) ReadSchemaVersion() (string, error) {
query := client.session.Query(readSchemaVersionCQL, client.clusterConfig.Keyspace)
iter := query.Iter()
var version string
if !iter.Scan(&version) {
iter.Close()
return "", errGetSchemaVersion
}
if err := iter.Close(); err != nil {
return "", err
}
return version, nil
}
// UpdateShemaVersion updates the schema version for the keyspace
func (client *cqlClient) UpdateSchemaVersion(newVersion string, minCompatibleVersion string) error {
query := client.session.Query(writeSchemaVersionCQL, client.clusterConfig.Keyspace, time.Now(), newVersion, minCompatibleVersion)
return query.Exec()
}
// WriteSchemaUpdateLog adds an entry to the schema update history table
func (client *cqlClient) WriteSchemaUpdateLog(oldVersion string, newVersion string, manifestMD5 string, desc string) error {
now := time.Now().UTC()
query := client.session.Query(writeSchemaUpdateHistoryCQL)
query.Bind(now.Year(), int(now.Month()), now, oldVersion, newVersion, manifestMD5, desc)
return query.Exec()
}
// Exec executes a cql statement
func (client *cqlClient) Exec(stmt string) error {
return client.session.Query(stmt).Exec()
}
// Close closes the cql client
func (client *cqlClient) Close() {
if client.session != nil {
client.session.Close()
}
}
func parseHosts(input string) []string {
var hosts = make([]string, 0)
for _, h := range strings.Split(input, ",") {
if host := strings.TrimSpace(h); len(host) > 0 {
hosts = append(hosts, host)
}
}
return hosts
}
// ParseCQLFile takes a cql file path as input
// and returns an array of cql statements on
// success.
func ParseCQLFile(filePath string) ([]string, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, err
}
reader := bufio.NewReader(f)
var line string
var currStmt string
var stmts = make([]string, 0, 4)
for err == nil {
line, err = reader.ReadString(newLineDelim)
line = strings.TrimSpace(line)
if len(line) < 1 {
continue
}
// Filter out the comment lines, the
// only recognized comment line format
// is any line that starts with double dashes
tokens := strings.Split(line, "--")
if len(tokens) > 0 && len(tokens[0]) > 0 {
currStmt += tokens[0]
// semi-colon is the end of statement delim
if strings.HasSuffix(currStmt, ";") {
stmts = append(stmts, currStmt)
currStmt = ""
}
}
}
if err == io.EOF {
return stmts, nil
}
return nil, err
}
// dropAllTablesTypes deletes all tables/types in the
// keyspace without deleting the keyspace
func dropAllTablesTypes(client CQLClient) {
tables, err := client.ListTables()
if err != nil {
return
}
log.Printf("Dropping following tables: %v\n", tables)
for _, table := range tables {
err1 := client.DropTable(table)
if err1 != nil {
log.Printf("Error dropping table %v, err=%v\n", table, err1)
}
}
types, err := client.ListTypes()
if err != nil {
return
}
log.Printf("Dropping following types: %v\n", types)
for _, t := range types {
err1 := client.DropType(t)
if err1 != nil {
log.Printf("Error dropping type %v, err=%v\n", t, err1)
}
}
}