2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017 Amdocs
7 * ===================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END============================================
20 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 package org.onap.aai.champtitan.graph.impl;
24 import java.time.temporal.ChronoUnit;
26 import java.util.Map.Entry;
27 import java.util.concurrent.ExecutionException;
28 import java.util.stream.Stream;
29 import java.util.stream.StreamSupport;
31 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
32 import org.apache.tinkerpop.gremlin.structure.Edge;
33 import org.apache.tinkerpop.gremlin.structure.Vertex;
34 import org.onap.aai.champcore.ChampCapabilities;
35 import org.onap.aai.champcore.FormatMapper;
36 import org.onap.aai.champcore.Formatter;
37 import org.onap.aai.champcore.exceptions.ChampIndexNotExistsException;
38 import org.onap.aai.champcore.exceptions.ChampSchemaViolationException;
39 import org.onap.aai.champcore.graph.impl.AbstractTinkerpopChampGraph;
40 import org.onap.aai.champcore.model.ChampCardinality;
41 import org.onap.aai.champcore.model.ChampObject;
42 import org.onap.aai.champcore.model.ChampObjectConstraint;
43 import org.onap.aai.champcore.model.ChampObjectIndex;
44 import org.onap.aai.champcore.model.ChampPropertyConstraint;
45 import org.onap.aai.champcore.model.ChampRelationship;
46 import org.onap.aai.champcore.model.ChampRelationshipConstraint;
47 import org.onap.aai.champcore.model.ChampRelationshipIndex;
48 import org.onap.aai.champcore.model.ChampSchema;
49 import org.onap.aai.champcore.schema.ChampSchemaEnforcer;
50 import org.onap.aai.champcore.schema.DefaultChampSchemaEnforcer;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 import com.thinkaurelius.titan.core.Cardinality;
55 import com.thinkaurelius.titan.core.EdgeLabel;
56 import com.thinkaurelius.titan.core.PropertyKey;
57 import com.thinkaurelius.titan.core.SchemaViolationException;
58 import com.thinkaurelius.titan.core.TitanEdge;
59 import com.thinkaurelius.titan.core.TitanFactory;
60 import com.thinkaurelius.titan.core.TitanGraph;
61 import com.thinkaurelius.titan.core.TitanVertex;
62 import com.thinkaurelius.titan.core.schema.SchemaAction;
63 import com.thinkaurelius.titan.core.schema.SchemaStatus;
64 import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
65 import com.thinkaurelius.titan.core.schema.TitanManagement;
66 import com.thinkaurelius.titan.graphdb.database.management.ManagementSystem;
68 public final class TitanChampGraphImpl extends AbstractTinkerpopChampGraph {
70 private static final Logger LOGGER = LoggerFactory.getLogger(TitanChampGraphImpl.class);
71 private static final String TITAN_UNIQUE_SUFFIX = "graph.unique-instance-id-suffix";
72 private static final String TITAN_CASSANDRA_KEYSPACE = "storage.cassandra.keyspace";
73 private static final String TITAN_HBASE_TABLE = "storage.hbase.table";
74 private static final ChampSchemaEnforcer SCHEMA_ENFORCER = new DefaultChampSchemaEnforcer();
75 private static final int REGISTER_OBJECT_INDEX_TIMEOUT_SECS = 30;
77 private static final ChampCapabilities CAPABILITIES = new ChampCapabilities() {
80 public boolean canDeleteObjectIndices() {
85 public boolean canDeleteRelationshipIndices() {
90 private final TitanGraph graph;
92 public TitanChampGraphImpl(Builder builder) {
93 super(builder.graphConfiguration);
94 final TitanFactory.Builder titanGraphBuilder = TitanFactory.build();
96 for (Entry<String, Object> titanGraphProperty : builder.graphConfiguration.entrySet()) {
97 titanGraphBuilder.set(titanGraphProperty.getKey(), titanGraphProperty.getValue());
100 titanGraphBuilder.set(TITAN_UNIQUE_SUFFIX, ((short) new Random().nextInt(Short.MAX_VALUE)+""));
102 final Object storageBackend = builder.graphConfiguration.get("storage.backend");
104 if ("cassandra".equals(storageBackend) ||
105 "cassandrathrift".equals(storageBackend) ||
106 "astyanax".equals(storageBackend) ||
107 "embeddedcassandra".equals(storageBackend)) {
108 titanGraphBuilder.set(TITAN_CASSANDRA_KEYSPACE, builder.graphName);
109 } else if ("hbase".equals(storageBackend)) {
110 titanGraphBuilder.set(TITAN_HBASE_TABLE, builder.graphName);
111 } else if ("berkleyje".equals(storageBackend)) {
112 throw new RuntimeException("storage.backend=berkleyje cannot handle multiple graphs on a single DB, not usable");
113 } else if ("inmemory".equals(storageBackend)) {
115 throw new RuntimeException("Unknown storage.backend=" + storageBackend);
118 LOGGER.info("Instantiated data access layer for Titan graph data store with backend: " + storageBackend);
120 this.graph = titanGraphBuilder.open();
123 public static class Builder {
124 private final String graphName;
126 private final Map<String, Object> graphConfiguration = new HashMap<String, Object> ();
128 public Builder(String graphName) {
129 this.graphName = graphName;
132 public Builder(String graphName, Map<String, Object> properties) {
133 this.graphName = graphName;
134 properties(properties);
137 public Builder properties(Map<String, Object> properties) {
138 if (properties.containsKey(TITAN_CASSANDRA_KEYSPACE))
139 throw new IllegalArgumentException("Cannot use path " + TITAN_CASSANDRA_KEYSPACE
140 + " in initial configuration - this path is used"
141 + " to specify graph names");
143 this.graphConfiguration.putAll(properties);
147 public Builder property(String path, Object value) {
148 if (path.equals(TITAN_CASSANDRA_KEYSPACE))
149 throw new IllegalArgumentException("Cannot use path " + TITAN_CASSANDRA_KEYSPACE
150 + " in initial configuration - this path is used"
151 + " to specify graph names");
152 graphConfiguration.put(path, value);
156 public TitanChampGraphImpl build() {
157 return new TitanChampGraphImpl(this);
162 protected TitanGraph getGraph() {
167 protected ChampSchemaEnforcer getSchemaEnforcer() {
168 return SCHEMA_ENFORCER;
171 public void executeStoreObjectIndex(ChampObjectIndex index) {
172 if (isShutdown()) throw new IllegalStateException("Cannot call storeObjectIndex() after shutdown has been initiated");
174 final TitanGraph graph = getGraph();
175 final TitanManagement createIndexMgmt = graph.openManagement();
176 final PropertyKey pk = createIndexMgmt.getOrCreatePropertyKey(index.getField().getName());
178 if (createIndexMgmt.getGraphIndex(index.getName()) != null) {
179 createIndexMgmt.rollback();
180 return; //Ignore, index already exists
183 createIndexMgmt.buildIndex(index.getName(), Vertex.class).addKey(pk).buildCompositeIndex();
185 createIndexMgmt.commit();
188 awaitIndexCreation(index.getName());
192 public Optional<ChampObjectIndex> retrieveObjectIndex(String indexName) {
193 if (isShutdown()) throw new IllegalStateException("Cannot call retrieveObjectIndex() after shutdown has been initiated");
195 final TitanManagement retrieveIndexMgmt = getGraph().openManagement();
196 final TitanGraphIndex index = retrieveIndexMgmt.getGraphIndex(indexName);
198 if (index == null) return Optional.empty();
199 if (index.getIndexedElement() != TitanVertex.class) return Optional.empty();
201 return Optional.of(ChampObjectIndex.create()
203 .onType(ChampObject.ReservedTypes.ANY.toString())
204 .forField(index.getFieldKeys()[0].name())
209 public Stream<ChampObjectIndex> retrieveObjectIndices() {
210 if (isShutdown()) throw new IllegalStateException("Cannot call retrieveObjectIndices() after shutdown has been initiated");
212 final TitanManagement createIndexMgmt = getGraph().openManagement();
213 final Iterator<TitanGraphIndex> indices = createIndexMgmt.getGraphIndexes(Vertex.class).iterator();
215 final Iterator<ChampObjectIndex> objIter = new Iterator<ChampObjectIndex> () {
217 private ChampObjectIndex next;
220 public boolean hasNext() {
221 if (indices.hasNext()) {
222 final TitanGraphIndex index = indices.next();
224 next = ChampObjectIndex.create()
225 .ofName(index.name())
226 .onType(ChampObject.ReservedTypes.ANY.toString())
227 .forField(index.getFieldKeys()[0].name())
237 public ChampObjectIndex next() {
238 if (next == null) throw new NoSuchElementException();
244 return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
245 objIter, Spliterator.ORDERED | Spliterator.NONNULL), false);
248 public void executeDeleteObjectIndex(String indexName) throws ChampIndexNotExistsException {
249 if (isShutdown()) throw new IllegalStateException("Cannot call deleteObjectIndex() after shutdown has been initiated");
251 throw new UnsupportedOperationException("Cannot delete indices using the TitanChampImpl");
254 public void executeStoreRelationshipIndex(ChampRelationshipIndex index) {
255 if (isShutdown()) throw new IllegalStateException("Cannot call storeRelationshipIndex() after shutdown has been initiated");
257 final TitanGraph graph = getGraph();
258 final TitanManagement createIndexMgmt = graph.openManagement();
259 final PropertyKey pk = createIndexMgmt.getOrCreatePropertyKey(index.getField().getName());
261 if (createIndexMgmt.getGraphIndex(index.getName()) != null) return; //Ignore, index already exists
262 createIndexMgmt.buildIndex(index.getName(), Edge.class).addKey(pk).buildCompositeIndex();
264 createIndexMgmt.commit();
267 awaitIndexCreation(index.getName());
271 public Optional<ChampRelationshipIndex> retrieveRelationshipIndex(String indexName) {
272 if (isShutdown()) throw new IllegalStateException("Cannot call retrieveRelationshipIndex() after shutdown has been initiated");
274 final TitanManagement retrieveIndexMgmt = getGraph().openManagement();
275 final TitanGraphIndex index = retrieveIndexMgmt.getGraphIndex(indexName);
277 if (index == null) return Optional.empty();
278 if (index.getIndexedElement() != TitanEdge.class) return Optional.empty();
280 return Optional.of(ChampRelationshipIndex.create()
282 .onType(ChampObject.ReservedTypes.ANY.toString())
283 .forField(index.getFieldKeys()[0].name())
288 public Stream<ChampRelationshipIndex> retrieveRelationshipIndices() {
289 if (isShutdown()) throw new IllegalStateException("Cannot call retrieveRelationshipIndices() after shutdown has been initiated");
291 final TitanManagement createIndexMgmt = getGraph().openManagement();
292 final Iterator<TitanGraphIndex> indices = createIndexMgmt.getGraphIndexes(Edge.class).iterator();
294 final Iterator<ChampRelationshipIndex> objIter = new Iterator<ChampRelationshipIndex> () {
296 private ChampRelationshipIndex next;
299 public boolean hasNext() {
300 if (indices.hasNext()) {
301 final TitanGraphIndex index = indices.next();
303 next = ChampRelationshipIndex.create()
304 .ofName(index.name())
305 .onType(ChampRelationship.ReservedTypes.ANY.toString())
306 .forField(index.getFieldKeys()[0].name())
316 public ChampRelationshipIndex next() {
317 if (next == null) throw new NoSuchElementException();
323 return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
324 objIter, Spliterator.ORDERED | Spliterator.NONNULL), false);
327 public void executeDeleteRelationshipIndex(String indexName) throws ChampIndexNotExistsException {
328 if (isShutdown()) throw new IllegalStateException("Cannot call deleteRelationshipIndex() after shutdown has been initiated");
330 throw new UnsupportedOperationException("Cannot delete indices using the TitanChampImpl");
333 private Cardinality getTitanCardinality(ChampCardinality cardinality) {
334 switch (cardinality) {
336 return Cardinality.LIST;
338 return Cardinality.SET;
340 return Cardinality.SINGLE;
342 throw new RuntimeException("Unknown ChampCardinality " + cardinality);
346 private void awaitIndexCreation(String indexName) {
347 //Wait for the index to become available
349 if (ManagementSystem.awaitGraphIndexStatus(graph, indexName)
350 .status(SchemaStatus.ENABLED)
351 .timeout(1, ChronoUnit.SECONDS)
354 return; //Empty graphs immediately ENABLE indices
357 if (!ManagementSystem.awaitGraphIndexStatus(graph, indexName)
358 .status(SchemaStatus.REGISTERED)
359 .timeout(REGISTER_OBJECT_INDEX_TIMEOUT_SECS, ChronoUnit.SECONDS)
362 LOGGER.warn("Object index was created, but timed out while waiting for it to be registered");
365 } catch (InterruptedException e) {
366 LOGGER.warn("Interrupted while waiting for object index creation status");
370 //Reindex the existing data
373 final TitanManagement updateIndexMgmt = graph.openManagement();
374 updateIndexMgmt.updateIndex(updateIndexMgmt.getGraphIndex(indexName),SchemaAction.REINDEX).get();
375 updateIndexMgmt.commit();
376 } catch (InterruptedException e) {
377 LOGGER.warn("Interrupted while reindexing for object index");
379 } catch (ExecutionException e) {
380 LOGGER.warn("Exception occurred during reindexing procedure for creating object index " + indexName, e);
384 ManagementSystem.awaitGraphIndexStatus(graph, indexName)
385 .status(SchemaStatus.ENABLED)
386 .timeout(10, ChronoUnit.MINUTES)
388 } catch (InterruptedException e) {
389 LOGGER.warn("Interrupted while waiting for index to transition to ENABLED state");
395 public ChampCapabilities capabilities() {
400 public void storeSchema(ChampSchema schema) throws ChampSchemaViolationException {
401 if (isShutdown()) throw new IllegalStateException("Cannot call storeSchema() after shutdown has been initiated");
403 final ChampSchema currentSchema = retrieveSchema();
404 final TitanManagement mgmt = getGraph().openManagement();
407 for (ChampObjectConstraint objConstraint : schema.getObjectConstraints().values()) {
408 for (ChampPropertyConstraint propConstraint : objConstraint.getPropertyConstraints()) {
409 final Optional<ChampObjectConstraint> currentObjConstraint = currentSchema.getObjectConstraint(objConstraint.getType());
411 if (currentObjConstraint.isPresent()) {
412 final Optional<ChampPropertyConstraint> currentPropConstraint = currentObjConstraint.get().getPropertyConstraint(propConstraint.getField().getName());
414 if (currentPropConstraint.isPresent() && currentPropConstraint.get().compareTo(propConstraint) != 0) {
415 throw new ChampSchemaViolationException("Cannot update already existing property on object type " + objConstraint.getType() + ": " + propConstraint);
419 final String newPropertyKeyName = propConstraint.getField().getName();
421 if (mgmt.getPropertyKey(newPropertyKeyName) != null) continue; //Check Titan to see if another node created this property key
423 mgmt.makePropertyKey(newPropertyKeyName)
424 .dataType(propConstraint.getField().getJavaType())
425 .cardinality(getTitanCardinality(propConstraint.getCardinality()))
430 for (ChampRelationshipConstraint relConstraint : schema.getRelationshipConstraints().values()) {
432 final Optional<ChampRelationshipConstraint> currentRelConstraint = currentSchema.getRelationshipConstraint(relConstraint.getType());
434 for (ChampPropertyConstraint propConstraint : relConstraint.getPropertyConstraints()) {
436 if (currentRelConstraint.isPresent()) {
437 final Optional<ChampPropertyConstraint> currentPropConstraint = currentRelConstraint.get().getPropertyConstraint(propConstraint.getField().getName());
439 if (currentPropConstraint.isPresent() && currentPropConstraint.get().compareTo(propConstraint) != 0) {
440 throw new ChampSchemaViolationException("Cannot update already existing property on relationship type " + relConstraint.getType());
444 final String newPropertyKeyName = propConstraint.getField().getName();
446 if (mgmt.getPropertyKey(newPropertyKeyName) != null) continue; //Check Titan to see if another node created this property key
448 mgmt.makePropertyKey(newPropertyKeyName)
449 .dataType(propConstraint.getField().getJavaType())
450 .cardinality(getTitanCardinality(propConstraint.getCardinality()))
454 final EdgeLabel edgeLabel = mgmt.getEdgeLabel(relConstraint.getType());
456 if (edgeLabel != null) mgmt.makeEdgeLabel(relConstraint.getType())
463 super.storeSchema(schema);
464 } catch (SchemaViolationException | ChampSchemaViolationException e) {
466 throw new ChampSchemaViolationException(e);
471 public GraphTraversal<?, ?> hasLabel(GraphTraversal<?, ?> query, Object type) {
472 return query.hasLabel((String) type);