forked from graphite-project/graphite-web
/
functions.py
2680 lines (2074 loc) · 81 KB
/
functions.py
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Copyright 2008 Orbitz WorldWide
#
#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.
from datetime import date, datetime, timedelta
from functools import partial
from itertools import izip, imap
import math
import re
import random
import time
from graphite.logger import log
from graphite.render.datalib import fetchData, TimeSeries, timestamp
from graphite.render.attime import parseTimeOffset
from graphite.events import models
#XXX format_units() should go somewhere else
from os import environ
if environ.get('READTHEDOCS'):
format_units = lambda *args, **kwargs: (0,'')
else:
from graphite.render.glyph import format_units
NAN = float('NaN')
INF = float('inf')
DAY = 86400
HOUR = 3600
MINUTE = 60
#Utility functions
def safeSum(values):
safeValues = [v for v in values if v is not None]
if safeValues:
return sum(safeValues)
def safeDiff(values):
safeValues = [v for v in values if v is not None]
if safeValues:
values = map(lambda x: x*-1, safeValues[1:])
values.insert(0, safeValues[0])
return sum(values)
def safeLen(values):
return len([v for v in values if v is not None])
def safeDiv(a,b):
if a is None: return None
if b in (0,None): return None
return float(a) / float(b)
def safeMul(*factors):
if None in factors:
return None
factors = map(float, factors)
product = reduce(lambda x,y: x*y, factors)
return product
def safeSubtract(a,b):
if a is None or b is None: return None
return float(a) - float(b)
def safeLast(values):
for v in reversed(values):
if v is not None: return v
def safeMin(values):
safeValues = [v for v in values if v is not None]
if safeValues:
return min(safeValues)
def safeMax(values):
safeValues = [v for v in values if v is not None]
if safeValues:
return max(safeValues)
def safeMap(function, values):
safeValues = [v for v in values if v is not None]
if safeValues:
return map(function, values)
def safeAbs(value):
if value is None: return None
return abs(value)
def lcm(a,b):
if a == b: return a
if a < b: (a,b) = (b,a) #ensure a > b
for i in xrange(1,a * b):
if a % (b * i) == 0 or (b * i) % a == 0: #probably inefficient
return max(a,b * i)
return a * b
def normalize(seriesLists):
seriesList = reduce(lambda L1,L2: L1+L2,seriesLists)
step = reduce(lcm,[s.step for s in seriesList])
for s in seriesList:
s.consolidate( step / s.step )
start = min([s.start for s in seriesList])
end = max([s.end for s in seriesList])
end -= (end - start) % step
return (seriesList,start,end,step)
# Series Functions
#NOTE: Some of the functions below use izip, which may be problematic.
#izip stops when it hits the end of the shortest series
#in practice this *shouldn't* matter because all series will cover
#the same interval, despite having possibly different steps...
def sumSeries(requestContext, *seriesLists):
"""
Short form: sum()
This will add metrics together and return the sum at each datapoint. (See
integral for a sum over time)
Example:
.. code-block:: none
&target=sum(company.server.application*.requestsHandled)
This would show the sum of all requests handled per minute (provided
requestsHandled are collected once a minute). If metrics with different
retention rates are combined, the coarsest metric is graphed, and the sum
of the other metrics is averaged for the metrics with finer retention rates.
"""
try:
(seriesList,start,end,step) = normalize(seriesLists)
except:
return []
#name = "sumSeries(%s)" % ','.join((s.name for s in seriesList))
name = "sumSeries(%s)" % ','.join(set([s.pathExpression for s in seriesList]))
values = ( safeSum(row) for row in izip(*seriesList) )
series = TimeSeries(name,start,end,step,values)
series.pathExpression = name
return [series]
def sumSeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Call sumSeries after inserting wildcards at the given position(s).
Example:
.. code-block:: none
&target=sumSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1)
This would be the equivalent of
``target=sumSeries(host.*.cpu-user.value)&target=sumSeries(host.*.cpu-system.value)``
"""
if type(position) is int:
positions = [position]
else:
positions = position
newSeries = {}
newNames = list()
for series in seriesList:
newname = '.'.join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.')))))
if newname in newSeries.keys():
newSeries[newname] = sumSeries(requestContext, (series, newSeries[newname]))[0]
else:
newSeries[newname] = series
newNames.append(newname)
newSeries[newname].name = newname
return [newSeries[name] for name in newNames]
def averageSeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Call averageSeries after inserting wildcards at the given position(s).
Example:
.. code-block:: none
&target=averageSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1)
This would be the equivalent of
``target=averageSeries(host.*.cpu-user.value)&target=averageSeries(host.*.cpu-system.value)``
"""
if type(position) is int:
positions = [position]
else:
positions = position
result = []
matchedList = {}
for series in seriesList:
newname = '.'.join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.')))))
if not matchedList.has_key(newname):
matchedList[newname] = []
matchedList[newname].append(series)
for name in matchedList.keys():
result.append( averageSeries(requestContext, (matchedList[name]))[0] )
result[-1].name = name
return result
def diffSeries(requestContext, *seriesLists):
"""
Can take two or more metrics, or a single metric and a constant.
Subtracts parameters 2 through n from parameter 1.
Example:
.. code-block:: none
&target=diffSeries(service.connections.total,service.connections.failed)
&target=diffSeries(service.connections.total,5)
"""
(seriesList,start,end,step) = normalize(seriesLists)
name = "diffSeries(%s)" % ','.join(set([s.pathExpression for s in seriesList]))
values = ( safeDiff(row) for row in izip(*seriesList) )
series = TimeSeries(name,start,end,step,values)
series.pathExpression = name
return [series]
def averageSeries(requestContext, *seriesLists):
"""
Short Alias: avg()
Takes one metric or a wildcard seriesList.
Draws the average value of all metrics passed at each time.
Example:
.. code-block:: none
&target=averageSeries(company.server.*.threads.busy)
"""
(seriesList,start,end,step) = normalize(seriesLists)
#name = "averageSeries(%s)" % ','.join((s.name for s in seriesList))
name = "averageSeries(%s)" % ','.join(set([s.pathExpression for s in seriesList]))
values = ( safeDiv(safeSum(row),safeLen(row)) for row in izip(*seriesList) )
series = TimeSeries(name,start,end,step,values)
series.pathExpression = name
return [series]
def minSeries(requestContext, *seriesLists):
"""
Takes one metric or a wildcard seriesList.
For each datapoint from each metric passed in, pick the minimum value and graph it.
Example:
.. code-block:: none
&target=minSeries(Server*.connections.total)
"""
(seriesList, start, end, step) = normalize(seriesLists)
pathExprs = list( set([s.pathExpression for s in seriesList]) )
name = "minSeries(%s)" % ','.join(pathExprs)
values = ( safeMin(row) for row in izip(*seriesList) )
series = TimeSeries(name, start, end, step, values)
series.pathExpression = name
return [series]
def maxSeries(requestContext, *seriesLists):
"""
Takes one metric or a wildcard seriesList.
For each datapoint from each metric passed in, pick the maximum value and graph it.
Example:
.. code-block:: none
&target=maxSeries(Server*.connections.total)
"""
(seriesList, start, end, step) = normalize(seriesLists)
pathExprs = list( set([s.pathExpression for s in seriesList]) )
name = "maxSeries(%s)" % ','.join(pathExprs)
values = ( safeMax(row) for row in izip(*seriesList) )
series = TimeSeries(name, start, end, step, values)
series.pathExpression = name
return [series]
def rangeOfSeries(requestContext, *seriesLists):
"""
Takes a wildcard seriesList.
Distills down a set of inputs into the range of the series
Example:
.. code-block:: none
&target=rangeOfSeries(Server*.connections.total)
"""
(seriesList,start,end,step) = normalize(seriesLists)
name = "rangeOfSeries(%s)" % ','.join(set([s.pathExpression for s in seriesList]))
values = ( safeSubtract(max(row), min(row)) for row in izip(*seriesList) )
series = TimeSeries(name,start,end,step,values)
series.pathExpression = name
return [series]
def percentileOfSeries(requestContext, seriesList, n, interpolate=False):
"""
percentileOfSeries returns a single series which is composed of the n-percentile
values taken across a wildcard series at each point. Unless `interpolate` is
set to True, percentile values are actual values contained in one of the
supplied series.
"""
if n <= 0:
raise ValueError('The requested percent is required to be greater than 0')
name = 'percentilesOfSeries(%s, %.1f)' % (seriesList[0].pathExpression, n)
(start, end, step) = normalize([seriesList])[1:]
values = [ _getPercentile(row, n, interpolate) for row in izip(*seriesList) ]
resultSeries = TimeSeries(name, start, end, step, values)
resultSeries.pathExpression = name
return [resultSeries]
def keepLastValue(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line.
Example:
.. code-block:: none
&target=keepLastValue(Server01.connections.handled)
"""
for series in seriesList:
series.name = "keepLastValue(%s)" % (series.name)
series.pathExpression = series.name
for i,value in enumerate(series):
if value is None and i != 0:
value = series[i-1]
series[i] = value
return seriesList
def asPercent(requestContext, seriesList, total=None):
"""
Calculates a percentage of the total of a wildcard series. If `total` is specified,
each series will be calculated as a percentage of that total. If `total` is not specified,
the sum of all points in the wildcard series will be used instead.
The `total` parameter may be a single series or a numeric value.
Example:
.. code-block:: none
&target=asPercent(Server01.connections.{failed,succeeded}, Server01.connections.attempted)
&target=asPercent(apache01.threads.busy,1500)
&target=asPercent(Server01.cpu.*.jiffies)
"""
normalize([seriesList])
if total is None:
totalValues = [ safeSum(row) for row in izip(*seriesList) ]
totalText = None # series.pathExpression
elif type(total) is list:
if len(total) != 1:
raise ValueError("asPercent second argument must reference exactly 1 series")
normalize([seriesList, total])
totalValues = total[0]
totalText = totalValues.name
else:
totalValues = [total] * len(seriesList[0])
totalText = str(total)
resultList = []
for series in seriesList:
resultValues = [ safeMul(safeDiv(val, totalVal), 100.0) for val,totalVal in izip(series,totalValues) ]
name = "asPercent(%s, %s)" % (series.name, totalText or series.pathExpression)
resultSeries = TimeSeries(name,series.start,series.end,series.step,resultValues)
resultSeries.pathExpression = name
resultList.append(resultSeries)
return resultList
def divideSeries(requestContext, dividendSeriesList, divisorSeriesList):
"""
Takes a dividend metric and a divisor metric and draws the division result.
A constant may *not* be passed. To divide by a constant, use the scale()
function (which is essentially a multiplication operation) and use the inverse
of the dividend. (Division by 8 = multiplication by 1/8 or 0.125)
Example:
.. code-block:: none
&target=divideSeries(Series.dividends,Series.divisors)
"""
if len(divisorSeriesList) != 1:
raise ValueError("divideSeries second argument must reference exactly 1 series")
divisorSeries = divisorSeriesList[0]
results = []
for dividendSeries in dividendSeriesList:
name = "divideSeries(%s,%s)" % (dividendSeries.name, divisorSeries.name)
bothSeries = (dividendSeries, divisorSeries)
step = reduce(lcm,[s.step for s in bothSeries])
for s in bothSeries:
s.consolidate( step / s.step )
start = min([s.start for s in bothSeries])
end = max([s.end for s in bothSeries])
end -= (end - start) % step
values = ( safeDiv(v1,v2) for v1,v2 in izip(*bothSeries) )
quotientSeries = TimeSeries(name, start, end, step, values)
quotientSeries.pathExpression = name
results.append(quotientSeries)
return results
def multiplySeries(requestContext, *seriesLists):
"""
Takes two or more series and multiplies their points. A constant may not be
used. To multiply by a constant, use the scale() function.
Example:
.. code-block:: none
&target=multiplySeries(Series.dividends,Series.divisors)
"""
(seriesList,start,end,step) = normalize(seriesLists)
if len(seriesList) == 1:
return seriesList
name = "multiplySeries(%s)" % ','.join([s.name for s in seriesList])
product = imap(lambda x: safeMul(*x), izip(*seriesList))
resultSeries = TimeSeries(name, start, end, step, product)
resultSeries.pathExpression = name
return [ resultSeries ]
def movingMedian(requestContext, seriesList, windowSize):
"""
Takes one metric or a wildcard seriesList followed by a number N of datapoints and graphs
the median of N previous datapoints. N-1 datapoints are set to None at the
beginning of the graph.
.. code-block:: none
&target=movingMedian(Server.instance01.threads.busy,10)
"""
for seriesIndex, series in enumerate(seriesList):
newName = "movingMedian(%s,%.1f)" % (series.name, float(windowSize))
newSeries = TimeSeries(newName, series.start, series.end, series.step, [])
newSeries.pathExpression = newName
windowIndex = windowSize - 1
for i in range( len(series) ):
if i < windowIndex: # Pad the beginning with None's since we don't have enough data
newSeries.append( None )
else:
window = series[i - windowIndex : i + 1]
nonNull = [ v for v in window if v is not None ]
if nonNull:
m_index = len(nonNull) / 2
newSeries.append(sorted(nonNull)[m_index])
else:
newSeries.append(None)
seriesList[ seriesIndex ] = newSeries
return seriesList
def scale(requestContext, seriesList, factor):
"""
Takes one metric or a wildcard seriesList followed by a constant, and multiplies the datapoint
by the constant provided at each point.
Example:
.. code-block:: none
&target=scale(Server.instance01.threads.busy,10)
&target=scale(Server.instance*.threads.busy,10)
"""
for series in seriesList:
series.name = "scale(%s,%.1f)" % (series.name,float(factor))
for i,value in enumerate(series):
series[i] = safeMul(value,factor)
return seriesList
def scaleToSeconds(requestContext, seriesList, seconds):
"""
Takes one metric or a wildcard seriesList and returns "value per seconds" where
seconds is a last argument to this functions.
Useful in conjunction with derivative or integral function if you want
to normalize its result to a known resolution for arbitrary retentions
"""
for series in seriesList:
series.name = "scaleToSeconds(%s,%d)" % (series.name,seconds)
for i,value in enumerate(series):
factor = seconds * 1.0 / series.step
series[i] = safeMul(value,factor)
return seriesList
def absolute(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList and applies the mathematical abs function to each
datapoint transforming it to its absolute value.
Example:
.. code-block:: none
&target=absolute(Server.instance01.threads.busy)
&target=absolute(Server.instance*.threads.busy)
"""
for series in seriesList:
series.name = "absolute(%s)" % (series.name)
for i,value in enumerate(series):
series[i] = safeAbs(value)
return seriesList
def offset(requestContext, seriesList, factor):
"""
Takes one metric or a wildcard seriesList followed by a constant, and adds the constant to
each datapoint.
Example:
.. code-block:: none
&target=offset(Server.instance01.threads.busy,10)
"""
for series in seriesList:
series.name = "offset(%s,%.1f)" % (series.name,float(factor))
for i,value in enumerate(series):
if value is not None:
series[i] = value + factor
return seriesList
def movingAverage(requestContext, seriesList, windowSize):
"""
Takes one metric or a wildcard seriesList followed by a number N of datapoints and graphs
the average of N previous datapoints. N-1 datapoints are set to None at the
beginning of the graph.
.. code-block:: none
&target=movingAverage(Server.instance01.threads.busy,10)
"""
for seriesIndex, series in enumerate(seriesList):
newName = "movingAverage(%s,%d)" % (series.name, windowSize)
newSeries = TimeSeries(newName, series.start, series.end, series.step, [])
newSeries.pathExpression = newName
windowIndex = int(windowSize) - 1
for i in range( len(series) ):
if i < windowIndex: # Pad the beginning with None's since we don't have enough data
newSeries.append( None )
else:
window = series[i - windowIndex : i + 1]
nonNull = [ v for v in window if v is not None ]
if nonNull:
newSeries.append( sum(nonNull) / len(nonNull) )
else:
newSeries.append(None)
seriesList[ seriesIndex ] = newSeries
return seriesList
def cumulative(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sets the consolidation function to 'sum' for the given metric seriesList.
Alias for :func:`consolidateBy(series, 'sum') <graphite.render.functions.consolidateBy>`
.. code-block:: none
&target=cumulative(Sales.widgets.largeBlue)
"""
return consolidateBy(requestContext, seriesList, 'sum')
def consolidateBy(requestContext, seriesList, consolidationFunc):
"""
Takes one metric or a wildcard seriesList and a consolidation function name.
Valid function names are 'sum', 'average', 'min', and 'max'
When a graph is drawn where width of the graph size in pixels is smaller than
the number of datapoints to be graphed, Graphite consolidates the values to
to prevent line overlap. The consolidateBy() function changes the consolidation
function from the default of 'average' to one of 'sum', 'max', or 'min'. This is
especially useful in sales graphs, where fractional values make no sense and a 'sum'
of consolidated values is appropriate.
.. code-block:: none
&target=consolidateBy(Sales.widgets.largeBlue, 'sum')
&target=consolidateBy(Servers.web01.sda1.free_space, 'max')
"""
for series in seriesList:
# datalib will throw an exception, so it's not necessary to validate here
series.consolidationFunc = consolidationFunc
series.name = 'consolidateBy(%s,"%s")' % (series.name, series.consolidationFunc)
return seriesList
def resample(requestContext, seriesList, pointsPerPx = 1):
"""
Resamples the given series according to the requested graph width and
$pointsPerPx aggregating by average. Total number of points after this
function == graph width * pointsPerPx.
This has two significant uses:
* Drastically speeds up render time when graphing high resolution data
or many metrics.
* Allows movingAverage() to have a consistent smoothness across timescales.
* Example: movingAverage(resample(metric,2),20) would end up with
a 10px moving average no matter what the scale of your graph.
* Allows a consistent number-of-samples to be returned from JSON requests
* the number of samples returned == graph width * points per pixel
Example:
.. code-block:: none
&target=resample(metric, 2)
&target=movingAverage(resample(metric, 2), 20)
"""
newSampleCount = requestContext['width']
for seriesIndex, series in enumerate(seriesList):
newValues = []
seriesLength = (series.end - series.start)
newStep = (float(seriesLength) / float(newSampleCount)) / float(pointsPerPx)
# Leave this series alone if we're asked to do upsampling
if newStep < series.step:
continue
sampleWidth = 0
sampleCount = 0
sampleSum = 0
for value in series:
if (value is not None):
sampleCount += 1
sampleSum += value
sampleWidth += series.step
# If the current sample covers the width of a new step, add it to the
# result
if (sampleWidth >= newStep):
if sampleCount > 0:
newValues.append(sampleSum / sampleCount)
else:
newValues.append(None)
sampleWidth -= newStep
sampleSum = 0
sampleCount = 0
# Process and add the left-over sample if it's not empty
if sampleCount > 0:
newValues.append(sampleSum / sampleCount)
newName = "resample(%s, %s)" % (series.name, pointsPerPx)
newSeries = TimeSeries(newName, series.start, series.end, newStep, newValues)
newSeries.pathExpression = newName
seriesList[seriesIndex] = newSeries
return seriesList
def smooth(requestContext, seriesList, windowPixelSize = 5):
"""
Resample and smooth a set of metrics. Provides line smoothing that is
independent of time scale (windowPixelSize ~ movingAverage over pixels)
An shorter and safer way of calling:
movingAverage(resample(seriesList, 2), smoothFactor * 2)
The windowPixelSize is effectively the number of pixels over which to perform
the movingAverage.
Note: This is safer in that if a series has fewer data points than pixels,
the metric won't be upsampled. Instead the movingAverage window size will be
adjusted to cover the same number of pixels.
"""
pointsPerPixel = 2
resampled = resample(requestContext, seriesList, pointsPerPixel)
sampleSize = int(windowPixelSize * pointsPerPixel)
expectedSamples = requestContext['width'] * pointsPerPixel
for index, series in enumerate(resampled):
# if we have fewer samples than expected, adjust the movingAverage sample
# size so it covers the same number of pixels
if (len(series) < expectedSamples * 0.95):
movingAverageSize = int((float(len(series)) / (expectedSamples)) * sampleSize)
else:
movingAverageSize = sampleSize
# If we are being asked to do a movingAverage over one point or less,
# don't bother
if (movingAverageSize <= 1):
continue
resampled[index] = movingAverage(requestContext, [series], movingAverageSize)[0]
return resampled
def derivative(requestContext, seriesList):
"""
This is the opposite of the integral function. This is useful for taking a
running total metric and showing how many requests per minute were handled.
Example:
.. code-block:: none
&target=derivative(company.server.application01.ifconfig.TXPackets)
Each time you run ifconfig, the RX and TXPackets are higher (assuming there
is network traffic.) By applying the derivative function, you can get an
idea of the packets per minute sent or received, even though you're only
recording the total.
"""
results = []
for series in seriesList:
newValues = []
prev = None
for val in series:
if None in (prev,val):
newValues.append(None)
prev = val
continue
newValues.append(val - prev)
prev = val
newName = "derivative(%s)" % series.name
newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def integral(requestContext, seriesList):
"""
This will show the sum over time, sort of like a continuous addition function.
Useful for finding totals or trends in metrics that are collected per minute.
Example:
.. code-block:: none
&target=integral(company.sales.perMinute)
This would start at zero on the left side of the graph, adding the sales each
minute, and show the total sales for the time period selected at the right
side, (time now, or the time specified by '&until=').
"""
results = []
for series in seriesList:
newValues = []
current = 0.0
for val in series:
if val is None:
newValues.append(None)
else:
current += val
newValues.append(current)
newName = "integral(%s)" % series.name
newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def nonNegativeDerivative(requestContext, seriesList, maxValue=None):
"""
Same as the derivative function above, but ignores datapoints that trend
down. Useful for counters that increase for a long time, then wrap or
reset. (Such as if a network interface is destroyed and recreated by unloading
and re-loading a kernel module, common with USB / WiFi cards.
Example:
.. code-block:: none
&target=derivative(company.server.application01.ifconfig.TXPackets)
"""
results = []
for series in seriesList:
newValues = []
prev = None
for val in series:
if None in (prev, val):
newValues.append(None)
prev = val
continue
diff = val - prev
if diff >= 0:
newValues.append(diff)
elif maxValue is not None and maxValue >= val:
newValues.append( (maxValue - prev) + val + 1 )
else:
newValues.append(None)
prev = val
newName = "nonNegativeDerivative(%s)" % series.name
newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues)
newSeries.pathExpression = newName
results.append(newSeries)
return results
def stacked(requestContext,seriesLists,stackName='__DEFAULT__'):
"""
Takes one metric or a wildcard seriesList and change them so they are
stacked. This is a way of stacking just a couple of metrics without having
to use the stacked area mode (that stacks everything). By means of this a mixed
stacked and non stacked graph can be made
It can also take an optional argument with a name of the stack, in case there is
more than one, e.g. for input and output metrics.
Example:
.. code-block:: none
&target=stacked(company.server.application01.ifconfig.TXPackets, 'tx')
"""
if 'totalStack' in requestContext:
totalStack = requestContext['totalStack'].get(stackName, [])
else:
requestContext['totalStack'] = {}
totalStack = [];
results = []
for series in seriesLists:
newValues = []
for i in range(len(series)):
if len(totalStack) <= i: totalStack.append(0)
if series[i] is not None:
totalStack[i] += series[i]
newValues.append(totalStack[i])
else:
newValues.append(None)
# Work-around for the case when legend is set
if stackName=='__DEFAULT__':
newName = "stacked(%s)" % series.name
else:
newName = series.name
newSeries = TimeSeries(newName, series.start, series.end, series.step, newValues)
newSeries.options['stacked'] = True
newSeries.pathExpression = newName
results.append(newSeries)
requestContext['totalStack'][stackName] = totalStack
return results
def areaBetween(requestContext, seriesList):
"""
Draws the area in between the two series in seriesList
"""
assert len(seriesList) == 2, "areaBetween series argument must reference *exactly* 2 series"
lower = seriesList[0]
upper = seriesList[1]
lower.options['stacked'] = True
lower.options['invisible'] = True
upper.options['stacked'] = True
lower.name = upper.name = "areaBetween(%s)" % upper.pathExpression
return seriesList
def aliasSub(requestContext, seriesList, search, replace):
"""
Runs series names through a regex search/replace.
.. code-block:: none
&target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\\1")
"""
for series in seriesList:
series.name = re.sub(search, replace, series.name)
return seriesList
def alias(requestContext, seriesList, newName):
"""
Takes one metric or a wildcard seriesList and a string in quotes.
Prints the string instead of the metric name in the legend.
.. code-block:: none
&target=alias(Sales.widgets.largeBlue,"Large Blue Widgets")
"""
for series in seriesList:
series.name = newName
return seriesList
def cactiStyle(requestContext, seriesList, system=None):
"""
Takes a series list and modifies the aliases to provide column aligned
output with Current, Max, and Min values in the style of cacti. Optonally
takes a "system" value to apply unit formatting in the same style as the
Y-axis.
NOTE: column alignment only works with monospace fonts such as terminus.
.. code-block:: none
&target=cactiStyle(ganglia.*.net.bytes_out,"si")
"""
if 0 == len(seriesList):
return seriesList
if system:
fmt = lambda x:"%2.f%s" % format_units(x,system=system)
else:
fmt = lambda x:"%2.f"%x
nameLen = max([len(getattr(series,"name")) for series in seriesList])
lastLen = max([len(fmt(int(safeLast(series) or 3))) for series in seriesList]) + 3
maxLen = max([len(fmt(int(safeMax(series) or 3))) for series in seriesList]) + 3
minLen = max([len(fmt(int(safeMin(series) or 3))) for series in seriesList]) + 3
for series in seriesList:
name = series.name
last = fmt(float(safeLast(series)))
maximum = fmt(float(safeMax(series)))
minimum = fmt(float(safeMin(series)))
if last is None:
last = NAN
if maximum is None:
maximum = NAN
if minimum is None:
minimum = NAN
series.name = "%*s Current:%*s Max:%*s Min:%*s " % \
(-nameLen, series.name,
-lastLen, last,
-maxLen, maximum,
-minLen, minimum)
return seriesList
def aliasByNode(requestContext, seriesList, *nodes):
"""
Takes a seriesList and applies an alias derived from one or more "node"
portion/s of the target name. Node indices are 0 indexed.
.. code-block:: none