Merge "renaming/constant instead of literal/unused items"
[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 package org.onap.aai.dbmap;
23
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.Properties;
31
32 import org.apache.commons.configuration.PropertiesConfiguration;
33 import org.apache.commons.lang.exception.ExceptionUtils;
34 import org.apache.tinkerpop.gremlin.structure.Graph;
35 import org.apache.tinkerpop.gremlin.structure.io.IoCore;
36 import org.onap.aai.dbgen.SchemaGenerator;
37 import org.onap.aai.exceptions.AAIException;
38 import org.onap.aai.util.AAIConstants;
39
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
42 import org.janusgraph.core.JanusGraphFactory;
43 import org.janusgraph.core.JanusGraph;
44 import org.janusgraph.core.schema.JanusGraphManagement;
45
46 /**
47  * Database Mapping class which acts as the middle man between the REST
48  * interface objects and JanusGraph DB objects. This class provides methods to commit
49  * the objects received on the REST interface into the JanusGraph graph database as
50  * vertices and edges. Transactions are also managed here by using a JanusGraph
51  * object to load, commit/rollback and shutdown for each request. The data model
52  * rules such as keys/required properties are handled by calling DBMeth methods
53  * which are driven by a specification file in json.
54  * 
55  
56  */
57 public class AAIGraph {
58
59     private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIGraph.class);
60     protected static final String COMPONENT = "aaidbmap";
61     protected Map<String, JanusGraph> graphs = new HashMap<>();
62     private static final String REALTIME_DB = "realtime";
63     private static final String CACHED_DB = "cached";
64     private static boolean isInit = false;
65
66
67
68     /**
69      * Instantiates a new AAI graph.
70      */
71     private AAIGraph() {
72         try {
73             String serviceName = System.getProperty("aai.service.name", "NA");
74             String rtConfig = System.getProperty("realtime.db.config");
75             String cachedConfig = System.getProperty("cached.db.config");
76             if (rtConfig == null) {
77                 rtConfig = AAIConstants.REALTIME_DB_CONFIG;
78             }
79             if (cachedConfig == null) {
80                 cachedConfig = AAIConstants.CACHED_DB_CONFIG;
81             }
82             this.loadGraph(REALTIME_DB, rtConfig, serviceName);
83             this.loadGraph(CACHED_DB, cachedConfig, serviceName);
84         } catch (Exception e) {
85             throw new RuntimeException("Failed to instantiate graphs", e);
86         }
87     }
88     
89     private static class Helper {
90         private static final AAIGraph INSTANCE = new AAIGraph();
91         private Helper() {
92             
93         }
94     }
95     
96     /**
97      * Gets the single instance of AAIGraph.
98      *
99      * @return single instance of AAIGraph
100      */
101     public static AAIGraph getInstance() {
102         isInit = true;
103         return Helper.INSTANCE;
104     }
105
106     public static boolean isInit() {
107         return isInit;
108     }
109     
110     private void loadGraph(String name, String configPath, String serviceName) throws Exception {
111         // Graph being opened by JanusGraphFactory is being placed in hashmap to be used later
112         // These graphs shouldn't be closed until the application shutdown
113         try {
114             PropertiesConfiguration propertiesConfiguration = new AAIGraphConfig.Builder(configPath).forService(serviceName).withGraphType(name).buildConfiguration();
115             JanusGraph graph = JanusGraphFactory.open(propertiesConfiguration);
116
117             Properties graphProps = new Properties();
118             propertiesConfiguration.getKeys().forEachRemaining(k -> graphProps.setProperty(k, propertiesConfiguration.getString(k)));
119
120             if ("inmemory".equals(graphProps.get("storage.backend"))) {
121                 // Load the propertyKeys, indexes and edge-Labels into the DB
122                 loadSchema(graph);
123                 loadSnapShotToInMemoryGraph(graph, graphProps);
124             }
125
126             if (graph == null) {
127                 throw new AAIException("AAI_5102");
128             }
129
130             graphs.put(name, graph);
131         } catch (FileNotFoundException fnfe) {
132             throw new AAIException("AAI_4001");
133         } catch (IOException e) {
134             throw new AAIException("AAI_4002");
135         }
136     }
137
138     private void loadSnapShotToInMemoryGraph(JanusGraph graph, Properties graphProps) {
139         if (logger.isDebugEnabled()) {
140             logger.debug("Load Snapshot to InMemory Graph");
141         }
142         if (graphProps.containsKey("load.snapshot.file")) {
143             String value = graphProps.getProperty("load.snapshot.file");
144             if ("true".equals(value)) {
145                 try (Graph transaction = graph.newTransaction()) {
146                     String location = System.getProperty("snapshot.location");
147                     logAndPrint(logger, "Loading snapshot to inmemory graph.");
148                     transaction.io(IoCore.graphson()).readGraph(location);
149                     transaction.tx().commit();
150                     logAndPrint(logger, "Snapshot loaded to inmemory graph.");
151                 } catch (Exception e) {
152                     logAndPrint(logger,
153                         "ERROR: Could not load datasnapshot to in memory graph. \n"
154                             + ExceptionUtils.getFullStackTrace(e));
155                     throw new RuntimeException(e);
156                 }
157             }
158         }
159     }
160
161     private void loadSchema(JanusGraph graph) {
162         // Load the propertyKeys, indexes and edge-Labels into the DB
163         JanusGraphManagement graphMgt = graph.openManagement();
164         
165         System.out.println("-- loading schema into JanusGraph");
166         SchemaGenerator.loadSchemaIntoJanusGraph( graph, graphMgt, "inmemory");
167     }
168
169     /**
170      * Close all of the graph connections made in the instance.
171      */
172     public void graphShutdown() {
173         graphs.values().stream().filter(JanusGraph::isOpen).forEach(JanusGraph::close);
174     }
175
176     /**
177      * Gets the graph.
178      *
179      * @return the graph
180      */
181     public JanusGraph getGraph() {
182         return graphs.get(REALTIME_DB);
183     }
184     
185     public void graphShutdown(DBConnectionType connectionType) {
186         
187         graphs.get(this.getGraphName(connectionType)).close();
188     }
189     
190     public JanusGraph getGraph(DBConnectionType connectionType) {
191         return graphs.get(this.getGraphName(connectionType));
192     }
193     
194     private String getGraphName(DBConnectionType connectionType) {
195         String graphName = "";
196         if (DBConnectionType.CACHED.equals(connectionType)) {
197             graphName = this.CACHED_DB;
198         } else if (DBConnectionType.REALTIME.equals(connectionType)) {
199             graphName = this.REALTIME_DB;
200         }
201         
202         return graphName;
203     }
204     
205     private void logAndPrint(EELFLogger logger, String msg) {
206         System.out.println(msg);
207         logger.info(msg);
208     }
209 }