blob: f3b10ec5aa040b4dac2861a3926a37548c489a1a [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
Jonathan Hart233a18a2015-03-02 17:24:58 -080018import java.util.List;
Ray Milkeydeeb7262019-04-22 15:21:37 -070019import java.util.concurrent.CopyOnWriteArrayList;
Jonathan Hart233a18a2015-03-02 17:24:58 -080020import java.util.concurrent.ScheduledExecutorService;
21import java.util.concurrent.TimeUnit;
22import java.util.concurrent.atomic.AtomicLong;
Jonathan Hart233a18a2015-03-02 17:24:58 -080023
24import static com.google.common.base.Preconditions.checkArgument;
Jordan Haltermandf4b08a2019-03-05 18:44:03 -080025import static java.lang.Math.min;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070026import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
27import static org.onlab.util.Tools.groupedThreads;
Jonathan Hart233a18a2015-03-02 17:24:58 -080028
29/**
30 * Maintains a sliding window of value counts. The sliding window counter is
31 * initialized with a number of window slots. Calls to #incrementCount() will
32 * increment the value in the current window slot. Periodically the window
33 * slides and the oldest value count is dropped. Calls to #get() will get the
34 * total count for the last N window slots.
35 */
36public final class SlidingWindowCounter {
37
38 private volatile int headSlot;
39 private final int windowSlots;
40
41 private final List<AtomicLong> counters;
42
43 private final ScheduledExecutorService background;
44
Jordan Haltermandf4b08a2019-03-05 18:44:03 -080045 private final AtomicLong totalCount = new AtomicLong();
46 private final AtomicLong totalSlots = new AtomicLong(1);
47
Jonathan Hart233a18a2015-03-02 17:24:58 -080048 private static final int SLIDE_WINDOW_PERIOD_SECONDS = 1;
49
50 /**
51 * Creates a new sliding window counter with the given total number of
52 * window slots.
53 *
54 * @param windowSlots total number of window slots
55 */
56 public SlidingWindowCounter(int windowSlots) {
57 checkArgument(windowSlots > 0, "Window size must be a positive integer");
58
59 this.windowSlots = windowSlots;
60 this.headSlot = 0;
61
62 // Initialize each item in the list to an AtomicLong of 0
Ray Milkeydeeb7262019-04-22 15:21:37 -070063 this.counters = new CopyOnWriteArrayList<>();
Jordan Haltermandf4b08a2019-03-05 18:44:03 -080064 this.counters.add(new AtomicLong());
Jonathan Hart233a18a2015-03-02 17:24:58 -080065
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070066 background = newSingleThreadScheduledExecutor(groupedThreads("SlidingWindowCounter", "bg-%d"));
Jordan Haltermandf4b08a2019-03-05 18:44:03 -080067 background.scheduleWithFixedDelay(this::advanceHead, 1,
Thomas Vachuskab0317c62015-04-08 23:58:58 -070068 SLIDE_WINDOW_PERIOD_SECONDS, TimeUnit.SECONDS);
Jonathan Hart233a18a2015-03-02 17:24:58 -080069 }
70
71 /**
72 * Releases resources used by the SlidingWindowCounter.
73 */
74 public void destroy() {
75 background.shutdownNow();
76 }
77
78 /**
79 * Increments the count of the current window slot by 1.
80 */
81 public void incrementCount() {
82 incrementCount(headSlot, 1);
83 }
84
85 /**
86 * Increments the count of the current window slot by the given value.
87 *
88 * @param value value to increment by
89 */
90 public void incrementCount(long value) {
91 incrementCount(headSlot, value);
92 }
93
94 private void incrementCount(int slot, long value) {
95 counters.get(slot).addAndGet(value);
Jordan Haltermandf4b08a2019-03-05 18:44:03 -080096 totalCount.addAndGet(value);
97 }
98
99 /**
100 * Gets the total count for the last N window slots.
101 *
102 * @param slots number of slots to include in the count
103 * @return total count for last N slots
104 * @deprecated since 1.12
105 */
106 @Deprecated
107 public long get(int slots) {
108 return getWindowCount(slots);
109 }
110
111 /**
112 * Gets the total count for all slots.
113 *
114 * @return total count for all slots
115 */
116 public long getWindowCount() {
117 return getWindowCount(windowSlots);
Jonathan Hart233a18a2015-03-02 17:24:58 -0800118 }
119
120 /**
121 * Gets the total count for the last N window slots.
122 *
123 * @param slots number of slots to include in the count
124 * @return total count for last N slots
125 */
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800126 public long getWindowCount(int slots) {
Jonathan Hart233a18a2015-03-02 17:24:58 -0800127 checkArgument(slots <= windowSlots,
128 "Requested window must be less than the total window slots");
129
130 long sum = 0;
131
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800132 slots = min(slots, counters.size());
Jonathan Hart233a18a2015-03-02 17:24:58 -0800133 for (int i = 0; i < slots; i++) {
134 int currentIndex = headSlot - i;
135 if (currentIndex < 0) {
136 currentIndex = counters.size() + currentIndex;
137 }
138 sum += counters.get(currentIndex).get();
139 }
140
141 return sum;
142 }
143
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800144 /**
145 * Returns the average rate over the window.
146 *
147 * @return the average rate over the window
148 */
149 public double getWindowRate() {
150 return getWindowRate(windowSlots);
151 }
152
153 /**
154 * Returns the average rate over the given window.
155 *
156 * @param slots the number of slots to include in the window
157 * @return the average rate over the given window
158 */
159 public double getWindowRate(int slots) {
160 return getWindowCount(slots) / (double) min(slots, counters.size());
161 }
162
163 /**
164 * Returns the overall number of increments.
165 *
166 * @return the overall number of increments
167 */
168 public long getOverallCount() {
169 return totalCount.get();
170 }
171
172 /**
173 * Returns the overall rate.
174 *
175 * @return the overall rate
176 */
177 public double getOverallRate() {
178 return totalCount.get() / (double) totalSlots.get();
179 }
180
181 /**
182 * Clears the counter.
183 */
184 public void clear() {
185 counters.clear();
186 counters.add(new AtomicLong());
187 totalCount.set(0);
188 totalSlots.set(1);
189 headSlot = 0;
190 }
191
Jonathan Hart233a18a2015-03-02 17:24:58 -0800192 void advanceHead() {
Jordan Halterman631e7702019-04-11 15:21:01 -0700193 if (counters.size() < windowSlots) {
194 counters.add(new AtomicLong(0));
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800195 } else {
196 counters.get(slotAfter(headSlot)).set(0);
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800197 }
Jordan Halterman631e7702019-04-11 15:21:01 -0700198 headSlot = slotAfter(headSlot);
Jordan Haltermandf4b08a2019-03-05 18:44:03 -0800199 totalSlots.incrementAndGet();
Jonathan Hart233a18a2015-03-02 17:24:58 -0800200 }
201
202 private int slotAfter(int slot) {
203 return (slot + 1) % windowSlots;
204 }
205
206}