-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
functions.py
6162 lines (4593 loc) · 194 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.
# make / work consistently between python 2.x and 3.x
# https://www.python.org/dev/peps/pep-0238/
from __future__ import division
import math
import random
import re
import time
from datetime import datetime, timedelta
from functools import reduce
from six.moves import range, zip
import six
try:
from itertools import izip, izip_longest
except ImportError:
# Python 3
from itertools import zip_longest as izip_longest
izip = zip
from os import environ
from django.conf import settings
from graphite.errors import NormalizeEmptyResultError, InputParameterError
from graphite.events import models
from graphite.functions import SeriesFunction, ParamTypes, Param, ParamTypeAggFunc, getAggFunc, safe
from graphite.logger import log
from graphite.render.attime import getUnitString, parseTimeOffset, parseATTime, SECONDS_STRING, MINUTES_STRING, HOURS_STRING, DAYS_STRING, WEEKS_STRING, MONTHS_STRING, YEARS_STRING
from graphite.render.evaluator import evaluateTarget
from graphite.render.grammar import grammar
from graphite.storage import STORE
from graphite.util import epoch, epoch_to_dt, timestamp, deltaseconds
# XXX format_units() should go somewhere else
if environ.get('READTHEDOCS'):
format_units = lambda *args, **kwargs: (0,'')
else:
from graphite.render.glyph import format_units
from graphite.render.datalib import TimeSeries
NAN = float('NaN')
INF = float('inf')
DAY = 86400
HOUR = 3600
MINUTE = 60
#Utility functions
# In Py2, None < (any integer) . Use -inf for same sorting on Python 3
def keyFunc(func):
def safeFunc(values):
val = func(values)
return val if val is not None else -INF
return safeFunc
# Greatest common divisor
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
# Least common multiple
def lcm(a, b):
if a == b: return a
if a < b: (a, b) = (b, a) #ensure a > b
return a // gcd(a,b) * b
# check list of values against xFilesFactor
def xffValues(values, xFilesFactor):
if not values:
return False
return xff(len([v for v in values if v is not None]), len(values), xFilesFactor)
def xff(nonNull, total, xFilesFactor=None):
if not nonNull or not total:
return False
return nonNull / total >= (xFilesFactor if xFilesFactor is not None else settings.DEFAULT_XFILES_FACTOR)
def getNodeOrTag(series, n, pathExpression=None):
try:
# if n is an integer use it as a node, otherwise catch ValueError and treat it as a tag
if n == int(n):
# first split off any tags, then list of nodes is name split on .
return (pathExpression or series.name).split(';', 2)[0].split('.')[n]
except (ValueError, IndexError):
# if node isn't an integer or isn't found then try it as a tag name
pass
# return tag value, default to '' if not found
return series.tags.get(str(n), '')
def aggKey(series, nodes, pathExpression=None):
# if series.name looks like it includes a function, use the first path expression
if pathExpression is None and series.name[-1] == ')':
pathExpression = _getFirstPathExpression(series.name)
return '.'.join([getNodeOrTag(series, n, pathExpression) for n in nodes])
def normalize(seriesLists):
if seriesLists:
seriesList = reduce(lambda L1,L2: L1+L2,seriesLists)
if seriesList:
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)
raise NormalizeEmptyResultError()
def matchSeries(seriesList1, seriesList2):
assert len(seriesList2) == len(seriesList1), "The number of series in each argument must be the same"
return izip(sorted(seriesList1, key=lambda a: a.name), sorted(seriesList2, key=lambda a: a.name))
def trimRecent(seriesList):
# trim right side of the graph to avoid dip when only part of most recent metrics has entered the system
for s in seriesList:
if len(s) > 1:
if (s[-1] is None) and (s[-2] is not None):
for sl in seriesList:
sl[-1] = None
break
for s in seriesList:
if len(s) > 2:
if (s[-2] is None) and (s[-3] is not None):
for sl in seriesList:
sl[-2] = None
break
return (seriesList)
def _compressPeriodicGaps(series):
# removing periodic gaps, using summarize(seriesList, '<desired step>', 'last')
# but trying to auto detect step by first three existing values
consolidate = series.consolidationFunc
tags = series.tags
xFilesFactor = series.xFilesFactor
pathExpression = series.pathExpression
# try to detect interval
firstSeen = -1
secondSeen = -1
interval = None
for i, value in enumerate(series):
if value:
if firstSeen >= 0:
secondSeen = i
break
else:
firstSeen = i
stepGuess = secondSeen - firstSeen
thirdSeen = secondSeen + stepGuess
if stepGuess > 1 and thirdSeen <= len(series) - 2: # protecting list boundaries
if series[thirdSeen]: # if we predict value
if series[thirdSeen - 1] is None and series[thirdSeen + 1] is None: # ..and it surrounded by Nones
interval = stepGuess * series.step # we probably guessed interval.
if interval is None:
# we couldn't detect interval, just return untouched series
return series
newStart = series.start + firstSeen * series.step # skipping initial Nones
(newValues, _) = _summarizeValues(series, 'last', interval, newStart, series.end)
newEnd = newStart + interval * (len(newValues) - 1) # calculating new end from summarized values
return TimeSeries(series.name, newStart, newEnd, interval, newValues,
consolidate=consolidate, tags=tags, xFilesFactor=xFilesFactor, pathExpression=pathExpression)
def formatPathExpressions(seriesList):
# remove duplicates
pathExpressions = []
[pathExpressions.append(s.pathExpression) for s in seriesList if not pathExpressions.count(s.pathExpression)]
return ','.join(pathExpressions)
# Series Functions
def aggregate(requestContext, seriesList, func, xFilesFactor=None):
"""
Aggregate series using the specified function.
Example:
.. code-block:: none
&target=aggregate(host.cpu-[0-7].cpu-{user,system}.value, "sum")
This would be the equivalent of
.. code-block:: none
&target=sumSeries(host.cpu-[0-7].cpu-{user,system}.value)
This function can be used with aggregation functions ``average`` (or ``avg``), ``avg_zero``,
``median``, ``sum`` (or ``total``), ``min``, ``max``, ``diff``, ``stddev``, ``count``,
``range`` (or ``rangeOf``) , ``multiply`` & ``last`` (or ``current``).
"""
# strip Series from func if func was passed like sumSeries
rawFunc = func
if func[-6:] == 'Series':
func = func[:-6]
consolidationFunc = getAggFunc(func, rawFunc)
# if seriesList is empty then just short-circuit
if not seriesList:
return []
# if seriesList is a single series then wrap it for normalize
if isinstance(seriesList[0], TimeSeries):
seriesList = [seriesList]
try:
(seriesList, start, end, step) = normalize(seriesList)
except NormalizeEmptyResultError:
return []
if (settings.RENDER_TRIM_RECENT_IN_AGGREGATE):
seriesList = trimRecent(seriesList)
xFilesFactor = xFilesFactor if xFilesFactor is not None else requestContext.get('xFilesFactor')
name = "%sSeries(%s)" % (func, formatPathExpressions(seriesList))
values = ( consolidationFunc(row) if xffValues(row, xFilesFactor) else None for row in izip_longest(*seriesList) )
tags = seriesList[0].tags
for series in seriesList:
tags = {tag: tags[tag] for tag in tags if tag in series.tags and tags[tag] == series.tags[tag]}
if 'name' not in tags:
tags['name'] = name
tags['aggregatedBy'] = func
series = TimeSeries(name, start, end, step, values, xFilesFactor=xFilesFactor, tags=tags)
return [series]
aggregate.group = 'Combine'
aggregate.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('func', ParamTypes.aggFunc, required=True),
Param('xFilesFactor', ParamTypes.float),
]
def aggregateSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos, func, xFilesFactor=None):
"""
Iterates over a two lists and aggregates using specified function
list1[0] to list2[0], list1[1] to list2[1] and so on.
The lists will need to be the same length
Position of seriesList matters. For example using "sum" function
``aggregateSeriesLists(list1[0..n], list2[0..n], "sum")``
it would find sum for each member
of the list ``list1[0] + list2[0], list1[1] + list2[1], list1[n] + list2[n]``.
Example:
.. code-block:: none
&target=aggregateSeriesLists(mining.{carbon,graphite,diamond}.extracted,mining.{carbon,graphite,diamond}.shipped, 'sum')
An example above would be the same as running :py:func:`aggregate <aggregate>` for each member of the list:
.. code-block:: none
?target=aggregate(mining.carbon.extracted,mining.carbon.shipped, 'sum')
&target=aggregate(mining.graphite.extracted,mining.graphite.shipped, 'sum')
&target=aggregate(mining.diamond.extracted,mining.diamond.shipped, 'sum')
This function can be used with aggregation functions ``average`` (or ``avg``), ``avg_zero``,
``median``, ``sum`` (or ``total``), ``min``, ``max``, ``diff``, ``stddev``, ``count``,
``range`` (or ``rangeOf``) , ``multiply`` & ``last`` (or ``current``).
"""
if len(seriesListFirstPos) != len(seriesListSecondPos):
raise InputParameterError(
"seriesListFirstPos and seriesListSecondPos argument must have equal length")
results = []
for i in range(0, len(seriesListFirstPos)):
firstSeries = seriesListFirstPos[i]
secondSeries = seriesListSecondPos[i]
aggregated = aggregate(requestContext, (firstSeries, secondSeries), func, xFilesFactor=xFilesFactor)
if not aggregated: # empty list, no data found
continue
result = aggregated[0] # aggregate() can only return len 1 list
result.name = result.name[:result.name.find('Series(')] + 'Series(%s,%s)' % (firstSeries.name, secondSeries.name)
results.append(result)
return results
aggregateSeriesLists.group = 'Combine'
aggregateSeriesLists.params = [
Param('seriesListFirstPos', ParamTypes.seriesList, required=True),
Param('seriesListSecondPos', ParamTypes.seriesList, required=True),
Param('func', ParamTypes.aggFunc, required=True),
Param('xFilesFactor', ParamTypes.float),
]
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.
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``sum``.
"""
return aggregate(requestContext, seriesLists, 'sum')
sumSeries.group = 'Combine'
sumSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
sumSeries.aggregator = True
def sumSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos):
"""
Iterates over a two lists and subtracts series lists 2 through n from series 1
list1[0] to list2[0], list1[1] to list2[1] and so on.
The lists will need to be the same length
Example:
.. code-block:: none
&target=sumSeriesLists(mining.{carbon,graphite,diamond}.extracted,mining.{carbon,graphite,diamond}.shipped)
An example above would be the same as running :py:func:`sumSeries <sumSeries>` for each member of the list:
.. code-block:: none
?target=sumSeries(mining.carbon.extracted,mining.carbon.shipped)
&target=sumSeries(mining.graphite.extracted,mining.graphite.shipped)
&target=sumSeries(mining.diamond.extracted,mining.diamond.shipped)
This is an alias for :py:func:`aggregateSeriesLists <aggregateSeriesLists>` with aggregation ``sum``.
"""
return aggregateSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos, 'sum')
sumSeriesLists.group = 'Combine'
sumSeriesLists.params = [
Param('seriesListFirstPos', ParamTypes.seriesList, required=True),
Param('seriesListSecondPos', ParamTypes.seriesList, required=True),
]
sumSeriesLists.aggregator = True
def sumSeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Categorizes the provided series in groups by name, by ignoring
("wildcarding") the given position(s) and calls sumSeries on each group.
Important: the introduction of wildcards only happens *after* retrieving
the input.
Example:
.. code-block:: none
&target=sumSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1)
This would be the equivalent of
.. code-block:: none
&target=sumSeries(host.cpu-[0-7].cpu-user.value)&target=sumSeries(host.cpu-[0-7].cpu-system.value)
This is an alias for :py:func:`aggregateWithWildcards <aggregateWithWildcards>` with aggregation ``sum``.
"""
return aggregateWithWildcards(requestContext, seriesList, 'sum', *position)
sumSeriesWithWildcards.group = 'Combine'
sumSeriesWithWildcards.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('position', ParamTypes.node, multiple=True),
]
sumSeriesWithWildcards.aggregator = True
def averageSeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Categorizes the provided series in groups by name, by ignoring
("wildcarding") the given position(s) and calls averageSeries on each group.
Important: the introduction of wildcards only happens *after* retrieving
the input.
Example:
.. code-block:: none
&target=averageSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1)
This would be the equivalent of
.. code-block:: none
&target=averageSeries(host.cpu-[0-7].cpu-user.value)&target=averageSeries(host.cpu-[0-7].cpu-system.value)
This is an alias for :py:func:`aggregateWithWildcards <aggregateWithWildcards>` with aggregation ``average``.
"""
return aggregateWithWildcards(requestContext, seriesList, 'average', *position)
averageSeriesWithWildcards.group = 'Combine'
averageSeriesWithWildcards.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('position', ParamTypes.node, multiple=True),
]
averageSeriesWithWildcards.aggregator = True
def multiplySeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Categorizes the provided series in groups by name, by ignoring
("wildcarding") the given position(s) and calls multiplySeries on each group.
Important: the introduction of wildcards only happens *after* retrieving
the input.
Example:
.. code-block:: none
&target=multiplySeriesWithWildcards(web.host-[0-7].{avg-response,total-request}.value, 2)
This would be the equivalent of
.. code-block:: none
&target=multiplySeries(web.host-0.{avg-response,total-request}.value)&target=multiplySeries(web.host-1.{avg-response,total-request}.value)...
This is an alias for :py:func:`aggregateWithWildcards <aggregateWithWildcards>` with aggregation ``multiply``.
"""
return aggregateWithWildcards(requestContext, seriesList, 'multiply', *position)
multiplySeriesWithWildcards.group = 'Combine'
multiplySeriesWithWildcards.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('position', ParamTypes.node, multiple=True),
]
multiplySeriesWithWildcards.aggregator = True
def aggregateWithWildcards(requestContext, seriesList, func, *positions):
"""
Call aggregator after inserting wildcards at the given position(s).
Example:
.. code-block:: none
&target=aggregateWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, "sum", 1)
This would be the equivalent of
.. code-block:: none
&target=sumSeries(host.cpu-[0-7].cpu-user.value)&target=sumSeries(host.cpu-[0-7].cpu-system.value)
# or
&target=aggregate(host.cpu-[0-7].cpu-user.value,"sum")&target=aggregate(host.cpu-[0-7].cpu-system.value,"sum")
This function can be used with all aggregation functions supported by
:py:func:`aggregate <aggregate>`: ``average``, ``median``, ``sum``, ``min``, ``max``, ``diff``,
``stddev``, ``range`` & ``multiply``.
This complements :py:func:`groupByNodes <groupByNodes>` which takes a list of nodes that must match in each group.
"""
metaSeries = {}
keys = []
for series in seriesList:
key = '.'.join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.')))))
if key not in metaSeries:
metaSeries[key] = [series]
keys.append(key)
else:
metaSeries[key].append(series)
for key in metaSeries.keys():
metaSeries[key] = aggregate(requestContext, metaSeries[key], func)[0]
metaSeries[key].name = key
return [ metaSeries[key] for key in keys ]
aggregateWithWildcards.group = 'Combine'
aggregateWithWildcards.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('func', ParamTypes.aggFunc, required=True),
Param('position', ParamTypes.node, multiple=True),
]
def diffSeries(requestContext, *seriesLists):
"""
Subtracts series 2 through n from series 1.
Example:
.. code-block:: none
&target=diffSeries(service.connections.total,service.connections.failed)
To diff a series and a constant, one should use offset instead of (or in
addition to) diffSeries
Example:
.. code-block:: none
&target=offset(service.connections.total,-5)
&target=offset(diffSeries(service.connections.total,service.connections.failed),-4)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``diff``.
"""
return aggregate(requestContext, seriesLists, 'diff')
diffSeries.group = 'Combine'
diffSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
diffSeries.aggregator = True
def diffSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos):
"""
Iterates over a two lists and subtracts series lists 2 through n from series 1
list1[0] to list2[0], list1[1] to list2[1] and so on.
The lists will need to be the same length
Example:
.. code-block:: none
&target=diffSeriesLists(mining.{carbon,graphite,diamond}.extracted,mining.{carbon,graphite,diamond}.shipped)
An example above would be the same as running :py:func:`diffSeries <diffSeries>` for each member of the list:
.. code-block:: none
?target=diffSeries(mining.carbon.extracted,mining.carbon.shipped)
&target=diffSeries(mining.graphite.extracted,mining.graphite.shipped)
&target=diffSeries(mining.diamond.extracted,mining.diamond.shipped)
This is an alias for :py:func:`aggregateSeriesLists <aggregateSeriesLists>` with aggregation ``diff``.
"""
return aggregateSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos, 'diff')
diffSeriesLists.group = 'Combine'
diffSeriesLists.params = [
Param('seriesListFirstPos', ParamTypes.seriesList, required=True),
Param('seriesListSecondPos', ParamTypes.seriesList, required=True),
]
diffSeriesLists.aggregator = True
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)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``average``.
"""
return aggregate(requestContext, seriesLists, 'average')
averageSeries.group = 'Combine'
averageSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
averageSeries.aggregator = True
def stddevSeries(requestContext, *seriesLists):
"""
Takes one metric or a wildcard seriesList.
Draws the standard deviation of all metrics passed at each time.
Example:
.. code-block:: none
&target=stddevSeries(company.server.*.threads.busy)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``stddev``.
"""
return aggregate(requestContext, seriesLists, 'stddev')
stddevSeries.group = 'Combine'
stddevSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
stddevSeries.aggregator = True
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)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``min``.
"""
return aggregate(requestContext, seriesLists, 'min')
minSeries.group = 'Combine'
minSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
minSeries.aggregator = True
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)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``max``.
"""
return aggregate(requestContext, seriesLists, 'max')
maxSeries.group = 'Combine'
maxSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
maxSeries.aggregator = True
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)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``rangeOf``.
"""
return aggregate(requestContext, seriesLists, 'rangeOf')
rangeOfSeries.group = 'Combine'
rangeOfSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
rangeOfSeries.aggregator = True
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 InputParameterError('The requested percent is required to be greater than 0')
# if seriesList is empty then just short-circuit
if not seriesList:
return []
name = 'percentileOfSeries(%s,%g)' % (seriesList[0].pathExpression, n)
(start, end, step) = normalize([seriesList])[1:]
values = [ _getPercentile(row, n, interpolate) for row in izip_longest(*seriesList) ]
resultSeries = TimeSeries(name, start, end, step, values, xFilesFactor=requestContext.get('xFilesFactor'))
return [resultSeries]
percentileOfSeries.group = 'Combine'
percentileOfSeries.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
Param('interpolate', ParamTypes.boolean, default=False),
]
def keepLastValue(requestContext, seriesList, limit = INF):
"""
Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over.
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)
&target=keepLastValue(Server01.connections.handled, 10)
"""
for series in seriesList:
series.name = "keepLastValue(%s)" % (series.name)
series.pathExpression = series.name
consecutiveNones = 0
lastVal = None
for i,value in enumerate(series):
if value is None:
consecutiveNones += 1
else:
if 0 < consecutiveNones <= limit and lastVal is not None:
# If a non-None value is seen before the limit of Nones is hit,
# backfill all the missing datapoints with the last known value.
for index in range(i - consecutiveNones, i):
series[index] = lastVal
consecutiveNones = 0
lastVal = value
# If the series ends with some None values, try to backfill a bit to cover it.
if 0 < consecutiveNones <= limit and lastVal is not None:
for index in range(len(series) - consecutiveNones, len(series)):
series[index] = lastVal
return seriesList
keepLastValue.group = 'Transform'
keepLastValue.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('limit', ParamTypes.intOrInf, default=INF),
]
def interpolate(requestContext, seriesList, limit = INF):
"""
Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over.
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=interpolate(Server01.connections.handled)
&target=interpolate(Server01.connections.handled, 10)
"""
for series in seriesList:
series.name = "interpolate(%s)" % (series.name)
series.pathExpression = series.name
consecutiveNones = 0
for i,value in enumerate(series):
series[i] = value
# No 'keeping' can be done on the first value because we have no idea
# what came before it.
if i == 0:
continue
if value is None:
consecutiveNones += 1
elif consecutiveNones == 0: # have a value but no need to interpolate
continue
elif series[i - consecutiveNones - 1] is None: # have a value but can't interpolate: reset count
consecutiveNones = 0
continue
else: # have a value and can interpolate
# If a non-None value is seen before the limit of Nones is hit,
# backfill all the missing datapoints with the last known value.
if 0 < consecutiveNones <= limit:
for index in range(i - consecutiveNones, i):
series[index] = series[i - consecutiveNones - 1] + (index - (i - consecutiveNones -1)) * (value - series[i - consecutiveNones - 1]) / (consecutiveNones + 1)
consecutiveNones = 0
# If the series ends with some None values, try to backfill a bit to cover it.
# if 0 < consecutiveNones < limit:
# for index in xrange(len(series) - consecutiveNones, len(series)):
# series[index] = series[len(series) - consecutiveNones - 1]
return seriesList
interpolate.group = 'Transform'
interpolate.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('limit', ParamTypes.intOrInf, default=INF),
]
def changed(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Output 1 when the value changed, 0 when null or the same
Example:
.. code-block:: none
&target=changed(Server01.connections.handled)
"""
for series in seriesList:
series.name = "changed(%s)" % (series.name)
series.pathExpression = series.name
previous = None
for i,value in enumerate(series):
if previous is None:
previous = value
series[i] = 0
elif value is not None and previous != value:
series[i] = 1
previous = value
else:
series[i] = 0
return seriesList
changed.group = 'Special'
changed.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def asPercent(requestContext, seriesList, total=None, *nodes):
"""
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.
A list of nodes can optionally be provided, if so they will be used to match series with their
corresponding totals following the same logic as :py:func:`groupByNodes <groupByNodes>`.
When passing `nodes` the `total` parameter may be a series list or `None`. If it is `None` then
for each series in `seriesList` the percentage of the sum of series in that group will be returned.
When not passing `nodes`, the `total` parameter may be a single series, reference the same number
of series as `seriesList` or be a numeric value.
Example:
.. code-block:: none
# Server01 connections failed and succeeded as a percentage of Server01 connections attempted
&target=asPercent(Server01.connections.{failed,succeeded}, Server01.connections.attempted)
# For each server, its connections failed as a percentage of its connections attempted
&target=asPercent(Server*.connections.failed, Server*.connections.attempted)
# For each server, its connections failed and succeeded as a percentage of its connections attempted
&target=asPercent(Server*.connections.{failed,succeeded}, Server*.connections.attempted, 0)
# apache01.threads.busy as a percentage of 1500
&target=asPercent(apache01.threads.busy,1500)
# Server01 cpu stats as a percentage of its total
&target=asPercent(Server01.cpu.*.jiffies)
# cpu stats for each server as a percentage of its total
&target=asPercent(Server*.cpu.*.jiffies, None, 0)
When using `nodes`, any series or totals that can't be matched will create output series with
names like ``asPercent(someSeries,MISSING)`` or ``asPercent(MISSING,someTotalSeries)`` and all
values set to None. If desired these series can be filtered out by piping the result through
``|exclude("MISSING")`` as shown below:
.. code-block:: none
&target=asPercent(Server{1,2}.memory.used,Server{1,3}.memory.total,0)
# will produce 3 output series:
# asPercent(Server1.memory.used,Server1.memory.total) [values will be as expected]
# asPercent(Server2.memory.used,MISSING) [all values will be None]
# asPercent(MISSING,Server3.memory.total) [all values will be None]
&target=asPercent(Server{1,2}.memory.used,Server{1,3}.memory.total,0)|exclude("MISSING")
# will produce 1 output series:
# asPercent(Server1.memory.used,Server1.memory.total) [values will be as expected]
Each node may be an integer referencing a node in the series name or a string identifying a tag.
.. note::
When `total` is a seriesList, specifying `nodes` to match series with the corresponding total
series will increase reliability.
"""
normalize([seriesList])
xFilesFactor=requestContext.get('xFilesFactor')
# if nodes are specified, use them to match series & total
if nodes:
keys = []
# group series together by key
metaSeries = {}
for series in seriesList:
key = aggKey(series, nodes)
if key not in metaSeries:
metaSeries[key] = [series]
keys.append(key)
else:
metaSeries[key].append(series)
# make list of totals
totalSeries = {}
# no total seriesList was specified, sum the values for each group of series
if total is None:
for key in keys:
if len(metaSeries[key]) == 1:
totalSeries[key] = metaSeries[key][0]
else:
name = 'sumSeries(%s)' % formatPathExpressions(metaSeries[key])
(seriesList,start,end,step) = normalize([metaSeries[key]])
totalValues = [ safe.safeSum(row) for row in izip_longest(*metaSeries[key]) ]
totalSeries[key] = TimeSeries(name,start,end,step,totalValues,xFilesFactor=xFilesFactor)
# total seriesList was specified, sum the values for each group of totals
elif isinstance(total, list):
for series in total:
key = aggKey(series, nodes)
if key not in totalSeries:
totalSeries[key] = [series]
if key not in keys:
keys.append(key)
else:
totalSeries[key].append(series)
for key in totalSeries.keys():
if len(totalSeries[key]) == 1:
totalSeries[key] = totalSeries[key][0]
else:
name = 'sumSeries(%s)' % formatPathExpressions(totalSeries[key])
(seriesList,start,end,step) = normalize([totalSeries[key]])
totalValues = [ safe.safeSum(row) for row in izip_longest(*totalSeries[key]) ]
totalSeries[key] = TimeSeries(name,start,end,step,totalValues,xFilesFactor=xFilesFactor)
# trying to use nodes with a total value, which isn't supported because it has no effect
else:
raise InputParameterError('total must be None or a seriesList')
resultList = []
for key in keys:
# no series, must have total only
if key not in metaSeries:
series2 = totalSeries[key]
name = "asPercent(%s,%s)" % ('MISSING', series2.name)
resultValues = [ None for v1 in series2 ]
resultSeries = TimeSeries(name,start,end,step,resultValues,xFilesFactor=xFilesFactor)