summaryrefslogtreecommitdiffstats
path: root/src/main/java/com/att/nsa/cambria/beans/DMaaPCambriaLimiter.java
blob: 1b609b04b7e7c69569f68bdf63eeaca42b11aee1 (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
221
222
223
224
225
226
227
/*******************************************************************************
 *  ============LICENSE_START=======================================================
 *  org.onap.dmaap
 *  ================================================================================
 *  Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 *  ================================================================================
 *  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=========================================================
 *
 *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
 *  
 *******************************************************************************/
package com.att.nsa.cambria.beans;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

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

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.att.nsa.cambria.CambriaApiException;
import com.att.nsa.cambria.constants.CambriaConstants;
import com.att.nsa.cambria.exception.DMaaPResponseCode;
import com.att.nsa.cambria.exception.ErrorResponse;
import com.att.nsa.drumlin.service.standards.HttpStatusCodes;
import com.att.nsa.drumlin.till.nv.rrNvReadable;
import com.att.nsa.drumlin.till.nv.rrNvReadable.invalidSettingValue;
import com.att.nsa.drumlin.till.nv.rrNvReadable.missingReqdSetting;
import com.att.nsa.metrics.impl.CdmRateTicker;

/**
 * class provide rate information
 * 
 * @author author
 *
 */
@Component
public class DMaaPCambriaLimiter {
	/**
	 * constructor initializes
	 * 
	 * @param settings
	 * @throws missingReqdSetting
	 * @throws invalidSettingValue
	 */
	@Autowired
	public DMaaPCambriaLimiter(@Qualifier("propertyReader") rrNvReadable settings)
			throws missingReqdSetting, invalidSettingValue {
		fRateInfo = new HashMap<String, RateInfo>();
		fMaxEmptyPollsPerMinute = settings.getDouble(CambriaConstants.kSetting_MaxEmptyPollsPerMinute,
				CambriaConstants.kDefault_MaxEmptyPollsPerMinute);
		fWindowLengthMins = settings.getInt(CambriaConstants.kSetting_RateLimitWindowLength,
				CambriaConstants.kDefault_RateLimitWindowLength);
		fSleepMs = settings.getLong(CambriaConstants.kSetting_MaxEmptyPollsPerMinute,
				CambriaConstants.kDefault_SleepMsOnRateLimit);
	}

	/**
	 * static method provide the sleep time
	 * 
	 * @param ratePerMinute
	 * @return
	 */
	public static long getSleepMsForRate(double ratePerMinute) {
		if (ratePerMinute <= 0.0)
			return 0;
		return Math.max(1000, Math.round(60 * 1000 / ratePerMinute));
	}

	/**
	 * Construct a rate limiter.
	 * 
	 * @param maxEmptyPollsPerMinute
	 *            Pass <= 0 to deactivate rate limiting.
	 *            @param windowLengthMins
	 */
	public DMaaPCambriaLimiter(double maxEmptyPollsPerMinute, int windowLengthMins) {
		this(maxEmptyPollsPerMinute, windowLengthMins, getSleepMsForRate(maxEmptyPollsPerMinute));
	}

	/**
	 * Construct a rate limiter
	 * 
	 * @param maxEmptyPollsPerMinute
	 *            Pass <= 0 to deactivate rate limiting.
	 * @param sleepMs
	 * @param windowLengthMins
	 */
	public DMaaPCambriaLimiter(double maxEmptyPollsPerMinute, int windowLengthMins, long sleepMs) {
		fRateInfo = new HashMap<String, RateInfo>();
		fMaxEmptyPollsPerMinute = Math.max(0, maxEmptyPollsPerMinute);
		fWindowLengthMins = windowLengthMins;
		fSleepMs = Math.max(0, sleepMs);
	}

	/**
	 * Tell the rate limiter about a call to a topic/group/id. If the rate is
	 * too high, this call delays its return and throws an exception.
	 * 
	 * @param topic
	 * @param consumerGroup
	 * @param clientId
	 * @throws CambriaApiException
	 */
	public void onCall(String topic, String consumerGroup, String clientId) throws CambriaApiException {
		// do nothing if rate is configured 0 or less
		if (fMaxEmptyPollsPerMinute <= 0) {
			return;
		}

		// setup rate info for this tuple
		final RateInfo ri = getRateInfo(topic, consumerGroup, clientId);

		final double rate = ri.onCall();
		log.info(ri.getLabel() + ": " + rate + " empty replies/minute.");

		if (rate > fMaxEmptyPollsPerMinute) {
			try {
				log.warn(ri.getLabel() + ": " + rate + " empty replies/minute, limit is " + fMaxEmptyPollsPerMinute
						+ ".");
				if (fSleepMs > 0) {
					log.warn(ri.getLabel() + ": " + "Slowing response with " + fSleepMs
							+ " ms sleep, then responding in error.");
					Thread.sleep(fSleepMs);
				} else {
					log.info(ri.getLabel() + ": " + "No sleep configured, just throwing error.");
				}
			} catch (InterruptedException e) {
				// ignore
			}
			ErrorResponse errRes = new ErrorResponse(HttpStatusCodes.k429_tooManyRequests, 
					DMaaPResponseCode.TOO_MANY_REQUESTS.getResponseCode(), 
					"This client is making too many requests. Please use a long poll "
							+ "setting to decrease the number of requests that result in empty responses. ");
			log.info(errRes.toString());
			throw new CambriaApiException(errRes);
		}
	}

	/**
	 * 
	 * @param topic
	 * @param consumerGroup
	 * @param clientId
	 * @param sentCount
	 */
	public void onSend(String topic, String consumerGroup, String clientId, long sentCount) {
		// check for good replies
		if (sentCount > 0) {
			// that was a good send, reset the metric
			getRateInfo(topic, consumerGroup, clientId).reset();
		}
	}

	private static class RateInfo {
		/**
		 * constructor initialzes
		 * 
		 * @param label
		 * @param windowLengthMinutes
		 */
		public RateInfo(String label, int windowLengthMinutes) {
			fLabel = label;
			fCallRateSinceLastMsgSend = new CdmRateTicker("Call rate since last msg send", 1, TimeUnit.MINUTES,
					windowLengthMinutes, TimeUnit.MINUTES);
		}

		public String getLabel() {
			return fLabel;
		}

		/**
		 * CdmRateTicker is reset
		 */
		public void reset() {
			fCallRateSinceLastMsgSend.reset();
		}

		/**
		 * 
		 * @return
		 */
		public double onCall() {
			fCallRateSinceLastMsgSend.tick();
			return fCallRateSinceLastMsgSend.getRate();
		}

		private final String fLabel;
		private final CdmRateTicker fCallRateSinceLastMsgSend;
	}

	private final HashMap<String, RateInfo> fRateInfo;
	private final double fMaxEmptyPollsPerMinute;
	private final int fWindowLengthMins;
	private final long fSleepMs;
	//private static final Logger log = LoggerFactory.getLogger(DMaaPCambriaLimiter.class);
	private static final EELFLogger log = EELFManager.getInstance().getLogger(DMaaPCambriaLimiter.class);
	private RateInfo getRateInfo(String topic, String consumerGroup, String clientId) {
		final String key = makeKey(topic, consumerGroup, clientId);
		RateInfo ri = fRateInfo.get(key);
		if (ri == null) {
			ri = new RateInfo(key, fWindowLengthMins);
			fRateInfo.put(key, ri);
		}
		return ri;
	}

	private String makeKey(String topic, String group, String id) {
		return topic + "::" + group + "::" + id;
	}
}