72beb8520eb134466e4b298422a65fafa235c47d
[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.io.IoCore;
33
34 import org.openecomp.aai.dbgen.SchemaGenerator;
35 import org.openecomp.aai.exceptions.AAIException;
36 import org.openecomp.aai.util.AAIConstants;
37 import com.att.eelf.configuration.EELFLogger;
38 import com.att.eelf.configuration.EELFManager;
39 import com.thinkaurelius.titan.core.TitanFactory;
40 import com.thinkaurelius.titan.core.TitanGraph;
41 import com.thinkaurelius.titan.core.TitanTransaction;
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         protected Map<String, TitanGraph> graphs = new HashMap<>();
58         protected static final String COMPONENT = "aaidbmap";
59         private final String REALTIME_DB = "realtime";
60         private final String CACHED_DB = "cached";
61         private final EELFLogger logger = EELFManager.getInstance().getLogger(this.getClass().getSimpleName());
62
63
64         /**
65          * Instantiates a new AAI graph.
66          */
67         private AAIGraph() {
68                 try {
69                         String rtConfig = System.getProperty("realtime.db.config");
70                         String cachedConfig = System.getProperty("cached.db.config");
71                         if (rtConfig == null) {
72                                 rtConfig = AAIConstants.REALTIME_DB_CONFIG;
73                         }
74                         if (cachedConfig == null) {
75                                 cachedConfig = AAIConstants.CACHED_DB_CONFIG;
76                         }
77                         this.loadGraph(REALTIME_DB, rtConfig);
78                         this.loadGraph(CACHED_DB, cachedConfig);
79                 } catch (Exception e) {
80                         throw new RuntimeException("Failed to instantiate graphs", e);
81                 }
82         }
83         
84         private static class Helper {
85                 private static final AAIGraph INSTANCE = new AAIGraph();
86         }
87         
88         /**
89          * Gets the single instance of AAIGraph.
90          *
91          * @return single instance of AAIGraph
92          */
93         public static AAIGraph getInstance() {
94                 return Helper.INSTANCE;
95         }
96         
97         private void loadGraph(String name, String configPath) throws AAIException {
98                 try {
99                         final TitanGraph graph = TitanFactory.open(configPath);
100                         InputStream is = new FileInputStream(configPath);
101                 Properties graphProps = new Properties();
102                 graphProps.load(is);
103                 
104                         if (graphProps.get("storage.backend").equals("inmemory")) { 
105                                 // Load the propertyKeys, indexes and edge-Labels into the DB
106                                 loadSchema(graph);
107                                 if (graphProps.containsKey("load.snapshot.file")) {
108                                         String value = graphProps.getProperty("load.snapshot.file");
109                                         if ("true".equals(value)) {
110                                                 try {
111                                                         String location = System.getProperty("snapshot.location");
112                                                         logAndPrint(logger, "Loading snapshot to inmemory graph.");
113                                                         TitanTransaction transaction = graph.newTransaction();
114                                                         transaction.io(IoCore.graphson()).readGraph(location);
115                                                         transaction.commit();
116                                                         logAndPrint(logger, "Snapshot loaded to inmemory graph.");
117                                                 } catch (IOException e) {
118                                                         graph.close();
119                                                         logAndPrint(logger, "ERROR: Could not load datasnapshot to in memory graph. \n" + ExceptionUtils.getFullStackTrace(e));
120                                                         System.exit(0);
121                                                 }
122                                         }
123                                 }
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         
139         private void loadSchema(TitanGraph graph) {
140                 // Load the propertyKeys, indexes and edge-Labels into the DB
141                 TitanManagement graphMgt = graph.openManagement();
142                 
143                 System.out.println("-- loading schema into Titan");
144                 SchemaGenerator.loadSchemaIntoTitan( graph, graphMgt );
145         }
146
147         /**
148          * Graph shutdown.
149          */
150         public void graphShutdown() {
151                 graphs.get(REALTIME_DB).close();
152         }
153
154         /**
155          * Gets the graph.
156          *
157          * @return the graph
158          */
159         public TitanGraph getGraph() {
160                 return graphs.get(REALTIME_DB);
161         }
162         
163         public void graphShutdown(DBConnectionType connectionType) {
164                 
165                 graphs.get(this.getGraphName(connectionType)).close();
166         }
167         
168         public TitanGraph getGraph(DBConnectionType connectionType) {
169                 return graphs.get(this.getGraphName(connectionType));
170         }
171         
172         private String getGraphName(DBConnectionType connectionType) {
173                 String graphName = "";
174                 if (DBConnectionType.CACHED.equals(connectionType)) {
175                         graphName = this.CACHED_DB;
176                 } else if (DBConnectionType.REALTIME.equals(connectionType)) {
177                         graphName = this.REALTIME_DB;
178                 }
179                 
180                 return graphName;
181         }
182         
183         private void logAndPrint(EELFLogger logger, String msg) {
184                 System.out.println(msg);
185                 logger.info(msg);
186         }
187 }