1
1
/**
2
- * Setup TTL indexes to delete older data for one specific app. This script should be run periodically, to create TTL indexes on new collections too, like new events, etc for specific app
2
+ * Sets index on cd field if it does not exists and stores retention period in database. Nightly job will clear data based on set retention period.
3
3
* Server: countly
4
4
* Path: countly dir/bin/scripts/expire-data
5
5
* Command: node countly_multi_app_expireData.js
@@ -24,44 +24,21 @@ Promise.all([plugins.dbConnection("countly"), plugins.dbConnection("countly_dril
24
24
}
25
25
if ( ! err && indexes ) {
26
26
var hasIndex = false ;
27
- var dropIndex = false ;
28
27
for ( var i = 0 ; i < indexes . length ; i ++ ) {
29
28
if ( indexes [ i ] . name == INDEX_NAME ) {
30
- if ( indexes [ i ] . expireAfterSeconds == EXPIRE_AFTER ) {
31
- //print("skipping", c)
32
- hasIndex = true ;
33
- }
34
- //has index but incorrect expire time, need to be reindexed
35
- else {
36
- dropIndex = true ;
37
- }
29
+ hasIndex = true ;
38
30
break ;
39
31
}
40
32
}
41
- if ( dropIndex ) {
42
- console . log ( "modifying index" , collection ) ;
43
- db_drill . command ( {
44
- "collMod" : collection ,
45
- "index" : {
46
- "keyPattern" : { "cd" : 1 } ,
47
- expireAfterSeconds : EXPIRE_AFTER
48
- }
49
- } , function ( err ) {
50
- if ( err ) {
51
- console . log ( err ) ;
52
- }
53
- done ( ) ;
54
- } ) ;
55
-
56
- }
57
- else if ( ! hasIndex ) {
33
+ if ( ! hasIndex ) {
58
34
console . log ( "creating index" , collection ) ;
59
- db_drill . collection ( collection ) . createIndex ( { "cd" : 1 } , { expireAfterSeconds : EXPIRE_AFTER , "background" : true } , function ( ) {
60
- done ( ) ;
35
+ db_drill . collection ( collection ) . createIndex ( { "cd" : 1 } , function ( ) {
36
+ done ( true ) ;
61
37
} ) ;
62
38
}
63
39
else {
64
- done ( ) ;
40
+ console . log ( "Appropriate index already set for" , collection ) ;
41
+ done ( true ) ;
65
42
}
66
43
}
67
44
else {
@@ -70,9 +47,23 @@ Promise.all([plugins.dbConnection("countly"), plugins.dbConnection("countly_dril
70
47
} ) ;
71
48
72
49
73
- function done ( ) {
74
- db . close ( ) ;
75
- db_drill . close ( ) ;
76
- }
50
+ function done ( index_set ) {
51
+ if ( index_set ) {
52
+ db . collection ( "plugins" ) . updateOne ( { "_id" : "retention" } , { "$set" : { "retention" : EXPIRE_AFTER } } , { "upsert" : true } , function ( err ) {
53
+ if ( err ) {
54
+ console . log ( "Error setting retention period" , err ) ;
55
+ }
56
+ else {
57
+ console . log ( "Retention period set: " + EXPIRE_AFTER ) ;
58
+ }
59
+ db . close ( ) ;
60
+ db_drill . close ( ) ;
77
61
62
+ } ) ;
63
+ }
64
+ else {
65
+ db . close ( ) ;
66
+ db_drill . close ( ) ;
67
+ }
68
+ }
78
69
} ) ;
0 commit comments