56434be36a0bc5357fd6dd4ab9f5283e42cee314
[aai/champ.git] / champ-lib / champ-titan / src / main / java / org / onap / aai / champtitan / graph / impl / TitanChampGraphImpl.java
1 /**
2  * ============LICENSE_START==========================================
3  * org.onap.aai
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
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
21  */
22 package org.onap.aai.champtitan.graph.impl;
23
24 import java.time.temporal.ChronoUnit;
25 import java.util.*;
26 import java.util.Map.Entry;
27 import java.util.concurrent.ExecutionException;
28 import java.util.stream.Stream;
29 import java.util.stream.StreamSupport;
30
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;
53
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;
67
68 public final class TitanChampGraphImpl extends AbstractTinkerpopChampGraph {
69
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;
76
77   private static final ChampCapabilities CAPABILITIES = new ChampCapabilities() {
78
79     @Override
80     public boolean canDeleteObjectIndices() {
81       return false;
82     }
83
84     @Override
85     public boolean canDeleteRelationshipIndices() {
86       return false;
87     }
88   };
89
90   private final TitanGraph graph;
91
92   public TitanChampGraphImpl(Builder builder) {
93     super(builder.graphConfiguration);
94     final TitanFactory.Builder titanGraphBuilder = TitanFactory.build();
95
96     for (Entry<String, Object> titanGraphProperty : builder.graphConfiguration.entrySet()) {
97       titanGraphBuilder.set(titanGraphProperty.getKey(), titanGraphProperty.getValue());
98     }
99
100     titanGraphBuilder.set(TITAN_UNIQUE_SUFFIX, ((short) new Random().nextInt(Short.MAX_VALUE)+""));
101     
102     final Object storageBackend = builder.graphConfiguration.get("storage.backend");
103
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)) {
114     } else {
115       throw new RuntimeException("Unknown storage.backend=" + storageBackend);
116     }
117     
118     LOGGER.info("Instantiated data access layer for Titan graph data store with backend: " + storageBackend);
119
120     this.graph = titanGraphBuilder.open();
121   }
122
123   public static class Builder {
124     private final String graphName;
125
126     private final Map<String, Object> graphConfiguration = new HashMap<String, Object> ();
127
128     public Builder(String graphName) {
129       this.graphName = graphName;
130     }
131     
132     public Builder(String graphName, Map<String, Object> properties) {
133         this.graphName = graphName;
134         properties(properties);
135     }
136
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");
142
143       this.graphConfiguration.putAll(properties);
144       return this;
145     }
146
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);
153       return this;
154     }
155
156     public TitanChampGraphImpl build() {
157       return new TitanChampGraphImpl(this);
158     }
159   }
160
161   @Override
162   protected TitanGraph getGraph() {
163     return graph;
164   }
165
166   @Override
167   protected ChampSchemaEnforcer getSchemaEnforcer() {
168     return SCHEMA_ENFORCER;
169   }
170
171   public void executeStoreObjectIndex(ChampObjectIndex index) {
172     if (isShutdown()) throw new IllegalStateException("Cannot call storeObjectIndex() after shutdown has been initiated");
173
174     final TitanGraph graph = getGraph();
175     final TitanManagement createIndexMgmt = graph.openManagement();
176     final PropertyKey pk = createIndexMgmt.getOrCreatePropertyKey(index.getField().getName());
177
178     if (createIndexMgmt.getGraphIndex(index.getName()) != null) {
179       createIndexMgmt.rollback();
180       return; //Ignore, index already exists
181     }
182
183     createIndexMgmt.buildIndex(index.getName(), Vertex.class).addKey(pk).buildCompositeIndex();
184
185     createIndexMgmt.commit();
186     graph.tx().commit();
187
188     awaitIndexCreation(index.getName());
189   }
190
191   @Override
192   public Optional<ChampObjectIndex> retrieveObjectIndex(String indexName) {
193     if (isShutdown()) throw new IllegalStateException("Cannot call retrieveObjectIndex() after shutdown has been initiated");
194
195     final TitanManagement retrieveIndexMgmt = getGraph().openManagement();
196     final TitanGraphIndex index = retrieveIndexMgmt.getGraphIndex(indexName);
197
198     if (index == null) return Optional.empty();
199     if (index.getIndexedElement() != TitanVertex.class) return Optional.empty();
200
201     return Optional.of(ChampObjectIndex.create()
202         .ofName(indexName)
203         .onType(ChampObject.ReservedTypes.ANY.toString())
204         .forField(index.getFieldKeys()[0].name())
205         .build());
206   }
207
208   @Override
209   public Stream<ChampObjectIndex> retrieveObjectIndices() {
210     if (isShutdown()) throw new IllegalStateException("Cannot call retrieveObjectIndices() after shutdown has been initiated");
211
212     final TitanManagement createIndexMgmt = getGraph().openManagement();
213     final Iterator<TitanGraphIndex> indices = createIndexMgmt.getGraphIndexes(Vertex.class).iterator();
214
215     final Iterator<ChampObjectIndex> objIter = new Iterator<ChampObjectIndex> () {
216
217       private ChampObjectIndex next;
218
219       @Override
220       public boolean hasNext() {
221         if (indices.hasNext()) {
222           final TitanGraphIndex index = indices.next();
223
224           next = ChampObjectIndex.create()
225               .ofName(index.name())
226               .onType(ChampObject.ReservedTypes.ANY.toString())
227               .forField(index.getFieldKeys()[0].name())
228               .build();
229           return true;
230         }
231
232         next = null;
233         return false;
234       }
235
236       @Override
237       public ChampObjectIndex next() {
238         if (next == null) throw new NoSuchElementException();
239
240         return next;
241       }
242     };
243
244     return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
245         objIter, Spliterator.ORDERED | Spliterator.NONNULL), false);
246   }
247
248   public void executeDeleteObjectIndex(String indexName) throws ChampIndexNotExistsException {
249     if (isShutdown()) throw new IllegalStateException("Cannot call deleteObjectIndex() after shutdown has been initiated");
250
251     throw new UnsupportedOperationException("Cannot delete indices using the TitanChampImpl");
252   }
253
254   public void executeStoreRelationshipIndex(ChampRelationshipIndex index) {
255     if (isShutdown()) throw new IllegalStateException("Cannot call storeRelationshipIndex() after shutdown has been initiated");
256
257     final TitanGraph graph = getGraph();
258     final TitanManagement createIndexMgmt = graph.openManagement();
259     final PropertyKey pk = createIndexMgmt.getOrCreatePropertyKey(index.getField().getName());
260
261     if (createIndexMgmt.getGraphIndex(index.getName()) != null) return; //Ignore, index already exists
262     createIndexMgmt.buildIndex(index.getName(), Edge.class).addKey(pk).buildCompositeIndex();
263
264     createIndexMgmt.commit();
265     graph.tx().commit();
266
267     awaitIndexCreation(index.getName());
268   }
269
270   @Override
271   public Optional<ChampRelationshipIndex> retrieveRelationshipIndex(String indexName) {
272     if (isShutdown()) throw new IllegalStateException("Cannot call retrieveRelationshipIndex() after shutdown has been initiated");
273
274     final TitanManagement retrieveIndexMgmt = getGraph().openManagement();
275     final TitanGraphIndex index = retrieveIndexMgmt.getGraphIndex(indexName);
276
277     if (index == null) return Optional.empty();
278     if (index.getIndexedElement() != TitanEdge.class) return Optional.empty();
279
280     return Optional.of(ChampRelationshipIndex.create()
281         .ofName(indexName)
282         .onType(ChampObject.ReservedTypes.ANY.toString())
283         .forField(index.getFieldKeys()[0].name())
284         .build());
285   }
286
287   @Override
288   public Stream<ChampRelationshipIndex> retrieveRelationshipIndices() {
289     if (isShutdown()) throw new IllegalStateException("Cannot call retrieveRelationshipIndices() after shutdown has been initiated");
290
291     final TitanManagement createIndexMgmt = getGraph().openManagement();
292     final Iterator<TitanGraphIndex> indices = createIndexMgmt.getGraphIndexes(Edge.class).iterator();
293
294     final Iterator<ChampRelationshipIndex> objIter = new Iterator<ChampRelationshipIndex> () {
295
296       private ChampRelationshipIndex next;
297
298       @Override
299       public boolean hasNext() {
300         if (indices.hasNext()) {
301           final TitanGraphIndex index = indices.next();
302
303           next = ChampRelationshipIndex.create()
304               .ofName(index.name())
305               .onType(ChampRelationship.ReservedTypes.ANY.toString())
306               .forField(index.getFieldKeys()[0].name())
307               .build();
308           return true;
309         }
310
311         next = null;
312         return false;
313       }
314
315       @Override
316       public ChampRelationshipIndex next() {
317         if (next == null) throw new NoSuchElementException();
318
319         return next;
320       }
321     };
322
323     return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
324         objIter, Spliterator.ORDERED | Spliterator.NONNULL), false);
325   }
326
327   public void executeDeleteRelationshipIndex(String indexName) throws ChampIndexNotExistsException {
328     if (isShutdown()) throw new IllegalStateException("Cannot call deleteRelationshipIndex() after shutdown has been initiated");
329
330     throw new UnsupportedOperationException("Cannot delete indices using the TitanChampImpl");
331   }
332
333   private Cardinality getTitanCardinality(ChampCardinality cardinality) {
334     switch (cardinality) {
335       case LIST:
336         return Cardinality.LIST;
337       case SET:
338         return Cardinality.SET;
339       case SINGLE:
340         return Cardinality.SINGLE;
341       default:
342         throw new RuntimeException("Unknown ChampCardinality " + cardinality);
343     }
344   }
345
346   private void awaitIndexCreation(String indexName) {
347     //Wait for the index to become available
348     try {
349       if (ManagementSystem.awaitGraphIndexStatus(graph, indexName)
350           .status(SchemaStatus.ENABLED)
351           .timeout(1, ChronoUnit.SECONDS)
352           .call()
353           .getSucceeded()) {
354         return; //Empty graphs immediately ENABLE indices
355       }
356
357       if (!ManagementSystem.awaitGraphIndexStatus(graph, indexName)
358           .status(SchemaStatus.REGISTERED)
359           .timeout(REGISTER_OBJECT_INDEX_TIMEOUT_SECS, ChronoUnit.SECONDS)
360           .call()
361           .getSucceeded()) {
362         LOGGER.warn("Object index was created, but timed out while waiting for it to be registered");
363         return;
364       }
365     } catch (InterruptedException e) {
366       LOGGER.warn("Interrupted while waiting for object index creation status");
367       return;
368     }
369
370     //Reindex the existing data
371
372     try {
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");
378       return;
379     } catch (ExecutionException e) {
380       LOGGER.warn("Exception occurred during reindexing procedure for creating object index " + indexName, e);
381     }
382
383     try {
384       ManagementSystem.awaitGraphIndexStatus(graph, indexName)
385           .status(SchemaStatus.ENABLED)
386           .timeout(10, ChronoUnit.MINUTES)
387           .call();
388     } catch (InterruptedException e) {
389       LOGGER.warn("Interrupted while waiting for index to transition to ENABLED state");
390       return;
391     }
392   }
393
394   @Override
395   public ChampCapabilities capabilities() {
396     return CAPABILITIES;
397   }
398
399   @Override
400   public void storeSchema(ChampSchema schema) throws ChampSchemaViolationException {
401     if (isShutdown()) throw new IllegalStateException("Cannot call storeSchema() after shutdown has been initiated");
402
403     final ChampSchema currentSchema = retrieveSchema();
404     final TitanManagement mgmt = getGraph().openManagement();
405
406     try {
407       for (ChampObjectConstraint objConstraint : schema.getObjectConstraints().values()) {
408         for (ChampPropertyConstraint propConstraint : objConstraint.getPropertyConstraints()) {
409           final Optional<ChampObjectConstraint> currentObjConstraint = currentSchema.getObjectConstraint(objConstraint.getType());
410
411           if (currentObjConstraint.isPresent()) {
412             final Optional<ChampPropertyConstraint> currentPropConstraint = currentObjConstraint.get().getPropertyConstraint(propConstraint.getField().getName());
413
414             if (currentPropConstraint.isPresent() && currentPropConstraint.get().compareTo(propConstraint) != 0) {
415               throw new ChampSchemaViolationException("Cannot update already existing property on object type " + objConstraint.getType() + ": " + propConstraint);
416             }
417           }
418
419           final String newPropertyKeyName = propConstraint.getField().getName();
420
421           if (mgmt.getPropertyKey(newPropertyKeyName) != null) continue; //Check Titan to see if another node created this property key
422
423           mgmt.makePropertyKey(newPropertyKeyName)
424               .dataType(propConstraint.getField().getJavaType())
425               .cardinality(getTitanCardinality(propConstraint.getCardinality()))
426               .make();
427         }
428       }
429
430       for (ChampRelationshipConstraint relConstraint : schema.getRelationshipConstraints().values()) {
431
432         final Optional<ChampRelationshipConstraint> currentRelConstraint = currentSchema.getRelationshipConstraint(relConstraint.getType());
433
434         for (ChampPropertyConstraint propConstraint : relConstraint.getPropertyConstraints()) {
435
436           if (currentRelConstraint.isPresent()) {
437             final Optional<ChampPropertyConstraint> currentPropConstraint = currentRelConstraint.get().getPropertyConstraint(propConstraint.getField().getName());
438
439             if (currentPropConstraint.isPresent() && currentPropConstraint.get().compareTo(propConstraint) != 0) {
440               throw new ChampSchemaViolationException("Cannot update already existing property on relationship type " + relConstraint.getType());
441             }
442           }
443
444           final String newPropertyKeyName = propConstraint.getField().getName();
445
446           if (mgmt.getPropertyKey(newPropertyKeyName) != null) continue; //Check Titan to see if another node created this property key
447
448           mgmt.makePropertyKey(newPropertyKeyName)
449               .dataType(propConstraint.getField().getJavaType())
450               .cardinality(getTitanCardinality(propConstraint.getCardinality()))
451               .make();
452         }
453
454         final EdgeLabel edgeLabel = mgmt.getEdgeLabel(relConstraint.getType());
455
456         if (edgeLabel != null) mgmt.makeEdgeLabel(relConstraint.getType())
457             .directed()
458             .make();
459       }
460
461       mgmt.commit();
462
463       super.storeSchema(schema);
464     } catch (SchemaViolationException | ChampSchemaViolationException e) {
465       mgmt.rollback();
466       throw new ChampSchemaViolationException(e);
467     }
468   }
469
470         @Override
471         public GraphTraversal<?, ?> hasLabel(GraphTraversal<?, ?> query, Object type) {
472                 return query.hasLabel((String) type);
473         }
474 }