various Updates
[music.git] / src / main / java / org / onap / music / main / CronJobManager.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
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  * 
19  * ============LICENSE_END=============================================
20  * ====================================================================
21  */
22 package org.onap.music.main;
23
24 import java.util.Iterator;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.concurrent.Executors;
28 import java.util.concurrent.ScheduledExecutorService;
29 import java.util.concurrent.TimeUnit;
30 import javax.servlet.ServletContextEvent;
31 import javax.servlet.ServletContextListener;
32 import javax.servlet.annotation.WebListener;
33
34 import org.onap.music.datastore.PreparedQueryObject;
35 import org.onap.music.exceptions.MusicLockingException;
36 import org.onap.music.exceptions.MusicServiceException;
37
38 import com.datastax.driver.core.ResultSet;
39 import com.datastax.driver.core.Row;
40
41 @WebListener
42 public class CronJobManager implements ServletContextListener {
43
44     private ScheduledExecutorService scheduler;
45
46     @Override
47     public void contextInitialized(ServletContextEvent event) {
48         scheduler = Executors.newSingleThreadScheduledExecutor();
49         scheduler.scheduleAtFixedRate(new CachingUtil(), 0, 24, TimeUnit.HOURS);
50         PreparedQueryObject pQuery = new PreparedQueryObject();
51         String consistency = MusicUtil.EVENTUAL;
52         pQuery.appendQueryString("CREATE TABLE IF NOT EXISTS admin.locks ( lock_id text PRIMARY KEY, ctime text)");
53         try {
54             ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
55         } catch (MusicServiceException e1) {
56             e1.printStackTrace();
57         }
58         
59         pQuery = new PreparedQueryObject();
60         pQuery.appendQueryString(
61                         "select * from admin.locks");
62             try {
63                 ResultSet rs = MusicCore.get(pQuery);
64                 Iterator<Row> it = rs.iterator();
65                 StringBuilder deleteKeys = new StringBuilder();
66                 Boolean expiredKeys = false;
67                 while (it.hasNext()) {
68                     Row row = (Row) it.next();
69                     String id = row.getString("lock_id");
70                     long ctime = Long.parseLong(row.getString("ctime"));
71                     if(System.currentTimeMillis() >= ctime + 24 * 60 * 60 * 1000) {
72                         expiredKeys = true;
73                         String new_id = id.substring(1);
74                         MusicCore.deleteLock(new_id);
75                         deleteKeys.append(id).append(",");
76                     }
77                     else {
78                         MusicUtil.zkNodeMap.put(id, ctime);
79                     }
80                 };
81                 if(expiredKeys) {
82                     deleteKeys.deleteCharAt(deleteKeys.length()-1);
83                     deleteKeysFromDB(deleteKeys);
84                }
85             } catch (MusicServiceException e) {
86                 e.printStackTrace();
87             } catch (MusicLockingException e) {
88                 e.printStackTrace();
89        }
90        
91       //Zookeeper cleanup
92         scheduler.scheduleAtFixedRate(new Runnable() {
93             @Override
94             public void run() {
95                 Iterator<Entry<String, Long>> it = MusicUtil.zkNodeMap.entrySet().iterator();
96                 StringBuilder deleteKeys = new StringBuilder();
97                 Boolean expiredKeys = false;
98                 while (it.hasNext()) {
99                     Map.Entry<String, Long> pair = (Map.Entry<String, Long>)it.next();
100                     long ctime = pair.getValue();
101                    if (System.currentTimeMillis() >= ctime + 24 * 60 * 60 * 1000) {
102                        try {
103                            expiredKeys = true;
104                            String id = pair.getKey();
105                            deleteKeys.append("'").append(id).append("'").append(",");
106                            MusicCore.deleteLock(id.substring(1));
107                            MusicUtil.zkNodeMap.remove(id);
108                            
109                        } catch (MusicLockingException e) {
110                           e.printStackTrace();
111                        }
112                    }
113                 }
114                 if(expiredKeys) {
115                     deleteKeys.deleteCharAt(deleteKeys.length()-1);
116                     deleteKeysFromDB(deleteKeys);
117                }
118             }
119         } , 0, 24, TimeUnit.HOURS);
120     }
121
122     @Override
123     public void contextDestroyed(ServletContextEvent event) {
124         scheduler.shutdownNow();
125     }
126     
127     public void deleteKeysFromDB(StringBuilder deleteKeys) {
128         PreparedQueryObject pQuery = new PreparedQueryObject();
129         pQuery.appendQueryString(
130                         "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")");
131         try {
132             MusicCore.nonKeyRelatedPut(pQuery, "eventual");
133         } catch (Exception e) {
134               e.printStackTrace();
135         }
136     }
137
138 }