Enhancements for the aai-common library
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / dbmap / AAIGraph.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  *  Modifications Copyright © 2018 IBM.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *    http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.aai.dbmap;
24
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import org.apache.commons.configuration.PropertiesConfiguration;
28 import org.apache.commons.lang.exception.ExceptionUtils;
29 import org.apache.tinkerpop.gremlin.structure.Graph;
30 import org.apache.tinkerpop.gremlin.structure.io.IoCore;
31 import org.janusgraph.core.JanusGraph;
32 import org.janusgraph.core.JanusGraphFactory;
33 import org.janusgraph.core.schema.JanusGraphManagement;
34 import org.onap.aai.config.SpringContextAware;
35 import org.onap.aai.dbgen.SchemaGenerator;
36 import org.onap.aai.dbgen.SchemaGenerator4Hist;
37 import org.onap.aai.exceptions.AAIException;
38 import org.onap.aai.util.AAIConstants;
39
40 import java.io.FileNotFoundException;
41 import java.util.Properties;
42
43 /**
44  * Database Mapping class which acts as the middle man between the REST
45  * interface objects and JanusGraph DB objects. This class provides methods to commit
46  * the objects received on the REST interface into the JanusGraph graph database as
47  * vertices and edges. Transactions are also managed here by using a JanusGraph
48  * object to load, commit/rollback and shutdown for each request. The data model
49  * rules such as keys/required properties are handled by calling DBMeth methods
50  * which are driven by a specification file in json.
51  *
52  *
53  */
54 public class AAIGraph {
55
56     private static final Logger logger = LoggerFactory.getLogger(AAIGraph.class);
57     protected JanusGraph graph;
58     private static boolean isInit = false;
59
60     /**
61      * Instantiates a new AAI graph.
62      */
63     private AAIGraph() {
64         try {
65             String serviceName = System.getProperty("aai.service.name", "NA");
66             String rtConfig = System.getProperty("realtime.db.config");
67             if (rtConfig == null) {
68                 rtConfig = AAIConstants.REALTIME_DB_CONFIG;
69             }
70             this.loadGraph(rtConfig, serviceName);
71         } catch (Exception e) {
72             throw new RuntimeException("Failed to instantiate graphs", e);
73         }
74     }
75
76     private static class Helper {
77         private static final AAIGraph INSTANCE = new AAIGraph();
78
79         private Helper() {
80
81         }
82     }
83
84     /**
85      * Gets the single instance of AAIGraph.
86      *
87      * @return single instance of AAIGraph
88      */
89     public static AAIGraph getInstance() {
90         isInit = true;
91         return Helper.INSTANCE;
92     }
93
94     public static boolean isInit() {
95         return isInit;
96     }
97
98     private void loadGraph(String configPath, String serviceName) throws Exception {
99         // Graph being opened by JanusGraphFactory is being placed in hashmap to be used later
100         // These graphs shouldn't be closed until the application shutdown
101         try {
102             PropertiesConfiguration propertiesConfiguration = new AAIGraphConfig.Builder(configPath)
103                     .forService(serviceName).withGraphType("realtime").buildConfiguration();
104             graph = JanusGraphFactory.open(propertiesConfiguration);
105
106             Properties graphProps = new Properties();
107             propertiesConfiguration.getKeys()
108                     .forEachRemaining(k -> graphProps.setProperty(k, propertiesConfiguration.getString(k)));
109
110             if ("inmemory".equals(graphProps.get("storage.backend"))) {
111                 // Load the propertyKeys, indexes and edge-Labels into the DB
112                 loadSchema(graph);
113                 loadSnapShotToInMemoryGraph(graph, graphProps);
114             }
115
116             if (graph == null) {
117                 throw new AAIException("AAI_5102");
118             }
119
120         } catch (FileNotFoundException e) {
121             throw new AAIException("AAI_4001", e);
122         }
123     }
124
125     private void loadSnapShotToInMemoryGraph(JanusGraph graph, Properties graphProps) {
126         if (logger.isDebugEnabled()) {
127             logger.debug("Load Snapshot to InMemory Graph");
128         }
129         if (graphProps.containsKey("load.snapshot.file")) {
130             String value = graphProps.getProperty("load.snapshot.file");
131             if ("true".equals(value)) {
132                 try (Graph transaction = graph.newTransaction()) {
133                     String location = System.getProperty("snapshot.location");
134                     logAndPrint("Loading snapshot to inmemory graph.");
135                     transaction.io(IoCore.graphson()).readGraph(location);
136                     transaction.tx().commit();
137                     logAndPrint("Snapshot loaded to inmemory graph.");
138                 } catch (Exception e) {
139                     logAndPrint("ERROR: Could not load datasnapshot to in memory graph. \n"
140                             + ExceptionUtils.getFullStackTrace(e));
141                     throw new RuntimeException(e);
142                 }
143             }
144         }
145     }
146
147     private void loadSchema(JanusGraph graph) {
148         // Load the propertyKeys, indexes and edge-Labels into the DB
149         JanusGraphManagement graphMgt = graph.openManagement();
150
151         System.out.println("-- loading schema into JanusGraph");
152         if ("true".equals(SpringContextAware.getApplicationContext().getEnvironment().getProperty("history.enabled", "false"))) {
153             SchemaGenerator4Hist.loadSchemaIntoJanusGraph(graph, graphMgt, "inmemory");
154         } else {
155             SchemaGenerator.loadSchemaIntoJanusGraph(graph, graphMgt, "inmemory");
156         }
157     }
158
159     /**
160      * Close all of the graph connections made in the instance.
161      */
162     public void graphShutdown() {
163         if (graph != null && graph.isOpen()) {
164             graph.close();
165         }
166     }
167
168     /**
169      * Gets the graph.
170      *
171      * @return the graph
172      */
173     public JanusGraph getGraph() {
174         return graph;
175     }
176
177     private void logAndPrint(String msg) {
178         System.out.println(msg);
179         logger.info(msg);
180     }
181 }