aboutsummaryrefslogtreecommitdiffstats
path: root/ajsc-aai/src/main/java/org/openecomp/aai/db/schema/ManageTitanSchema.java
blob: 0824f615f7308840b9cf3a01ad29bce06680773e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*-
 * ============LICENSE_START=======================================================
 * org.openecomp.aai
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.aai.db.schema;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.openecomp.aai.introspection.Version;

import com.thinkaurelius.titan.core.PropertyKey;
import com.thinkaurelius.titan.core.TitanGraph;
import com.thinkaurelius.titan.core.schema.SchemaStatus;
import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
import com.thinkaurelius.titan.core.schema.TitanManagement;
import com.thinkaurelius.titan.core.schema.TitanManagement.IndexBuilder;

public class ManageTitanSchema {

	
	private TitanManagement graphMgmt;
	private TitanGraph graph;
	private List<DBProperty> aaiProperties;
	private List<DBIndex> aaiIndexes;
	private List<EdgeProperty> aaiEdgeProperties;
	private Auditor oxmInfo = null;
	private Auditor graphInfo = null;
	
	/**
	 * Instantiates a new manage titan schema.
	 *
	 * @param graph the graph
	 */
	public ManageTitanSchema(final TitanGraph graph) {
		this.graph = graph;
		oxmInfo = AuditorFactory.getOXMAuditor(Version.v8);
		graphInfo = AuditorFactory.getGraphAuditor(graph);
	}
	
	
	/**
	 * Builds the schema.
	 */
	public void buildSchema() {
		
		this.graphMgmt = graph.openManagement();
		aaiProperties = new ArrayList<>();
		aaiEdgeProperties = new ArrayList<>();
		aaiIndexes = new ArrayList<>();
		aaiProperties.addAll(oxmInfo.getAuditDoc().getProperties());
		aaiIndexes.addAll(oxmInfo.getAuditDoc().getIndexes());
		aaiEdgeProperties.addAll(oxmInfo.getAuditDoc().getEdgeLabels());
		try {
			createPropertyKeys();
			createIndexes();
			createEdgeLabels();
		} catch (Exception e) {
			e.printStackTrace();
			graphMgmt.rollback();
		}
		graphMgmt.commit();
	}
	
	/**
	 * Creates the property keys.
	 */
	private void createPropertyKeys() {
		
		
		for (DBProperty prop : aaiProperties) {
			
			if (graphMgmt.containsPropertyKey(prop.getName())) {
				PropertyKey key = graphMgmt.getPropertyKey(prop.getName());
				boolean isChanged = false;
				if (!prop.getCardinality().equals(key.cardinality())) {
					isChanged = true;
				}
				if (!prop.getTypeClass().equals(key.dataType())) {
					isChanged = true;
				}
				if (isChanged) {
					//must modify!
					this.replaceProperty(prop);
				}
			} else {
				//create a new property key
				System.out.println("Key: " + prop.getName() + " not found - adding");
				graphMgmt.makePropertyKey(prop.getName()).dataType(prop.getTypeClass()).cardinality(prop.getCardinality()).make();
			}
		}
		
	}
	
	/**
	 * Creates the indexes.
	 */
	private void createIndexes() {
		
		for (DBIndex index : aaiIndexes) {
			Set<DBProperty> props = index.getProperties();
			boolean isChanged = false;
			boolean isNew = false;
			List<PropertyKey> keyList = new ArrayList<>();
			for (DBProperty prop : props) {
				keyList.add(graphMgmt.getPropertyKey(prop.getName()));
			}
			if (graphMgmt.containsGraphIndex(index.getName())) {
				TitanGraphIndex titanIndex = graphMgmt.getGraphIndex(index.getName());
				PropertyKey[] dbKeys = titanIndex.getFieldKeys();
				if (dbKeys.length != keyList.size()) {
					isChanged = true;
				} else {
					int i = 0;
					for (PropertyKey key : keyList) {
						if (!dbKeys[i].equals(key)) {
							isChanged = true;
							break;
						}
						i++;
					}
				}
			} else {
				isNew = true;
			}
			if (keyList.size() > 0) {
				this.createIndex(graphMgmt, index.getName(), keyList, index.isUnique(), isNew, isChanged);
			}
		}
	}
	
	// Use EdgeRules to make sure edgeLabels are defined in the db.  NOTE: the multiplicty used here is 
	// always "MULTI".  This is not the same as our internal "Many2Many", "One2One", "One2Many" or "Many2One"
	// We use the same edge-label for edges between many different types of nodes and our internal
	// multiplicty definitions depends on which two types of nodes are being connected.
	/**
	 * Creates the edge labels.
	 */
	private void createEdgeLabels() {
		
		
		for (EdgeProperty prop : aaiEdgeProperties) {
		
			if (graphMgmt.containsEdgeLabel(prop.getName())) {
				// see what changed
			} else {
				graphMgmt.makeEdgeLabel(prop.getName()).multiplicity(prop.getMultiplicity()).make();
			}
			
		}
		
		
	}
	
