11/**
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.
33 * Server: countly
44 * Path: countly dir/bin/scripts/expire-data
55 * Command: node countly_multi_app_expireData.js
@@ -24,44 +24,21 @@ Promise.all([plugins.dbConnection("countly"), plugins.dbConnection("countly_dril
2424 }
2525 if ( ! err && indexes ) {
2626 var hasIndex = false ;
27- var dropIndex = false ;
2827 for ( var i = 0 ; i < indexes . length ; i ++ ) {
2928 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 ;
3830 break ;
3931 }
4032 }
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 ) {
5834 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 ) ;
6137 } ) ;
6238 }
6339 else {
64- done ( ) ;
40+ console . log ( "Appropriate index already set for" , collection ) ;
41+ done ( true ) ;
6542 }
6643 }
6744 else {
@@ -70,9 +47,23 @@ Promise.all([plugins.dbConnection("countly"), plugins.dbConnection("countly_dril
7047 } ) ;
7148
7249
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 ( ) ;
7761
62+ } ) ;
63+ }
64+ else {
65+ db . close ( ) ;
66+ db_drill . close ( ) ;
67+ }
68+ }
7869} ) ;
0 commit comments