passenger 4.0.42 → 4.0.43
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of passenger might be problematic. Click here for more details.
- checksums.yaml +8 -8
- checksums.yaml.gz.asc +7 -7
- data.tar.gz.asc +7 -7
- data/CHANGELOG +13 -0
- data/CONTRIBUTING.md +2 -19
- data/build/agents.rb +4 -1
- data/build/cxx_tests.rb +7 -2
- data/build/debian.rb +1 -1
- data/debian.template/control.template +0 -2
- data/doc/CodingTipsAndPitfalls.md +56 -0
- data/doc/Users guide Apache.idmap.txt +16 -14
- data/doc/Users guide Nginx.idmap.txt +8 -6
- data/doc/Users guide Standalone.idmap.txt +3 -1
- data/doc/Users guide Standalone.txt +1 -1
- data/doc/users_guide_snippets/environment_variables.txt +1 -0
- data/doc/users_guide_snippets/installation.txt +5 -5
- data/doc/users_guide_snippets/support_information.txt +42 -9
- data/doc/users_guide_snippets/troubleshooting/default.txt +42 -0
- data/ext/common/ApplicationPool2/Common.h +1 -0
- data/ext/common/ApplicationPool2/DirectSpawner.h +2 -7
- data/ext/common/ApplicationPool2/DummySpawner.h +1 -1
- data/ext/common/ApplicationPool2/Group.h +4 -2
- data/ext/common/ApplicationPool2/Options.h +9 -7
- data/ext/common/ApplicationPool2/Pool.h +83 -40
- data/ext/common/ApplicationPool2/Process.h +2 -6
- data/ext/common/ApplicationPool2/README.md +0 -40
- data/ext/common/ApplicationPool2/SmartSpawner.h +2 -9
- data/ext/common/ApplicationPool2/Spawner.h +1 -4
- data/ext/common/ApplicationPool2/SpawnerFactory.h +6 -9
- data/ext/common/ApplicationPool2/SuperGroup.h +3 -3
- data/ext/common/Constants.h +1 -1
- data/ext/common/UnionStation/Connection.h +227 -0
- data/ext/common/UnionStation/Core.h +497 -0
- data/ext/common/UnionStation/ScopeLog.h +172 -0
- data/ext/common/UnionStation/Transaction.h +276 -0
- data/ext/common/Utils.cpp +83 -8
- data/ext/common/Utils.h +25 -4
- data/ext/common/Utils/AnsiColorConstants.h +1 -0
- data/ext/common/Utils/ProcessMetricsCollector.h +6 -170
- data/ext/common/Utils/SpeedMeter.h +258 -0
- data/ext/common/Utils/StrIntUtils.cpp +6 -0
- data/ext/common/Utils/StringScanning.h +277 -0
- data/ext/common/Utils/SystemMetricsCollector.h +1460 -0
- data/ext/common/agents/Base.cpp +8 -8
- data/ext/common/agents/HelperAgent/Main.cpp +12 -6
- data/ext/common/agents/HelperAgent/RequestHandler.h +15 -16
- data/ext/common/agents/HelperAgent/SystemMetricsTool.cpp +199 -0
- data/ext/common/agents/LoggingAgent/LoggingServer.h +2 -1
- data/ext/common/agents/SpawnPreparer.cpp +20 -32
- data/lib/phusion_passenger.rb +1 -1
- data/lib/phusion_passenger/config/list_instances_command.rb +118 -0
- data/lib/phusion_passenger/config/main.rb +22 -4
- data/lib/phusion_passenger/config/system_metrics_command.rb +37 -0
- data/lib/phusion_passenger/config/utils.rb +1 -1
- data/lib/phusion_passenger/loader_shared_helpers.rb +8 -5
- data/lib/phusion_passenger/platform_info/compiler.rb +1 -1
- data/resources/templates/error_layout.html.template +3 -3
- data/test/cxx/ApplicationPool2/DirectSpawnerTest.cpp +3 -5
- data/test/cxx/ApplicationPool2/PoolTest.cpp +1 -3
- data/test/cxx/ApplicationPool2/ProcessTest.cpp +4 -4
- data/test/cxx/ApplicationPool2/SmartSpawnerTest.cpp +5 -7
- data/test/cxx/RequestHandlerTest.cpp +9 -3
- data/test/cxx/UnionStationTest.cpp +61 -64
- metadata +13 -4
- metadata.gz.asc +7 -7
- data/ext/common/UnionStation.h +0 -968
- data/helper-scripts/system-memory-stats.py +0 -207
data/ext/common/Utils.h
CHANGED
@@ -201,7 +201,7 @@ string extractBaseName(const StaticString &path);
|
|
201
201
|
* @throws std::bad_alloc Something went wrong.
|
202
202
|
* @ingroup Support
|
203
203
|
*/
|
204
|
-
string escapeForXml(const
|
204
|
+
string escapeForXml(const StaticString &input);
|
205
205
|
|
206
206
|
/**
|
207
207
|
* Returns the username of the user that the current process is running as.
|
@@ -385,6 +385,14 @@ void disableMallocDebugging();
|
|
385
385
|
*/
|
386
386
|
int runShellCommand(const StaticString &command);
|
387
387
|
|
388
|
+
/**
|
389
|
+
* Run a command and capture its stdout output.
|
390
|
+
*
|
391
|
+
* @param command The argument to pass to execvp();
|
392
|
+
* @throws SystemException.
|
393
|
+
*/
|
394
|
+
string runCommandAndCaptureOutput(const char **command);
|
395
|
+
|
388
396
|
/**
|
389
397
|
* Async-signal safe way to fork().
|
390
398
|
*
|
@@ -395,15 +403,28 @@ int runShellCommand(const StaticString &command);
|
|
395
403
|
* OS X apparently does something similar, except they use a
|
396
404
|
* spinlock so it results in 100% CPU. See _cthread_fork_prepare()
|
397
405
|
* at http://www.opensource.apple.com/source/Libc/Libc-166/threads.subproj/cthreads.c
|
406
|
+
* However, since POSIX in OS X is implemented on top of a Mach layer,
|
407
|
+
* calling asyncFork() can mess up the state of the Mach layer, causing
|
408
|
+
* some POSIX functions to mysteriously fail. See
|
409
|
+
* https://code.google.com/p/phusion-passenger/issues/detail?id=1094
|
410
|
+
* You should therefore not use asyncFork() unless you're in a signal
|
411
|
+
* handler.
|
398
412
|
*/
|
399
413
|
pid_t asyncFork();
|
400
414
|
|
401
415
|
/**
|
402
416
|
* Close all file descriptors that are higher than <em>lastToKeepOpen</em>.
|
403
|
-
*
|
404
|
-
*
|
417
|
+
*
|
418
|
+
* If you set `asyncSignalSafe` to true, then this function becomes fully async-signal,
|
419
|
+
* through the use of asyncFork() instead of fork(). However, read the documentation
|
420
|
+
* for asyncFork() to learn about its caveats.
|
421
|
+
*
|
422
|
+
* Also, regardless of whether `asyncSignalSafe` is true or not, this function is not
|
423
|
+
* *thread* safe. Make sure there are no other threads running that might open file
|
424
|
+
* descriptors, otherwise some file descriptors might not be closed even though they
|
425
|
+
* should be.
|
405
426
|
*/
|
406
|
-
void closeAllFileDescriptors(int lastToKeepOpen);
|
427
|
+
void closeAllFileDescriptors(int lastToKeepOpen, bool asyncSignalSafe = false);
|
407
428
|
|
408
429
|
/**
|
409
430
|
* A no-op, but usually set as a breakpoint in gdb. See CONTRIBUTING.md.
|
@@ -62,6 +62,7 @@
|
|
62
62
|
#include <Utils.h>
|
63
63
|
#include <Utils/ScopeGuard.h>
|
64
64
|
#include <Utils/IOUtils.h>
|
65
|
+
#include <Utils/StringScanning.h>
|
65
66
|
|
66
67
|
namespace Passenger {
|
67
68
|
|
@@ -185,183 +186,18 @@ public:
|
|
185
186
|
* command name, etc.
|
186
187
|
*/
|
187
188
|
class ProcessMetricsCollector {
|
188
|
-
public:
|
189
|
-
struct ParseException {};
|
190
|
-
|
191
189
|
private:
|
192
190
|
bool canMeasureRealMemory;
|
193
191
|
string psOutput;
|
194
192
|
|
195
|
-
/**
|
196
|
-
* Scan the given data for the first word that appears on the first line.
|
197
|
-
* Leading whitespaces (but not newlines) are ignored. If a word is found
|
198
|
-
* then the word is returned and the data pointer is moved to the end of
|
199
|
-
* the word. Otherwise, a ParseException is thrown.
|
200
|
-
*
|
201
|
-
* @post result.size() > 0
|
202
|
-
*/
|
203
|
-
static StaticString readNextWord(const char **data) {
|
204
|
-
// Skip leading whitespaces.
|
205
|
-
while (**data == ' ') {
|
206
|
-
(*data)++;
|
207
|
-
}
|
208
|
-
if (**data == '\n' || **data == '\0') {
|
209
|
-
throw ParseException();
|
210
|
-
}
|
211
|
-
|
212
|
-
// Find end of word and extract the word.
|
213
|
-
const char *endOfWord = *data;
|
214
|
-
while (*endOfWord != ' ' && *endOfWord != '\n' && *endOfWord != '\0') {
|
215
|
-
endOfWord++;
|
216
|
-
}
|
217
|
-
StaticString result(*data, endOfWord - *data);
|
218
|
-
|
219
|
-
// Move data pointer to the end of this word.
|
220
|
-
*data = endOfWord;
|
221
|
-
return result;
|
222
|
-
}
|
223
|
-
|
224
|
-
static long long processNextWordAsLongLong(const StaticString &word, char *nullTerminatedWord) {
|
225
|
-
memcpy(nullTerminatedWord, word.c_str(), word.size());
|
226
|
-
nullTerminatedWord[word.size()] = '\0';
|
227
|
-
if (*nullTerminatedWord == '\0') {
|
228
|
-
throw ParseException();
|
229
|
-
} else {
|
230
|
-
return atoll(nullTerminatedWord);
|
231
|
-
}
|
232
|
-
}
|
233
|
-
|
234
|
-
static long long readNextWordAsLongLong(const char **data) {
|
235
|
-
StaticString word = readNextWord(data);
|
236
|
-
if (word.size() < 50) {
|
237
|
-
char nullTerminatedWord[50];
|
238
|
-
return processNextWordAsLongLong(word, nullTerminatedWord);
|
239
|
-
} else {
|
240
|
-
string nullTerminatedWord(word.size() + 1, '\0');
|
241
|
-
return processNextWordAsLongLong(word, &nullTerminatedWord[0]);
|
242
|
-
}
|
243
|
-
}
|
244
|
-
|
245
|
-
static int processNextWordAsInt(const StaticString &word, char *nullTerminatedWord) {
|
246
|
-
memcpy(nullTerminatedWord, word.c_str(), word.size());
|
247
|
-
nullTerminatedWord[word.size()] = '\0';
|
248
|
-
if (*nullTerminatedWord == '\0') {
|
249
|
-
throw ParseException();
|
250
|
-
} else {
|
251
|
-
return atoi(nullTerminatedWord);
|
252
|
-
}
|
253
|
-
}
|
254
|
-
|
255
|
-
static int readNextWordAsInt(const char **data) {
|
256
|
-
StaticString word = readNextWord(data);
|
257
|
-
if (word.size() < 50) {
|
258
|
-
char nullTerminatedWord[50];
|
259
|
-
return processNextWordAsInt(word, nullTerminatedWord);
|
260
|
-
} else {
|
261
|
-
string nullTerminatedWord(word.size() + 1, '\0');
|
262
|
-
return processNextWordAsInt(word, &nullTerminatedWord[0]);
|
263
|
-
}
|
264
|
-
}
|
265
|
-
|
266
|
-
string runCommandAndCaptureOutput(const char **command) const {
|
267
|
-
pid_t pid;
|
268
|
-
int e;
|
269
|
-
Pipe p;
|
270
|
-
|
271
|
-
p = createPipe();
|
272
|
-
|
273
|
-
this_thread::disable_syscall_interruption dsi;
|
274
|
-
pid = syscalls::fork();
|
275
|
-
if (pid == 0) {
|
276
|
-
// Make ps nicer, we want to have as little impact on the rest
|
277
|
-
// of the system as possible while collecting the metrics.
|
278
|
-
int prio = getpriority(PRIO_PROCESS, getpid());
|
279
|
-
prio++;
|
280
|
-
if (prio > 20) {
|
281
|
-
prio = 20;
|
282
|
-
}
|
283
|
-
setpriority(PRIO_PROCESS, getpid(), prio);
|
284
|
-
|
285
|
-
dup2(p[1], 1);
|
286
|
-
close(p[0]);
|
287
|
-
close(p[1]);
|
288
|
-
closeAllFileDescriptors(2);
|
289
|
-
execvp(command[0], (char * const *) command);
|
290
|
-
_exit(1);
|
291
|
-
} else if (pid == -1) {
|
292
|
-
e = errno;
|
293
|
-
throw SystemException("Cannot fork() a new process", e);
|
294
|
-
} else {
|
295
|
-
bool done = false;
|
296
|
-
string result;
|
297
|
-
|
298
|
-
p[1].close();
|
299
|
-
while (!done) {
|
300
|
-
char buf[1024 * 4];
|
301
|
-
ssize_t ret;
|
302
|
-
|
303
|
-
try {
|
304
|
-
this_thread::restore_syscall_interruption rsi(dsi);
|
305
|
-
ret = syscalls::read(p[0], buf, sizeof(buf));
|
306
|
-
} catch (const thread_interrupted &) {
|
307
|
-
syscalls::kill(SIGKILL, pid);
|
308
|
-
syscalls::waitpid(pid, NULL, 0);
|
309
|
-
throw;
|
310
|
-
}
|
311
|
-
if (ret == -1) {
|
312
|
-
e = errno;
|
313
|
-
syscalls::kill(SIGKILL, pid);
|
314
|
-
syscalls::waitpid(pid, NULL, 0);
|
315
|
-
throw SystemException("Cannot read output from the 'ps' command", e);
|
316
|
-
}
|
317
|
-
done = ret == 0;
|
318
|
-
result.append(buf, ret);
|
319
|
-
}
|
320
|
-
p[0].close();
|
321
|
-
syscalls::waitpid(pid, NULL, 0);
|
322
|
-
|
323
|
-
if (result.empty()) {
|
324
|
-
throw RuntimeException("The 'ps' command failed");
|
325
|
-
} else {
|
326
|
-
return result;
|
327
|
-
}
|
328
|
-
}
|
329
|
-
}
|
330
|
-
|
331
|
-
string readRestOfLine(const char *data) const {
|
332
|
-
// Skip leading whitespaces.
|
333
|
-
while (*data == ' ') {
|
334
|
-
data++;
|
335
|
-
}
|
336
|
-
// Rest of line is allowed to be empty.
|
337
|
-
if (*data == '\n' || *data == '\0') {
|
338
|
-
return "";
|
339
|
-
}
|
340
|
-
|
341
|
-
// Look for newline character. From there, scan back until we've
|
342
|
-
// found a non-whitespace character.
|
343
|
-
const char *endOfLine = strchr(data, '\n');
|
344
|
-
if (endOfLine == NULL) {
|
345
|
-
throw ParseException();
|
346
|
-
}
|
347
|
-
while (*(endOfLine - 1) == ' ') {
|
348
|
-
endOfLine--;
|
349
|
-
}
|
350
|
-
|
351
|
-
return string(data, endOfLine - data);
|
352
|
-
}
|
353
|
-
|
354
193
|
template<typename Collection, typename ConstIterator>
|
355
194
|
ProcessMetricMap parsePsOutput(const string &output, const Collection &allowedPids) const {
|
356
195
|
ProcessMetricMap result;
|
196
|
+
const char *start = output.c_str();
|
197
|
+
|
357
198
|
// Ignore first line, it contains the column names.
|
358
|
-
|
359
|
-
|
360
|
-
// Skip to beginning of next line.
|
361
|
-
start++;
|
362
|
-
if (*start == '\0') {
|
363
|
-
start = NULL;
|
364
|
-
}
|
199
|
+
if (!skipToNextLine(&start) || *start == '\0') {
|
200
|
+
start = NULL;
|
365
201
|
}
|
366
202
|
|
367
203
|
#ifndef PS_SUPPORTS_MULTIPLE_PIDS
|
@@ -428,7 +264,7 @@ public:
|
|
428
264
|
*
|
429
265
|
* Returns a map which maps a given PID to its collected metrics.
|
430
266
|
*
|
431
|
-
* @throws
|
267
|
+
* @throws ParseException The ps output cannot be parsed.
|
432
268
|
* @throws SystemException
|
433
269
|
* @throws RuntimeException
|
434
270
|
*/
|
@@ -0,0 +1,258 @@
|
|
1
|
+
/*
|
2
|
+
* Phusion Passenger - https://www.phusionpassenger.com/
|
3
|
+
* Copyright (c) 2014 Phusion
|
4
|
+
*
|
5
|
+
* "Phusion Passenger" is a trademark of Hongli Lai & Ninh Bui.
|
6
|
+
*
|
7
|
+
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
8
|
+
* of this software and associated documentation files (the "Software"), to deal
|
9
|
+
* in the Software without restriction, including without limitation the rights
|
10
|
+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
11
|
+
* copies of the Software, and to permit persons to whom the Software is
|
12
|
+
* furnished to do so, subject to the following conditions:
|
13
|
+
*
|
14
|
+
* The above copyright notice and this permission notice shall be included in
|
15
|
+
* all copies or substantial portions of the Software.
|
16
|
+
*
|
17
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
18
|
+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
19
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
20
|
+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
21
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
22
|
+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
23
|
+
* THE SOFTWARE.
|
24
|
+
*/
|
25
|
+
#ifndef _PASSENGER_SPEED_METER_H_
|
26
|
+
#define _PASSENGER_SPEED_METER_H_
|
27
|
+
|
28
|
+
#include <cstdio>
|
29
|
+
#include <cstdlib>
|
30
|
+
#include <cassert>
|
31
|
+
#include <limits>
|
32
|
+
#include <Utils/SystemTime.h>
|
33
|
+
|
34
|
+
namespace Passenger {
|
35
|
+
|
36
|
+
/**
|
37
|
+
* Utility class which, when periodically fed with quantities, measures the
|
38
|
+
* rate of change in the most recent time period. It does this by storing
|
39
|
+
* samples of the most recent quantities, calculating a weighted average of
|
40
|
+
* the differences between each sample, and extrapolating that over a time
|
41
|
+
* period.
|
42
|
+
*
|
43
|
+
* For example,
|
44
|
+
*
|
45
|
+
* * When periodically given the number of miles a car has driven so far,
|
46
|
+
* the average speed of the most recent 10 minutes can be calculated.
|
47
|
+
* * When periodically given the number of processes the OS has created
|
48
|
+
* so far, the average fork rate (per minute) of the most recent minute
|
49
|
+
* can be calculated.
|
50
|
+
*
|
51
|
+
* SpeedMeter is designed to use as little memory as possible, and designed
|
52
|
+
* so that samples can be taken at erratic intervals. This is why it limits
|
53
|
+
* the number of samples that can be stored in memory, and why it puts time
|
54
|
+
* limits on the samples.
|
55
|
+
*
|
56
|
+
*
|
57
|
+
* ## Template parameters
|
58
|
+
*
|
59
|
+
* ### `maxSamples`
|
60
|
+
*
|
61
|
+
* `maxSamples` dictates the sample buffer size: the maximum number of samples
|
62
|
+
* to hold in memory. Defaults to 6.
|
63
|
+
*
|
64
|
+
* The more samples you have, the more historical data influences the results.
|
65
|
+
* If you have few samples then recent data have the most impact on the results.
|
66
|
+
*
|
67
|
+
* ### `minAge`
|
68
|
+
*
|
69
|
+
* A new sample is only accepted if at least `minAge` microseconds
|
70
|
+
* have passed since the last sample. This is to ensure that the sample
|
71
|
+
* buffer contains enough historical data so that results are not skewed by
|
72
|
+
* adding samples too quickly. A full sample buffer is guaranteed to cover
|
73
|
+
* the last `minAge * maxSamples` microseconds.
|
74
|
+
*
|
75
|
+
* Defaults to 1 second (1 000 000 usec).
|
76
|
+
*
|
77
|
+
* To see why this is useful, consider when `maxSamples` is 5 and `minAge` is 0.
|
78
|
+
* If you measure the number of processes 5 times with 10 ms in between,
|
79
|
+
* then it's unlikely that the OS has spawned any processes in that 50 ms time
|
80
|
+
* interval. However you've now filled the sample buffer with only data from
|
81
|
+
* those 5 recent measurements, so SpeedMeter thinks the rate of change is 0.
|
82
|
+
* If you set `minAge` to, say, 5 seconds, then the sample buffer will be updated
|
83
|
+
* at most once every 5 seconds, guaranteeing that it can retain historical data
|
84
|
+
* for the last 25 seconds.
|
85
|
+
*
|
86
|
+
* `minAge * maxSamples` should be larger than `window`.
|
87
|
+
*
|
88
|
+
* ### `maxAge`
|
89
|
+
*
|
90
|
+
* When calculating the result, samples older than `maxAge` usec ago are ignored.
|
91
|
+
* This value should be larger than `window`. Defaults to 1 minute (60 000 000
|
92
|
+
* usec).
|
93
|
+
*
|
94
|
+
* ### `window`
|
95
|
+
*
|
96
|
+
* When calculating the result, this value dictates the time interval over which
|
97
|
+
* the rate of change should be calculated. Defaults to 1 second (1 000 000 usec),
|
98
|
+
* meaning that by default the result describes the speed per second.
|
99
|
+
*
|
100
|
+
*
|
101
|
+
* ## Interpreting the parameters
|
102
|
+
*
|
103
|
+
* Given parameters, the behavior of SpeedMeter can be interpreted as follows:
|
104
|
+
*
|
105
|
+
* All samples that have been collected in the last `minAge * maxSamples` usecs
|
106
|
+
* (or the last `maxAge` usecs, if samples have been collected slowly), are used for
|
107
|
+
* calculating the speed per `window` usecs.
|
108
|
+
*
|
109
|
+
* Thus, given the default parameter values, we can say:
|
110
|
+
*
|
111
|
+
* All samples that have been collected in the last 8 seconds (the last 1 minute,
|
112
|
+
* if samples have been collected slowly), are used for calculating the speed
|
113
|
+
* per second.
|
114
|
+
*/
|
115
|
+
template<
|
116
|
+
typename ValueType = double,
|
117
|
+
unsigned int maxSamples = 8,
|
118
|
+
unsigned int minAge = 1000000,
|
119
|
+
unsigned int maxAge = 60 * 1000000,
|
120
|
+
unsigned int window = 1000000
|
121
|
+
>
|
122
|
+
class SpeedMeter {
|
123
|
+
private:
|
124
|
+
struct Sample {
|
125
|
+
unsigned long long timestamp;
|
126
|
+
ValueType val;
|
127
|
+
|
128
|
+
Sample()
|
129
|
+
: timestamp(0),
|
130
|
+
val(0)
|
131
|
+
{ }
|
132
|
+
};
|
133
|
+
|
134
|
+
unsigned short start, count;
|
135
|
+
Sample samples[maxSamples];
|
136
|
+
|
137
|
+
static int mod(int a, int b) {
|
138
|
+
int r = a % b;
|
139
|
+
return r < 0 ? r + b : r;
|
140
|
+
}
|
141
|
+
|
142
|
+
const Sample &getSample(int index) const {
|
143
|
+
return samples[mod(start + index, maxSamples)];
|
144
|
+
}
|
145
|
+
|
146
|
+
const Sample &getLastSample() const {
|
147
|
+
return getSample(count - 1);
|
148
|
+
}
|
149
|
+
|
150
|
+
unsigned long long getTimeThreshold() const {
|
151
|
+
const unsigned long long currentTime = SystemTime::getUsec();
|
152
|
+
if (currentTime > maxAge) {
|
153
|
+
return currentTime - maxAge;
|
154
|
+
} else {
|
155
|
+
return 0;
|
156
|
+
}
|
157
|
+
}
|
158
|
+
|
159
|
+
public:
|
160
|
+
SpeedMeter()
|
161
|
+
: start(0),
|
162
|
+
count(0)
|
163
|
+
{ }
|
164
|
+
|
165
|
+
bool addSample(ValueType val, unsigned long long timestamp = 0) {
|
166
|
+
if (timestamp == 0) {
|
167
|
+
timestamp = SystemTime::getUsec();
|
168
|
+
}
|
169
|
+
|
170
|
+
const Sample &lastSample = getLastSample();
|
171
|
+
// Timestamp must be larger than that of previous sample.
|
172
|
+
assert(lastSample.timestamp <= timestamp);
|
173
|
+
|
174
|
+
if (lastSample.timestamp <= timestamp - minAge) {
|
175
|
+
Sample &nextSample = samples[(start + count) % maxSamples];
|
176
|
+
nextSample.timestamp = timestamp;
|
177
|
+
nextSample.val = val;
|
178
|
+
if (count == maxSamples) {
|
179
|
+
start = (start + 1) % maxSamples;
|
180
|
+
} else {
|
181
|
+
count++;
|
182
|
+
}
|
183
|
+
return true;
|
184
|
+
} else {
|
185
|
+
return false;
|
186
|
+
}
|
187
|
+
}
|
188
|
+
|
189
|
+
/** Number of items in the sample buffer. */
|
190
|
+
unsigned int size() const {
|
191
|
+
return count;
|
192
|
+
}
|
193
|
+
|
194
|
+
/** Current speed over the configured window. Returns NaN if less than 2
|
195
|
+
* samples have been collected so far.
|
196
|
+
*/
|
197
|
+
double currentSpeed() const {
|
198
|
+
const unsigned long long timeThreshold = getTimeThreshold();
|
199
|
+
int begin = 0, i;
|
200
|
+
unsigned long long interval;
|
201
|
+
double avgWeight = 0, sum = 0;
|
202
|
+
|
203
|
+
// Ignore samples that are too old.
|
204
|
+
while (begin < (int) count - 1
|
205
|
+
&& getSample(begin).timestamp <= timeThreshold)
|
206
|
+
{
|
207
|
+
begin++;
|
208
|
+
}
|
209
|
+
|
210
|
+
// Given the deltas of each sample and the next sample,
|
211
|
+
// calculate the weighted average of all those deltas,
|
212
|
+
// with time interval of each delta as the weight,
|
213
|
+
// and calculate the average weight.
|
214
|
+
for (i = begin; i < (int) count - 1; i++) {
|
215
|
+
const Sample &cur = getSample(i);
|
216
|
+
const Sample &next = getSample(i + 1);
|
217
|
+
ValueType delta = next.val - cur.val;
|
218
|
+
unsigned long long weight = next.timestamp - cur.timestamp;
|
219
|
+
sum += (double) delta * weight;
|
220
|
+
avgWeight += weight;
|
221
|
+
}
|
222
|
+
avgWeight /= std::max(1, (int) count - 1 - begin);
|
223
|
+
|
224
|
+
interval = getSample(count - 1).timestamp - getSample(begin).timestamp;
|
225
|
+
if (interval > 0) {
|
226
|
+
// sum / interval is the speed per average delta interval,
|
227
|
+
// so we extrapolate that over the entire window interval.
|
228
|
+
return (sum / interval) * (window / avgWeight);
|
229
|
+
} else {
|
230
|
+
return numeric_limits<double>::quiet_NaN();
|
231
|
+
}
|
232
|
+
}
|
233
|
+
|
234
|
+
#if 1
|
235
|
+
void debug() const {
|
236
|
+
const unsigned long long timeThreshold = getTimeThreshold();
|
237
|
+
|
238
|
+
printf("---- begin debug ----\n");
|
239
|
+
printf("timeThreshold: %llu\n", timeThreshold);
|
240
|
+
for (int i = 0; i < (int) maxSamples; i++) {
|
241
|
+
const Sample &sample = samples[i];
|
242
|
+
printf("elem %u, sample %u: timestamp = %llu, val = %.0f%s%s%s\n",
|
243
|
+
i,
|
244
|
+
mod(i - start, maxSamples),
|
245
|
+
sample.timestamp,
|
246
|
+
(double) sample.val,
|
247
|
+
(sample.timestamp <= timeThreshold) ? " X" : "",
|
248
|
+
(i == start) ? " <-- start" : "",
|
249
|
+
(count > 0 && i == mod((int) start + count - 1, maxSamples)) ? " <-- last" : "");
|
250
|
+
}
|
251
|
+
printf("---- end debug ----\n");
|
252
|
+
}
|
253
|
+
#endif
|
254
|
+
};
|
255
|
+
|
256
|
+
} // namespace Passenger
|
257
|
+
|
258
|
+
#endif /* _PASSENGER_SPEED_METER_H_ */
|