blob: e1b0557375a8f7d6851d23679aa6820f616d9e7b [file] [log] [blame]
Jonathan Hart233a18a2015-03-02 17:24:58 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Jonathan Hart233a18a2015-03-02 17:24:58 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onlab.util;
17
Jordan Haltermand884d8a2019-04-23 10:39:03 -070018import com.google.common.collect.ImmutableList;
19
Jonathan Hart233a18a2015-03-02 17:24:58 -080020import java.util.List;
Jonathan Hart233a18a2015-03-02 17:24:58 -080021import java.util.concurrent.ScheduledExecutorService;
22import java.util.concurrent.TimeUnit;
23import java.util.concurrent.atomic.AtomicLong;
Jordan Haltermand884d8a2019-04-23 10:39:03 -070024import java.util.stream.Collectors;
25import java.util.stream.IntStream;
Jonathan Hart233a18a2015-03-02 17:24:58 -080026
27import static com.google.common.base.Preconditions.checkArgument;
Jordan Haltermandf4b08a2019-03-05 18:44:03 -080028import static java.lang.Math.min;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070029import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
30import static org.onlab.util.Tools.groupedThreads;
Jonathan Hart233a18a2015-03-02 17:24:58 -080031
32/**
33 * Maintains a sliding window of value counts. The sliding window counter is
34 * initialized with a number of window slots. Calls to #incrementCount() will
35 * increment the value in the current window slot. Periodically the window
36 * slides and the oldest value count is dropped. Calls to #get() will get the
37 * total count for the last N window slots.
38 */
39public final class SlidingWindowCounter {
40
41 private volatile int headSlot;
42 private final int windowSlots;
43
44 private final List<AtomicLong> counters;
45
46 private final ScheduledExecutorService background;
47
Jordan Haltermandf4b08a2019-03-05 18:44:03 -080048 private final AtomicLong totalCount = new AtomicLong();
49 private final AtomicLong totalSlots = new AtomicLong(1);
50
Jonathan Hart233a18a2015-03-02 17:24:58 -080051 private static final int SLIDE_WINDOW_PERIOD_SECONDS = 1;
52
53 /**
54 * Creates a new sliding window counter with the given total number of
55 * window slots.
56 *
57 * @param windowSlots total number of window slots
58 */
59 public SlidingWindowCounter(int windowSlots) {
60 checkArgument(windowSlots > 0, "Window size must be a positive integer");
61
62 this.windowSlots = windowSlots;
63 this.headSlot = 0;
64
65 // Initialize each item in the list to an AtomicLong of 0
Jordan Haltermand884d8a2019-04-23 10:39:03 -070066 this.counters = ImmutableList.copyOf(IntStream.range(0, windowSlots)
67 .mapToObj(i -> new AtomicLong())
68 .collect(Collectors.toList()));
Jonathan Hart233a18a2015-03-02 17:24:58 -080069
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070070 background = newSingleThreadScheduledExecutor(groupedThreads("SlidingWindowCounter", "bg-%d"));
Jordan Haltermandf4b08a2019-03-05 18:44:03 -080071 background.scheduleWithFixedDelay(this::advanceHead, 1,
Thomas Vachuskab0317c62015-04-08 23:58:58 -070072 SLIDE_WINDOW_PERIOD_SECONDS, TimeUnit.SECONDS);
Jonathan Hart233a18a2015-03-02 17:24:58 -080073 }
74
75 /**
76 * Releases resources used by the SlidingWindowCounter.
77 */
78 public void destroy() {
79 background.shutdownNow();
80 }
81
82 /**
83 * Increments the count of the current window slot by 1.
84 */
85 public void incrementCount() {
86 incrementCount(headSlot, 1);
87 }
88
89 /**
90 * Increments the count of the current window slot by the given value.
91 *
92 * @param value value to increment by
93 */
94 public void incrementCount(long value) {
95 incrementCount(headSlot, value);
96 }
97
Jordan Haltermand884d8a2019-04-23 10:39:03 -070098 /**
99 * Increments the count of the given window slot by the given value.
100 *
101 * @param slot the slot to increment
102 * @param value the value by which to increment the slot
103 */
Jonathan Hart233a18a2015-03-02 17:24:58 -0800104 private void incrementCount(int slot, long value) {
105 counters.get(slot).addAndGet(value);
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800106 totalCount.addAndGet(value);
107 }
108
109 /**
110 * Gets the total count for the last N window slots.
111 *
112 * @param slots number of slots to include in the count
113 * @return total count for last N slots
114 * @deprecated since 1.12
115 */
116 @Deprecated
117 public long get(int slots) {
118 return getWindowCount(slots);
119 }
120
121 /**
122 * Gets the total count for all slots.
123 *
124 * @return total count for all slots
125 */
126 public long getWindowCount() {
127 return getWindowCount(windowSlots);
Jonathan Hart233a18a2015-03-02 17:24:58 -0800128 }
129
130 /**
131 * Gets the total count for the last N window slots.
132 *
133 * @param slots number of slots to include in the count
134 * @return total count for last N slots
135 */
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800136 public long getWindowCount(int slots) {
Jonathan Hart233a18a2015-03-02 17:24:58 -0800137 checkArgument(slots <= windowSlots,
138 "Requested window must be less than the total window slots");
139
140 long sum = 0;
141
Jordan Haltermand884d8a2019-04-23 10:39:03 -0700142 slots = getMinSlots(slots);
Jonathan Hart233a18a2015-03-02 17:24:58 -0800143 for (int i = 0; i < slots; i++) {
144 int currentIndex = headSlot - i;
145 if (currentIndex < 0) {
146 currentIndex = counters.size() + currentIndex;
147 }
148 sum += counters.get(currentIndex).get();
149 }
150
151 return sum;
152 }
153
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800154 /**
155 * Returns the average rate over the window.
156 *
157 * @return the average rate over the window
158 */
159 public double getWindowRate() {
160 return getWindowRate(windowSlots);
161 }
162
163 /**
164 * Returns the average rate over the given window.
165 *
166 * @param slots the number of slots to include in the window
167 * @return the average rate over the given window
168 */
169 public double getWindowRate(int slots) {
Jordan Haltermand884d8a2019-04-23 10:39:03 -0700170 // Compute the minimum slots to before computing the window count to ensure
171 // the window count and number of slots are for the same window.
172 slots = getMinSlots(slots);
173 return getWindowCount(slots) / (double) slots;
174 }
175
176 private int getMinSlots(int slots) {
177 return min(slots, (int) min(totalSlots.get(), Integer.MAX_VALUE));
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800178 }
179
180 /**
181 * Returns the overall number of increments.
182 *
183 * @return the overall number of increments
184 */
185 public long getOverallCount() {
186 return totalCount.get();
187 }
188
189 /**
190 * Returns the overall rate.
191 *
192 * @return the overall rate
193 */
194 public double getOverallRate() {
195 return totalCount.get() / (double) totalSlots.get();
196 }
197
198 /**
199 * Clears the counter.
200 */
201 public void clear() {
Jordan Haltermand884d8a2019-04-23 10:39:03 -0700202 counters.forEach(value -> value.set(0));
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800203 totalCount.set(0);
204 totalSlots.set(1);
205 headSlot = 0;
206 }
207
Jonathan Hart233a18a2015-03-02 17:24:58 -0800208 void advanceHead() {
Jordan Haltermand884d8a2019-04-23 10:39:03 -0700209 counters.get(slotAfter(headSlot)).set(0);
Jordan Halterman631e7702019-04-11 15:21:01 -0700210 headSlot = slotAfter(headSlot);
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800211 totalSlots.incrementAndGet();
Jonathan Hart233a18a2015-03-02 17:24:58 -0800212 }
213
214 private int slotAfter(int slot) {
215 return (slot + 1) % windowSlots;
216 }
217
218}