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.openecomp.aai.champ.graph.impl;
24 import com.thinkaurelius.titan.core.Cardinality;
25 import com.thinkaurelius.titan.core.EdgeLabel;
26 import com.thinkaurelius.titan.core.PropertyKey;
27 import com.thinkaurelius.titan.core.SchemaViolationException;
28 import com.thinkaurelius.titan.core.TitanEdge;
29 import com.thinkaurelius.titan.core.TitanFactory;
30 import com.thinkaurelius.titan.core.TitanGraph;
31 import com.thinkaurelius.titan.core.TitanVertex;
32 import com.thinkaurelius.titan.core.schema.SchemaAction;
33 import com.thinkaurelius.titan.core.schema.SchemaStatus;
34 import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
35 import com.thinkaurelius.titan.core.schema.TitanManagement;
36 import com.thinkaurelius.titan.graphdb.database.management.ManagementSystem;
37 import org.apache.tinkerpop.gremlin.structure.Edge;
38 import org.apache.tinkerpop.gremlin.structure.Vertex;
39 import org.openecomp.aai.champ.ChampCapabilities;
40 import org.openecomp.aai.champ.exceptions.ChampIndexNotExistsException;
41 import org.openecomp.aai.champ.exceptions.ChampSchemaViolationException;
42 import org.openecomp.aai.champ.model.ChampCardinality;
43 import org.openecomp.aai.champ.model.ChampObject;
44 import org.openecomp.aai.champ.model.ChampObjectConstraint;
45 import org.openecomp.aai.champ.model.ChampObjectIndex;
46 import org.openecomp.aai.champ.model.ChampPropertyConstraint;
47 import org.openecomp.aai.champ.model.ChampRelationship;
48 import org.openecomp.aai.champ.model.ChampRelationshipConstraint;
49 import org.openecomp.aai.champ.model.ChampRelationshipIndex;
50 import org.openecomp.aai.champ.model.ChampSchema;
51 import org.openecomp.aai.champ.schema.ChampSchemaEnforcer;
52 import org.openecomp.aai.champ.schema.DefaultChampSchemaEnforcer;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 import java.time.temporal.ChronoUnit;
57 import java.util.HashMap;
58 import java.util.Iterator;
60 import java.util.Map.Entry;
61 import java.util.NoSuchElementException;
62 import java.util.Optional;
63 import java.util.Spliterator;
64 import java.util.Spliterators;
65 import java.util.concurrent.ExecutionException;
66 import java.util.stream.Stream;
67 import java.util.stream.StreamSupport;
69 public final class TitanChampGraphImpl extends AbstractTinkerpopChampGraph {
71 private static final Logger LOGGER = LoggerFactory.getLogger(TitanChampGraphImpl.class);
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 private 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 final Object storageBackend = builder.graphConfiguration.get("storage.backend");
102 if ("cassandra".equals(storageBackend) || "cassandrathrift".equals(storageBackend)
103 || "astyanax".equals(storageBackend) || "embeddedcassandra".equals(storageBackend)) {
104 titanGraphBuilder.set(TITAN_CASSANDRA_KEYSPACE, builder.graphName);
105 } else if ("hbase".equals(storageBackend)) {
106 titanGraphBuilder.set(TITAN_HBASE_TABLE, builder.graphName);
107 } else if ("berkleyje".equals(storageBackend)) {
108 throw new RuntimeException("storage.backend=berkleyje cannot handle multiple graphs on a single DB, not usable");
109 } else if ("inmemory".equals(storageBackend)) {
111 throw new RuntimeException("Unknown storage.backend=" + storageBackend);
114 this.graph = titanGraphBuilder.open();
117 public static class Builder {
118 private final String graphName;
120 private final Map<String, Object> graphConfiguration = new HashMap<String, Object> ();
122 public Builder(String graphName) {
123 this.graphName = graphName;
126 public Builder properties(Map<String, Object> properties) {
127 if (properties.containsKey(TITAN_CASSANDRA_KEYSPACE))
128 throw new IllegalArgumentException("Cannot use path " + TITAN_CASSANDRA_KEYSPACE
129 + " in initial configuration - this path is used"
130 + " to specify graph names");
132 this.graphConfiguration.putAll(properties);
136 public Builder property(String path, Object value) {
137 if (path.equals(TITAN_CASSANDRA_KEYSPACE))
138 throw new IllegalArgumentException("Cannot use path " + TITAN_CASSANDRA_KEYSPACE
139 + " in initial configuration - this path is used"
140 + " to specify graph names");
141 graphConfiguration.put(path, value);
145 public TitanChampGraphImpl build() {
146 return new TitanChampGraphImpl(this);
151 protected TitanGraph getGraph() {
156 protected ChampSchemaEnforcer getSchemaEnforcer() {
157 return SCHEMA_ENFORCER;
160 public void executeStoreObjectIndex(ChampObjectIndex index) {
161 if (isShutdown()) throw new IllegalStateException("Cannot call storeObjectIndex() after shutdown has been initiated");
163 final TitanGraph graph = getGraph();
164 final TitanManagement createIndexMgmt = graph.openManagement();
165 final PropertyKey pk = createIndexMgmt.getOrCreatePropertyKey(index.getField().getName());
167 if (createIndexMgmt.getGraphIndex(index.getName()) != null) {
168 createIndexMgmt.rollback();
169 return; //Ignore, index already exists
172 createIndexMgmt.buildIndex(index.getName(), Vertex.class).addKey(pk).buildCompositeIndex();
174 createIndexMgmt.commit();
177 awaitIndexCreation(index.getName());
181 public Optional<ChampObjectIndex> retrieveObjectIndex(String indexName) {
182 if (isShutdown()) throw new IllegalStateException("Cannot call retrieveObjectIndex() after shutdown has been initiated");
184 final TitanManagement retrieveIndexMgmt = getGraph().openManagement();
185 final TitanGraphIndex index = retrieveIndexMgmt.getGraphIndex(indexName);
187 if (index == null) return Optional.empty();
188 if (index.getIndexedElement() != TitanVertex.class) return Optional.empty();
190 return Optional.of(ChampObjectIndex.create()
192 .onType(ChampObject.ReservedTypes.ANY.toString())
193 .forField(index.getFieldKeys()[0].name())
198 public Stream<ChampObjectIndex> retrieveObjectIndices() {
199 if (isShutdown()) throw new IllegalStateException("Cannot call retrieveObjectIndices() after shutdown has been initiated");
201 final TitanManagement createIndexMgmt = getGraph().openManagement();
202 final Iterator<TitanGraphIndex> indices = createIndexMgmt.getGraphIndexes(Vertex.class).iterator();
204 final Iterator<ChampObjectIndex> objIter = new Iterator<ChampObjectIndex> () {
206 private ChampObjectIndex next;
209 public boolean hasNext() {
210 if (indices.hasNext()) {
211 final TitanGraphIndex index = indices.next();
213 next = ChampObjectIndex.create()
214 .ofName(index.name())
215 .onType(ChampObject.ReservedTypes.ANY.toString())
216 .forField(index.getFieldKeys()[0].name())
226 public ChampObjectIndex next() {
227 if (next == null) throw new NoSuchElementException();
233 return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
234 objIter, Spliterator.ORDERED | Spliterator.NONNULL), false);
237 public void executeDeleteObjectIndex(String indexName) throws ChampIndexNotExistsException {
238 if (isShutdown()) throw new IllegalStateException("Cannot call deleteObjectIndex() after shutdown has been initiated");
240 throw new UnsupportedOperationException("Cannot delete indices using the TitanChampImpl");
243 public void executeStoreRelationshipIndex(ChampRelationshipIndex index) {
244 if (isShutdown()) throw new IllegalStateException("Cannot call storeRelationshipIndex() after shutdown has been initiated");
246 final TitanGraph graph = getGraph();
247 final TitanManagement createIndexMgmt = graph.openManagement();
248 final PropertyKey pk = createIndexMgmt.getOrCreatePropertyKey(index.getField().getName());
250 if (createIndexMgmt.getGraphIndex(index.getName()) != null) return; //Ignore, index already exists
251 createIndexMgmt.buildIndex(index.getName(), Edge.class).addKey(pk).buildCompositeIndex();
253 createIndexMgmt.commit();
256 awaitIndexCreation(index.getName());
260 public Optional<ChampRelationshipIndex> retrieveRelationshipIndex(String indexName) {
261 if (isShutdown()) throw new IllegalStateException("Cannot call retrieveRelationshipIndex() after shutdown has been initiated");
263 final TitanManagement retrieveIndexMgmt = getGraph().openManagement();
264 final TitanGraphIndex index = retrieveIndexMgmt.getGraphIndex(indexName);
266 if (index == null) return Optional.empty();
267 if (index.getIndexedElement() != TitanEdge.class) return Optional.empty();
269 return Optional.of(ChampRelationshipIndex.create()
271 .onType(ChampObject.ReservedTypes.ANY.toString())
272 .forField(index.getFieldKeys()[0].name())
277 public Stream<ChampRelationshipIndex> retrieveRelationshipIndices() {
278 if (isShutdown()) throw new IllegalStateException("Cannot call retrieveRelationshipIndices() after shutdown has been initiated");
280 final TitanManagement createIndexMgmt = getGraph().openManagement();
281 final Iterator<TitanGraphIndex> indices = createIndexMgmt.getGraphIndexes(Edge.class).iterator();
283 final Iterator<ChampRelationshipIndex> objIter = new Iterator<ChampRelationshipIndex> () {
285 private ChampRelationshipIndex next;
288 public boolean hasNext() {
289 if (indices.hasNext()) {
290 final TitanGraphIndex index = indices.next();
292 next = ChampRelationshipIndex.create()
293 .ofName(index.name())
294 .onType(ChampRelationship.ReservedTypes.ANY.toString())
295 .forField(index.getFieldKeys()[0].name())
305 public ChampRelationshipIndex next() {
306 if (next == null) throw new NoSuchElementException();
312 return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
313 objIter, Spliterator.ORDERED | Spliterator.NONNULL), false);
316 public void executeDeleteRelationshipIndex(String indexName) throws ChampIndexNotExistsException {
317 if (isShutdown()) throw new IllegalStateException("Cannot call deleteRelationshipIndex() after shutdown has been initiated");
319 throw new UnsupportedOperationException("Cannot delete indices using the TitanChampImpl");
322 private Cardinality getTitanCardinality(ChampCardinality cardinality) {
323 switch (cardinality) {
325 return Cardinality.LIST;
327 return Cardinality.SET;
329 return Cardinality.SINGLE;
331 throw new RuntimeException("Unknown ChampCardinality " + cardinality);
335 private void awaitIndexCreation(String indexName) {
336 //Wait for the index to become available
338 if (ManagementSystem.awaitGraphIndexStatus(graph, indexName)
339 .status(SchemaStatus.ENABLED)
340 .timeout(1, ChronoUnit.SECONDS)
343 return; //Empty graphs immediately ENABLE indices
346 if (!ManagementSystem.awaitGraphIndexStatus(graph, indexName)
347 .status(SchemaStatus.REGISTERED)
348 .timeout(REGISTER_OBJECT_INDEX_TIMEOUT_SECS, ChronoUnit.SECONDS)
351 LOGGER.warn("Object index was created, but timed out while waiting for it to be registered");
354 } catch (InterruptedException e) {
355 LOGGER.warn("Interrupted while waiting for object index creation status");
359 //Reindex the existing data
362 final TitanManagement updateIndexMgmt = graph.openManagement();
363 updateIndexMgmt.updateIndex(updateIndexMgmt.getGraphIndex(indexName),SchemaAction.REINDEX).get();
364 updateIndexMgmt.commit();
365 } catch (InterruptedException e) {
366 LOGGER.warn("Interrupted while reindexing for object index");
368 } catch (ExecutionException e) {
369 LOGGER.warn("Exception occurred during reindexing procedure for creating object index " + indexName, e);
373 ManagementSystem.awaitGraphIndexStatus(graph, indexName)
374 .status(SchemaStatus.ENABLED)
375 .timeout(10, ChronoUnit.MINUTES)
377 } catch (InterruptedException e) {
378 LOGGER.warn("Interrupted while waiting for index to transition to ENABLED state");
384 public ChampCapabilities capabilities() {
389 public void storeSchema(ChampSchema schema) throws ChampSchemaViolationException {
390 if (isShutdown()) throw new IllegalStateException("Cannot call storeSchema() after shutdown has been initiated");
392 final ChampSchema currentSchema = retrieveSchema();
393 final TitanManagement mgmt = getGraph().openManagement();
396 for (ChampObjectConstraint objConstraint : schema.getObjectConstraints().values()) {
397 for (ChampPropertyConstraint propConstraint : objConstraint.getPropertyConstraints()) {
398 final Optional<ChampObjectConstraint> currentObjConstraint = currentSchema.getObjectConstraint(objConstraint.getType());
400 if (currentObjConstraint.isPresent()) {
401 final Optional<ChampPropertyConstraint> currentPropConstraint = currentObjConstraint.get().getPropertyConstraint(propConstraint.getField().getName());
403 if (currentPropConstraint.isPresent() && currentPropConstraint.get().compareTo(propConstraint) != 0) {
404 throw new ChampSchemaViolationException("Cannot update already existing property on object type " + objConstraint.getType() + ": " + propConstraint);
408 final String newPropertyKeyName = propConstraint.getField().getName();
410 if (mgmt.getPropertyKey(newPropertyKeyName) != null) continue; //Check Titan to see if another node created this property key
412 mgmt.makePropertyKey(newPropertyKeyName)
413 .dataType(propConstraint.getField().getJavaType())
414 .cardinality(getTitanCardinality(propConstraint.getCardinality()))
419 for (ChampRelationshipConstraint relConstraint : schema.getRelationshipConstraints().values()) {
421 final Optional<ChampRelationshipConstraint> currentRelConstraint = currentSchema.getRelationshipConstraint(relConstraint.getType());
423 for (ChampPropertyConstraint propConstraint : relConstraint.getPropertyConstraints()) {
425 if (currentRelConstraint.isPresent()) {
426 final Optional<ChampPropertyConstraint> currentPropConstraint = currentRelConstraint.get().getPropertyConstraint(propConstraint.getField().getName());
428 if (currentPropConstraint.isPresent() && currentPropConstraint.get().compareTo(propConstraint) != 0) {
429 throw new ChampSchemaViolationException("Cannot update already existing property on relationship type " + relConstraint.getType());
433 final String newPropertyKeyName = propConstraint.getField().getName();
435 if (mgmt.getPropertyKey(newPropertyKeyName) != null) continue; //Check Titan to see if another node created this property key
437 mgmt.makePropertyKey(newPropertyKeyName)
438 .dataType(propConstraint.getField().getJavaType())
439 .cardinality(getTitanCardinality(propConstraint.getCardinality()))
443 final EdgeLabel edgeLabel = mgmt.getEdgeLabel(relConstraint.getType());
445 if (edgeLabel != null) mgmt.makeEdgeLabel(relConstraint.getType())
452 super.storeSchema(schema);
453 } catch (SchemaViolationException | ChampSchemaViolationException e) {
455 throw new ChampSchemaViolationException(e);