proj_name
stringclasses 110
values | relative_path
stringlengths 40
228
| class_name
stringlengths 1
68
⌀ | func_name
stringlengths 1
98
⌀ | masked_class
stringlengths 58
2.52M
⌀ | func_body
stringlengths 0
166k
⌀ |
---|---|---|---|---|---|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | run | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {<FILL_FUNCTION_BODY>}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
CleanUp.shutdownNow();
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | init | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {<FILL_FUNCTION_BODY>}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | cleanup | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {<FILL_FUNCTION_BODY>}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | getWriter | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {<FILL_FUNCTION_BODY>}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | createBatchWriter | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {<FILL_FUNCTION_BODY>}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | getRow | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {<FILL_FUNCTION_BODY>}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | read | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {<FILL_FUNCTION_BODY>}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | scan | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {<FILL_FUNCTION_BODY>}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | update | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | insert | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
return update(t, key, values);
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | delete | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {<FILL_FUNCTION_BODY>}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | deleteRow | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {<FILL_FUNCTION_BODY>}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
}
} |
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
|
brianfrankcooper_YCSB | YCSB/accumulo1.9/src/main/java/site/ycsb/db/accumulo/AccumuloClient.java | AccumuloClient | deleteRow | class AccumuloClient extends DB {
private ZooKeeperInstance inst;
private Connector connector;
private Text colFam = new Text("");
private byte[] colFamBytes = new byte[0];
private final ConcurrentHashMap<String, BatchWriter> writers = new ConcurrentHashMap<>();
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
CleanUp.shutdownNow();
}
});
}
@Override
public void init() throws DBException {
colFam = new Text(getProperties().getProperty("accumulo.columnFamily"));
colFamBytes = colFam.toString().getBytes(UTF_8);
inst = new ZooKeeperInstance(new ClientConfiguration()
.withInstance(getProperties().getProperty("accumulo.instanceName"))
.withZkHosts(getProperties().getProperty("accumulo.zooKeepers")));
try {
String principal = getProperties().getProperty("accumulo.username");
AuthenticationToken token =
new PasswordToken(getProperties().getProperty("accumulo.password"));
connector = inst.getConnector(principal, token);
} catch (AccumuloException | AccumuloSecurityException e) {
throw new DBException(e);
}
if (!(getProperties().getProperty("accumulo.pcFlag", "none").equals("none"))) {
System.err.println("Sorry, the ZK based producer/consumer implementation has been removed. " +
"Please see YCSB issue #416 for work on adding a general solution to coordinated work.");
}
}
@Override
public void cleanup() throws DBException {
try {
Iterator<BatchWriter> iterator = writers.values().iterator();
while (iterator.hasNext()) {
BatchWriter writer = iterator.next();
writer.close();
iterator.remove();
}
} catch (MutationsRejectedException e) {
throw new DBException(e);
}
}
/**
* Called when the user specifies a table that isn't the same as the existing
* table. Connect to it and if necessary, close our current connection.
*
* @param table
* The table to open.
*/
public BatchWriter getWriter(String table) throws TableNotFoundException {
// tl;dr We're paying a cost for the ConcurrentHashMap here to deal with the DB api.
// We know that YCSB is really only ever going to send us data for one table, so using
// a concurrent data structure is overkill (especially in such a hot code path).
// However, the impact seems to be relatively negligible in trivial local tests and it's
// "more correct" WRT to the API.
BatchWriter writer = writers.get(table);
if (null == writer) {
BatchWriter newWriter = createBatchWriter(table);
BatchWriter oldWriter = writers.putIfAbsent(table, newWriter);
// Someone beat us to creating a BatchWriter for this table, use their BatchWriters
if (null != oldWriter) {
try {
// Make sure to clean up our new batchwriter!
newWriter.close();
} catch (MutationsRejectedException e) {
throw new RuntimeException(e);
}
writer = oldWriter;
} else {
writer = newWriter;
}
}
return writer;
}
/**
* Creates a BatchWriter with the expected configuration.
*
* @param table The table to write to
*/
private BatchWriter createBatchWriter(String table) throws TableNotFoundException {
BatchWriterConfig bwc = new BatchWriterConfig();
bwc.setMaxLatency(
Long.parseLong(getProperties()
.getProperty("accumulo.batchWriterMaxLatency", "30000")),
TimeUnit.MILLISECONDS);
bwc.setMaxMemory(Long.parseLong(
getProperties().getProperty("accumulo.batchWriterSize", "100000")));
final String numThreadsValue = getProperties().getProperty("accumulo.batchWriterThreads");
// Try to saturate the client machine.
int numThreads = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
if (null != numThreadsValue) {
numThreads = Integer.parseInt(numThreadsValue);
}
System.err.println("Using " + numThreads + " threads to write data");
bwc.setMaxWriteThreads(numThreads);
return connector.createBatchWriter(table, bwc);
}
/**
* Gets a scanner from Accumulo over one row.
*
* @param row the row to scan
* @param fields the set of columns to scan
* @return an Accumulo {@link Scanner} bound to the given row and columns
*/
private Scanner getRow(String table, Text row, Set<String> fields) throws TableNotFoundException {
Scanner scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(row));
if (fields != null) {
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
return scanner;
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Scanner scanner = null;
try {
scanner = getRow(table, new Text(key), null);
// Pick out the results we care about.
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
entry.getKey().getColumnQualifier(cq);
Value v = entry.getValue();
byte[] buf = v.get();
result.put(cq.toString(),
new ByteArrayByteIterator(buf));
}
} catch (Exception e) {
System.err.println("Error trying to reading Accumulo table " + table + " " + key);
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Just make the end 'infinity' and only read as much as we need.
Scanner scanner = null;
try {
scanner = connector.createScanner(table, Authorizations.EMPTY);
scanner.setRange(new Range(new Text(startkey), null));
// Have Accumulo send us complete rows, serialized in a single Key-Value pair
IteratorSetting cfg = new IteratorSetting(100, WholeRowIterator.class);
scanner.addScanIterator(cfg);
// If no fields are provided, we assume one column/row.
if (fields != null) {
// And add each of them as fields we want.
for (String field : fields) {
scanner.fetchColumn(colFam, new Text(field));
}
}
int count = 0;
for (Entry<Key, Value> entry : scanner) {
// Deserialize the row
SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
HashMap<String, ByteIterator> rowData;
if (null != fields) {
rowData = new HashMap<>(fields.size());
} else {
rowData = new HashMap<>();
}
result.add(rowData);
// Parse the data in the row, avoid unnecessary Text object creation
final Text cq = new Text();
for (Entry<Key, Value> rowEntry : row.entrySet()) {
rowEntry.getKey().getColumnQualifier(cq);
rowData.put(cq.toString(), new ByteArrayByteIterator(rowEntry.getValue().get()));
}
if (count++ == recordcount) { // Done reading the last row.
break;
}
}
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
} catch (IOException e) {
System.err.println("Error deserializing data from Accumulo.");
e.printStackTrace();
return Status.ERROR;
} finally {
if (null != scanner) {
scanner.close();
}
}
return Status.OK;
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
BatchWriter bw = null;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error opening batch writer to Accumulo table " + table);
e.printStackTrace();
return Status.ERROR;
}
Mutation mutInsert = new Mutation(key.getBytes(UTF_8));
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
mutInsert.put(colFamBytes, entry.getKey().getBytes(UTF_8), entry.getValue().toArray());
}
try {
bw.addMutation(mutInsert);
} catch (MutationsRejectedException e) {
System.err.println("Error performing update.");
e.printStackTrace();
return Status.ERROR;
}
return Status.BATCHED_OK;
}
@Override
public Status insert(String t, String key,
Map<String, ByteIterator> values) {
return update(t, key, values);
}
@Override
public Status delete(String table, String key) {
BatchWriter bw;
try {
bw = getWriter(table);
} catch (TableNotFoundException e) {
System.err.println("Error trying to connect to Accumulo table.");
e.printStackTrace();
return Status.ERROR;
}
try {
deleteRow(table, new Text(key), bw);
} catch (TableNotFoundException | MutationsRejectedException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
} catch (RuntimeException e) {
System.err.println("Error performing delete.");
e.printStackTrace();
return Status.ERROR;
}
return Status.OK;
}
// These functions are adapted from RowOperations.java:
private void deleteRow(String table, Text row, BatchWriter bw) throws MutationsRejectedException,
TableNotFoundException {
// TODO Use a batchDeleter instead
deleteRow(getRow(table, row, null), bw);
}
/**
* Deletes a row, given a Scanner of JUST that row.
*/
private void deleteRow(Scanner scanner, BatchWriter bw) throws MutationsRejectedException {<FILL_FUNCTION_BODY>}
} |
Mutation deleter = null;
// iterate through the keys
final Text row = new Text();
final Text cf = new Text();
final Text cq = new Text();
for (Entry<Key, Value> entry : scanner) {
// create a mutation for the row
if (deleter == null) {
entry.getKey().getRow(row);
deleter = new Mutation(row);
}
entry.getKey().getColumnFamily(cf);
entry.getKey().getColumnQualifier(cq);
// the remove function adds the key with the delete flag set to true
deleter.putDelete(cf, cq);
}
bw.addMutation(deleter);
|
brianfrankcooper_YCSB | YCSB/aerospike/src/main/java/site/ycsb/db/AerospikeClient.java | AerospikeClient | init | class AerospikeClient extends site.ycsb.DB {
private static final String DEFAULT_HOST = "localhost";
private static final String DEFAULT_PORT = "3000";
private static final String DEFAULT_TIMEOUT = "10000";
private static final String DEFAULT_NAMESPACE = "ycsb";
private String namespace = null;
private com.aerospike.client.AerospikeClient client = null;
private Policy readPolicy = new Policy();
private WritePolicy insertPolicy = new WritePolicy();
private WritePolicy updatePolicy = new WritePolicy();
private WritePolicy deletePolicy = new WritePolicy();
@Override
public void init() throws DBException {<FILL_FUNCTION_BODY>}
@Override
public void cleanup() throws DBException {
client.close();
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
Record record;
if (fields != null) {
record = client.get(readPolicy, new Key(namespace, table, key),
fields.toArray(new String[fields.size()]));
} else {
record = client.get(readPolicy, new Key(namespace, table, key));
}
if (record == null) {
System.err.println("Record key " + key + " not found (read)");
return Status.ERROR;
}
for (Map.Entry<String, Object> entry: record.bins.entrySet()) {
result.put(entry.getKey(),
new ByteArrayByteIterator((byte[])entry.getValue()));
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while reading key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status scan(String table, String start, int count, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
System.err.println("Scan not implemented");
return Status.ERROR;
}
private Status write(String table, String key, WritePolicy writePolicy,
Map<String, ByteIterator> values) {
Bin[] bins = new Bin[values.size()];
int index = 0;
for (Map.Entry<String, ByteIterator> entry: values.entrySet()) {
bins[index] = new Bin(entry.getKey(), entry.getValue().toArray());
++index;
}
Key keyObj = new Key(namespace, table, key);
try {
client.put(writePolicy, keyObj, bins);
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while writing key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, updatePolicy, values);
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, insertPolicy, values);
}
@Override
public Status delete(String table, String key) {
try {
if (!client.delete(deletePolicy, new Key(namespace, table, key))) {
System.err.println("Record key " + key + " not found (delete)");
return Status.ERROR;
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while deleting key " + key + ": " + e);
return Status.ERROR;
}
}
} |
insertPolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;
updatePolicy.recordExistsAction = RecordExistsAction.REPLACE_ONLY;
Properties props = getProperties();
namespace = props.getProperty("as.namespace", DEFAULT_NAMESPACE);
String host = props.getProperty("as.host", DEFAULT_HOST);
String user = props.getProperty("as.user");
String password = props.getProperty("as.password");
int port = Integer.parseInt(props.getProperty("as.port", DEFAULT_PORT));
int timeout = Integer.parseInt(props.getProperty("as.timeout",
DEFAULT_TIMEOUT));
readPolicy.timeout = timeout;
insertPolicy.timeout = timeout;
updatePolicy.timeout = timeout;
deletePolicy.timeout = timeout;
ClientPolicy clientPolicy = new ClientPolicy();
if (user != null && password != null) {
clientPolicy.user = user;
clientPolicy.password = password;
}
try {
client =
new com.aerospike.client.AerospikeClient(clientPolicy, host, port);
} catch (AerospikeException e) {
throw new DBException(String.format("Error while creating Aerospike " +
"client for %s:%d.", host, port), e);
}
|
brianfrankcooper_YCSB | YCSB/aerospike/src/main/java/site/ycsb/db/AerospikeClient.java | AerospikeClient | cleanup | class AerospikeClient extends site.ycsb.DB {
private static final String DEFAULT_HOST = "localhost";
private static final String DEFAULT_PORT = "3000";
private static final String DEFAULT_TIMEOUT = "10000";
private static final String DEFAULT_NAMESPACE = "ycsb";
private String namespace = null;
private com.aerospike.client.AerospikeClient client = null;
private Policy readPolicy = new Policy();
private WritePolicy insertPolicy = new WritePolicy();
private WritePolicy updatePolicy = new WritePolicy();
private WritePolicy deletePolicy = new WritePolicy();
@Override
public void init() throws DBException {
insertPolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;
updatePolicy.recordExistsAction = RecordExistsAction.REPLACE_ONLY;
Properties props = getProperties();
namespace = props.getProperty("as.namespace", DEFAULT_NAMESPACE);
String host = props.getProperty("as.host", DEFAULT_HOST);
String user = props.getProperty("as.user");
String password = props.getProperty("as.password");
int port = Integer.parseInt(props.getProperty("as.port", DEFAULT_PORT));
int timeout = Integer.parseInt(props.getProperty("as.timeout",
DEFAULT_TIMEOUT));
readPolicy.timeout = timeout;
insertPolicy.timeout = timeout;
updatePolicy.timeout = timeout;
deletePolicy.timeout = timeout;
ClientPolicy clientPolicy = new ClientPolicy();
if (user != null && password != null) {
clientPolicy.user = user;
clientPolicy.password = password;
}
try {
client =
new com.aerospike.client.AerospikeClient(clientPolicy, host, port);
} catch (AerospikeException e) {
throw new DBException(String.format("Error while creating Aerospike " +
"client for %s:%d.", host, port), e);
}
}
@Override
public void cleanup() throws DBException {<FILL_FUNCTION_BODY>}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
Record record;
if (fields != null) {
record = client.get(readPolicy, new Key(namespace, table, key),
fields.toArray(new String[fields.size()]));
} else {
record = client.get(readPolicy, new Key(namespace, table, key));
}
if (record == null) {
System.err.println("Record key " + key + " not found (read)");
return Status.ERROR;
}
for (Map.Entry<String, Object> entry: record.bins.entrySet()) {
result.put(entry.getKey(),
new ByteArrayByteIterator((byte[])entry.getValue()));
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while reading key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status scan(String table, String start, int count, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
System.err.println("Scan not implemented");
return Status.ERROR;
}
private Status write(String table, String key, WritePolicy writePolicy,
Map<String, ByteIterator> values) {
Bin[] bins = new Bin[values.size()];
int index = 0;
for (Map.Entry<String, ByteIterator> entry: values.entrySet()) {
bins[index] = new Bin(entry.getKey(), entry.getValue().toArray());
++index;
}
Key keyObj = new Key(namespace, table, key);
try {
client.put(writePolicy, keyObj, bins);
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while writing key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, updatePolicy, values);
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, insertPolicy, values);
}
@Override
public Status delete(String table, String key) {
try {
if (!client.delete(deletePolicy, new Key(namespace, table, key))) {
System.err.println("Record key " + key + " not found (delete)");
return Status.ERROR;
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while deleting key " + key + ": " + e);
return Status.ERROR;
}
}
} |
client.close();
|
brianfrankcooper_YCSB | YCSB/aerospike/src/main/java/site/ycsb/db/AerospikeClient.java | AerospikeClient | read | class AerospikeClient extends site.ycsb.DB {
private static final String DEFAULT_HOST = "localhost";
private static final String DEFAULT_PORT = "3000";
private static final String DEFAULT_TIMEOUT = "10000";
private static final String DEFAULT_NAMESPACE = "ycsb";
private String namespace = null;
private com.aerospike.client.AerospikeClient client = null;
private Policy readPolicy = new Policy();
private WritePolicy insertPolicy = new WritePolicy();
private WritePolicy updatePolicy = new WritePolicy();
private WritePolicy deletePolicy = new WritePolicy();
@Override
public void init() throws DBException {
insertPolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;
updatePolicy.recordExistsAction = RecordExistsAction.REPLACE_ONLY;
Properties props = getProperties();
namespace = props.getProperty("as.namespace", DEFAULT_NAMESPACE);
String host = props.getProperty("as.host", DEFAULT_HOST);
String user = props.getProperty("as.user");
String password = props.getProperty("as.password");
int port = Integer.parseInt(props.getProperty("as.port", DEFAULT_PORT));
int timeout = Integer.parseInt(props.getProperty("as.timeout",
DEFAULT_TIMEOUT));
readPolicy.timeout = timeout;
insertPolicy.timeout = timeout;
updatePolicy.timeout = timeout;
deletePolicy.timeout = timeout;
ClientPolicy clientPolicy = new ClientPolicy();
if (user != null && password != null) {
clientPolicy.user = user;
clientPolicy.password = password;
}
try {
client =
new com.aerospike.client.AerospikeClient(clientPolicy, host, port);
} catch (AerospikeException e) {
throw new DBException(String.format("Error while creating Aerospike " +
"client for %s:%d.", host, port), e);
}
}
@Override
public void cleanup() throws DBException {
client.close();
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {<FILL_FUNCTION_BODY>}
@Override
public Status scan(String table, String start, int count, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
System.err.println("Scan not implemented");
return Status.ERROR;
}
private Status write(String table, String key, WritePolicy writePolicy,
Map<String, ByteIterator> values) {
Bin[] bins = new Bin[values.size()];
int index = 0;
for (Map.Entry<String, ByteIterator> entry: values.entrySet()) {
bins[index] = new Bin(entry.getKey(), entry.getValue().toArray());
++index;
}
Key keyObj = new Key(namespace, table, key);
try {
client.put(writePolicy, keyObj, bins);
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while writing key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, updatePolicy, values);
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, insertPolicy, values);
}
@Override
public Status delete(String table, String key) {
try {
if (!client.delete(deletePolicy, new Key(namespace, table, key))) {
System.err.println("Record key " + key + " not found (delete)");
return Status.ERROR;
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while deleting key " + key + ": " + e);
return Status.ERROR;
}
}
} |
try {
Record record;
if (fields != null) {
record = client.get(readPolicy, new Key(namespace, table, key),
fields.toArray(new String[fields.size()]));
} else {
record = client.get(readPolicy, new Key(namespace, table, key));
}
if (record == null) {
System.err.println("Record key " + key + " not found (read)");
return Status.ERROR;
}
for (Map.Entry<String, Object> entry: record.bins.entrySet()) {
result.put(entry.getKey(),
new ByteArrayByteIterator((byte[])entry.getValue()));
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while reading key " + key + ": " + e);
return Status.ERROR;
}
|
brianfrankcooper_YCSB | YCSB/aerospike/src/main/java/site/ycsb/db/AerospikeClient.java | AerospikeClient | scan | class AerospikeClient extends site.ycsb.DB {
private static final String DEFAULT_HOST = "localhost";
private static final String DEFAULT_PORT = "3000";
private static final String DEFAULT_TIMEOUT = "10000";
private static final String DEFAULT_NAMESPACE = "ycsb";
private String namespace = null;
private com.aerospike.client.AerospikeClient client = null;
private Policy readPolicy = new Policy();
private WritePolicy insertPolicy = new WritePolicy();
private WritePolicy updatePolicy = new WritePolicy();
private WritePolicy deletePolicy = new WritePolicy();
@Override
public void init() throws DBException {
insertPolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;
updatePolicy.recordExistsAction = RecordExistsAction.REPLACE_ONLY;
Properties props = getProperties();
namespace = props.getProperty("as.namespace", DEFAULT_NAMESPACE);
String host = props.getProperty("as.host", DEFAULT_HOST);
String user = props.getProperty("as.user");
String password = props.getProperty("as.password");
int port = Integer.parseInt(props.getProperty("as.port", DEFAULT_PORT));
int timeout = Integer.parseInt(props.getProperty("as.timeout",
DEFAULT_TIMEOUT));
readPolicy.timeout = timeout;
insertPolicy.timeout = timeout;
updatePolicy.timeout = timeout;
deletePolicy.timeout = timeout;
ClientPolicy clientPolicy = new ClientPolicy();
if (user != null && password != null) {
clientPolicy.user = user;
clientPolicy.password = password;
}
try {
client =
new com.aerospike.client.AerospikeClient(clientPolicy, host, port);
} catch (AerospikeException e) {
throw new DBException(String.format("Error while creating Aerospike " +
"client for %s:%d.", host, port), e);
}
}
@Override
public void cleanup() throws DBException {
client.close();
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
Record record;
if (fields != null) {
record = client.get(readPolicy, new Key(namespace, table, key),
fields.toArray(new String[fields.size()]));
} else {
record = client.get(readPolicy, new Key(namespace, table, key));
}
if (record == null) {
System.err.println("Record key " + key + " not found (read)");
return Status.ERROR;
}
for (Map.Entry<String, Object> entry: record.bins.entrySet()) {
result.put(entry.getKey(),
new ByteArrayByteIterator((byte[])entry.getValue()));
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while reading key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status scan(String table, String start, int count, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {<FILL_FUNCTION_BODY>}
private Status write(String table, String key, WritePolicy writePolicy,
Map<String, ByteIterator> values) {
Bin[] bins = new Bin[values.size()];
int index = 0;
for (Map.Entry<String, ByteIterator> entry: values.entrySet()) {
bins[index] = new Bin(entry.getKey(), entry.getValue().toArray());
++index;
}
Key keyObj = new Key(namespace, table, key);
try {
client.put(writePolicy, keyObj, bins);
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while writing key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, updatePolicy, values);
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, insertPolicy, values);
}
@Override
public Status delete(String table, String key) {
try {
if (!client.delete(deletePolicy, new Key(namespace, table, key))) {
System.err.println("Record key " + key + " not found (delete)");
return Status.ERROR;
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while deleting key " + key + ": " + e);
return Status.ERROR;
}
}
} |
System.err.println("Scan not implemented");
return Status.ERROR;
|
brianfrankcooper_YCSB | YCSB/aerospike/src/main/java/site/ycsb/db/AerospikeClient.java | AerospikeClient | write | class AerospikeClient extends site.ycsb.DB {
private static final String DEFAULT_HOST = "localhost";
private static final String DEFAULT_PORT = "3000";
private static final String DEFAULT_TIMEOUT = "10000";
private static final String DEFAULT_NAMESPACE = "ycsb";
private String namespace = null;
private com.aerospike.client.AerospikeClient client = null;
private Policy readPolicy = new Policy();
private WritePolicy insertPolicy = new WritePolicy();
private WritePolicy updatePolicy = new WritePolicy();
private WritePolicy deletePolicy = new WritePolicy();
@Override
public void init() throws DBException {
insertPolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;
updatePolicy.recordExistsAction = RecordExistsAction.REPLACE_ONLY;
Properties props = getProperties();
namespace = props.getProperty("as.namespace", DEFAULT_NAMESPACE);
String host = props.getProperty("as.host", DEFAULT_HOST);
String user = props.getProperty("as.user");
String password = props.getProperty("as.password");
int port = Integer.parseInt(props.getProperty("as.port", DEFAULT_PORT));
int timeout = Integer.parseInt(props.getProperty("as.timeout",
DEFAULT_TIMEOUT));
readPolicy.timeout = timeout;
insertPolicy.timeout = timeout;
updatePolicy.timeout = timeout;
deletePolicy.timeout = timeout;
ClientPolicy clientPolicy = new ClientPolicy();
if (user != null && password != null) {
clientPolicy.user = user;
clientPolicy.password = password;
}
try {
client =
new com.aerospike.client.AerospikeClient(clientPolicy, host, port);
} catch (AerospikeException e) {
throw new DBException(String.format("Error while creating Aerospike " +
"client for %s:%d.", host, port), e);
}
}
@Override
public void cleanup() throws DBException {
client.close();
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
Record record;
if (fields != null) {
record = client.get(readPolicy, new Key(namespace, table, key),
fields.toArray(new String[fields.size()]));
} else {
record = client.get(readPolicy, new Key(namespace, table, key));
}
if (record == null) {
System.err.println("Record key " + key + " not found (read)");
return Status.ERROR;
}
for (Map.Entry<String, Object> entry: record.bins.entrySet()) {
result.put(entry.getKey(),
new ByteArrayByteIterator((byte[])entry.getValue()));
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while reading key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status scan(String table, String start, int count, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
System.err.println("Scan not implemented");
return Status.ERROR;
}
private Status write(String table, String key, WritePolicy writePolicy,
Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, updatePolicy, values);
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, insertPolicy, values);
}
@Override
public Status delete(String table, String key) {
try {
if (!client.delete(deletePolicy, new Key(namespace, table, key))) {
System.err.println("Record key " + key + " not found (delete)");
return Status.ERROR;
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while deleting key " + key + ": " + e);
return Status.ERROR;
}
}
} |
Bin[] bins = new Bin[values.size()];
int index = 0;
for (Map.Entry<String, ByteIterator> entry: values.entrySet()) {
bins[index] = new Bin(entry.getKey(), entry.getValue().toArray());
++index;
}
Key keyObj = new Key(namespace, table, key);
try {
client.put(writePolicy, keyObj, bins);
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while writing key " + key + ": " + e);
return Status.ERROR;
}
|
brianfrankcooper_YCSB | YCSB/aerospike/src/main/java/site/ycsb/db/AerospikeClient.java | AerospikeClient | update | class AerospikeClient extends site.ycsb.DB {
private static final String DEFAULT_HOST = "localhost";
private static final String DEFAULT_PORT = "3000";
private static final String DEFAULT_TIMEOUT = "10000";
private static final String DEFAULT_NAMESPACE = "ycsb";
private String namespace = null;
private com.aerospike.client.AerospikeClient client = null;
private Policy readPolicy = new Policy();
private WritePolicy insertPolicy = new WritePolicy();
private WritePolicy updatePolicy = new WritePolicy();
private WritePolicy deletePolicy = new WritePolicy();
@Override
public void init() throws DBException {
insertPolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;
updatePolicy.recordExistsAction = RecordExistsAction.REPLACE_ONLY;
Properties props = getProperties();
namespace = props.getProperty("as.namespace", DEFAULT_NAMESPACE);
String host = props.getProperty("as.host", DEFAULT_HOST);
String user = props.getProperty("as.user");
String password = props.getProperty("as.password");
int port = Integer.parseInt(props.getProperty("as.port", DEFAULT_PORT));
int timeout = Integer.parseInt(props.getProperty("as.timeout",
DEFAULT_TIMEOUT));
readPolicy.timeout = timeout;
insertPolicy.timeout = timeout;
updatePolicy.timeout = timeout;
deletePolicy.timeout = timeout;
ClientPolicy clientPolicy = new ClientPolicy();
if (user != null && password != null) {
clientPolicy.user = user;
clientPolicy.password = password;
}
try {
client =
new com.aerospike.client.AerospikeClient(clientPolicy, host, port);
} catch (AerospikeException e) {
throw new DBException(String.format("Error while creating Aerospike " +
"client for %s:%d.", host, port), e);
}
}
@Override
public void cleanup() throws DBException {
client.close();
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
Record record;
if (fields != null) {
record = client.get(readPolicy, new Key(namespace, table, key),
fields.toArray(new String[fields.size()]));
} else {
record = client.get(readPolicy, new Key(namespace, table, key));
}
if (record == null) {
System.err.println("Record key " + key + " not found (read)");
return Status.ERROR;
}
for (Map.Entry<String, Object> entry: record.bins.entrySet()) {
result.put(entry.getKey(),
new ByteArrayByteIterator((byte[])entry.getValue()));
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while reading key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status scan(String table, String start, int count, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
System.err.println("Scan not implemented");
return Status.ERROR;
}
private Status write(String table, String key, WritePolicy writePolicy,
Map<String, ByteIterator> values) {
Bin[] bins = new Bin[values.size()];
int index = 0;
for (Map.Entry<String, ByteIterator> entry: values.entrySet()) {
bins[index] = new Bin(entry.getKey(), entry.getValue().toArray());
++index;
}
Key keyObj = new Key(namespace, table, key);
try {
client.put(writePolicy, keyObj, bins);
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while writing key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, insertPolicy, values);
}
@Override
public Status delete(String table, String key) {
try {
if (!client.delete(deletePolicy, new Key(namespace, table, key))) {
System.err.println("Record key " + key + " not found (delete)");
return Status.ERROR;
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while deleting key " + key + ": " + e);
return Status.ERROR;
}
}
} |
return write(table, key, updatePolicy, values);
|
brianfrankcooper_YCSB | YCSB/aerospike/src/main/java/site/ycsb/db/AerospikeClient.java | AerospikeClient | insert | class AerospikeClient extends site.ycsb.DB {
private static final String DEFAULT_HOST = "localhost";
private static final String DEFAULT_PORT = "3000";
private static final String DEFAULT_TIMEOUT = "10000";
private static final String DEFAULT_NAMESPACE = "ycsb";
private String namespace = null;
private com.aerospike.client.AerospikeClient client = null;
private Policy readPolicy = new Policy();
private WritePolicy insertPolicy = new WritePolicy();
private WritePolicy updatePolicy = new WritePolicy();
private WritePolicy deletePolicy = new WritePolicy();
@Override
public void init() throws DBException {
insertPolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;
updatePolicy.recordExistsAction = RecordExistsAction.REPLACE_ONLY;
Properties props = getProperties();
namespace = props.getProperty("as.namespace", DEFAULT_NAMESPACE);
String host = props.getProperty("as.host", DEFAULT_HOST);
String user = props.getProperty("as.user");
String password = props.getProperty("as.password");
int port = Integer.parseInt(props.getProperty("as.port", DEFAULT_PORT));
int timeout = Integer.parseInt(props.getProperty("as.timeout",
DEFAULT_TIMEOUT));
readPolicy.timeout = timeout;
insertPolicy.timeout = timeout;
updatePolicy.timeout = timeout;
deletePolicy.timeout = timeout;
ClientPolicy clientPolicy = new ClientPolicy();
if (user != null && password != null) {
clientPolicy.user = user;
clientPolicy.password = password;
}
try {
client =
new com.aerospike.client.AerospikeClient(clientPolicy, host, port);
} catch (AerospikeException e) {
throw new DBException(String.format("Error while creating Aerospike " +
"client for %s:%d.", host, port), e);
}
}
@Override
public void cleanup() throws DBException {
client.close();
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
Record record;
if (fields != null) {
record = client.get(readPolicy, new Key(namespace, table, key),
fields.toArray(new String[fields.size()]));
} else {
record = client.get(readPolicy, new Key(namespace, table, key));
}
if (record == null) {
System.err.println("Record key " + key + " not found (read)");
return Status.ERROR;
}
for (Map.Entry<String, Object> entry: record.bins.entrySet()) {
result.put(entry.getKey(),
new ByteArrayByteIterator((byte[])entry.getValue()));
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while reading key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status scan(String table, String start, int count, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
System.err.println("Scan not implemented");
return Status.ERROR;
}
private Status write(String table, String key, WritePolicy writePolicy,
Map<String, ByteIterator> values) {
Bin[] bins = new Bin[values.size()];
int index = 0;
for (Map.Entry<String, ByteIterator> entry: values.entrySet()) {
bins[index] = new Bin(entry.getKey(), entry.getValue().toArray());
++index;
}
Key keyObj = new Key(namespace, table, key);
try {
client.put(writePolicy, keyObj, bins);
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while writing key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, updatePolicy, values);
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>}
@Override
public Status delete(String table, String key) {
try {
if (!client.delete(deletePolicy, new Key(namespace, table, key))) {
System.err.println("Record key " + key + " not found (delete)");
return Status.ERROR;
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while deleting key " + key + ": " + e);
return Status.ERROR;
}
}
} |
return write(table, key, insertPolicy, values);
|
brianfrankcooper_YCSB | YCSB/aerospike/src/main/java/site/ycsb/db/AerospikeClient.java | AerospikeClient | delete | class AerospikeClient extends site.ycsb.DB {
private static final String DEFAULT_HOST = "localhost";
private static final String DEFAULT_PORT = "3000";
private static final String DEFAULT_TIMEOUT = "10000";
private static final String DEFAULT_NAMESPACE = "ycsb";
private String namespace = null;
private com.aerospike.client.AerospikeClient client = null;
private Policy readPolicy = new Policy();
private WritePolicy insertPolicy = new WritePolicy();
private WritePolicy updatePolicy = new WritePolicy();
private WritePolicy deletePolicy = new WritePolicy();
@Override
public void init() throws DBException {
insertPolicy.recordExistsAction = RecordExistsAction.CREATE_ONLY;
updatePolicy.recordExistsAction = RecordExistsAction.REPLACE_ONLY;
Properties props = getProperties();
namespace = props.getProperty("as.namespace", DEFAULT_NAMESPACE);
String host = props.getProperty("as.host", DEFAULT_HOST);
String user = props.getProperty("as.user");
String password = props.getProperty("as.password");
int port = Integer.parseInt(props.getProperty("as.port", DEFAULT_PORT));
int timeout = Integer.parseInt(props.getProperty("as.timeout",
DEFAULT_TIMEOUT));
readPolicy.timeout = timeout;
insertPolicy.timeout = timeout;
updatePolicy.timeout = timeout;
deletePolicy.timeout = timeout;
ClientPolicy clientPolicy = new ClientPolicy();
if (user != null && password != null) {
clientPolicy.user = user;
clientPolicy.password = password;
}
try {
client =
new com.aerospike.client.AerospikeClient(clientPolicy, host, port);
} catch (AerospikeException e) {
throw new DBException(String.format("Error while creating Aerospike " +
"client for %s:%d.", host, port), e);
}
}
@Override
public void cleanup() throws DBException {
client.close();
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
try {
Record record;
if (fields != null) {
record = client.get(readPolicy, new Key(namespace, table, key),
fields.toArray(new String[fields.size()]));
} else {
record = client.get(readPolicy, new Key(namespace, table, key));
}
if (record == null) {
System.err.println("Record key " + key + " not found (read)");
return Status.ERROR;
}
for (Map.Entry<String, Object> entry: record.bins.entrySet()) {
result.put(entry.getKey(),
new ByteArrayByteIterator((byte[])entry.getValue()));
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while reading key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status scan(String table, String start, int count, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
System.err.println("Scan not implemented");
return Status.ERROR;
}
private Status write(String table, String key, WritePolicy writePolicy,
Map<String, ByteIterator> values) {
Bin[] bins = new Bin[values.size()];
int index = 0;
for (Map.Entry<String, ByteIterator> entry: values.entrySet()) {
bins[index] = new Bin(entry.getKey(), entry.getValue().toArray());
++index;
}
Key keyObj = new Key(namespace, table, key);
try {
client.put(writePolicy, keyObj, bins);
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while writing key " + key + ": " + e);
return Status.ERROR;
}
}
@Override
public Status update(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, updatePolicy, values);
}
@Override
public Status insert(String table, String key,
Map<String, ByteIterator> values) {
return write(table, key, insertPolicy, values);
}
@Override
public Status delete(String table, String key) {<FILL_FUNCTION_BODY>}
} |
try {
if (!client.delete(deletePolicy, new Key(namespace, table, key))) {
System.err.println("Record key " + key + " not found (delete)");
return Status.ERROR;
}
return Status.OK;
} catch (AerospikeException e) {
System.err.println("Error while deleting key " + key + ": " + e);
return Status.ERROR;
}
|
brianfrankcooper_YCSB | YCSB/arangodb/src/main/java/site/ycsb/db/arangodb/ArangoDBClient.java | ArangoDBClient | init | class ArangoDBClient extends DB {
private static Logger logger = LoggerFactory.getLogger(ArangoDBClient.class);
/**
* Count the number of times initialized to teardown on the last
* {@link #cleanup()}.
*/
private static final AtomicInteger INIT_COUNT = new AtomicInteger(0);
/** ArangoDB Driver related, Singleton. */
private ArangoDB arangoDB;
private String databaseName = "ycsb";
private String collectionName;
private Boolean dropDBBeforeRun;
private Boolean waitForSync = false;
private Boolean transactionUpdate = false;
/**
* Initialize any state for this DB. Called once per DB instance; there is
* one DB instance per client thread.
*
* Actually, one client process will share one DB instance here.(Coincide to
* mongoDB driver)
*/
@Override
public void init() throws DBException {<FILL_FUNCTION_BODY>}
/**
* Cleanup any state for this DB. Called once per DB instance; there is one
* DB instance per client thread.
*
* Actually, one client process will share one DB instance here.(Coincide to
* mongoDB driver)
*/
@Override
public void cleanup() throws DBException {
if (INIT_COUNT.decrementAndGet() == 0) {
arangoDB.shutdown();
arangoDB = null;
logger.info("Local cleaned up.");
}
}
/**
* Insert a record in the database. Any field/value pairs in the specified
* values HashMap will be written into the record with the specified record
* key.
*
* @param table
* The name of the table
* @param key
* The record key of the record to insert.
* @param values
* A HashMap of field/value pairs to insert in the record
* @return Zero on success, a non-zero error code on error. See the
* {@link DB} class's description for a discussion of error codes.
*/
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
try {
BaseDocument toInsert = new BaseDocument(key);
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
toInsert.addAttribute(entry.getKey(), byteIteratorToString(entry.getValue()));
}
DocumentCreateOptions options = new DocumentCreateOptions().waitForSync(waitForSync);
arangoDB.db(databaseName).collection(table).insertDocument(toInsert, options);
return Status.OK;
} catch (ArangoDBException e) {
logger.error("Exception while trying insert {} {} with ex {}", table, key, e.toString());
}
return Status.ERROR;
}
/**
* Read a record from the database. Each field/value pair from the result
* will be stored in a HashMap.
*
* @param table
* The name of the table
* @param key
* The record key of the record to read.
* @param fields
* The list of fields to read, or null for all of them
* @param result
* A HashMap of field/value pairs for the result
* @return Zero on success, a non-zero error code on error or "not found".
*/
@Override
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {
try {
VPackSlice document = arangoDB.db(databaseName).collection(table).getDocument(key, VPackSlice.class, null);
if (!this.fillMap(result, document, fields)) {
return Status.ERROR;
}
return Status.OK;
} catch (ArangoDBException e) {
logger.error("Exception while trying read {} {} with ex {}", table, key, e.toString());
}
return Status.ERROR;
}
/**
* Update a record in the database. Any field/value pairs in the specified
* values HashMap will be written into the record with the specified record
* key, overwriting any existing values with the same field name.
*
* @param table
* The name of the table
* @param key
* The record key of the record to write.
* @param values
* A HashMap of field/value pairs to update in the record
* @return Zero on success, a non-zero error code on error. See this class's
* description for a discussion of error codes.
*/
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
try {
if (!transactionUpdate) {
BaseDocument updateDoc = new BaseDocument();
for (Entry<String, ByteIterator> field : values.entrySet()) {
updateDoc.addAttribute(field.getKey(), byteIteratorToString(field.getValue()));
}
arangoDB.db(databaseName).collection(table).updateDocument(key, updateDoc);
return Status.OK;
} else {
// id for documentHandle
String transactionAction = "function (id) {"
// use internal database functions
+ "var db = require('internal').db;"
// collection.update(document, data, overwrite, keepNull, waitForSync)
+ String.format("db._update(id, %s, true, false, %s);}",
mapToJson(values), Boolean.toString(waitForSync).toLowerCase());
TransactionOptions options = new TransactionOptions();
options.writeCollections(table);
options.params(createDocumentHandle(table, key));
arangoDB.db(databaseName).transaction(transactionAction, Void.class, options);
return Status.OK;
}
} catch (ArangoDBException e) {
logger.error("Exception while trying update {} {} with ex {}", table, key, e.toString());
}
return Status.ERROR;
}
/**
* Delete a record from the database.
*
* @param table
* The name of the table
* @param key
* The record key of the record to delete.
* @return Zero on success, a non-zero error code on error. See the
* {@link DB} class's description for a discussion of error codes.
*/
@Override
public Status delete(String table, String key) {
try {
arangoDB.db(databaseName).collection(table).deleteDocument(key);
return Status.OK;
} catch (ArangoDBException e) {
logger.error("Exception while trying delete {} {} with ex {}", table, key, e.toString());
}
return Status.ERROR;
}
/**
* Perform a range scan for a set of records in the database. Each
* field/value pair from the result will be stored in a HashMap.
*
* @param table
* The name of the table
* @param startkey
* The record key of the first record to read.
* @param recordcount
* The number of records to read
* @param fields
* The list of fields to read, or null for all of them
* @param result
* A Vector of HashMaps, where each HashMap is a set field/value
* pairs for one record
* @return Zero on success, a non-zero error code on error. See the
* {@link DB} class's description for a discussion of error codes.
*/
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
ArangoCursor<VPackSlice> cursor = null;
try {
String aqlQuery = String.format(
"FOR target IN %s FILTER target._key >= @key SORT target._key ASC LIMIT %d RETURN %s ", table,
recordcount, constructReturnForAQL(fields, "target"));
Map<String, Object> bindVars = new MapBuilder().put("key", startkey).get();
cursor = arangoDB.db(databaseName).query(aqlQuery, bindVars, null, VPackSlice.class);
while (cursor.hasNext()) {
VPackSlice aDocument = cursor.next();
HashMap<String, ByteIterator> aMap = new HashMap<String, ByteIterator>(aDocument.size());
if (!this.fillMap(aMap, aDocument)) {
return Status.ERROR;
}
result.add(aMap);
}
return Status.OK;
} catch (Exception e) {
logger.error("Exception while trying scan {} {} {} with ex {}", table, startkey, recordcount, e.toString());
} finally {
if (cursor != null) {
try {
cursor.close();
} catch (IOException e) {
logger.error("Fail to close cursor", e);
}
}
}
return Status.ERROR;
}
private String createDocumentHandle(String collection, String documentKey) throws ArangoDBException {
validateCollectionName(collection);
return collection + "/" + documentKey;
}
private void validateCollectionName(String name) throws ArangoDBException {
if (name.indexOf('/') != -1) {
throw new ArangoDBException("does not allow '/' in name.");
}
}
private String constructReturnForAQL(Set<String> fields, String targetName) {
// Construct the AQL query string.
String resultDes = targetName;
if (fields != null && fields.size() != 0) {
StringBuilder builder = new StringBuilder("{");
for (String field : fields) {
builder.append(String.format("\n\"%s\" : %s.%s,", field, targetName, field));
}
//Replace last ',' to newline.
builder.setCharAt(builder.length() - 1, '\n');
builder.append("}");
resultDes = builder.toString();
}
return resultDes;
}
private boolean fillMap(Map<String, ByteIterator> resultMap, VPackSlice document) {
return fillMap(resultMap, document, null);
}
/**
* Fills the map with the properties from the BaseDocument.
*
* @param resultMap
* The map to fill/
* @param document
* The record to read from
* @param fields
* The list of fields to read, or null for all of them
* @return isSuccess
*/
private boolean fillMap(Map<String, ByteIterator> resultMap, VPackSlice document, Set<String> fields) {
if (fields == null || fields.size() == 0) {
for (Iterator<Entry<String, VPackSlice>> iterator = document.objectIterator(); iterator.hasNext();) {
Entry<String, VPackSlice> next = iterator.next();
VPackSlice value = next.getValue();
if (value.isString()) {
resultMap.put(next.getKey(), stringToByteIterator(value.getAsString()));
} else if (!value.isCustom()) {
logger.error("Error! Not the format expected! Actually is {}",
value.getClass().getName());
return false;
}
}
} else {
for (String field : fields) {
VPackSlice value = document.get(field);
if (value.isString()) {
resultMap.put(field, stringToByteIterator(value.getAsString()));
} else if (!value.isCustom()) {
logger.error("Error! Not the format expected! Actually is {}",
value.getClass().getName());
return false;
}
}
}
return true;
}
private String byteIteratorToString(ByteIterator byteIter) {
return new String(byteIter.toArray());
}
private ByteIterator stringToByteIterator(String content) {
return new StringByteIterator(content);
}
private String mapToJson(Map<String, ByteIterator> values) {
VPackBuilder builder = new VPackBuilder().add(ValueType.OBJECT);
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
builder.add(entry.getKey(), byteIteratorToString(entry.getValue()));
}
builder.close();
return arangoDB.util().deserialize(builder.slice(), String.class);
}
} |
synchronized (ArangoDBClient.class) {
Properties props = getProperties();
collectionName = props.getProperty("table", "usertable");
// Set the DB address
String ip = props.getProperty("arangodb.ip", "localhost");
String portStr = props.getProperty("arangodb.port", "8529");
int port = Integer.parseInt(portStr);
// Set network protocol
String protocolStr = props.getProperty("arangodb.protocol", "VST");
Protocol protocol = Protocol.valueOf(protocolStr);
// If clear db before run
String dropDBBeforeRunStr = props.getProperty("arangodb.dropDBBeforeRun", "false");
dropDBBeforeRun = Boolean.parseBoolean(dropDBBeforeRunStr);
// Set the sync mode
String waitForSyncStr = props.getProperty("arangodb.waitForSync", "false");
waitForSync = Boolean.parseBoolean(waitForSyncStr);
// Set if transaction for update
String transactionUpdateStr = props.getProperty("arangodb.transactionUpdate", "false");
transactionUpdate = Boolean.parseBoolean(transactionUpdateStr);
// Init ArangoDB connection
try {
arangoDB = new ArangoDB.Builder().host(ip).port(port).useProtocol(protocol).build();
} catch (Exception e) {
logger.error("Failed to initialize ArangoDB", e);
System.exit(-1);
}
if(INIT_COUNT.getAndIncrement() == 0) {
// Init the database
if (dropDBBeforeRun) {
// Try delete first
try {
arangoDB.db(databaseName).drop();
} catch (ArangoDBException e) {
logger.info("Fail to delete DB: {}", databaseName);
}
}
try {
arangoDB.createDatabase(databaseName);
logger.info("Database created: " + databaseName);
} catch (ArangoDBException e) {
logger.error("Failed to create database: {} with ex: {}", databaseName, e.toString());
}
try {
arangoDB.db(databaseName).createCollection(collectionName);
logger.info("Collection created: " + collectionName);
} catch (ArangoDBException e) {
logger.error("Failed to create collection: {} with ex: {}", collectionName, e.toString());
}
logger.info("ArangoDB client connection created to {}:{}", ip, port);
// Log the configuration
logger.info("Arango Configuration: dropDBBeforeRun: {}; address: {}:{}; databaseName: {};"
+ " waitForSync: {}; transactionUpdate: {};",
dropDBBeforeRun, ip, port, databaseName, waitForSync, transactionUpdate);
}
}
|
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 0