aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/aai/historytruncate/HistoryTruncate.java
blob: 45b5d049f00eeefea81bee5703d982c08c983526 (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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 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.onap.aai.historytruncate;

import java.util.*;
import java.util.concurrent.TimeUnit;

import org.onap.aai.config.PropertyPasswordConfiguration;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.logging.ErrorLogHelper;
import org.onap.aai.logging.LogFormatTools;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
import org.onap.aai.util.AAISystemExitUtil;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.att.eelf.configuration.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.janusgraph.core.JanusGraph;

public class HistoryTruncate {

	private static Logger LOGGER = LoggerFactory.getLogger(HistoryTruncate.class);
	
	/* Using realtime d */
	private static final String REALTIME_DB = "realtime";
	
	private static final String LOG_ONLY_MODE = "LOG_ONLY";
	private static final String DELETE_AND_LOG_MODE = "DELETE_AND_LOG";
	private static final String SILENT_DELETE_MODE = "SILENT_DELETE";	
	static ArrayList <String> VALIDMODES = new <String> ArrayList ();
	static {
		VALIDMODES.add(LOG_ONLY_MODE);
		VALIDMODES.add(DELETE_AND_LOG_MODE);
		VALIDMODES.add(SILENT_DELETE_MODE);
	}

	private static final int batchCommitSize = 500;  
	
	private static boolean historyEnabled;
	private static String defaultTruncateMode;
	private static Integer defaultTruncateWindowDays;

	
	/**
	 * The main method.
	 *
	 */
	public static void main(String[] args) {
		
		// Set the logging file properties to be used by EELFManager
		System.setProperty("aai.service.name", HistoryTruncate.class.getSimpleName());
		Properties props = System.getProperties();
		props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_LOGBACK_PROPS);
		props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_BUNDLECONFIG);
			
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		PropertyPasswordConfiguration initializer = new PropertyPasswordConfiguration();
		initializer.initialize(ctx);
		try {
			ctx.scan(
					"org.onap.aai.config",
					"org.onap.aai.setup"
			);
			ctx.refresh();
		} catch (Exception e) {
			LOGGER.error("Error - Could not initialize context beans for HistoryTruncate. ");
			AAISystemExitUtil.systemExitCloseAAIGraph(1);
		}
		
		historyEnabled = Boolean.parseBoolean(ctx.getEnvironment().getProperty("history.enabled","false"));
		if( !historyEnabled ) {
			String emsg = "Error - HistoryTruncate may only be used when history.enabled=true. ";
			System.out.println(emsg);
			LOGGER.error(emsg);
			AAISystemExitUtil.systemExitCloseAAIGraph(1);
		}
		
		defaultTruncateWindowDays = Integer.parseInt(ctx.getEnvironment().getProperty("history.truncate.window.days","999"));
		defaultTruncateMode = ctx.getEnvironment().getProperty("history.truncate.mode",LOG_ONLY_MODE);
			
		HistoryTruncate histTrunc = new HistoryTruncate();	
		boolean success = histTrunc.executeCommand(args);
		if(success){
			AAISystemExitUtil.systemExitCloseAAIGraph(0);
		} else {
			AAISystemExitUtil.systemExitCloseAAIGraph(1);
		}

	}// End of main()


	public boolean executeCommand(String[] args) {
		boolean successStatus = true;
		// If they passed in args on the command line, then we should 
		// use those in place of the default ones we got from environment variables.
		// "-truncateMode","LOG_ONLY","-truncateWindow","999"
		String truncateMode = defaultTruncateMode;
		int truncateWindowDays = defaultTruncateWindowDays;
				
        if (args != null && args.length > 0) {
            // They passed some arguments in that will affect processing
            for (int i = 0; i < args.length; i++) {
                String thisArg = args[i];
                if (thisArg.equals("-truncateMode")) {
                    i++;
                    if (i >= args.length) {
                        LOGGER.error(" No value passed with -truncateMode option.  ");
                        return false;
                    }
                    if( !VALIDMODES.contains(args[i]) ) {
                        LOGGER.error(" Unrecognized -truncateMode value passed: [" +
                        	args[i] + "].  Valid values = " + VALIDMODES.toString() );
                        return false;
                    }
                    truncateMode = args[i];
                } else if (thisArg.equals("-truncateWindowDays")) {
                    i++;
                    if (i >= args.length) {
                        LOGGER.error("No value passed with -truncateWindowDays option.");
                        return false;
                    }
                    String nextArg = args[i];
                    try {
                        truncateWindowDays = Integer.parseInt(nextArg);
                    } catch (Exception e) {
                        LOGGER.error("Bad value passed with -truncateWindowDays option: ["
                                + nextArg + "]");
                        return false;
                    }
                } else {
                    LOGGER.error(" Unrecognized argument passed to HistoryTruncate: ["
                            + thisArg + "]. ");
                    LOGGER.error(" Valid values are: -truncateMode -truncateWindowDays ");
                    return false;
                }
            }
        }

		LOGGER.debug(" Running HistoryTruncate with: truncateMode = " + truncateMode +
				", truncateWindowDays = " + truncateWindowDays );
		
		Long truncateEndTs = calculateTruncWindowEndTimeStamp(truncateWindowDays);
		JanusGraph jgraph = null;
		long scriptStartTime = System.currentTimeMillis();
		Boolean doLogging = doLoggingOrNot( truncateMode );
		Boolean doDelete = doDeleteOrNot( truncateMode );
		
		try {
			AAIConfig.init();
			ErrorLogHelper.loadProperties();

			LOGGER.debug("    ---- NOTE --- about to open graph (takes a little while) ");
			verifyGraph(AAIGraph.getInstance().getGraph());
			jgraph = AAIGraph.getInstance().getGraph();
			LOGGER.debug(" ---- got the new graph instance. ");
			
			// Note - process edges first so they get logged as they are deleted since
			//   edges connected to vertices being deleted would get auto-deleted by the db.
			long timeA = System.nanoTime();
			processEdges(jgraph, truncateEndTs, doLogging, doDelete);
			long timeB = System.nanoTime();
			long diffTime =  timeB - timeA;
			long minCount = TimeUnit.NANOSECONDS.toMinutes(diffTime);
			long secCount = TimeUnit.NANOSECONDS.toSeconds(diffTime) - (60 * minCount);
			LOGGER.debug(" Took this long to process the Edges: " +
					minCount + " minutes, " + secCount + " seconds " );
			
			processVerts(jgraph, truncateEndTs, doLogging, doDelete);
			long timeC = System.nanoTime();
			diffTime =  timeC - timeB;
			minCount = TimeUnit.NANOSECONDS.toMinutes(diffTime);
			secCount = TimeUnit.NANOSECONDS.toSeconds(diffTime) - (60 * minCount);
			LOGGER.debug(" Took this long to process the Vertices: " +
					minCount + " minutes, " + secCount + " seconds " );
							
		} catch (AAIException e) {
			ErrorLogHelper.logError("AAI_6128", e.getMessage());
			LOGGER.error("Encountered an exception during the historyTruncate: ", e);
			e.printStackTrace();
			successStatus = false;
		} catch (Exception ex) {
			ErrorLogHelper.logError("AAI_6128", ex.getMessage());
			LOGGER.error("Encountered an exception during the historyTruncate: ", ex);
			ex.printStackTrace();
			successStatus = false;
		} finally {
			if (jgraph != null ) {
				// Any changes that worked correctly should have already done
				// their commits.
				if(!"true".equals(System.getProperty("org.onap.aai.graphadmin.started"))) {
					if (jgraph.isOpen()) {
						jgraph.tx().rollback();
						jgraph.close();
					}
				}
			}
		}

		return successStatus;
	}
	
	
	public void processVerts(JanusGraph jgraph, Long truncBeforeTs, 
			Boolean doLogging, Boolean doDelete ) {

		Graph g = jgraph.newTransaction();
		GraphTraversalSource gts = g.traversal();
		//Iterator <Vertex> vertItr = gts.V().has(AAIProperties.END_TS, P.lt(truncBeforeTs));
		Iterator <Vertex> vertItr = gts.V().has("end-ts", P.lt(truncBeforeTs));
		ArrayList <Long> vidList = new ArrayList <Long> ();
		while( vertItr.hasNext() ) {
			Vertex tmpV = vertItr.next();
			Long tmpVid = Long.valueOf(tmpV.id().toString());
			vidList.add(tmpVid);
		}		

		int vTotalCount = vidList.size();
		int batchCount = vTotalCount / batchCommitSize;
		if((batchCount * batchCommitSize) < vTotalCount){
			batchCount++;
		}
		
		LOGGER.info( " Vertex TotalCount = " + vTotalCount +
				", we get batchCount = " + batchCount + 
				", using commit size = " + batchCommitSize );
		
		int vIndex = 0; 
		for(int batchNo=1; batchNo<=batchCount; batchNo++){
			ArrayList <Long> batchVids = new ArrayList <Long> ();
			int thisBVCount = 0; 
			while( (thisBVCount < batchCommitSize) && (vIndex < vTotalCount) ) {
				batchVids.add(vidList.get(vIndex));
				thisBVCount++;
				vIndex++;
			}
			// now process this batch
			LOGGER.info( "Process vertex batch # " + batchNo +
					", which contains " + batchVids.size() + " ids. ");			
			processVertBatch(jgraph, doLogging, doDelete, batchVids);
		}
	}

	
	private void processVertBatch(JanusGraph jgraph, Boolean doLogging, 
			Boolean doDelete, ArrayList <Long> vidList ) {

		Graph g = jgraph.newTransaction();
		GraphTraversalSource gts = g.traversal();
		int delFailCount = 0;
		int vCount = 0;
		int delCount = 0;
		
		Iterator <Vertex> vertItr = gts.V(vidList);
		while( vertItr.hasNext() ) {
			vCount++;
			Vertex tmpV = vertItr.next();
			String tmpVid = tmpV.id().toString();
			String tmpPropsStr = "";
			if( doLogging ) {
				Iterator<VertexProperty<Object>> pI = tmpV.properties();
				while( pI.hasNext() ){
					VertexProperty<Object> tp = pI.next();
					Object val = tp.value();
					tmpPropsStr = tmpPropsStr + "[" + tp.key() + "=" + val + "]";
				}
				LOGGER.info(" vid = " + tmpVid + ", props: (" + tmpPropsStr + ") " );
			}
				
			if( doDelete ) {
				LOGGER.info("Removing vid = " + tmpVid );
				try {
					tmpV.remove();
					delCount++;
				} catch ( Exception e ) {
					// figure out what to do
					delFailCount++;
					LOGGER.error("ERROR trying to delete Candidate VID = " + tmpVid + " " + LogFormatTools.getStackTop(e));
				}
			}
		}
			
		if( doDelete ) {
			LOGGER.info("Calling commit on delete of Vertices." );
			try {
				g.tx().commit();
			} catch ( Exception e ) {
				LOGGER.error("ERROR trying to commit Vertex Deletes for this batch. " + 
						LogFormatTools.getStackTop(e) );
				LOGGER.info( vCount + " candidate vertices processed.  " 
						+ " vertex deletes - COMMIT FAILED. ");
				return;
			}
		}
			
		if( doDelete ) {
			LOGGER.info( vCount + " candidate vertices processed.  " +
					delFailCount + " delete attempts failed, " +
					delCount + " deletes successful. ");
		}
		else {
			LOGGER.info( vCount + " candidate vertices processed in this batch.  " );
		}
	}

		
	public void processEdges(JanusGraph jgraph, Long truncBeforeTs, 
			Boolean doLogging, Boolean doDelete ) {

		Graph g = jgraph.newTransaction();
		GraphTraversalSource gts = g.traversal();
		//Iterator <Edge> edgeItr = gts.E().has(AAIProperties.END_TS, P.lt(truncBeforeTs));
		Iterator <Edge> edgeItr = gts.E().has("end-ts", P.lt(truncBeforeTs));
		ArrayList <String> eidList = new ArrayList <String> ();
		while( edgeItr.hasNext() ) {
			Edge tmpE = edgeItr.next();
			String tmpEid = tmpE.id().toString();
			eidList.add(tmpEid);
		}		

		int eTotalCount = eidList.size();
		int batchCount = eTotalCount / batchCommitSize;
		if((batchCount * batchCommitSize) < eTotalCount){
			batchCount++;
		}
		
		LOGGER.info( " Edge TotalCount = " + eTotalCount +
				", we get batchCount = " + batchCount + 
				", using commit size = " + batchCommitSize );
		
		int eIndex = 0; 
		for(int batchNo=1; batchNo<=batchCount; batchNo++){
			ArrayList <String> batchEids = new ArrayList <String> ();
			int thisBECount = 0; 
			while( (thisBECount < batchCommitSize) && (eIndex < eTotalCount) ) {
				batchEids.add(eidList.get(eIndex));
				thisBECount++;
				eIndex++;
			}
			// now process this batch
			LOGGER.info( "Process edge batch # " + batchNo +
					", which contains " + batchEids.size() + " ids. ");			
			processEdgeBatch(jgraph, doLogging, doDelete, batchEids);
		}
	}

	
	private void processEdgeBatch(JanusGraph jgraph, Boolean doLogging, 
			Boolean doDelete, ArrayList <String> eidList ) {

		Graph g = jgraph.newTransaction();
		GraphTraversalSource gts = g.traversal();
		int delFailCount = 0;
		int eCount = 0;
		int delCount = 0;
		
		Iterator <Edge> edgeItr = gts.E(eidList);
		while( edgeItr.hasNext() ) {
			eCount++;
			Edge tmpE = edgeItr.next();
			String tmpEid = tmpE.id().toString();
			if( doLogging ) {
				String tmpEProps = "";
				Iterator<Property<Object>> epI = tmpE.properties();
				while( epI.hasNext() ){
					Property<Object> ep = epI.next();
					Object val = ep.value();
					tmpEProps = tmpEProps + "[" + ep.key() + "=" + val + "]";
				}
				Iterator <Vertex> conVtxs = tmpE.bothVertices();
				String tmpConVs = "";
				while( conVtxs.hasNext() ) {
					Vertex conV = conVtxs.next();
					tmpConVs = tmpConVs + "[" + conV.id().toString() + "] ";
				}
				LOGGER.info(" eid = " + tmpEid 
						+ ", Connecting vids = " + tmpConVs
						+ ", props: (" + tmpEProps + "). "  );
			}
			
			if( doDelete ) {
				LOGGER.info("Removing Edge eid = " + tmpEid );
				try {
					tmpE.remove();
					delCount++;
				} catch ( Exception e ) {
					delFailCount++;
					LOGGER.error("ERROR trying to delete Candidate Edge with eid = " + tmpEid + " " + LogFormatTools.getStackTop(e));
				}
			}
		}
			
		if( doDelete ) {
			LOGGER.info("Calling commit on delete of Edges." );
			try {
				g.tx().commit();
			} catch ( Exception e ) {
				LOGGER.error("ERROR trying to commit Edge Deletes for this batch. " + 
						LogFormatTools.getStackTop(e) );
				LOGGER.info( eCount + " candidate edges processed.  " 
						+ " edge deletes - COMMIT FAILED. ");
				return;
			}
		}
			
		if( doDelete ) {
			LOGGER.info( eCount + " candidate edges processed.  " +
					delFailCount + " delete attempts failed, " +
					delCount + " deletes successful. ");
		}
		else {
			LOGGER.info( eCount + " candidate edges processed in this batch.  " );
		}
	}
	
	
	public int getCandidateVertexCount(JanusGraph jgraph, int windowDaysVal) {
		Graph g = jgraph.newTransaction();
		GraphTraversalSource gts = g.traversal();
		Long truncTs = calculateTruncWindowEndTimeStamp(windowDaysVal);		
		//int candVCount = gts.V().has(AAIProperties.END_TS, P.lt(truncTs)).count().next().intValue();
		int candVCount = gts.V().has("end-ts", P.lt(truncTs)).count().next().intValue();
		LOGGER.info( " for the timeStamp = " + truncTs 
				+ ", which corresponds to the passed truncateWindowDays = " 
				+ windowDaysVal 
				+ ", found " + candVCount 
				+ " candidate vertices. ");
		return candVCount;
	}

	
	public int getCandidateEdgeCount(JanusGraph jgraph, int windowDaysVal) {
		Graph g = jgraph.newTransaction();
		GraphTraversalSource gts = g.traversal();
		Long truncTs = calculateTruncWindowEndTimeStamp(windowDaysVal);		
		//int candECount = gts.E().has(AAIProperties.END_TS, P.lt(truncTs)).count().next().intValue();
		int candECount = gts.E().has("end-ts", P.lt(truncTs)).count().next().intValue();
		LOGGER.info( " for the timeStamp = " + truncTs 
				+ ", which corresponds to the passed truncateWindowDays = " 
				+ windowDaysVal 
				+ ", found " + candECount 
				+ " candidate Edges. ");
		return candECount;
	}

	
	public static void verifyGraph(JanusGraph graph) {

		if (graph == null) {
			String emsg = "Not able to get a graph object in DataSnapshot.java\n";
			LOGGER.debug(emsg);
			AAISystemExitUtil.systemExitCloseAAIGraph(1);
		}

	}

	public long calculateTruncWindowEndTimeStamp( int timeWindowDays ){
		// Given a window size in days, calculate the timestamp that 
		//   represents the early-edge of that window.
		
		long unixTimeNow = System.currentTimeMillis();
		if( timeWindowDays <= 0 ){
			// This just means that they want to truncate all the way up to the current time
			return unixTimeNow;
		}
		
		long windowInMillis = timeWindowDays * 24 * 60 * 60L * 1000;
		long windowEdgeTimeStampInMs = unixTimeNow - windowInMillis;
		return windowEdgeTimeStampInMs;
		
	} 

	private Boolean doLoggingOrNot( String truncMode ){
		if( truncMode.equals(SILENT_DELETE_MODE) ){
			return false;
		}
		else {
			return true;
		}
	} 
	
	private Boolean doDeleteOrNot( String truncMode ){
		if( truncMode.equals(LOG_ONLY_MODE) ){
			return false;
		}
		else {
			return true;
		}
	} 
	
	
}