	/**
	 * Creates the property.
	 *
	 * @param mgmt the mgmt
	 * @param prop the prop
	 */
	private void createProperty(TitanManagement mgmt, DBProperty prop) {
		if (mgmt.containsPropertyKey(prop.getName())) {
			PropertyKey key = mgmt.getPropertyKey(prop.getName());
			boolean isChanged = false;
			if (!prop.getCardinality().equals(key.cardinality())) {
				isChanged = true;
			}
			if (!prop.getTypeClass().equals(key.dataType())) {
				isChanged = true;
			}
			if (isChanged) {
				//must modify!
				this.replaceProperty(prop);
			}
		} else {
			//create a new property key
			System.out.println("Key: " + prop.getName() + " not found - adding");
			mgmt.makePropertyKey(prop.getName()).dataType(prop.getTypeClass()).cardinality(prop.getCardinality()).make();
		}
	}
	
	/**
	 * Creates the index.
	 *
	 * @param mgmt the mgmt
	 * @param indexName the index name
	 * @param keys the keys
	 * @param isUnique the is unique
	 * @param isNew the is new
	 * @param isChanged the is changed
	 */
	private void createIndex(TitanManagement mgmt, String indexName, List<PropertyKey> keys, boolean isUnique, boolean isNew, boolean isChanged) {
		
		/*if (isChanged) {
			System.out.println("Changing index: " + indexName);
			TitanGraphIndex oldIndex = mgmt.getGraphIndex(indexName);
			mgmt.updateIndex(oldIndex, SchemaAction.DISABLE_INDEX);
			mgmt.commit();
			//cannot remove indexes
			//graphMgmt.updateIndex(oldIndex, SchemaAction.REMOVE_INDEX);
		}*/
		if (isNew || isChanged) {
			
			if (isNew) {
				IndexBuilder builder = mgmt.buildIndex(indexName,Vertex.class);
				for (PropertyKey k : keys) {
					builder.addKey(k);
				}
				if (isUnique) {
					builder.unique();
				}
				builder.buildCompositeIndex();
				System.out.println("Built index for " + indexName + " with keys: " + keys);

				//mgmt.commit();
			}

			//mgmt = graph.getManagementSystem();
			//mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.REGISTER_INDEX);
			//mgmt.commit();
			
			try {
				//waitForCompletion(indexName);
				//TitanIndexRepair.hbaseRepair(AAIConstants.AAI_CONFIG_FILENAME, indexName, "");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				graph.tx().rollback();
				graph.close();
				e.printStackTrace();
			}
			
			//mgmt = graph.getManagementSystem();
			//mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.REINDEX);
			
			//mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.ENABLE_INDEX);
			
			//mgmt.commit();
			
		}
	}
	
	/**
	 * Wait for completion.
	 *
	 * @param name the name
	 * @throws InterruptedException the interrupted exception
	 */
	private void waitForCompletion(String name) throws InterruptedException {
		
		boolean registered = false;
		long before = System.currentTimeMillis();
		while (!registered) {
		    Thread.sleep(500L);
		    TitanManagement mgmt = graph.openManagement();
		    TitanGraphIndex idx  = mgmt.getGraphIndex(name);
		    registered = true;
		    for (PropertyKey k : idx.getFieldKeys()) {
		        SchemaStatus s = idx.getIndexStatus(k);  
		        registered &= s.equals(SchemaStatus.REGISTERED);
		    }
		    mgmt.rollback();
		}
		System.out.println("Index REGISTERED in " + (System.currentTimeMillis() - before) + " ms");
	}
	
	/**
	 * Replace property.
	 *
	 * @param key the key
	 */
	private void replaceProperty(DBProperty key) {
		
		
		
		
	}

	/**
	 * Update index.
	 *
	 * @param index the index
	 */
	public void updateIndex(DBIndex index) {

		TitanManagement mgmt = graph.openManagement();
		List<PropertyKey> keys = new ArrayList<>();
		boolean isNew = false;
		boolean isChanged = false;
		for (DBProperty prop : index.getProperties()) {
			createProperty(mgmt, prop);
			keys.add(mgmt.getPropertyKey(prop.getName()));
		}
		if (mgmt.containsGraphIndex(index.getName())) {
			System.out.println("index already exists");
			isNew = false;
			isChanged = true;
		} else {
			isNew = true;
			isChanged = false;
		}
		this.createIndex(mgmt, index.getName(), keys, index.isUnique(), isNew, isChanged);

		mgmt.commit();
		
	}
	
	
	
	
	
}