1 /****************************************************************************
2 * RRDtool 1.4.3 Copyright by Tobi Oetiker, 1997-2010
3 ****************************************************************************
4 * rrd_rpncalc.c RPN calculator functions
5 ****************************************************************************/
12 #include "rrd_rpncalc.h"
13 // #include "rrd_graph.h"
20 unsigned short *offset);
22 time_t); /* used to implement LTIME */
32 /* count the number of rpn nodes */
33 while (rpnp[*count].op != OP_END)
35 if (++(*count) > DS_CDEF_MAX_RPN_NODES) {
36 rrd_set_error("Maximum %d RPN nodes permitted",
37 DS_CDEF_MAX_RPN_NODES);
42 *rpnc = (rpn_cdefds_t *) calloc(*count, sizeof(rpn_cdefds_t));
43 for (i = 0; rpnp[i].op != OP_END; i++) {
44 (*rpnc)[i].op = (char) rpnp[i].op;
45 if (rpnp[i].op == OP_NUMBER) {
46 /* rpnp.val is a double, rpnc.val is a short */
47 double temp = floor(rpnp[i].val);
49 if (temp < SHRT_MIN || temp > SHRT_MAX) {
51 ("constants must be integers in the interval (%d, %d)",
56 (*rpnc)[i].val = (short) temp;
57 } else if (rpnp[i].op == OP_VARIABLE || rpnp[i].op == OP_PREV_OTHER) {
58 (*rpnc)[i].val = (short) rpnp[i].ptr;
61 /* terminate the sequence */
62 (*rpnc)[(*count) - 1].op = OP_END;
72 /* DS_CDEF_MAX_RPN_NODES is small, so at the expense of some wasted
73 * memory we avoid any reallocs */
74 rpnp = (rpnp_t *) calloc(DS_CDEF_MAX_RPN_NODES, sizeof(rpnp_t));
76 rrd_set_error("failed allocating rpnp array");
79 for (i = 0; rpnc[i].op != OP_END; ++i) {
80 rpnp[i].op = (enum op_en)rpnc[i].op;
81 if (rpnp[i].op == OP_NUMBER) {
82 rpnp[i].val = (double) rpnc[i].val;
83 } else if (rpnp[i].op == OP_VARIABLE || rpnp[i].op == OP_PREV_OTHER) {
84 rpnp[i].ptr = (long) rpnc[i].val;
87 /* terminate the sequence */
92 /* rpn_compact2str: convert a compact sequence of RPN operator nodes back
93 * into a CDEF string. This function is used by rrd_dump.
95 * rpnc: an array of compact RPN operator nodes
96 * ds_def: a pointer to the data source definition section of an RRD header
97 * for lookup of data source names by index
98 * str: out string, memory is allocated by the function, must be freed by the
100 void rpn_compact2str(
105 unsigned short i, offset = 0;
106 char buffer[7]; /* short as a string */
108 for (i = 0; rpnc[i].op != OP_END; i++) {
110 (*str)[offset++] = ',';
112 #define add_op(VV,VVV) \
113 if (addop2str((enum op_en)(rpnc[i].op), VV, VVV, str, &offset) == 1) continue;
115 if (rpnc[i].op == OP_NUMBER) {
116 /* convert a short into a string */
117 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
118 _itoa(rpnc[i].val, buffer, 10);
120 sprintf(buffer, "%d", rpnc[i].val);
122 add_op(OP_NUMBER, buffer)
125 if (rpnc[i].op == OP_VARIABLE) {
126 char *ds_name = ds_def[rpnc[i].val].ds_nam;
128 add_op(OP_VARIABLE, ds_name)
131 if (rpnc[i].op == OP_PREV_OTHER) {
132 char *ds_name = ds_def[rpnc[i].val].ds_nam;
134 add_op(OP_VARIABLE, ds_name)
138 #define add_op(VV,VVV) \
139 if (addop2str((enum op_en)rpnc[i].op, VV, #VVV, str, &offset) == 1) continue;
149 add_op(OP_FLOOR, FLOOR)
150 add_op(OP_CEIL, CEIL)
163 add_op(OP_LIMIT, LIMIT)
164 add_op(OP_UNKN, UNKN)
166 add_op(OP_NEGINF, NEGINF)
168 add_op(OP_PREV, PREV)
170 add_op(OP_ISINF, ISINF)
172 add_op(OP_LTIME, LTIME)
173 add_op(OP_TIME, TIME)
174 add_op(OP_ATAN2, ATAN2)
175 add_op(OP_ATAN, ATAN)
176 add_op(OP_SQRT, SQRT)
177 add_op(OP_SORT, SORT)
179 add_op(OP_TREND, TREND)
180 add_op(OP_TRENDNAN, TRENDNAN)
181 add_op(OP_PREDICT, PREDICT)
182 add_op(OP_PREDICTSIGMA, PREDICTSIGMA)
183 add_op(OP_RAD2DEG, RAD2DEG)
184 add_op(OP_DEG2RAD, DEG2RAD)
187 add_op(OP_ADDNAN, ADDNAN)
190 (*str)[offset] = '\0';
199 unsigned short *offset)
204 op_len = strlen(op_str);
205 *result_str = (char *) rrd_realloc(*result_str,
207 *offset) * sizeof(char));
208 if (*result_str == NULL) {
209 rrd_set_error("failed to alloc memory in addop2str");
212 strncpy(&((*result_str)[*offset]), op_str, op_len);
225 rpn_cdefds_t *rpnc = NULL;
228 rpnp = rpn_parse((void *) rrd, def, &lookup_DS);
230 rrd_set_error("failed to parse computed data source");
233 /* Check for OP nodes not permitted in COMPUTE DS.
234 * Moved this check from within rpn_compact() because it really is
235 * COMPUTE DS specific. This is less efficient, but creation doesn't
236 * occur too often. */
237 for (i = 0; rpnp[i].op != OP_END; i++) {
238 if (rpnp[i].op == OP_TIME || rpnp[i].op == OP_LTIME ||
239 rpnp[i].op == OP_PREV || rpnp[i].op == OP_COUNT) {
241 ("operators time, ltime, prev and count not supported with DS COMPUTE");
246 if (rpn_compact(rpnp, &rpnc, &count) == -1) {
250 /* copy the compact rpn representation over the ds_def par array */
251 memcpy((void *) &(rrd->ds_def[ds_idx].par[DS_cdef]),
252 (void *) rpnc, count * sizeof(rpn_cdefds_t));
257 /* lookup a data source name in the rrd struct and return the index,
258 * should use ds_match() here except:
259 * (1) need a void * pointer to the rrd
260 * (2) error handling is left to the caller
269 rrd = (rrd_t *) rrd_vptr;
271 for (i = 0; i < rrd->stat_head->ds_cnt; ++i) {
272 if (strcmp(ds_name, rrd->ds_def[i].ds_nam) == 0)
275 /* the caller handles a bad data source name in the rpn string */
279 /* rpn_parse : parse a string and generate a rpnp array; modified
280 * str2rpn() originally included in rrd_graph.c
282 * key_hash: a transparent argument passed to lookup(); conceptually this
283 * is a hash object for lookup of a numeric key given a variable name
284 * expr: the string RPN expression, including variable names
285 * lookup(): a function that retrieves a numeric key given a variable name
289 const char *const expr_const,
290 long (*lookup) (void *,
297 char vname[MAX_VNAME_LEN + 10];
300 old_locale = setlocale(LC_NUMERIC, "C");
303 expr = (char *) expr_const;
306 if ((rpnp = (rpnp_t *) rrd_realloc(rpnp, (++steps + 2) *
307 sizeof(rpnp_t))) == NULL) {
308 setlocale(LC_NUMERIC, old_locale);
312 else if ((sscanf(expr, "%lf%n", &rpnp[steps].val, &pos) == 1)
313 && (expr[pos] == ',')) {
314 rpnp[steps].op = OP_NUMBER;
317 #define match_op(VV,VVV) \
318 else if (strncmp(expr, #VVV, strlen(#VVV))==0 && ( expr[strlen(#VVV)] == ',' || expr[strlen(#VVV)] == '\0' )){ \
319 rpnp[steps].op = VV; \
320 expr+=strlen(#VVV); \
323 #define match_op_param(VV,VVV) \
324 else if (sscanf(expr, #VVV "(" DEF_NAM_FMT ")",vname) == 1) { \
326 if ((length = strlen(#VVV)+strlen(vname)+2, \
327 expr[length] == ',' || expr[length] == '\0') ) { \
328 rpnp[steps].op = VV; \
329 rpnp[steps].ptr = (*lookup)(key_hash,vname); \
330 if (rpnp[steps].ptr < 0) { \
333 } else expr+=length; \
342 match_op(OP_SIN, SIN)
343 match_op(OP_COS, COS)
344 match_op(OP_LOG, LOG)
345 match_op(OP_FLOOR, FLOOR)
346 match_op(OP_CEIL, CEIL)
347 match_op(OP_EXP, EXP)
348 match_op(OP_DUP, DUP)
349 match_op(OP_EXC, EXC)
350 match_op(OP_POP, POP)
351 match_op(OP_LTIME, LTIME)
358 match_op(OP_MIN, MIN)
359 match_op(OP_MAX, MAX)
360 match_op(OP_LIMIT, LIMIT)
361 /* order is important here ! .. match longest first */
362 match_op(OP_UNKN, UNKN)
364 match_op(OP_NEGINF, NEGINF)
366 match_op(OP_COUNT, COUNT)
367 match_op_param(OP_PREV_OTHER, PREV)
368 match_op(OP_PREV, PREV)
369 match_op(OP_INF, INF)
370 match_op(OP_ISINF, ISINF)
371 match_op(OP_NOW, NOW)
372 match_op(OP_TIME, TIME)
373 match_op(OP_ATAN2, ATAN2)
374 match_op(OP_ATAN, ATAN)
375 match_op(OP_SQRT, SQRT)
376 match_op(OP_SORT, SORT)
377 match_op(OP_REV, REV)
378 match_op(OP_TREND, TREND)
379 match_op(OP_TRENDNAN, TRENDNAN)
380 match_op(OP_PREDICT, PREDICT)
381 match_op(OP_PREDICTSIGMA, PREDICTSIGMA)
382 match_op(OP_RAD2DEG, RAD2DEG)
383 match_op(OP_DEG2RAD, DEG2RAD)
384 match_op(OP_AVG, AVG)
385 match_op(OP_ABS, ABS)
386 match_op(OP_ADDNAN, ADDNAN)
388 else if ((sscanf(expr, DEF_NAM_FMT "%n", vname, &pos) == 1)
389 && ((rpnp[steps].ptr = (*lookup) (key_hash, vname)) !=
391 rpnp[steps].op = OP_VARIABLE;
396 setlocale(LC_NUMERIC, old_locale);
406 setlocale(LC_NUMERIC, old_locale);
411 rpnp[steps + 1].op = OP_END;
412 setlocale(LC_NUMERIC, old_locale);
417 rpnstack_t *rpnstack)
420 rpnstack->dc_stacksize = 0;
421 rpnstack->dc_stackblock = 100;
425 rpnstack_t *rpnstack)
427 if (rpnstack->s != NULL)
429 rpnstack->dc_stacksize = 0;
432 static int rpn_compare_double(
436 double diff = *((const double *) x) - *((const double *) y);
438 return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
441 /* rpn_calc: run the RPN calculator; also performs variable substitution;
442 * moved and modified from data_calc() originally included in rrd_graph.c
444 * rpnp : an array of RPN operators (including variable references)
445 * rpnstack : the initialized stack
446 * data_idx : when data_idx is a multiple of rpnp.step, the rpnp.data pointer
447 * is advanced by rpnp.ds_cnt; used only for variable substitution
448 * output : an array of output values; OP_PREV assumes this array contains
449 * the "previous" value at index position output_idx-1; the definition of
450 * "previous" depends on the calling environment
451 * output_idx : an index into the output array in which to store the output
452 * of the RPN calculator
453 * returns: -1 if the computation failed (also calls rrd_set_error)
458 rpnstack_t *rpnstack,
466 /* process each op from the rpn in turn */
467 for (rpi = 0; rpnp[rpi].op != OP_END; rpi++) {
468 /* allocate or grow the stack */
469 if (stptr + 5 > rpnstack->dc_stacksize) {
470 /* could move this to a separate function */
471 rpnstack->dc_stacksize += rpnstack->dc_stackblock;
472 rpnstack->s = (double*)rrd_realloc(rpnstack->s,
473 (rpnstack->dc_stacksize) *
474 sizeof(*(rpnstack->s)));
475 if (rpnstack->s == NULL) {
476 rrd_set_error("RPN stack overflow");
480 #define stackunderflow(MINSIZE) \
482 rrd_set_error("RPN stack underflow"); \
486 switch (rpnp[rpi].op) {
488 rpnstack->s[++stptr] = rpnp[rpi].val;
492 /* Sanity check: VDEFs shouldn't make it here */
493 if (rpnp[rpi].ds_cnt == 0) {
494 rrd_set_error("VDEF made it into rpn_calc... aborting");
497 /* make sure we pull the correct value from
498 * the *.data array. Adjust the pointer into
499 * the array acordingly. Advance the ptr one
500 * row in the rra (skip over non-relevant
503 if (rpnp[rpi].op == OP_VARIABLE) {
504 rpnstack->s[++stptr] = *(rpnp[rpi].data);
506 if ((output_idx) <= 0) {
507 rpnstack->s[++stptr] = DNAN;
509 rpnstack->s[++stptr] =
510 *(rpnp[rpi].data - rpnp[rpi].ds_cnt);
514 if (data_idx % rpnp[rpi].step == 0) {
515 rpnp[rpi].data += rpnp[rpi].ds_cnt;
520 rpnstack->s[++stptr] = (output_idx + 1); /* Note: Counter starts at 1 */
523 if ((output_idx) <= 0) {
524 rpnstack->s[++stptr] = DNAN;
526 rpnstack->s[++stptr] = output[output_idx - 1];
530 rpnstack->s[++stptr] = DNAN;
533 rpnstack->s[++stptr] = DINF;
536 rpnstack->s[++stptr] = -DINF;
539 rpnstack->s[++stptr] = (double) time(NULL);
542 /* HACK: this relies on the data_idx being the time,
543 ** which the within-function scope is unaware of */
544 rpnstack->s[++stptr] = (double) data_idx;
547 rpnstack->s[++stptr] =
548 (double) tzoffset(data_idx) + (double) data_idx;
552 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
553 + rpnstack->s[stptr];
558 if (isnan(rpnstack->s[stptr - 1])) {
559 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
560 } else if (isnan(rpnstack->s[stptr])) {
562 /* rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]; */
564 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
565 + rpnstack->s[stptr];
572 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
573 - rpnstack->s[stptr];
578 rpnstack->s[stptr - 1] = (rpnstack->s[stptr - 1])
579 * (rpnstack->s[stptr]);
584 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
585 / rpnstack->s[stptr];
590 rpnstack->s[stptr - 1] = fmod(rpnstack->s[stptr - 1]
591 , rpnstack->s[stptr]);
596 rpnstack->s[stptr] = sin(rpnstack->s[stptr]);
600 rpnstack->s[stptr] = atan(rpnstack->s[stptr]);
604 rpnstack->s[stptr] = 57.29577951 * rpnstack->s[stptr];
608 rpnstack->s[stptr] = 0.0174532952 * rpnstack->s[stptr];
612 rpnstack->s[stptr - 1] = atan2(rpnstack->s[stptr - 1],
618 rpnstack->s[stptr] = cos(rpnstack->s[stptr]);
622 rpnstack->s[stptr] = ceil(rpnstack->s[stptr]);
626 rpnstack->s[stptr] = floor(rpnstack->s[stptr]);
630 rpnstack->s[stptr] = log(rpnstack->s[stptr]);
634 rpnstack->s[stptr + 1] = rpnstack->s[stptr];
646 dummy = rpnstack->s[stptr];
647 rpnstack->s[stptr] = rpnstack->s[stptr - 1];
648 rpnstack->s[stptr - 1] = dummy;
653 rpnstack->s[stptr] = exp(rpnstack->s[stptr]);
657 if (isnan(rpnstack->s[stptr - 1]));
658 else if (isnan(rpnstack->s[stptr]))
659 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
661 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <
662 rpnstack->s[stptr] ? 1.0 : 0.0;
667 if (isnan(rpnstack->s[stptr - 1]));
668 else if (isnan(rpnstack->s[stptr]))
669 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
671 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <=
672 rpnstack->s[stptr] ? 1.0 : 0.0;
677 if (isnan(rpnstack->s[stptr - 1]));
678 else if (isnan(rpnstack->s[stptr]))
679 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
681 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >
682 rpnstack->s[stptr] ? 1.0 : 0.0;
687 if (isnan(rpnstack->s[stptr - 1]));
688 else if (isnan(rpnstack->s[stptr]))
689 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
691 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >=
692 rpnstack->s[stptr] ? 1.0 : 0.0;
697 if (isnan(rpnstack->s[stptr - 1]));
698 else if (isnan(rpnstack->s[stptr]))
699 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
701 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
702 rpnstack->s[stptr] ? 0.0 : 1.0;
707 if (isnan(rpnstack->s[stptr - 1]));
708 else if (isnan(rpnstack->s[stptr]))
709 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
711 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
712 rpnstack->s[stptr] ? 1.0 : 0.0;
717 rpnstack->s[stptr - 2] = (isnan(rpnstack->s[stptr - 2])
718 || rpnstack->s[stptr - 2] ==
719 0.0) ? rpnstack->s[stptr] : rpnstack->
726 if (isnan(rpnstack->s[stptr - 1]));
727 else if (isnan(rpnstack->s[stptr]))
728 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
729 else if (rpnstack->s[stptr - 1] > rpnstack->s[stptr])
730 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
735 if (isnan(rpnstack->s[stptr - 1]));
736 else if (isnan(rpnstack->s[stptr]))
737 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
738 else if (rpnstack->s[stptr - 1] < rpnstack->s[stptr])
739 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
744 if (isnan(rpnstack->s[stptr - 2]));
745 else if (isnan(rpnstack->s[stptr - 1]))
746 rpnstack->s[stptr - 2] = rpnstack->s[stptr - 1];
747 else if (isnan(rpnstack->s[stptr]))
748 rpnstack->s[stptr - 2] = rpnstack->s[stptr];
749 else if (rpnstack->s[stptr - 2] < rpnstack->s[stptr - 1])
750 rpnstack->s[stptr - 2] = DNAN;
751 else if (rpnstack->s[stptr - 2] > rpnstack->s[stptr])
752 rpnstack->s[stptr - 2] = DNAN;
757 rpnstack->s[stptr] = isnan(rpnstack->s[stptr]) ? 1.0 : 0.0;
761 rpnstack->s[stptr] = isinf(rpnstack->s[stptr]) ? 1.0 : 0.0;
765 rpnstack->s[stptr] = sqrt(rpnstack->s[stptr]);
770 int spn = (int) rpnstack->s[stptr--];
772 stackunderflow(spn - 1);
773 qsort(rpnstack->s + stptr - spn + 1, spn, sizeof(double),
780 int spn = (int) rpnstack->s[stptr--];
783 stackunderflow(spn - 1);
785 p = rpnstack->s + stptr - spn + 1;
786 q = rpnstack->s + stptr;
796 case OP_PREDICTSIGMA:
799 /* the local averaging window (similar to trend, but better here, as we get better statistics thru numbers)*/
800 int locstepsize = rpnstack->s[--stptr];
801 /* the number of shifts and range-checking*/
802 int shifts = rpnstack->s[--stptr];
803 stackunderflow(shifts);
804 // handle negative shifts special
810 /* the real calculation */
812 /* the info on the datasource */
813 time_t dsstep = (time_t) rpnp[rpi - 1].step;
814 int dscount = rpnp[rpi - 1].ds_cnt;
815 int locstep = (int)ceil((float)locstepsize/(float)dsstep);
821 /* now loop for each position */
823 if (shifts<0) { doshifts=-shifts; }
824 for(int loop=0;loop<doshifts;loop++) {
825 /* calculate shift step */
828 shiftstep = loop*rpnstack->s[stptr];
830 shiftstep = rpnstack->s[stptr+loop];
833 rrd_set_error("negative shift step not allowed: %i",shiftstep);
836 shiftstep=(int)ceil((float)shiftstep/(float)dsstep);
837 /* loop all local shifts */
838 for(int i=0;i<=locstep;i++) {
839 /* now calculate offset into data-array - relative to output_idx*/
840 int offset=shiftstep+i;
841 /* and process if we have index 0 of above */
842 if ((offset>=0)&&(offset<output_idx)) {
844 val =rpnp[rpi - 1].data[-dscount * offset];
845 /* and handle the non NAN case only*/
854 /* do the final calculations */
856 if (rpnp[rpi].op == OP_PREDICT) { /* the average */
858 val = sum/(double)count;
861 if (count>1) { /* the sigma case */
862 val=count*sum2-sum*sum;
866 val=sqrt(val/((float)count*((float)count-1.0)));
870 rpnstack->s[stptr] = val;
876 if ((rpi < 2) || (rpnp[rpi - 2].op != OP_VARIABLE)) {
877 rrd_set_error("malformed trend arguments");
880 time_t dur = (time_t) rpnstack->s[stptr];
881 time_t step = (time_t) rpnp[rpi - 2].step;
883 if (output_idx > (int) ceil((float) dur / (float) step)) {
884 int ignorenan = (rpnp[rpi].op == OP_TREND);
891 rpnp[rpi - 2].data[rpnp[rpi - 2].ds_cnt * i--];
892 if (ignorenan || !isnan(val)) {
900 rpnstack->s[--stptr] =
901 (count == 0) ? DNAN : (accum / count);
903 rpnstack->s[--stptr] = DNAN;
909 int i = (int) rpnstack->s[stptr--];
913 stackunderflow(i - 1);
915 double val = rpnstack->s[stptr--];
924 /* now push the result back on stack */
926 rpnstack->s[++stptr] = sum / count;
928 rpnstack->s[++stptr] = DNAN;
934 rpnstack->s[stptr] = fabs(rpnstack->s[stptr]);
939 #undef stackunderflow
942 rrd_set_error("RPN final stack size != 1");
946 output[output_idx] = rpnstack->s[0];
950 /* figure out what the local timezone offset for any point in
951 time was. Return it in seconds */
955 int gm_sec, gm_min, gm_hour, gm_yday, gm_year,
956 l_sec, l_min, l_hour, l_yday, l_year;
966 localtime_r(&now, &t);
973 (l_sec - gm_sec) + (l_min - gm_min) * 60 + (l_hour - gm_hour) * 3600;
974 if (l_yday > gm_yday || l_year > gm_year) {
976 } else if (l_yday < gm_yday || l_year < gm_year) {