1 /****************************************************************************
2 * RRDtool 1.4.1 Copyright by Tobi Oetiker, 1997-2009
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));
77 for (i = 0; rpnc[i].op != OP_END; ++i) {
78 rpnp[i].op = rpnc[i].op;
79 if (rpnp[i].op == OP_NUMBER) {
80 rpnp[i].val = (double) rpnc[i].val;
81 } else if (rpnp[i].op == OP_VARIABLE || rpnp[i].op == OP_PREV_OTHER) {
82 rpnp[i].ptr = (long) rpnc[i].val;
85 /* terminate the sequence */
90 /* rpn_compact2str: convert a compact sequence of RPN operator nodes back
91 * into a CDEF string. This function is used by rrd_dump.
93 * rpnc: an array of compact RPN operator nodes
94 * ds_def: a pointer to the data source definition section of an RRD header
95 * for lookup of data source names by index
96 * str: out string, memory is allocated by the function, must be freed by the
103 unsigned short i, offset = 0;
104 char buffer[7]; /* short as a string */
106 for (i = 0; rpnc[i].op != OP_END; i++) {
108 (*str)[offset++] = ',';
110 #define add_op(VV,VVV) \
111 if (addop2str((enum op_en)(rpnc[i].op), VV, VVV, str, &offset) == 1) continue;
113 if (rpnc[i].op == OP_NUMBER) {
114 /* convert a short into a string */
115 #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__CYGWIN32__)
116 _itoa(rpnc[i].val, buffer, 10);
118 sprintf(buffer, "%d", rpnc[i].val);
120 add_op(OP_NUMBER, buffer)
123 if (rpnc[i].op == OP_VARIABLE) {
124 char *ds_name = ds_def[rpnc[i].val].ds_nam;
126 add_op(OP_VARIABLE, ds_name)
129 if (rpnc[i].op == OP_PREV_OTHER) {
130 char *ds_name = ds_def[rpnc[i].val].ds_nam;
132 add_op(OP_VARIABLE, ds_name)
136 #define add_op(VV,VVV) \
137 if (addop2str((enum op_en)rpnc[i].op, VV, #VVV, str, &offset) == 1) continue;
147 add_op(OP_FLOOR, FLOOR)
148 add_op(OP_CEIL, CEIL)
161 add_op(OP_LIMIT, LIMIT)
162 add_op(OP_UNKN, UNKN)
164 add_op(OP_NEGINF, NEGINF)
166 add_op(OP_PREV, PREV)
168 add_op(OP_ISINF, ISINF)
170 add_op(OP_LTIME, LTIME)
171 add_op(OP_TIME, TIME)
172 add_op(OP_ATAN2, ATAN2)
173 add_op(OP_ATAN, ATAN)
174 add_op(OP_SQRT, SQRT)
175 add_op(OP_SORT, SORT)
177 add_op(OP_TREND, TREND)
178 add_op(OP_TRENDNAN, TRENDNAN)
179 add_op(OP_PREDICT, PREDICT)
180 add_op(OP_PREDICTSIGMA, PREDICTSIGMA)
181 add_op(OP_RAD2DEG, RAD2DEG)
182 add_op(OP_DEG2RAD, DEG2RAD)
185 add_op(OP_ADDNAN, ADDNAN)
188 (*str)[offset] = '\0';
197 unsigned short *offset)
202 op_len = strlen(op_str);
203 *result_str = (char *) rrd_realloc(*result_str,
205 *offset) * sizeof(char));
206 if (*result_str == NULL) {
207 rrd_set_error("failed to alloc memory in addop2str");
210 strncpy(&((*result_str)[*offset]), op_str, op_len);
223 rpn_cdefds_t *rpnc = NULL;
226 rpnp = rpn_parse((void *) rrd, def, &lookup_DS);
228 rrd_set_error("failed to parse computed data source");
231 /* Check for OP nodes not permitted in COMPUTE DS.
232 * Moved this check from within rpn_compact() because it really is
233 * COMPUTE DS specific. This is less efficient, but creation doesn't
234 * occur too often. */
235 for (i = 0; rpnp[i].op != OP_END; i++) {
236 if (rpnp[i].op == OP_TIME || rpnp[i].op == OP_LTIME ||
237 rpnp[i].op == OP_PREV || rpnp[i].op == OP_COUNT) {
239 ("operators time, ltime, prev and count not supported with DS COMPUTE");
244 if (rpn_compact(rpnp, &rpnc, &count) == -1) {
248 /* copy the compact rpn representation over the ds_def par array */
249 memcpy((void *) &(rrd->ds_def[ds_idx].par[DS_cdef]),
250 (void *) rpnc, count * sizeof(rpn_cdefds_t));
255 /* lookup a data source name in the rrd struct and return the index,
256 * should use ds_match() here except:
257 * (1) need a void * pointer to the rrd
258 * (2) error handling is left to the caller
267 rrd = (rrd_t *) rrd_vptr;
269 for (i = 0; i < rrd->stat_head->ds_cnt; ++i) {
270 if (strcmp(ds_name, rrd->ds_def[i].ds_nam) == 0)
273 /* the caller handles a bad data source name in the rpn string */
277 /* rpn_parse : parse a string and generate a rpnp array; modified
278 * str2rpn() originally included in rrd_graph.c
280 * key_hash: a transparent argument passed to lookup(); conceptually this
281 * is a hash object for lookup of a numeric key given a variable name
282 * expr: the string RPN expression, including variable names
283 * lookup(): a function that retrieves a numeric key given a variable name
287 const char *const expr_const,
288 long (*lookup) (void *,
295 char vname[MAX_VNAME_LEN + 10];
298 old_locale = setlocale(LC_NUMERIC, "C");
301 expr = (char *) expr_const;
304 if ((rpnp = (rpnp_t *) rrd_realloc(rpnp, (++steps + 2) *
305 sizeof(rpnp_t))) == NULL) {
306 setlocale(LC_NUMERIC, old_locale);
310 else if ((sscanf(expr, "%lf%n", &rpnp[steps].val, &pos) == 1)
311 && (expr[pos] == ',')) {
312 rpnp[steps].op = OP_NUMBER;
315 #define match_op(VV,VVV) \
316 else if (strncmp(expr, #VVV, strlen(#VVV))==0 && ( expr[strlen(#VVV)] == ',' || expr[strlen(#VVV)] == '\0' )){ \
317 rpnp[steps].op = VV; \
318 expr+=strlen(#VVV); \
321 #define match_op_param(VV,VVV) \
322 else if (sscanf(expr, #VVV "(" DEF_NAM_FMT ")",vname) == 1) { \
324 if ((length = strlen(#VVV)+strlen(vname)+2, \
325 expr[length] == ',' || expr[length] == '\0') ) { \
326 rpnp[steps].op = VV; \
327 rpnp[steps].ptr = (*lookup)(key_hash,vname); \
328 if (rpnp[steps].ptr < 0) { \
331 } else expr+=length; \
340 match_op(OP_SIN, SIN)
341 match_op(OP_COS, COS)
342 match_op(OP_LOG, LOG)
343 match_op(OP_FLOOR, FLOOR)
344 match_op(OP_CEIL, CEIL)
345 match_op(OP_EXP, EXP)
346 match_op(OP_DUP, DUP)
347 match_op(OP_EXC, EXC)
348 match_op(OP_POP, POP)
349 match_op(OP_LTIME, LTIME)
356 match_op(OP_MIN, MIN)
357 match_op(OP_MAX, MAX)
358 match_op(OP_LIMIT, LIMIT)
359 /* order is important here ! .. match longest first */
360 match_op(OP_UNKN, UNKN)
362 match_op(OP_NEGINF, NEGINF)
364 match_op(OP_COUNT, COUNT)
365 match_op_param(OP_PREV_OTHER, PREV)
366 match_op(OP_PREV, PREV)
367 match_op(OP_INF, INF)
368 match_op(OP_ISINF, ISINF)
369 match_op(OP_NOW, NOW)
370 match_op(OP_TIME, TIME)
371 match_op(OP_ATAN2, ATAN2)
372 match_op(OP_ATAN, ATAN)
373 match_op(OP_SQRT, SQRT)
374 match_op(OP_SORT, SORT)
375 match_op(OP_REV, REV)
376 match_op(OP_TREND, TREND)
377 match_op(OP_TRENDNAN, TRENDNAN)
378 match_op(OP_PREDICT, PREDICT)
379 match_op(OP_PREDICTSIGMA, PREDICTSIGMA)
380 match_op(OP_RAD2DEG, RAD2DEG)
381 match_op(OP_DEG2RAD, DEG2RAD)
382 match_op(OP_AVG, AVG)
383 match_op(OP_ABS, ABS)
384 match_op(OP_ADDNAN, ADDNAN)
386 else if ((sscanf(expr, DEF_NAM_FMT "%n", vname, &pos) == 1)
387 && ((rpnp[steps].ptr = (*lookup) (key_hash, vname)) !=
389 rpnp[steps].op = OP_VARIABLE;
394 setlocale(LC_NUMERIC, old_locale);
404 setlocale(LC_NUMERIC, old_locale);
409 rpnp[steps + 1].op = OP_END;
410 setlocale(LC_NUMERIC, old_locale);
415 rpnstack_t *rpnstack)
418 rpnstack->dc_stacksize = 0;
419 rpnstack->dc_stackblock = 100;
423 rpnstack_t *rpnstack)
425 if (rpnstack->s != NULL)
427 rpnstack->dc_stacksize = 0;
430 static int rpn_compare_double(
434 double diff = *((const double *) x) - *((const double *) y);
436 return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
439 /* rpn_calc: run the RPN calculator; also performs variable substitution;
440 * moved and modified from data_calc() originally included in rrd_graph.c
442 * rpnp : an array of RPN operators (including variable references)
443 * rpnstack : the initialized stack
444 * data_idx : when data_idx is a multiple of rpnp.step, the rpnp.data pointer
445 * is advanced by rpnp.ds_cnt; used only for variable substitution
446 * output : an array of output values; OP_PREV assumes this array contains
447 * the "previous" value at index position output_idx-1; the definition of
448 * "previous" depends on the calling environment
449 * output_idx : an index into the output array in which to store the output
450 * of the RPN calculator
451 * returns: -1 if the computation failed (also calls rrd_set_error)
456 rpnstack_t *rpnstack,
464 /* process each op from the rpn in turn */
465 for (rpi = 0; rpnp[rpi].op != OP_END; rpi++) {
466 /* allocate or grow the stack */
467 if (stptr + 5 > rpnstack->dc_stacksize) {
468 /* could move this to a separate function */
469 rpnstack->dc_stacksize += rpnstack->dc_stackblock;
470 rpnstack->s = (double*)rrd_realloc(rpnstack->s,
471 (rpnstack->dc_stacksize) *
472 sizeof(*(rpnstack->s)));
473 if (rpnstack->s == NULL) {
474 rrd_set_error("RPN stack overflow");
478 #define stackunderflow(MINSIZE) \
480 rrd_set_error("RPN stack underflow"); \
484 switch (rpnp[rpi].op) {
486 rpnstack->s[++stptr] = rpnp[rpi].val;
490 /* Sanity check: VDEFs shouldn't make it here */
491 if (rpnp[rpi].ds_cnt == 0) {
492 rrd_set_error("VDEF made it into rpn_calc... aborting");
495 /* make sure we pull the correct value from
496 * the *.data array. Adjust the pointer into
497 * the array acordingly. Advance the ptr one
498 * row in the rra (skip over non-relevant
501 if (rpnp[rpi].op == OP_VARIABLE) {
502 rpnstack->s[++stptr] = *(rpnp[rpi].data);
504 if ((output_idx) <= 0) {
505 rpnstack->s[++stptr] = DNAN;
507 rpnstack->s[++stptr] =
508 *(rpnp[rpi].data - rpnp[rpi].ds_cnt);
512 if (data_idx % rpnp[rpi].step == 0) {
513 rpnp[rpi].data += rpnp[rpi].ds_cnt;
518 rpnstack->s[++stptr] = (output_idx + 1); /* Note: Counter starts at 1 */
521 if ((output_idx) <= 0) {
522 rpnstack->s[++stptr] = DNAN;
524 rpnstack->s[++stptr] = output[output_idx - 1];
528 rpnstack->s[++stptr] = DNAN;
531 rpnstack->s[++stptr] = DINF;
534 rpnstack->s[++stptr] = -DINF;
537 rpnstack->s[++stptr] = (double) time(NULL);
540 /* HACK: this relies on the data_idx being the time,
541 ** which the within-function scope is unaware of */
542 rpnstack->s[++stptr] = (double) data_idx;
545 rpnstack->s[++stptr] =
546 (double) tzoffset(data_idx) + (double) data_idx;
550 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
551 + rpnstack->s[stptr];
556 if (isnan(rpnstack->s[stptr - 1])) {
557 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
558 } else if (isnan(rpnstack->s[stptr])) {
560 /* rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]; */
562 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
563 + rpnstack->s[stptr];
570 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
571 - rpnstack->s[stptr];
576 rpnstack->s[stptr - 1] = (rpnstack->s[stptr - 1])
577 * (rpnstack->s[stptr]);
582 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
583 / rpnstack->s[stptr];
588 rpnstack->s[stptr - 1] = fmod(rpnstack->s[stptr - 1]
589 , rpnstack->s[stptr]);
594 rpnstack->s[stptr] = sin(rpnstack->s[stptr]);
598 rpnstack->s[stptr] = atan(rpnstack->s[stptr]);
602 rpnstack->s[stptr] = 57.29577951 * rpnstack->s[stptr];
606 rpnstack->s[stptr] = 0.0174532952 * rpnstack->s[stptr];
610 rpnstack->s[stptr - 1] = atan2(rpnstack->s[stptr - 1],
616 rpnstack->s[stptr] = cos(rpnstack->s[stptr]);
620 rpnstack->s[stptr] = ceil(rpnstack->s[stptr]);
624 rpnstack->s[stptr] = floor(rpnstack->s[stptr]);
628 rpnstack->s[stptr] = log(rpnstack->s[stptr]);
632 rpnstack->s[stptr + 1] = rpnstack->s[stptr];
644 dummy = rpnstack->s[stptr];
645 rpnstack->s[stptr] = rpnstack->s[stptr - 1];
646 rpnstack->s[stptr - 1] = dummy;
651 rpnstack->s[stptr] = exp(rpnstack->s[stptr]);
655 if (isnan(rpnstack->s[stptr - 1]));
656 else if (isnan(rpnstack->s[stptr]))
657 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
659 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <
660 rpnstack->s[stptr] ? 1.0 : 0.0;
665 if (isnan(rpnstack->s[stptr - 1]));
666 else if (isnan(rpnstack->s[stptr]))
667 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
669 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <=
670 rpnstack->s[stptr] ? 1.0 : 0.0;
675 if (isnan(rpnstack->s[stptr - 1]));
676 else if (isnan(rpnstack->s[stptr]))
677 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
679 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >
680 rpnstack->s[stptr] ? 1.0 : 0.0;
685 if (isnan(rpnstack->s[stptr - 1]));
686 else if (isnan(rpnstack->s[stptr]))
687 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
689 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >=
690 rpnstack->s[stptr] ? 1.0 : 0.0;
695 if (isnan(rpnstack->s[stptr - 1]));
696 else if (isnan(rpnstack->s[stptr]))
697 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
699 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
700 rpnstack->s[stptr] ? 0.0 : 1.0;
705 if (isnan(rpnstack->s[stptr - 1]));
706 else if (isnan(rpnstack->s[stptr]))
707 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
709 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
710 rpnstack->s[stptr] ? 1.0 : 0.0;
715 rpnstack->s[stptr - 2] = (isnan(rpnstack->s[stptr - 2])
716 || rpnstack->s[stptr - 2] ==
717 0.0) ? rpnstack->s[stptr] : rpnstack->
724 if (isnan(rpnstack->s[stptr - 1]));
725 else if (isnan(rpnstack->s[stptr]))
726 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
727 else if (rpnstack->s[stptr - 1] > rpnstack->s[stptr])
728 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
733 if (isnan(rpnstack->s[stptr - 1]));
734 else if (isnan(rpnstack->s[stptr]))
735 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
736 else if (rpnstack->s[stptr - 1] < rpnstack->s[stptr])
737 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
742 if (isnan(rpnstack->s[stptr - 2]));
743 else if (isnan(rpnstack->s[stptr - 1]))
744 rpnstack->s[stptr - 2] = rpnstack->s[stptr - 1];
745 else if (isnan(rpnstack->s[stptr]))
746 rpnstack->s[stptr - 2] = rpnstack->s[stptr];
747 else if (rpnstack->s[stptr - 2] < rpnstack->s[stptr - 1])
748 rpnstack->s[stptr - 2] = DNAN;
749 else if (rpnstack->s[stptr - 2] > rpnstack->s[stptr])
750 rpnstack->s[stptr - 2] = DNAN;
755 rpnstack->s[stptr] = isnan(rpnstack->s[stptr]) ? 1.0 : 0.0;
759 rpnstack->s[stptr] = isinf(rpnstack->s[stptr]) ? 1.0 : 0.0;
763 rpnstack->s[stptr] = sqrt(rpnstack->s[stptr]);
768 int spn = (int) rpnstack->s[stptr--];
770 stackunderflow(spn - 1);
771 qsort(rpnstack->s + stptr - spn + 1, spn, sizeof(double),
778 int spn = (int) rpnstack->s[stptr--];
781 stackunderflow(spn - 1);
783 p = rpnstack->s + stptr - spn + 1;
784 q = rpnstack->s + stptr;
794 case OP_PREDICTSIGMA:
797 /* the local averaging window (similar to trend, but better here, as we get better statistics thru numbers)*/
798 int locstepsize = rpnstack->s[--stptr];
799 /* the number of shifts and range-checking*/
800 int shifts = rpnstack->s[--stptr];
801 stackunderflow(shifts);
802 // handle negative shifts special
808 /* the real calculation */
810 /* the info on the datasource */
811 time_t dsstep = (time_t) rpnp[rpi - 1].step;
812 int dscount = rpnp[rpi - 1].ds_cnt;
813 int locstep = (int)ceil((float)locstepsize/(float)dsstep);
819 /* now loop for each position */
821 if (shifts<0) { doshifts=-shifts; }
822 for(int loop=0;loop<doshifts;loop++) {
823 /* calculate shift step */
826 shiftstep = loop*rpnstack->s[stptr];
828 shiftstep = rpnstack->s[stptr+loop];
831 rrd_set_error("negative shift step not allowed: %i",shiftstep);
834 shiftstep=(int)ceil((float)shiftstep/(float)dsstep);
835 /* loop all local shifts */
836 for(int i=0;i<=locstep;i++) {
837 /* now calculate offset into data-array - relative to output_idx*/
838 int offset=shiftstep+i;
839 /* and process if we have index 0 of above */
840 if ((offset>=0)&&(offset<output_idx)) {
842 val =rpnp[rpi - 1].data[-dscount * offset];
843 /* and handle the non NAN case only*/
852 /* do the final calculations */
854 if (rpnp[rpi].op == OP_PREDICT) { /* the average */
856 val = sum/(double)count;
859 if (count>1) { /* the sigma case */
860 val=count*sum2-sum*sum;
864 val=sqrt(val/((float)count*((float)count-1.0)));
868 rpnstack->s[stptr] = val;
874 if ((rpi < 2) || (rpnp[rpi - 2].op != OP_VARIABLE)) {
875 rrd_set_error("malformed trend arguments");
878 time_t dur = (time_t) rpnstack->s[stptr];
879 time_t step = (time_t) rpnp[rpi - 2].step;
881 if (output_idx > (int) ceil((float) dur / (float) step)) {
882 int ignorenan = (rpnp[rpi].op == OP_TREND);
889 rpnp[rpi - 2].data[rpnp[rpi - 2].ds_cnt * i--];
890 if (ignorenan || !isnan(val)) {
898 rpnstack->s[--stptr] =
899 (count == 0) ? DNAN : (accum / count);
901 rpnstack->s[--stptr] = DNAN;
907 int i = (int) rpnstack->s[stptr--];
911 stackunderflow(i - 1);
913 double val = rpnstack->s[stptr--];
922 /* now push the result back on stack */
924 rpnstack->s[++stptr] = sum / count;
926 rpnstack->s[++stptr] = DNAN;
932 rpnstack->s[stptr] = fabs(rpnstack->s[stptr]);
937 #undef stackunderflow
940 rrd_set_error("RPN final stack size != 1");
944 output[output_idx] = rpnstack->s[0];
948 /* figure out what the local timezone offset for any point in
949 time was. Return it in seconds */
953 int gm_sec, gm_min, gm_hour, gm_yday, gm_year,
954 l_sec, l_min, l_hour, l_yday, l_year;
964 localtime_r(&now, &t);
971 (l_sec - gm_sec) + (l_min - gm_min) * 60 + (l_hour - gm_hour) * 3600;
972 if (l_yday > gm_yday || l_year > gm_year) {
974 } else if (l_yday < gm_yday || l_year < gm_year) {