Error in ScheduledPublishingPolicyImpl
[appc.git] / appc-metric / appc-metric-bundle / src / main / java / org / onap / appc / metricservice / policy / impl / ScheduledPublishingPolicyImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications (C) 2019 Ericsson
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.metricservice.policy.impl;
27
28 import java.text.SimpleDateFormat;
29 import java.util.Date;
30 import java.util.Properties;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.ScheduledExecutorService;
33 import java.util.concurrent.ThreadFactory;
34 import java.util.concurrent.TimeUnit;
35
36 import org.onap.appc.configuration.Configuration;
37 import org.onap.appc.configuration.ConfigurationFactory;
38 import org.onap.appc.exceptions.APPCException;
39 import org.onap.appc.metricservice.MetricRegistry;
40 import org.onap.appc.metricservice.Publisher;
41 import org.onap.appc.metricservice.metric.Metric;
42 import org.onap.appc.metricservice.policy.ScheduledPublishingPolicy;
43 import com.att.eelf.configuration.EELFLogger;
44 import com.att.eelf.configuration.EELFManager;
45
46
47 public class ScheduledPublishingPolicyImpl implements ScheduledPublishingPolicy {
48     private long startTime;
49     private long period;
50     private Publisher[] publishers;
51     private Metric[] metrics;
52     private MetricRegistry metricRegistry;
53     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ScheduledPublishingPolicyImpl.class);
54     private static final int DEFAULT_PERIOD = 100000;
55     private ScheduledExecutorService scheduleExecutor;
56     private Configuration configuration;
57
58     public ScheduledPublishingPolicyImpl(long startTime, long period, Publisher[] publishers, Metric[] metrics) {
59         this.startTime = startTime;
60         this.period = period;
61         this.publishers = publishers;
62         this.metrics = metrics;
63         this.scheduleExecutor= Executors.newSingleThreadScheduledExecutor(getThreadFactory(true));
64     }
65
66     public ScheduledPublishingPolicyImpl( Publisher[] publishers, Metric[] metrics) {
67         configuration = ConfigurationFactory.getConfiguration();
68         Properties properties = configuration.getProperties();
69         if(properties != null){
70             if(properties.getProperty("schedule.policy.metric.period") != null && properties.getProperty("schedule.policy.metric.start.time") != null) {
71                 this.startTime = getConfigStartTime(properties);
72                 this.period = getConfigPeriod(properties);
73                 logger.info("Metric Properties read from configuration Start Time :" + this.startTime+", Period :" + this.period);
74             }else if(properties.getProperty("schedule.policy.metric.period") != null){
75                 this.startTime = 1;
76                 this.period = getConfigPeriod(properties);
77                 logger.info("Metric Properties read from configuration Start Time :" + this.startTime+", Period :" + this.period);
78
79             }else if(properties.getProperty("schedule.policy.metric.period") == null && properties.getProperty("schedule.policy.metric.start.time") != null) {
80                 this.startTime = getConfigStartTime("00:00:00", properties);
81                 this.period = (24 * 60 * 60 * 1000l) -1;
82                 logger.info("Metric Properties read from configuration Start Time :" + this.startTime+", Period :" + this.period);
83
84             }else{
85                 logger.info("Metric Properties coming as null,setting to default Start Time :1 ms,Period : 100000 ms");
86                 this.startTime = 1;
87                 this.period = DEFAULT_PERIOD;
88                 logger.info("Metric Properties read from configuration Start Time :" + this.startTime+", Period :" + this.period);
89
90             }
91         } else  {
92             logger.info("Metric Properties coming as null,setting to default Start Time :1 ms,Period : 100000 ms");
93             this.startTime = 1;
94             this.period = DEFAULT_PERIOD;
95             logger.info("Metric Properties read from configuration Start Time :"+this.startTime+", Period :" + this.period);
96         }
97         this.publishers = publishers;
98         this.metrics = metrics;
99         this.scheduleExecutor= Executors.newSingleThreadScheduledExecutor(getThreadFactory(true));
100     }
101
102     private long getConfigPeriod(Properties properties) {
103         String period = properties.getProperty("schedule.policy.metric.period");
104         // Check for when this is called as part of the case when metric period property is not set
105         if (period != null) {
106             logger.info("Metric period : " + period);
107             long periodInMs = Integer.parseInt(period) * 1000l;
108             logger.info("Metric period in long : " + periodInMs);
109             return periodInMs;
110         }
111         return DEFAULT_PERIOD;
112     }
113
114     private long getTimeInMs(String time) {
115         String[] strings=time.split(":");
116         if(strings.length == 3) {
117             long hour = Integer.parseInt(strings[0]) * 60 * 60 * 1000l;
118             long min = Integer.parseInt(strings[1]) * 60 * 1000l;
119             long sec = Integer.parseInt(strings[2]) * 1000l;
120             return hour + min + sec;
121         }else{
122             return 0;
123         }
124
125     }
126
127
128
129     private long getConfigStartTime(Properties properties) {
130         System.out.println(properties);
131
132         String startTime = properties.getProperty("schedule.policy.metric.start.time");
133
134         if(startTime != null){
135             long timeDiff = (getTimeInMs(startTime)) - (getTimeInMs((new SimpleDateFormat("HH:mm:ss")).format(new Date())));
136             long period = getConfigPeriod(properties);
137             if(timeDiff >= 0){
138                 return timeDiff;
139             }else{
140                 return period - ((timeDiff * -1) % period);
141             }
142         }
143         return 0;
144     }
145
146     private long getConfigStartTime(String startTime, Properties properties) {
147         if(startTime != null) {
148             long timeDiff = (getTimeInMs(startTime)) - (getTimeInMs((new SimpleDateFormat("HH:mm:ss")).format(new Date())));
149             long period = getConfigPeriod(properties);
150             if(timeDiff >= 0){
151                 return timeDiff % period;
152             }else{
153                 return period-((timeDiff * -1) % period);
154             }
155         }
156         return 0;
157     }
158     @Override
159     public void onMetricChange(Metric metric) throws APPCException {
160         //TODO
161     }
162
163     @Override
164     public Metric[] metrics() {
165         return metrics;
166     }
167
168     @Override
169     public void init() {
170         Properties properties=configuration.getProperties();
171         boolean isMetricEnabled=false;
172         if(properties!=null){
173             String metricProperty=properties.getProperty("metric.enabled");
174             if(metricProperty!=null){
175                 isMetricEnabled=Boolean.valueOf(metricProperty);
176             }
177         }
178         if(isMetricEnabled){
179             logger.info("Metric Service is enabled, hence policies getting scheduled");
180             for(final Publisher publisher:this.getPublishers()){
181                 scheduleExecutor.scheduleWithFixedDelay(new Runnable()
182                 {
183                     public void run() {
184                         try {
185                             publisher.publish(metricRegistry, metrics);
186                             reset();
187                         } catch (RuntimeException ex) {
188                             logger.error("RuntimeException thrown from {}#report. Exception was suppressed.", publisher.getClass().getSimpleName(), ex);
189                         }
190                     }
191                 }
192                         , startTime, period, TimeUnit.MILLISECONDS);
193             }
194         }else{
195             logger.info("Metric Service is not enabled, hence policies not getting scheduled");
196
197         }
198     }
199
200     @Override
201     public long getStartTime() {
202         return this.startTime;
203     }
204
205     @Override
206     public long getPeriod() {
207         return this.period;
208     }
209
210     @Override
211     public Publisher[] getPublishers() {
212         return this.publishers;
213     }
214
215     @Override
216     public void reset() {
217         for(Metric metric:this.metrics){
218             metric.reset();}
219     }
220
221
222     private  ThreadFactory getThreadFactory(final boolean isDaemon){
223         return new ThreadFactory() {
224             public Thread newThread(Runnable r) {
225                 Thread t = Executors.defaultThreadFactory().newThread(r);
226                 t.setDaemon(isDaemon);
227                 return t;
228             }
229         };
230     }
231
232 }