Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* 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.
*/
package com.alibaba.csp.sentinel.node;

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

import com.alibaba.csp.sentinel.node.metric.MetricNode;

/**
* Tracks active requests and their per-second peaks. A request that is still active
* at a second boundary contributes to the next second, even if no request arrives there.
*/
final class ConcurrencyCounter {

private static final long SEALED = Long.MIN_VALUE;

private final int[] completedPeaks;
private long idleThrough;
private long lastNonzeroSecond = -1;
private volatile Window current = new Window(0, 0);

ConcurrencyCounter(int seconds) {
completedPeaks = new int[seconds];
}

int currentCount() {
return (int)current.counts.get();
}

void add(int delta, long timeMillis) {
long second = timeMillis / 1000;
Window window = current;
while (window.second < second || !window.add(delta)) {
window = advance(second);
}
}

private synchronized Window advance(long second) {
second = Math.max(second, idleThrough);
Window previous = current;
if (second <= previous.second) {
return previous;
}
// Seal before reading the final count and peak. A racing update will retry in the new window.
long counts = previous.counts.getAndUpdate(value -> value | SEALED);
int active = (int)counts;
if (peak(counts) > 0) {
lastNonzeroSecond = active > 0 ? second - 1 : previous.second;
}
long first = Math.max(previous.second, second - completedPeaks.length + 1);
for (long t = first; t < second; t++) {
completedPeaks[index(t)] = t == previous.second ? peak(counts) : Math.max(0, active);
}
current = new Window(second, active);
return current;
}

/** Returns null when there are no positive peaks in the retained interval. */
synchronized Peaks snapshot(long timeMillis) {
long second = timeMillis / 1000;
Window previous = current;
if (second > previous.second && lastNonzeroSecond < Math.max(0, second - completedPeaks.length + 1)
&& (previous.counts.get() == SEALED || previous.counts.compareAndSet(0, SEALED))) {
// Keep an empty window sealed across polls. Reopen on the next request, even if its timestamp is stale.
idleThrough = Math.max(idleThrough, second);
return null;
}
Window window = advance(second);
long first = Math.max(0, window.second - completedPeaks.length + 1);
int currentPeak = peak(window.counts.get());
if (currentPeak == 0 && lastNonzeroSecond < first) {
return null;
}
int[] peaks = completedPeaks.clone();
peaks[index(window.second)] = currentPeak;
return new Peaks(peaks, first, window.second);
}

static final class Peaks {
private final int[] peaks;
private final long first;
private final long last;

private Peaks(int[] peaks, long first, long last) {
this.peaks = peaks;
this.first = first;
this.last = last;
}

void addTo(List<MetricNode> nodes) {
for (MetricNode node : nodes) {
long second = node.getTimestamp() / 1000;
if (second >= first && second <= last) {
int index = (int)(second % peaks.length);
node.setConcurrency(peaks[index]);
peaks[index] = 0;
}
}
// In-flight requests can span seconds with no other metrics.
for (long second = first; second <= last; second++) {
int peak = peaks[(int)(second % peaks.length)];
if (peak > 0) {
MetricNode node = new MetricNode();
node.setTimestamp(second * 1000);
node.setConcurrency(peak);
nodes.add(node);
}
}
}
}

private int index(long second) {
return (int)(second % completedPeaks.length);
}

private static int peak(long counts) {
return (int)(counts >>> 32) & Integer.MAX_VALUE;
}

private static final class Window {
final long second;
// Low 32 bits hold the active count. High 31 bits hold its peak and the sign bit seals the window.
final AtomicLong counts;

Window(long second, int active) {
this.second = second;
this.counts = new AtomicLong(pack(active, Math.max(0, active)));
}

boolean add(int delta) {
long before = counts.get();
while (before >= 0) {
int active = (int)before + delta;
if (counts.compareAndSet(before, pack(active, Math.max(peak(before), active)))) {
return true;
}
before = counts.get();
}
return false;
}

private static long pack(int active, int peak) {
return ((long)peak << 32) | (active & 0xffffffffL);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;

import com.alibaba.csp.sentinel.node.metric.MetricNode;
import com.alibaba.csp.sentinel.slots.statistic.metric.ArrayMetric;
Expand Down Expand Up @@ -89,6 +88,8 @@
*/
public class StatisticNode implements Node {

private static final int SECONDS_PER_MINUTE = 60;

/**
* Holds statistics of the recent {@code INTERVAL} milliseconds. The {@code INTERVAL} is divided into time spans
* by given {@code sampleCount}.
Expand All @@ -100,12 +101,13 @@ public class StatisticNode implements Node {
* Holds statistics of the recent 60 seconds. The windowLengthInMs is deliberately set to 1000 milliseconds,
* meaning each bucket per second, in this way we can get accurate statistics of each second.
*/
private transient Metric rollingCounterInMinute = new ArrayMetric(60, 60 * 1000, false);
private transient Metric rollingCounterInMinute = new ArrayMetric(SECONDS_PER_MINUTE,
SECONDS_PER_MINUTE * 1000, false);

/**
* The counter for thread count.
*/
private LongAdder curThreadNum = new LongAdder();
private final ConcurrencyCounter concurrency = new ConcurrencyCounter(SECONDS_PER_MINUTE);

/**
* The last timestamp when metrics were fetched.
Expand All @@ -118,7 +120,7 @@ public Map<Long, MetricNode> metrics() {
long currentTime = TimeUtil.currentTimeMillis();
currentTime = currentTime - currentTime % 1000;
Map<Long, MetricNode> metrics = new ConcurrentHashMap<>();
List<MetricNode> nodesOfEverySecond = rollingCounterInMinute.details();
List<MetricNode> nodesOfEverySecond = metricsWithConcurrency(currentTime, null);
long newLastFetchTime = lastFetchTime;
// Iterate metrics of all resources, filter valid metrics (not-empty and up-to-date).
for (MetricNode node : nodesOfEverySecond) {
Expand All @@ -134,7 +136,22 @@ public Map<Long, MetricNode> metrics() {

@Override
public List<MetricNode> rawMetricsInMin(Predicate<Long> timePredicate) {
return rollingCounterInMinute.detailsOnCondition(timePredicate);
long now = TimeUtil.currentTimeMillis();
// ArrayMetric may create the next second's bucket while the snapshot is being read.
return metricsWithConcurrency(now, t -> t <= now && (timePredicate == null || timePredicate.test(t)));
}

private List<MetricNode> metricsWithConcurrency(long now, Predicate<Long> timePredicate) {
ConcurrencyCounter.Peaks peaks = concurrency.snapshot(now);
if (peaks == null) {
return rollingCounterInMinute.detailsOnCondition(timePredicate);
}
List<MetricNode> nodes = rollingCounterInMinute.details();
peaks.addTo(nodes);
if (timePredicate != null) {
nodes.removeIf(node -> !timePredicate.test(node.getTimestamp()));
}
return nodes;
}

private boolean isNodeInTime(MetricNode node, long currentTime) {
Expand All @@ -143,7 +160,8 @@ private boolean isNodeInTime(MetricNode node, long currentTime) {

private boolean isValidMetricNode(MetricNode node) {
return node.getPassQps() > 0 || node.getBlockQps() > 0 || node.getSuccessQps() > 0
|| node.getExceptionQps() > 0 || node.getRt() > 0 || node.getOccupiedPassQps() > 0;
|| node.getExceptionQps() > 0 || node.getRt() > 0 || node.getOccupiedPassQps() > 0
|| node.getConcurrency() > 0;
}

@Override
Expand Down Expand Up @@ -239,7 +257,7 @@ public double minRt() {

@Override
public int curThreadNum() {
return (int)curThreadNum.sum();
return concurrency.currentCount();
}

@Override
Expand Down Expand Up @@ -271,12 +289,12 @@ public void increaseExceptionQps(int count) {

@Override
public void increaseThreadNum() {
curThreadNum.increment();
concurrency.add(1, TimeUtil.currentTimeMillis());
}

@Override
public void decreaseThreadNum() {
curThreadNum.decrement();
concurrency.add(-1, TimeUtil.currentTimeMillis());
}

@Override
Expand Down
Loading