aboutsummaryrefslogtreecommitdiffstats
path: root/dblib/provider/src/main/java/org/onap/ccsdk/sli/core/dblib/pm/PollingWorker.java
blob: 4bfa058a82d0624bac7c570176ab5732d683962f (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
/*-
 * ============LICENSE_START=======================================================
 * onap
 * ================================================================================
 * Copyright (C) 2016 - 2017 ONAP
 * ================================================================================
 * 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.ccsdk.sli.core.dblib.pm;

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

public class PollingWorker implements Runnable {

	private Logger LOGGER = LoggerFactory.getLogger(PollingWorker.class);

	private static PollingWorker self = null;

	private LinkedBlockingQueue tasks = new LinkedBlockingQueue(100);
	private long interval = 1000L;
	private Thread worker = null;
	private AtomicLong[] counters = null;
	private int[] bucketUnit = null;
	private static boolean enabled = false;
	private Timer timer = null;

	public static void post(long starttime){
		PollingWorker temp = self;
		if(temp != null && enabled) {
			temp.register(new TestSample(starttime));
		}
	}

	public static void createInistance(Properties props){
		self = new PollingWorker(props);
	}

	private PollingWorker(Properties ctxprops){
		if(ctxprops==null ||  ctxprops.getProperty("org.onap.ccsdk.dblib.pm") == null){
			enabled = false;
		} else {
			if("true".equalsIgnoreCase((String)ctxprops.getProperty("org.onap.ccsdk.dblib.pm"))){
				enabled = true;
			} else {
				enabled = false;
			}
		}

		interval = Long.parseLong(( ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.interval") == null) ? "60" : (String)ctxprops.getProperty("org.onap.ccsdk.dblib.pm.interval"));
		// '0' bucket is to count exceptions
		String sampling[] = ((ctxprops == null || ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling")==null) ? "0,2,5,10,20,50,100" :	(String)ctxprops.getProperty("org.onap.ccsdk.dblib.pm.sampling")).split(",");

		if(enabled){
			bucketUnit = new int[sampling.length];
			for(int i=0, max = bucketUnit.length; i<max; i++){
				bucketUnit[i] = Integer.parseInt(sampling[i].trim());
			}
			counters = new AtomicLong[bucketUnit.length+1];
			for(int i=0, max = counters.length; i<max; i++){
				counters[i] = new AtomicLong();
			}
			worker = new Thread(this);
			worker.setDaemon(true);
			worker.start();
			timer = new Timer(true);
			timer.schedule(new MyTimerTask(), interval*1000L, interval*1000L);
		}
	}

	private void register(TestSample object){
		try {
			tasks.add(object);
		} catch(Throwable exc) {
			// if cannot add an object to the queue, do nothing
		}
	}

	private void deRegister(TestSample object){
		tasks.remove(object);
	}

	@Override
	public void run() {
		for(;;){
			Set data = new TreeSet();
			tasks.drainTo(data);
			for(Iterator it = data.iterator(); it.hasNext(); ){
				Object next = it.next();
				if(next instanceof TestSample){
					consume((TestSample)next);
				} else {
					System.out.println(next.getClass().getName());
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}
	public void clearReqister(){
		AtomicLong[] tmp = new AtomicLong[counters.length];
		for(int i=0, max = tmp.length; i<max; i++){
			tmp[i] = new AtomicLong();
		}
		AtomicLong[] tmp2 = counters;
		synchronized(tmp2){
			counters = tmp;
		}
		StringBuffer sb = new StringBuffer("CPM: ");
		for(int i=0, max = tmp2.length; i < max; i++){
			if(i==0 && bucketUnit[0]==0){
				sb.append("[Exc]=");
			} else {
				sb.append("[");
				if(i==bucketUnit.length){
					sb.append("Other]=");
				} else {
					sb.append(bucketUnit[i]).append(" ms]=");
				}
			}
			sb.append(tmp2[i].get()).append("\t");
		}
		LOGGER.info(sb.toString());
	}

	class MyTimerTask extends TimerTask{

		@Override
		public void run() {

			clearReqister();
		}

	}

	private void consume(TestSample probe) {
		AtomicLong[] tmp = counters;
		synchronized(tmp){
			counters[getBucket(probe.getDuration())].incrementAndGet();
		}
	}

	/*
	 * This method is used to find the offset of the bucket in
	 * counters. 'counters' array is 1 size longer than bucketUnit,
	 * hence by default it returns 'bucketUnit.length'
	 */
	private int getBucket(long difftime){
		for(int i=0; i<bucketUnit.length; i++){
			if(difftime < bucketUnit[i]){
				return i;
			}
		}
		return bucketUnit.length;
	}

	private static boolean isEnabled() {
		return enabled;
	}
	/**
	 * @author Rich Tabedzki
	 *  A helper class to pass measured parameter to the counter.
	 */
	static class TestSample implements Comparable{
		private long starttime;
		private long endtime;

		public TestSample(long starttime) {
			this.endtime = System.currentTimeMillis();
			this.starttime = starttime;
		}

		public long getDuration(){
			return endtime - starttime;
		}

		@Override
		public int compareTo(Object o) {
			if(o instanceof TestSample){
				TestSample x = (TestSample)o;
				if(starttime < x.starttime)
					return 1;
				if(endtime < x.endtime)
					return 1;
				if(starttime > x.starttime)
					return -1;
				if(endtime > x.endtime)
					return -1;
				return 0;
			}
			return 1;
		}
	}
}