blob: 634df25da6f26fcee258b1f3c8afb2fd0435f50f [file] [log] [blame]
Yuta HIGUCHIa1e655a2014-01-23 17:43:11 -08001/* Copyright (c) 2013 Stanford University
2 *
3 * Permission to use, copy, modify, and distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
10 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 */
15
yoshi28bac132014-01-22 11:00:17 -080016package com.tinkerpop.blueprints.impls.ramcloud;
17
18import java.io.Serializable;
19import java.io.UnsupportedEncodingException;
20import java.nio.ByteBuffer;
21import java.util.ArrayList;
22import java.util.Iterator;
23import java.util.List;
24import java.util.Map;
25import java.util.Set;
26import java.util.TreeMap;
27
28import org.slf4j.Logger;
29import org.slf4j.LoggerFactory;
30
31import com.google.protobuf.InvalidProtocolBufferException;
32import com.tinkerpop.blueprints.CloseableIterable;
33import com.tinkerpop.blueprints.Element;
34import com.tinkerpop.blueprints.Index;
35import com.tinkerpop.blueprints.util.ExceptionFactory;
36import com.tinkerpop.blueprints.impls.ramcloud.PerfMon;
37import com.tinkerpop.blueprints.impls.ramcloud.RamCloudGraphProtos.IndexBlob;
38import com.tinkerpop.blueprints.impls.ramcloud.RamCloudGraphProtos.IndexBlob.Builder;
39
40import edu.stanford.ramcloud.JRamCloud;
41
42// FIXME Index instance should be representing an Index table, not a IndexTable K-V pair
43public class RamCloudIndex<T extends Element> implements Index<T>, Serializable {
44
45 private final static Logger log = LoggerFactory.getLogger(RamCloudGraph.class);
46 protected RamCloudGraph graph;
47 private long tableId;
48 private String indexName;
49 protected byte[] rcKey;
50 private Class<T> indexClass;
51 // FIXME this should not be defined here
52 private long indexVersion;
53
yoshi28bac132014-01-22 11:00:17 -080054 public RamCloudIndex(long tableId, String indexName, Object propValue, RamCloudGraph graph, Class<T> indexClass) {
55 this.tableId = tableId;
56 this.graph = graph;
57 this.rcKey = indexToRcKey(indexName, propValue);
58 this.indexName = indexName;
59 this.indexClass = indexClass;
60 }
61
62 public RamCloudIndex(long tableId, byte[] rcKey, RamCloudGraph graph, Class<T> indexClass) {
63 this.tableId = tableId;
64 this.graph = graph;
65 this.rcKey = rcKey;
66 this.indexName = rcKeyToIndexName(rcKey);
67 this.indexClass = indexClass;
68 }
69
70 public boolean exists() {
71 PerfMon pm = PerfMon.getInstance();
72
73 try {
74 JRamCloud.Object vertTableEntry;
75 JRamCloud vertTable = graph.getRcClient();
76
yoshi28bac132014-01-22 11:00:17 -080077 pm.indexread_start("RamCloudIndex exists()");
78 vertTableEntry = vertTable.read(tableId, rcKey);
79 pm.indexread_end("RamCloudIndex exists()");
80 indexVersion = vertTableEntry.version;
81 return true;
82 } catch (Exception e) {
83 pm.indexread_end("RamCloudIndex exists()");
84 log.debug("IndexTable entry for {} does not exists(): {}@{} [{}]", indexName, new String(rcKey), tableId, this);
85 return false;
86 }
87 }
88
89 public void create() {
90 if (!exists()) {
91 PerfMon pm = PerfMon.getInstance();
92 try {
93 JRamCloud rcClient = graph.getRcClient();
94 JRamCloud.RejectRules rules = rcClient.new RejectRules();
95 rules.setExists();
96
yoshi28bac132014-01-22 11:00:17 -080097 pm.indexwrite_start("RamCloudIndex create()");
98 rcClient.writeRule(tableId, rcKey, ByteBuffer.allocate(0).array(), rules);
99 pm.indexwrite_end("RamCloudIndex create()");
100 } catch (Exception e) {
101 pm.indexwrite_end("RamCloudIndex create()");
102 log.info(toString() + ": Write create index list: ", e);
103 }
104 }
105 }
106
107 public static byte[] indexToRcKey(String key, Object propValue) {
108 try {
109 String s = key + "=" + propValue;
110 return ByteBuffer.allocate(s.getBytes().length).put(s.getBytes("UTF-8")).array();
111 } catch (UnsupportedEncodingException ex) {
112 log.error("indexToRcKey({}, {}) failed with exception {}", key, propValue, ex);
113 }
114 return null;
115 }
116
117 public static String rcKeyToIndexName(byte[] rcKey) {
118 try {
119 String s = new String(rcKey, "UTF-8");
120 return s.substring(0, s.indexOf('='));
121 } catch (UnsupportedEncodingException ex) {
122 log.error("rcKeyToIndexName({}) failed with exception {}", rcKey, ex);
123 }
124 return null;
125 }
126 public static String rcKeyToPropName(byte[] rcKey) {
127 try {
128 String s = new String(rcKey, "UTF-8");
129 return s.substring(s.indexOf('=')+1);
130 } catch (UnsupportedEncodingException ex) {
131 log.error("rcKeyToPropName({}) failed with exception {}", rcKey, ex);
132 }
133 return null;
134 }
135
136 @Override
137 public String getIndexName() {
138 return this.indexName;
139 }
140
141 @Override
142 public Class<T> getIndexClass() {
143 return this.indexClass;
144 }
145
146 @Override
147 public void put(String key, Object value, T element) {
148 getSetProperty(key, value, element.getId());
149 }
150
151 public void getSetProperty(String key, Object propValue, Object elmId) {
152 if (elmId == null) {
153 // FIXME Throw appropriate Exception
154 log.error("Element Id cannot be null");
155 return;
156 //throw ExceptionFactory.vertexIdCanNotBeNull();
157 //throw ExceptionFactory.edgeIdCanNotBeNull();
158 }
159
160 long startTime = 0;
161 if (graph.measureBPTimeProp == 1) {
162 startTime = System.nanoTime();
163 }
164
165 create();
166
Yoshi Muroi815c7f92014-01-30 18:06:16 -0800167 for (int i = 0; i < graph.CONDITIONALWRITE_RETRY_MAX; i++) {
yoshi28bac132014-01-22 11:00:17 -0800168 Map<Object, List<Object>> map = readIndexPropertyMapFromDB();
169 List<Object> values = map.get(propValue);
170 if (values == null) {
171 values = new ArrayList<Object>();
172 map.put(propValue, values);
173 }
174 if (!values.contains(elmId)) {
175 values.add(elmId);
176 }
177
yoshi28bac132014-01-22 11:00:17 -0800178 byte[] rcValue = convertIndexPropertyMapToRcBytes(map);
yoshi28bac132014-01-22 11:00:17 -0800179
180 if (rcValue.length != 0) {
181 if (writeWithRules(rcValue)) {
182 break;
183 } else {
184 log.debug("getSetProperty(String {}, Object {}) cond. write failure RETRYING {}", propValue, elmId, i+1);
Yoshi Muroi815c7f92014-01-30 18:06:16 -0800185 if (i + 1 == graph.CONDITIONALWRITE_RETRY_MAX) {
yoshi28bac132014-01-22 11:00:17 -0800186 log.error("getSetProperty(String {}, Object {}) cond. write failure Gaveup RETRYING", propValue, elmId);
187 }
188 }
189 }
190 }
191
192 if (graph.measureBPTimeProp == 1) {
193 long endTime = System.nanoTime();
194 log.error("Performance index setProperty total time {}", endTime - startTime);
195 }
196 }
197
198 @Override
199 public CloseableIterable<T> get(String string, Object value) {
200 // FIXME Do we need this implemented
201 throw new RuntimeException("Not implemented yet");
202 //return getElmIdListForPropValue(value);
203 }
204
205 @Override
206 public CloseableIterable<T> query(String string, Object o) {
207 throw new UnsupportedOperationException("Not supported yet.");
208 }
209
210 @Override
211 public long count(String key, Object value) {
212 Map<Object, List<Object>> map = readIndexPropertyMapFromDB();
213 List<Object> values = map.get(value);
214 if (null == values) {
215 return 0;
216 } else {
217 return values.size();
218 }
219 }
220
221 @Override
222 public void remove(String propName, Object propValue, T element) {
223
224 if (propName == null) {
225 throw ExceptionFactory.propertyKeyCanNotBeNull();
226 }
227
228 if (propName.equals("")) {
229 throw ExceptionFactory.propertyKeyCanNotBeEmpty();
230 }
231
232 if (propName.equals("id")) {
233 throw ExceptionFactory.propertyKeyIdIsReserved();
234 }
235
236 if (!propName.equals(indexName)) {
237 log.error("Index name mismatch indexName:{}, remove({},{},...). SOMETHING IS WRONG", indexName, propName, propValue);
238 }
239
Yoshi Muroi815c7f92014-01-30 18:06:16 -0800240 for (int i = 0; i < graph.CONDITIONALWRITE_RETRY_MAX; ++i) {
yoshi28bac132014-01-22 11:00:17 -0800241 Map<Object, List<Object>> map = readIndexPropertyMapFromDB();
242
243 if (map.containsKey(propValue)) {
244 List<Object> idList = map.get(propValue);
245 if (null != idList) {
246 idList.remove(element.getId());
247 if (idList.isEmpty()) {
248 log.debug("remove({},{},...) called, and list became empty.", propName, propValue);
249 map.remove(propValue);
250 }
251 }
252 } else {
253 // propValue not found
254 log.warn("remove({},{},...) called on '{}' index table, but was not found on index. SOMETHING MAY BE WRONG", propName, propValue, this.indexName);
255 // no change to DB so exit now
256 return;
257 }
yoshi28bac132014-01-22 11:00:17 -0800258 byte[] rcValue = convertIndexPropertyMapToRcBytes(map);
yoshi28bac132014-01-22 11:00:17 -0800259
260 if (rcValue.length == 0) {
261 return;
262 }
263
264 if (writeWithRules(rcValue)) {
265 break;
266 } else {
267 log.debug("remove({}, {}, T element) write failure RETRYING {}", propName, propValue, (i + 1));
Yoshi Muroi815c7f92014-01-30 18:06:16 -0800268 if (i + 1 == graph.CONDITIONALWRITE_RETRY_MAX) {
yoshi28bac132014-01-22 11:00:17 -0800269 log.error("remove({}, {}, T element) write failed completely. gave up RETRYING", propName, propValue);
270 }
271 }
272 }
273
274 }
275
276 public void removeElement(T element) {
277 removeElement(this.tableId, element, this.graph);
278 }
279
280 // FIXME this methods should not be defined here
281 public <T extends Element> void removeElement(long tableId, T element, RamCloudGraph graph) {
282 JRamCloud.TableEnumerator tableEnum = graph.getRcClient().new TableEnumerator(tableId);
283
284 while (tableEnum.hasNext()) {
285 JRamCloud.Object tableEntry = tableEnum.next();
286 Map<Object, List<Object>> indexValMap = convertRcBytesToIndexPropertyMap(tableEntry.value);
287
288 boolean madeChange = false;
289 Iterator<Map.Entry<Object, List<Object>>> indexValMapIt = indexValMap.entrySet().iterator();
290 while (indexValMapIt.hasNext()) {
291 Map.Entry<Object, List<Object>> entry = indexValMapIt.next();
292 List<Object> idList = entry.getValue();
293 madeChange |= idList.remove(element.getId());
294 if (idList.isEmpty()) {
295 madeChange = true;
296 indexValMapIt.remove();
297 }
298 }
299 if (madeChange == false) {
300 continue;
301 }
302
303 byte[] rcValue = convertIndexPropertyMapToRcBytes(indexValMap);
304 if (rcValue.length == 0) {
305 // nothing to write
306 continue;
307 }
Yoshi Muroi815c7f92014-01-30 18:06:16 -0800308 if (RamCloudWrite.writeWithRules(tableId, tableEntry.key, rcValue, tableEntry.version, graph, RamCloudWrite.PerfMonEnum.INDEXWRITE)) {
yoshi28bac132014-01-22 11:00:17 -0800309 // cond. write success
310 continue;
311 } else {
312 // cond. write failure
313 log.debug("removeElement({}, {}, ...) cond. key/value write failure RETRYING", tableId, element );
314 // FIXME Dirty hack
Yoshi Muroi815c7f92014-01-30 18:06:16 -0800315 for (int retry = graph.CONDITIONALWRITE_RETRY_MAX; retry >= 0; --retry) {
yoshi28bac132014-01-22 11:00:17 -0800316 RamCloudKeyIndex idx = new RamCloudKeyIndex(tableId, tableEntry.key, graph, element.getClass());
317 Map<Object, List<Object>> rereadMap = idx.readIndexPropertyMapFromDB();
318
319 boolean madeChangeOnRetry = false;
320 Iterator<Map.Entry<Object, List<Object>>> rereadIndexValMapIt = rereadMap.entrySet().iterator();
321 while (rereadIndexValMapIt.hasNext()) {
322 Map.Entry<Object, List<Object>> entry = rereadIndexValMapIt.next();
323 List<Object> idList = entry.getValue();
324 madeChangeOnRetry |= idList.remove(element.getId());
325 if (idList.isEmpty()) {
326 madeChangeOnRetry = true;
327 rereadIndexValMapIt.remove();
328 }
329 }
330 if (madeChangeOnRetry == false) {
331 log.debug("removeElement({}, {}, ...) no more write required. SOMETHING MAY BE WRONG", tableId, element);
332 break;
333 }
334
335 if (idx.writeWithRules(convertIndexPropertyMapToRcBytes(rereadMap))) {
Yoshi Muroi815c7f92014-01-30 18:06:16 -0800336 log.debug("removeElement({}, {}, ...) cond. key/value {} write failure RETRYING {}", tableId, element, rereadMap, graph.CONDITIONALWRITE_RETRY_MAX - retry);
yoshi28bac132014-01-22 11:00:17 -0800337 // cond. re-write success
338 break;
339 }
340 if (retry == 0) {
341 log.error("removeElement({}, {}, ...) cond. write failed completely. Gave up RETRYING", tableId, element);
342 // XXX may be we should throw some kind of exception here?
343 }
344 }
345 }
346 }
347 }
348
349 public Map<Object, List<Object>> readIndexPropertyMapFromDB() {
yoshi28bac132014-01-22 11:00:17 -0800350 JRamCloud.Object propTableEntry;
yoshi28bac132014-01-22 11:00:17 -0800351 PerfMon pm = PerfMon.getInstance();
352
353 try {
354 JRamCloud vertTable = graph.getRcClient();
yoshi28bac132014-01-22 11:00:17 -0800355 pm.indexread_start("RamCloudIndex readIndexPropertyMapFromDB()");
356 propTableEntry = vertTable.read(tableId, rcKey);
357 pm.indexread_end("RamCloudIndex readIndexPropertyMapFromDB()");
yoshi28bac132014-01-22 11:00:17 -0800358 indexVersion = propTableEntry.version;
359 } catch (Exception e) {
360 pm.indexread_end("RamCloudIndex readIndexPropertyMapFromDB()");
361 indexVersion = 0;
Yoshi Muroi815c7f92014-01-30 18:06:16 -0800362 if (e instanceof JRamCloud.ObjectDoesntExistException) {
363 return null;
yoshi28bac132014-01-22 11:00:17 -0800364 }
365 log.warn("readIndexPropertyMapFromDB() Element does not have a index property table entry! tableId :" + tableId + " indexName : " + indexName + " ", e);
366 return null;
367 }
368
369 return convertRcBytesToIndexPropertyMap(propTableEntry.value);
370 }
371
372 public Map<Object, List<Object>> convertRcBytesToIndexPropertyMap(byte[] byteArray) {
373 if (byteArray == null) {
374 log.error("Got a null byteArray argument");
375 return null;
376 } else if (byteArray.length != 0) {
377 PerfMon pm = PerfMon.getInstance();
yoshi28bac132014-01-22 11:00:17 -0800378 pm.indexdeser_start("RamCloudIndex convertRcBytesToIndexPropertyMap()");
379 IndexBlob blob;
380 TreeMap<Object, List<Object>> map = new TreeMap<Object, List<Object>>();
381 try {
382 blob = IndexBlob.parseFrom(byteArray);
383 List const_list = blob.getVertexIdList();
384 ArrayList list = new ArrayList<>(const_list);
yoshi28bac132014-01-22 11:00:17 -0800385 map.put(rcKeyToPropName(rcKey), list);
386 } catch (InvalidProtocolBufferException e) {
387 log.error("{" + toString() + "}: Read malformed edge list: ", e);
388 } finally {
389 pm.indexdeser_end("RamCloudIndex convertRcBytesToIndexPropertyMap()");
390 }
yoshi28bac132014-01-22 11:00:17 -0800391 return map;
392 } else {
393 return new TreeMap<Object, List<Object>>();
394 }
395 }
396
397 public static byte[] convertIndexPropertyMapToRcBytes(Map<Object, List<Object>> map) {
398 PerfMon pm = PerfMon.getInstance();
yoshi28bac132014-01-22 11:00:17 -0800399 byte[] bytes;
400
401 pm.indexser_start("RamCloudIndex convertIndexPropertyMapToRcBytes()");
402 Builder builder = IndexBlob.newBuilder();
403 if ( map.values().size() != 0 ) {
404 List<Long> vtxIds = (List)map.values().iterator().next();
405 builder.addAllVertexId(vtxIds);
406 }
407 IndexBlob blob = builder.build();
408 bytes = blob.toByteArray();
yoshi28bac132014-01-22 11:00:17 -0800409 pm.indexser_end("RamCloudIndex convertIndexPropertyMapToRcBytes()");
yoshi28bac132014-01-22 11:00:17 -0800410 return bytes;
411 }
412
413 protected boolean writeWithRules(byte[] rcValue) {
Yoshi Muroi815c7f92014-01-30 18:06:16 -0800414 return RamCloudWrite.writeWithRules(this.tableId, this.rcKey, rcValue, this.indexVersion, this.graph, RamCloudWrite.PerfMonEnum.INDEXWRITE);
yoshi28bac132014-01-22 11:00:17 -0800415 }
416
417 public List<Object> getElmIdListForPropValue(Object propValue) {
418 Map<Object, List<Object>> map = readIndexPropertyMapFromDB();
419 if (map == null) {
420 log.debug("IndexPropertyMap was null. {} : {}", indexName, propValue);
421 return null;
422 }
423 return map.get(propValue);
424 }
425
426 public Set<Object> getIndexPropertyKeys() {
427 Map<Object, List<Object>> map = readIndexPropertyMapFromDB();
428 return map.keySet();
429 }
430
431 public <T> T removeIndexProperty(String key) {
Yoshi Muroi815c7f92014-01-30 18:06:16 -0800432 for (int i = 0; i < graph.CONDITIONALWRITE_RETRY_MAX; ++i) {
yoshi28bac132014-01-22 11:00:17 -0800433 Map<Object, List<Object>> map = readIndexPropertyMapFromDB();
434 T retVal = (T) map.remove(key);
435 byte[] rcValue = convertIndexPropertyMapToRcBytes(map);
436 if (rcValue.length != 0) {
437 if (writeWithRules(rcValue)) {
438 return retVal;
439 } else {
440 log.debug("removeIndexProperty({}) cond. key/value write failure RETRYING {}", tableId, (i + 1));
441 }
442 }
443 }
444 log.error("removeIndexProperty({}) cond. key/value write failure gave up RETRYING", tableId);
445 // XXX ?Is this correct
446 return null;
447 }
448
449 public void removeIndex() {
450 log.info("Removing Index: {} was version {} [{}]", indexName, indexVersion, this);
451 graph.getRcClient().remove(tableId, rcKey);
452 }
453}