Fixed Concurrent Updates overriding the AAI object
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / dbgen / SchemaGenerator.java
1 /*
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.aai.dbgen;
22 import org.onap.aai.util.AAIConstants;
23 import com.google.common.collect.Multimap;
24 import org.apache.tinkerpop.gremlin.structure.Vertex;
25 import org.janusgraph.core.Cardinality;
26 import org.janusgraph.core.Multiplicity;
27 import org.janusgraph.core.PropertyKey;
28 import org.janusgraph.core.schema.JanusGraphManagement;
29 import org.janusgraph.core.schema.JanusGraphIndex;
30 import org.janusgraph.core.schema.ConsistencyModifier;
31 import org.onap.aai.config.SpringContextAware;
32 import org.onap.aai.edges.EdgeIngestor;
33 import org.onap.aai.edges.EdgeRule;
34 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
35 import org.onap.aai.introspection.Introspector;
36 import org.onap.aai.introspection.LoaderUtil;
37 import org.onap.aai.logging.LogFormatTools;
38 import org.onap.aai.schema.enums.PropertyMetadata;
39 import org.onap.aai.util.AAIConfig;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 import java.util.HashMap;
44 import java.util.HashSet;
45 import java.util.Map;
46 import java.util.Optional;
47 import java.util.Set;
48 import java.util.function.Function;
49 import java.util.stream.Collectors;
50
51 public class SchemaGenerator {
52
53     private static final Logger LOGGER = LoggerFactory.getLogger(SchemaGenerator.class);
54
55     private SchemaGenerator() {
56     }
57
58     /**
59      * Load schema into JanusGraph.
60      *
61      * @param graphMgmt
62      *        the graph mgmt
63      */
64     public static void loadSchemaIntoJanusGraph(final JanusGraphManagement graphMgmt, String backend) {
65
66         try {
67             AAIConfig.init();
68         } catch (Exception ex) {
69             LOGGER.error(" ERROR - Could not run AAIConfig.init(). {}", LogFormatTools.getStackTop(ex));
70             System.exit(1);
71         }
72
73         // NOTE - JanusGraph 0.5.3 doesn't keep a list of legal node Labels.
74         // They are only used when a vertex is actually being created.
75         // JanusGraph 1.1 will keep track (we think).
76
77         // Use EdgeRules to make sure edgeLabels are defined in the db. NOTE:
78         // the multiplicty used here is
79         // always "MULTI". This is not the same as our internal "Many2Many",
80         // "One2One", "One2Many" or "Many2One"
81         // We use the same edge-label for edges between many different types of
82         // nodes and our internal
83         // multiplicty definitions depends on which two types of nodes are being
84         // connected.
85
86         makeEdgeLabels(graphMgmt);
87
88
89         Map<String, Introspector> objs = LoaderUtil.getLatestVersion().getAllObjects();
90         Map<String, PropertyKey> seenProps = new HashMap<>();
91
92         for (Introspector obj : objs.values()) {
93             for (String propName : obj.getProperties()) {
94                 String dbPropName = propName;
95                 Optional<String> alias = obj.getPropertyMetadata(propName, PropertyMetadata.DB_ALIAS);
96                 if (alias.isPresent()) {
97                     dbPropName = alias.get();
98                 }
99                 if (graphMgmt.containsRelationType(dbPropName)) {
100                     LOGGER.debug(" PropertyKey  [{}] already existed in the DB. ", dbPropName);
101                 } else {
102                     Class<?> type = obj.getClass(propName);
103                     Cardinality cardinality = Cardinality.SINGLE;
104                     boolean process = false;
105                     if (obj.isListType(propName) && obj.isSimpleGenericType(propName)) {
106                         cardinality = Cardinality.SET;
107                         type = obj.getGenericTypeClass(propName);
108                         process = true;
109                     } else if (obj.isSimpleType(propName)) {
110                         process = true;
111                     }
112
113                     if (process) {
114
115                         LOGGER.info("Creating PropertyKey: [{}], [{}], [{}]",
116                                 dbPropName, type.getSimpleName(), cardinality);
117                         PropertyKey propK;
118                         if (!seenProps.containsKey(dbPropName)) {
119                             propK = graphMgmt.makePropertyKey(dbPropName).dataType(type).cardinality(cardinality)
120                                     .make();
121                             if (dbPropName.equals("aai-uri")) {
122                                 String aai_uri_lock_enabled = AAIConfig.get(AAIConstants.AAI_LOCK_URI_ENABLED, "false");
123                                 LOGGER.info(" Info: aai_uri_lock_enabled:" + aai_uri_lock_enabled);
124                                 if ("true".equals(aai_uri_lock_enabled)) {
125                                     LOGGER.info(" Lock is being set for aai-uri Property.");
126                                     graphMgmt.setConsistency(propK, ConsistencyModifier.LOCK);
127                                 }
128                             }
129                             else if (dbPropName.equals("resource-version")) {
130                                 String aai_rv_lock_enabled = AAIConfig.get(AAIConstants.AAI_LOCK_RV_ENABLED, "false");
131                                 LOGGER.info(" Info: aai_rv_lock_enabled:" + aai_rv_lock_enabled);
132                                 if ("true".equals(aai_rv_lock_enabled)) {
133                                     LOGGER.info(" Lock is being set for resource-version Property.");
134                                     graphMgmt.setConsistency(propK, ConsistencyModifier.LOCK);
135                                 }
136                             }
137                             seenProps.put(dbPropName, propK);
138                         } else {
139                             propK = seenProps.get(dbPropName);
140                         }
141                         if (graphMgmt.containsGraphIndex(dbPropName)) {
142                             LOGGER.debug(" Index  [{}] already existed in the DB. ", dbPropName);
143                         } else {
144                             if (obj.getIndexedProperties().contains(propName)) {
145                                 JanusGraphIndex indexG = null;
146                                 if (obj.getUniqueProperties().contains(propName)) {
147                                     LOGGER.info("Add Unique index for PropertyKey: [{}]", dbPropName);
148                                     indexG = graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).unique()
149                                            .buildCompositeIndex();
150                                 } else {
151                                     LOGGER.info("Add index for PropertyKey: [{}]", dbPropName);
152                                     indexG = graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).buildCompositeIndex();
153                                 }
154                                 if (indexG != null && dbPropName.equals("aai-uri")) {
155                                     String aai_uri_lock_enabled = AAIConfig.get(AAIConstants.AAI_LOCK_URI_ENABLED, "false");
156                                     LOGGER.info(" Info:: aai_uri_lock_enabled:" + aai_uri_lock_enabled);
157                                     if ("true".equals(aai_uri_lock_enabled)) {
158                                         LOGGER.info("Lock is being set for aai-uri Index.");
159                                         graphMgmt.setConsistency(indexG, ConsistencyModifier.LOCK);
160                                     }
161                                 }
162                                 else if (indexG != null && dbPropName.equals("resource-version")) {
163                                     String aai_rv_lock_enabled = AAIConfig.get(AAIConstants.AAI_LOCK_RV_ENABLED, "false");
164                                     LOGGER.info(" Info:: aai_rv_lock_enabled:" + aai_rv_lock_enabled);
165                                     if ("true".equals(aai_rv_lock_enabled)) {
166                                         LOGGER.info("Lock is being set for resource-version Index.");
167                                         graphMgmt.setConsistency(indexG, ConsistencyModifier.LOCK);
168                                     }
169                                 }
170                             } else {
171                                 LOGGER.info("No index added for PropertyKey: [{}]", dbPropName);
172                             }
173                         }
174                     }
175                 }
176             }
177         }
178
179         LOGGER.info("-- About to call graphMgmt commit");
180         if (backend != null) {
181             LOGGER.info("Successfully loaded the schema to {}", backend);
182         }
183
184         graphMgmt.commit();
185     }
186
187     private static void makeEdgeLabels(JanusGraphManagement graphMgmt) {
188         try {
189             EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
190
191             Set<String> labels = Optional.ofNullable(edgeIngestor.getAllCurrentRules())
192                     .map(collectValues(EdgeRule::getLabel))
193                     .orElseGet(HashSet::new);
194
195             labels.forEach(label -> {
196                 if (graphMgmt.containsRelationType(label)) {
197                     LOGGER.debug(" EdgeLabel  [{}] already existed. ", label);
198                 } else {
199                     LOGGER.debug("Making EdgeLabel: [{}]", label);
200                     graphMgmt.makeEdgeLabel(label).multiplicity(Multiplicity.valueOf("MULTI")).make();
201                 }
202             });
203         } catch (EdgeRuleNotFoundException e) {
204             LOGGER.error("Unable to find all rules {}", LogFormatTools.getStackTop(e));
205         }
206     }
207
208     /**
209      * Returns a function collecting all the values in a {@link com.google.common.collect.Multimap}
210      * given a mapping function
211      *
212      * @param f The mapper function
213      * @param <K> The type of key used by the provided {@link com.google.common.collect.Multimap}
214      * @param <V> The type of value used by the provided {@link com.google.common.collect.Multimap}
215      * @param <V0> The type which <V> is mapped to
216      */
217     private static <K, V, V0> Function<Multimap<K, V>, Set<V0>> collectValues(Function<V, V0> f) {
218         return as -> as.values().stream().map(f).collect(Collectors.toSet());
219     }
220
221 }