/
CassandraStore.java
526 lines (435 loc) · 17.3 KB
/
CassandraStore.java
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*
* Copyright 2017 HugeGraph Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.baidu.hugegraph.backend.store.cassandra;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import com.baidu.hugegraph.backend.BackendException;
import com.baidu.hugegraph.backend.id.Id;
import com.baidu.hugegraph.backend.query.Query;
import com.baidu.hugegraph.backend.store.AbstractBackendStore;
import com.baidu.hugegraph.backend.store.BackendAction;
import com.baidu.hugegraph.backend.store.BackendEntry;
import com.baidu.hugegraph.backend.store.BackendFeatures;
import com.baidu.hugegraph.backend.store.BackendMutation;
import com.baidu.hugegraph.backend.store.BackendStoreProvider;
import com.baidu.hugegraph.config.HugeConfig;
import com.baidu.hugegraph.type.HugeType;
import com.baidu.hugegraph.util.E;
import com.baidu.hugegraph.util.Log;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.exceptions.DriverException;
import com.datastax.driver.core.exceptions.InvalidQueryException;
import com.datastax.driver.core.schemabuilder.SchemaBuilder;
public abstract class CassandraStore extends AbstractBackendStore {
private static final Logger LOG = Log.logger(CassandraStore.class);
private static final BackendFeatures FEATURES = new CassandraFeatures();
private final String store;
private final String keyspace;
private final BackendStoreProvider provider;
private final CassandraSessionPool sessions;
// TODO: move to parent class
private final Map<HugeType, CassandraTable> tables;
private HugeConfig conf;
public CassandraStore(final BackendStoreProvider provider,
final String keyspace, final String store) {
E.checkNotNull(keyspace, "keyspace");
E.checkNotNull(store, "store");
this.provider = provider;
this.keyspace = keyspace;
this.store = store;
this.sessions = new CassandraSessionPool(keyspace, store);
this.tables = new ConcurrentHashMap<>();
this.conf = null;
this.registerMetaHandlers();
LOG.debug("Store loaded: {}", store);
}
private void registerMetaHandlers() {
this.registerMetaHandler("metrics", (session, meta, args) -> {
CassandraMetrics metrics = new CassandraMetrics(cluster(), conf);
return metrics.getMetrics();
});
}
protected void registerTableManager(HugeType type, CassandraTable table) {
this.tables.put(type, table);
}
@Override
public String store() {
return this.store;
}
@Override
public String database() {
return this.keyspace;
}
@Override
public BackendStoreProvider provider() {
return this.provider;
}
@Override
public void open(HugeConfig config) {
LOG.debug("Store open: {}", this.store);
E.checkNotNull(config, "config");
if (this.sessions.opened()) {
// TODO: maybe we should throw an exception here instead of ignore
LOG.debug("Store {} has been opened before", this.store);
this.sessions.useSession();
return;
}
this.conf = config;
// Init cluster
this.sessions.open(config);
// Init a session for current thread
try {
LOG.debug("Store connect with keyspace: {}", this.keyspace);
try {
this.sessions.session().open();
} catch (InvalidQueryException e) {
// TODO: the error message may be changed in different versions
if (!e.getMessage().contains(String.format(
"Keyspace '%s' does not exist", this.keyspace))) {
throw e;
}
LOG.info("Failed to connect keyspace: {}, " +
"try to init keyspace later", this.keyspace);
}
} catch (Throwable e) {
try {
this.sessions.close();
} catch (Throwable e2) {
LOG.warn("Failed to close cluster after an error", e2);
}
throw e;
}
LOG.debug("Store opened: {}", this.store);
}
@Override
public void close() {
LOG.debug("Store close: {}", this.store);
this.sessions.close();
}
@Override
public void mutate(BackendMutation mutation) {
if (LOG.isDebugEnabled()) {
LOG.debug("Store {} mutation: {}", this.store, mutation);
}
this.checkSessionConnected();
CassandraSessionPool.Session session = this.sessions.session();
for (Iterator<BackendAction> it = mutation.mutation(); it.hasNext();) {
this.mutate(session, it.next());
}
}
private void mutate(CassandraSessionPool.Session session,
BackendAction item) {
CassandraBackendEntry entry = castBackendEntry(item.entry());
// Check if the entry has no change
if (!entry.selfChanged() && entry.subRows().isEmpty()) {
LOG.warn("The entry will be ignored due to no change: {}", entry);
}
switch (item.action()) {
case INSERT:
// Insert entry
if (entry.selfChanged()) {
this.table(entry.type()).insert(session, entry.row());
}
// Insert sub rows (edges)
for (CassandraBackendEntry.Row row : entry.subRows()) {
this.table(row.type()).insert(session, row);
}
break;
case DELETE:
// Delete entry
if (entry.selfChanged()) {
this.table(entry.type()).delete(session, entry.row());
}
// Delete sub rows (edges)
for (CassandraBackendEntry.Row row : entry.subRows()) {
this.table(row.type()).delete(session, row);
}
break;
case APPEND:
// Append entry
if (entry.selfChanged()) {
this.table(entry.type()).append(session, entry.row());
}
// Append sub rows (edges)
for (CassandraBackendEntry.Row row : entry.subRows()) {
this.table(row.type()).append(session, row);
}
break;
case ELIMINATE:
// Eliminate entry
if (entry.selfChanged()) {
this.table(entry.type()).eliminate(session, entry.row());
}
// Eliminate sub rows (edges)
for (CassandraBackendEntry.Row row : entry.subRows()) {
this.table(row.type()).eliminate(session, row);
}
break;
default:
throw new AssertionError(String.format(
"Unsupported mutate action: %s", item.action()));
}
}
@Override
public Iterator<BackendEntry> query(Query query) {
this.checkSessionConnected();
CassandraTable table = this.table(CassandraTable.tableType(query));
return table.query(this.sessions.session(), query);
}
@Override
public BackendFeatures features() {
return FEATURES;
}
@Override
public void init() {
this.checkClusterConnected();
this.initKeyspace();
this.checkSessionConnected();
this.initTables();
LOG.info("Store initialized: {}", this.store);
}
@Override
public void clear() {
this.checkClusterConnected();
if (this.existsKeyspace()) {
this.checkSessionConnected();
this.clearTables();
this.clearKeyspace();
}
LOG.info("Store cleared: {}", this.store);
}
@Override
public void beginTx() {
this.checkSessionConnected();
CassandraSessionPool.Session session = this.sessions.session();
if (session.txState() != TxState.CLEAN) {
LOG.warn("Store {} expect state CLEAN than {} when begin()",
this.store, session.txState());
}
session.txState(TxState.BEGIN);
}
@Override
public void commitTx() {
this.checkSessionConnected();
CassandraSessionPool.Session session = this.sessions.session();
if (session.txState() != TxState.BEGIN) {
LOG.warn("Store {} expect state BEGIN than {} when commit()",
this.store, session.txState());
}
if (!session.hasChanges()) {
session.txState(TxState.CLEAN);
LOG.debug("Store {} has nothing to commit", this.store);
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Store {} commit {} statements: {}", this.store,
session.statements().size(), session.statements());
}
// TODO how to implement tx perfectly?
// Do update
session.txState(TxState.COMMITTING);
try {
session.commit();
session.txState(TxState.CLEAN);
} catch (DriverException e) {
session.txState(TxState.COMMITT_FAIL);
LOG.error("Failed to commit statements due to:", e);
assert session.statements().size() > 0;
throw new BackendException(
"Failed to commit %s statements: '%s'...", e,
session.statements().size(),
session.statements().iterator().next());
}
}
@Override
public void rollbackTx() {
this.checkSessionConnected();
CassandraSessionPool.Session session = this.sessions.session();
// TODO how to implement perfectly?
if (session.txState() != TxState.COMMITT_FAIL &&
session.txState() != TxState.CLEAN) {
LOG.warn("Store {} expect state COMMITT_FAIL/COMMITTING/CLEAN " +
"than {} when rollback()", this.store, session.txState());
}
session.txState(TxState.ROLLBACKING);
try {
session.clear();
} finally {
// Assume batch commit would auto rollback
session.txState(TxState.CLEAN);
}
}
@Override
public String toString() {
return this.store;
}
protected Cluster cluster() {
return this.sessions.cluster();
}
protected void initKeyspace() {
// Replication strategy: SimpleStrategy or NetworkTopologyStrategy
String strategy = this.conf.get(CassandraOptions.CASSANDRA_STRATEGY);
// Replication factor
int factor = this.conf.get(CassandraOptions.CASSANDRA_REPLICATION);
Map<String, Object> replication = new HashMap<>();
replication.putIfAbsent("class", strategy);
replication.putIfAbsent("replication_factor", factor);
Statement stmt = SchemaBuilder.createKeyspace(this.keyspace)
.ifNotExists().with().replication(replication);
// Create keyspace with non-keyspace-session
LOG.debug("Create keyspace: {}", stmt);
Session session = this.cluster().connect();
try {
session.execute(stmt);
} finally {
if (!session.isClosed()) {
session.close();
}
}
this.sessions.session().open();
}
protected void clearKeyspace() {
// Drop keyspace with non-keyspace-session
Statement stmt = SchemaBuilder.dropKeyspace(this.keyspace).ifExists();
LOG.debug("Drop keyspace: {}", stmt);
Session session = this.cluster().connect();
try {
session.execute(stmt);
} finally {
if (!session.isClosed()) {
session.close();
}
}
}
protected boolean existsKeyspace() {
return this.cluster().getMetadata().getKeyspace(this.keyspace) != null;
}
protected void initTables() {
CassandraSessionPool.Session session = this.sessions.session();
for (CassandraTable table : this.tables.values()) {
table.init(session);
}
}
protected void clearTables() {
CassandraSessionPool.Session session = this.sessions.session();
for (CassandraTable table : this.tables.values()) {
table.clear(session);
}
}
@Override
protected final CassandraTable table(HugeType type) {
assert type != null;
CassandraTable table = this.tables.get(type);
if (table == null) {
throw new BackendException("Unsupported table type: %s", type);
}
return table;
}
@Override
protected CassandraSessionPool.Session session(HugeType type) {
this.checkSessionConnected();
return this.sessions.session();
}
protected final void checkClusterConnected() {
E.checkState(this.sessions != null,
"Cassandra store has not been initialized");
this.sessions.checkClusterConnected();
}
protected final void checkSessionConnected() {
E.checkState(this.sessions != null,
"Cassandra store has not been initialized");
try {
this.sessions.checkSessionConnected();
} catch (DriverException e) {
throw new BackendException("Can't connect to cassandra", e);
}
}
protected static final CassandraBackendEntry castBackendEntry(
BackendEntry entry) {
assert entry instanceof CassandraBackendEntry : entry.getClass();
if (!(entry instanceof CassandraBackendEntry)) {
throw new BackendException(
"Cassandra store only supports CassandraBackendEntry");
}
return (CassandraBackendEntry) entry;
}
/***************************** Store defines *****************************/
public static class CassandraSchemaStore extends CassandraStore {
private final CassandraTables.Counters counters;
public CassandraSchemaStore(BackendStoreProvider provider,
String keyspace, String store) {
super(provider, keyspace, store);
this.counters = new CassandraTables.Counters();
registerTableManager(HugeType.VERTEX_LABEL,
new CassandraTables.VertexLabel());
registerTableManager(HugeType.EDGE_LABEL,
new CassandraTables.EdgeLabel());
registerTableManager(HugeType.PROPERTY_KEY,
new CassandraTables.PropertyKey());
registerTableManager(HugeType.INDEX_LABEL,
new CassandraTables.IndexLabel());
}
@Override
protected void initTables() {
super.initTables();
CassandraSessionPool.Session session = super.sessions.session();
this.counters.init(session);
}
@Override
protected void clearTables() {
super.clearTables();
CassandraSessionPool.Session session = super.sessions.session();
this.counters.clear(session);
}
@Override
public Id nextId(HugeType type) {
this.checkSessionConnected();
CassandraSessionPool.Session session = super.sessions.session();
return this.counters.nextId(session, type);
}
}
public static class CassandraGraphStore extends CassandraStore {
public CassandraGraphStore(BackendStoreProvider provider,
String keyspace, String store) {
super(provider, keyspace, store);
registerTableManager(HugeType.VERTEX,
new CassandraTables.Vertex(store));
registerTableManager(HugeType.EDGE_OUT,
CassandraTables.Edge.out(store));
registerTableManager(HugeType.EDGE_IN,
CassandraTables.Edge.in(store));
registerTableManager(HugeType.SECONDARY_INDEX,
new CassandraTables.SecondaryIndex(store));
registerTableManager(HugeType.RANGE_INDEX,
new CassandraTables.RangeIndex(store));
registerTableManager(HugeType.SEARCH_INDEX,
new CassandraTables.SearchIndex(store));
}
@Override
public Id nextId(HugeType type) {
throw new UnsupportedOperationException(
"CassandraGraphStore.nextId()");
}
}
}