Fixed concurrency issue in PNF uploading
[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                             seenProps.put(dbPropName, propK);
130                         } else {
131                             propK = seenProps.get(dbPropName);
132                         }
133                         if (graphMgmt.containsGraphIndex(dbPropName)) {
134                             LOGGER.debug(" Index  [{}] already existed in the DB. ", dbPropName);
135                         } else {
136                             if (obj.getIndexedProperties().contains(propName)) {
137                                 JanusGraphIndex indexG = null;
138                                 if (obj.getUniqueProperties().contains(propName)) {
139                                     LOGGER.info("Add Unique index for PropertyKey: [{}]", dbPropName);
140                                     indexG = graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).unique()
141                                            .buildCompositeIndex();
142                                 } else {
143                                     LOGGER.info("Add index for PropertyKey: [{}]", dbPropName);
144                                     indexG = graphMgmt.buildIndex(dbPropName, Vertex.class).addKey(propK).buildCompositeIndex();
145                                 }
146                                 if (indexG != null && dbPropName.equals("aai-uri")) {
147                                     String aai_uri_lock_enabled = AAIConfig.get(AAIConstants.AAI_LOCK_URI_ENABLED, "false");
148                                     LOGGER.info(" Info:: aai_uri_lock_enabled:" + aai_uri_lock_enabled);
149                                     if ("true".equals(aai_uri_lock_enabled)) {
150                                         LOGGER.info("Lock is being set for aai-uri Index.");
151                                         graphMgmt.setConsistency(indexG, ConsistencyModifier.LOCK);
152                                     }
153                                 }
154                             } else {
155                                 LOGGER.info("No index added for PropertyKey: [{}]", dbPropName);
156                             }
157                         }
158                     }
159                 }
160             }
161         }
162
163         LOGGER.info("-- About to call graphMgmt commit");
164         if (backend != null) {
165             LOGGER.info("Successfully loaded the schema to {}", backend);
166         }
167
168         graphMgmt.commit();
169     }
170
171     private static void makeEdgeLabels(JanusGraphManagement graphMgmt) {
172         try {
173             EdgeIngestor edgeIngestor = SpringContextAware.getBean(EdgeIngestor.class);
174
175             Set<String> labels = Optional.ofNullable(edgeIngestor.getAllCurrentRules())
176                     .map(collectValues(EdgeRule::getLabel))
177                     .orElseGet(HashSet::new);
178
179             labels.forEach(label -> {
180                 if (graphMgmt.containsRelationType(label)) {
181                     LOGGER.debug(" EdgeLabel  [{}] already existed. ", label);
182                 } else {
183                     LOGGER.debug("Making EdgeLabel: [{}]", label);
184                     graphMgmt.makeEdgeLabel(label).multiplicity(Multiplicity.valueOf("MULTI")).make();
185                 }
186             });
187         } catch (EdgeRuleNotFoundException e) {
188             LOGGER.error("Unable to find all rules {}", LogFormatTools.getStackTop(e));
189         }
190     }
191
192     /**
193      * Returns a function collecting all the values in a {@link com.google.common.collect.Multimap}
194      * given a mapping function
195      *
196      * @param f The mapper function
197      * @param <K> The type of key used by the provided {@link com.google.common.collect.Multimap}
198      * @param <V> The type of value used by the provided {@link com.google.common.collect.Multimap}
199      * @param <V0> The type which <V> is mapped to
200      */
201     private static <K, V, V0> Function<Multimap<K, V>, Set<V0>> collectValues(Function<V, V0> f) {
202         return as -> as.values().stream().map(f).collect(Collectors.toSet());
203     }
204
205 }