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