e392a656bb95163bf7116d5a00014445f5be01d5
[rrdtool.git] / src / rrd_rpncalc.c
1 /****************************************************************************
2  * RRDtool 1.4.3  Copyright by Tobi Oetiker, 1997-2010
3  ****************************************************************************
4  * rrd_rpncalc.c  RPN calculator functions
5  ****************************************************************************/
6
7 #include <limits.h>
8 #include <locale.h>
9 #include <stdlib.h>
10
11 #include "rrd_tool.h"
12 #include "rrd_rpncalc.h"
13 // #include "rrd_graph.h"
14
15 short     addop2str(
16     enum op_en op,
17     enum op_en op_type,
18     char *op_str,
19     char **result_str,
20     unsigned short *offset);
21 int       tzoffset(
22     time_t);            /* used to implement LTIME */
23
24 short rpn_compact(
25     rpnp_t *rpnp,
26     rpn_cdefds_t **rpnc,
27     short *count)
28 {
29     short     i;
30
31     *count = 0;
32     /* count the number of rpn nodes */
33     while (rpnp[*count].op != OP_END)
34         (*count)++;
35     if (++(*count) > DS_CDEF_MAX_RPN_NODES) {
36         rrd_set_error("Maximum %d RPN nodes permitted",
37                       DS_CDEF_MAX_RPN_NODES);
38         return -1;
39     }
40
41     /* allocate memory */
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);
48
49             if (temp < SHRT_MIN || temp > SHRT_MAX) {
50                 rrd_set_error
51                     ("constants must be integers in the interval (%d, %d)",
52                      SHRT_MIN, SHRT_MAX);
53                 free(*rpnc);
54                 return -1;
55             }
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;
59         }
60     }
61     /* terminate the sequence */
62     (*rpnc)[(*count) - 1].op = OP_END;
63     return 0;
64 }
65
66 rpnp_t   *rpn_expand(
67     rpn_cdefds_t *rpnc)
68 {
69     short     i;
70     rpnp_t   *rpnp;
71
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));
75     if (rpnp == NULL)
76         return NULL;
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;
83         }
84     }
85     /* terminate the sequence */
86     rpnp[i].op = OP_END;
87     return rpnp;
88 }
89
90 /* rpn_compact2str: convert a compact sequence of RPN operator nodes back
91  * into a CDEF string. This function is used by rrd_dump.
92  * arguments:
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
97  *   the caller */
98 void rpn_compact2str(
99     rpn_cdefds_t *rpnc,
100     ds_def_t *ds_def,
101     char **str)
102 {
103     unsigned short i, offset = 0;
104     char      buffer[7];    /* short as a string */
105
106     for (i = 0; rpnc[i].op != OP_END; i++) {
107         if (i > 0)
108             (*str)[offset++] = ',';
109
110 #define add_op(VV,VVV) \
111           if (addop2str((enum op_en)(rpnc[i].op), VV, VVV, str, &offset) == 1) continue;
112
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);
117 #else
118             sprintf(buffer, "%d", rpnc[i].val);
119 #endif
120             add_op(OP_NUMBER, buffer)
121         }
122
123         if (rpnc[i].op == OP_VARIABLE) {
124             char     *ds_name = ds_def[rpnc[i].val].ds_nam;
125
126             add_op(OP_VARIABLE, ds_name)
127         }
128
129         if (rpnc[i].op == OP_PREV_OTHER) {
130             char     *ds_name = ds_def[rpnc[i].val].ds_nam;
131
132             add_op(OP_VARIABLE, ds_name)
133         }
134 #undef add_op
135
136 #define add_op(VV,VVV) \
137           if (addop2str((enum op_en)rpnc[i].op, VV, #VVV, str, &offset) == 1) continue;
138
139         add_op(OP_ADD, +)
140             add_op(OP_SUB, -)
141             add_op(OP_MUL, *)
142             add_op(OP_DIV, /)
143             add_op(OP_MOD, %)
144             add_op(OP_SIN, SIN)
145             add_op(OP_COS, COS)
146             add_op(OP_LOG, LOG)
147             add_op(OP_FLOOR, FLOOR)
148             add_op(OP_CEIL, CEIL)
149             add_op(OP_EXP, EXP)
150             add_op(OP_DUP, DUP)
151             add_op(OP_EXC, EXC)
152             add_op(OP_POP, POP)
153             add_op(OP_LT, LT)
154             add_op(OP_LE, LE)
155             add_op(OP_GT, GT)
156             add_op(OP_GE, GE)
157             add_op(OP_EQ, EQ)
158             add_op(OP_IF, IF)
159             add_op(OP_MIN, MIN)
160             add_op(OP_MAX, MAX)
161             add_op(OP_LIMIT, LIMIT)
162             add_op(OP_UNKN, UNKN)
163             add_op(OP_UN, UN)
164             add_op(OP_NEGINF, NEGINF)
165             add_op(OP_NE, NE)
166             add_op(OP_PREV, PREV)
167             add_op(OP_INF, INF)
168             add_op(OP_ISINF, ISINF)
169             add_op(OP_NOW, NOW)
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)
176             add_op(OP_REV, REV)
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)
183             add_op(OP_AVG, AVG)
184             add_op(OP_ABS, ABS)
185             add_op(OP_ADDNAN, ADDNAN)
186 #undef add_op
187     }
188     (*str)[offset] = '\0';
189
190 }
191
192 short addop2str(
193     enum op_en op,
194     enum op_en op_type,
195     char *op_str,
196     char **result_str,
197     unsigned short *offset)
198 {
199     if (op == op_type) {
200         short     op_len;
201
202         op_len = strlen(op_str);
203         *result_str = (char *) rrd_realloc(*result_str,
204                                            (op_len + 1 +
205                                             *offset) * sizeof(char));
206         if (*result_str == NULL) {
207             rrd_set_error("failed to alloc memory in addop2str");
208             return -1;
209         }
210         strncpy(&((*result_str)[*offset]), op_str, op_len);
211         *offset += op_len;
212         return 1;
213     }
214     return 0;
215 }
216
217 void parseCDEF_DS(
218     const char *def,
219     rrd_t *rrd,
220     int ds_idx)
221 {
222     rpnp_t   *rpnp = NULL;
223     rpn_cdefds_t *rpnc = NULL;
224     short     count, i;
225
226     rpnp = rpn_parse((void *) rrd, def, &lookup_DS);
227     if (rpnp == NULL) {
228         rrd_set_error("failed to parse computed data source");
229         return;
230     }
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) {
238             rrd_set_error
239                 ("operators time, ltime, prev and count not supported with DS COMPUTE");
240             free(rpnp);
241             return;
242         }
243     }
244     if (rpn_compact(rpnp, &rpnc, &count) == -1) {
245         free(rpnp);
246         return;
247     }
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));
251     free(rpnp);
252     free(rpnc);
253 }
254
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
259  */
260 long lookup_DS(
261     void *rrd_vptr,
262     char *ds_name)
263 {
264     unsigned int i;
265     rrd_t    *rrd;
266
267     rrd = (rrd_t *) rrd_vptr;
268
269     for (i = 0; i < rrd->stat_head->ds_cnt; ++i) {
270         if (strcmp(ds_name, rrd->ds_def[i].ds_nam) == 0)
271             return i;
272     }
273     /* the caller handles a bad data source name in the rpn string */
274     return -1;
275 }
276
277 /* rpn_parse : parse a string and generate a rpnp array; modified
278  * str2rpn() originally included in rrd_graph.c
279  * arguments:
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
284  */
285 rpnp_t   *rpn_parse(
286     void *key_hash,
287     const char *const expr_const,
288     long      (*lookup) (void *,
289                          char *))
290 {
291     int       pos = 0;
292     char     *expr;
293     long      steps = -1;
294     rpnp_t   *rpnp;
295     char      vname[MAX_VNAME_LEN + 10];
296     char     *old_locale;
297
298     old_locale = setlocale(LC_NUMERIC, "C");
299
300     rpnp = NULL;
301     expr = (char *) expr_const;
302
303     while (*expr) {
304         if ((rpnp = (rpnp_t *) rrd_realloc(rpnp, (++steps + 2) *
305                                            sizeof(rpnp_t))) == NULL) {
306             setlocale(LC_NUMERIC, old_locale);
307             return NULL;
308         }
309
310         else if ((sscanf(expr, "%lf%n", &rpnp[steps].val, &pos) == 1)
311                  && (expr[pos] == ',')) {
312             rpnp[steps].op = OP_NUMBER;
313             expr += pos;
314         }
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); \
319         }
320
321 #define match_op_param(VV,VVV) \
322         else if (sscanf(expr, #VVV "(" DEF_NAM_FMT ")",vname) == 1) { \
323           int length = 0; \
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) { \
329                            free(rpnp); \
330                            return NULL; \
331                          } else expr+=length; \
332           } \
333         }
334
335         match_op(OP_ADD, +)
336             match_op(OP_SUB, -)
337             match_op(OP_MUL, *)
338             match_op(OP_DIV, /)
339             match_op(OP_MOD, %)
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)
350             match_op(OP_LT, LT)
351             match_op(OP_LE, LE)
352             match_op(OP_GT, GT)
353             match_op(OP_GE, GE)
354             match_op(OP_EQ, EQ)
355             match_op(OP_IF, IF)
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)
361             match_op(OP_UN, UN)
362             match_op(OP_NEGINF, NEGINF)
363             match_op(OP_NE, NE)
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)
385 #undef match_op
386             else if ((sscanf(expr, DEF_NAM_FMT "%n", vname, &pos) == 1)
387                      && ((rpnp[steps].ptr = (*lookup) (key_hash, vname)) !=
388                          -1)) {
389             rpnp[steps].op = OP_VARIABLE;
390             expr += pos;
391         }
392
393         else {
394             setlocale(LC_NUMERIC, old_locale);
395             free(rpnp);
396             return NULL;
397         }
398
399         if (*expr == 0)
400             break;
401         if (*expr == ',')
402             expr++;
403         else {
404             setlocale(LC_NUMERIC, old_locale);
405             free(rpnp);
406             return NULL;
407         }
408     }
409     rpnp[steps + 1].op = OP_END;
410     setlocale(LC_NUMERIC, old_locale);
411     return rpnp;
412 }
413
414 void rpnstack_init(
415     rpnstack_t *rpnstack)
416 {
417     rpnstack->s = NULL;
418     rpnstack->dc_stacksize = 0;
419     rpnstack->dc_stackblock = 100;
420 }
421
422 void rpnstack_free(
423     rpnstack_t *rpnstack)
424 {
425     if (rpnstack->s != NULL)
426         free(rpnstack->s);
427     rpnstack->dc_stacksize = 0;
428 }
429
430 static int rpn_compare_double(
431     const void *x,
432     const void *y)
433 {
434     double    diff = *((const double *) x) - *((const double *) y);
435
436     return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
437 }
438
439 /* rpn_calc: run the RPN calculator; also performs variable substitution;
440  * moved and modified from data_calc() originally included in rrd_graph.c 
441  * arguments:
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)
452  *           0 on success
453  */
454 short rpn_calc(
455     rpnp_t *rpnp,
456     rpnstack_t *rpnstack,
457     long data_idx,
458     rrd_value_t *output,
459     int output_idx)
460 {
461     int       rpi;
462     long      stptr = -1;
463
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");
475                 return -1;
476             }
477         }
478 #define stackunderflow(MINSIZE)                         \
479         if(stptr<MINSIZE){                              \
480             rrd_set_error("RPN stack underflow");       \
481             return -1;                                  \
482         }
483
484         switch (rpnp[rpi].op) {
485         case OP_NUMBER:
486             rpnstack->s[++stptr] = rpnp[rpi].val;
487             break;
488         case OP_VARIABLE:
489         case OP_PREV_OTHER:
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");
493                 return -1;
494             } else {
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
499                  * data sources)
500                  */
501                 if (rpnp[rpi].op == OP_VARIABLE) {
502                     rpnstack->s[++stptr] = *(rpnp[rpi].data);
503                 } else {
504                     if ((output_idx) <= 0) {
505                         rpnstack->s[++stptr] = DNAN;
506                     } else {
507                         rpnstack->s[++stptr] =
508                             *(rpnp[rpi].data - rpnp[rpi].ds_cnt);
509                     }
510
511                 }
512                 if (data_idx % rpnp[rpi].step == 0) {
513                     rpnp[rpi].data += rpnp[rpi].ds_cnt;
514                 }
515             }
516             break;
517         case OP_COUNT:
518             rpnstack->s[++stptr] = (output_idx + 1);    /* Note: Counter starts at 1 */
519             break;
520         case OP_PREV:
521             if ((output_idx) <= 0) {
522                 rpnstack->s[++stptr] = DNAN;
523             } else {
524                 rpnstack->s[++stptr] = output[output_idx - 1];
525             }
526             break;
527         case OP_UNKN:
528             rpnstack->s[++stptr] = DNAN;
529             break;
530         case OP_INF:
531             rpnstack->s[++stptr] = DINF;
532             break;
533         case OP_NEGINF:
534             rpnstack->s[++stptr] = -DINF;
535             break;
536         case OP_NOW:
537             rpnstack->s[++stptr] = (double) time(NULL);
538             break;
539         case OP_TIME:
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;
543             break;
544         case OP_LTIME:
545             rpnstack->s[++stptr] =
546                 (double) tzoffset(data_idx) + (double) data_idx;
547             break;
548         case OP_ADD:
549             stackunderflow(1);
550             rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
551                 + rpnstack->s[stptr];
552             stptr--;
553             break;
554         case OP_ADDNAN:
555             stackunderflow(1);
556             if (isnan(rpnstack->s[stptr - 1])) {
557                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
558             } else if (isnan(rpnstack->s[stptr])) {
559                 /* NOOP */
560                 /* rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]; */
561             } else {
562                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
563                     + rpnstack->s[stptr];
564             }
565
566             stptr--;
567             break;
568         case OP_SUB:
569             stackunderflow(1);
570             rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
571                 - rpnstack->s[stptr];
572             stptr--;
573             break;
574         case OP_MUL:
575             stackunderflow(1);
576             rpnstack->s[stptr - 1] = (rpnstack->s[stptr - 1])
577                 * (rpnstack->s[stptr]);
578             stptr--;
579             break;
580         case OP_DIV:
581             stackunderflow(1);
582             rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1]
583                 / rpnstack->s[stptr];
584             stptr--;
585             break;
586         case OP_MOD:
587             stackunderflow(1);
588             rpnstack->s[stptr - 1] = fmod(rpnstack->s[stptr - 1]
589                                           , rpnstack->s[stptr]);
590             stptr--;
591             break;
592         case OP_SIN:
593             stackunderflow(0);
594             rpnstack->s[stptr] = sin(rpnstack->s[stptr]);
595             break;
596         case OP_ATAN:
597             stackunderflow(0);
598             rpnstack->s[stptr] = atan(rpnstack->s[stptr]);
599             break;
600         case OP_RAD2DEG:
601             stackunderflow(0);
602             rpnstack->s[stptr] = 57.29577951 * rpnstack->s[stptr];
603             break;
604         case OP_DEG2RAD:
605             stackunderflow(0);
606             rpnstack->s[stptr] = 0.0174532952 * rpnstack->s[stptr];
607             break;
608         case OP_ATAN2:
609             stackunderflow(1);
610             rpnstack->s[stptr - 1] = atan2(rpnstack->s[stptr - 1],
611                                            rpnstack->s[stptr]);
612             stptr--;
613             break;
614         case OP_COS:
615             stackunderflow(0);
616             rpnstack->s[stptr] = cos(rpnstack->s[stptr]);
617             break;
618         case OP_CEIL:
619             stackunderflow(0);
620             rpnstack->s[stptr] = ceil(rpnstack->s[stptr]);
621             break;
622         case OP_FLOOR:
623             stackunderflow(0);
624             rpnstack->s[stptr] = floor(rpnstack->s[stptr]);
625             break;
626         case OP_LOG:
627             stackunderflow(0);
628             rpnstack->s[stptr] = log(rpnstack->s[stptr]);
629             break;
630         case OP_DUP:
631             stackunderflow(0);
632             rpnstack->s[stptr + 1] = rpnstack->s[stptr];
633             stptr++;
634             break;
635         case OP_POP:
636             stackunderflow(0);
637             stptr--;
638             break;
639         case OP_EXC:
640             stackunderflow(1);
641             {
642                 double    dummy;
643
644                 dummy = rpnstack->s[stptr];
645                 rpnstack->s[stptr] = rpnstack->s[stptr - 1];
646                 rpnstack->s[stptr - 1] = dummy;
647             }
648             break;
649         case OP_EXP:
650             stackunderflow(0);
651             rpnstack->s[stptr] = exp(rpnstack->s[stptr]);
652             break;
653         case OP_LT:
654             stackunderflow(1);
655             if (isnan(rpnstack->s[stptr - 1]));
656             else if (isnan(rpnstack->s[stptr]))
657                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
658             else
659                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <
660                     rpnstack->s[stptr] ? 1.0 : 0.0;
661             stptr--;
662             break;
663         case OP_LE:
664             stackunderflow(1);
665             if (isnan(rpnstack->s[stptr - 1]));
666             else if (isnan(rpnstack->s[stptr]))
667                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
668             else
669                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] <=
670                     rpnstack->s[stptr] ? 1.0 : 0.0;
671             stptr--;
672             break;
673         case OP_GT:
674             stackunderflow(1);
675             if (isnan(rpnstack->s[stptr - 1]));
676             else if (isnan(rpnstack->s[stptr]))
677                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
678             else
679                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >
680                     rpnstack->s[stptr] ? 1.0 : 0.0;
681             stptr--;
682             break;
683         case OP_GE:
684             stackunderflow(1);
685             if (isnan(rpnstack->s[stptr - 1]));
686             else if (isnan(rpnstack->s[stptr]))
687                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
688             else
689                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] >=
690                     rpnstack->s[stptr] ? 1.0 : 0.0;
691             stptr--;
692             break;
693         case OP_NE:
694             stackunderflow(1);
695             if (isnan(rpnstack->s[stptr - 1]));
696             else if (isnan(rpnstack->s[stptr]))
697                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
698             else
699                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
700                     rpnstack->s[stptr] ? 0.0 : 1.0;
701             stptr--;
702             break;
703         case OP_EQ:
704             stackunderflow(1);
705             if (isnan(rpnstack->s[stptr - 1]));
706             else if (isnan(rpnstack->s[stptr]))
707                 rpnstack->s[stptr - 1] = rpnstack->s[stptr];
708             else
709                 rpnstack->s[stptr - 1] = rpnstack->s[stptr - 1] ==
710                     rpnstack->s[stptr] ? 1.0 : 0.0;
711             stptr--;
712             break;
713         case OP_IF:
714             stackunderflow(2);
715             rpnstack->s[stptr - 2] = (isnan(rpnstack->s[stptr - 2])
716                                       || rpnstack->s[stptr - 2] ==
717                                       0.0) ? rpnstack->s[stptr] : rpnstack->
718                 s[stptr - 1];
719             stptr--;
720             stptr--;
721             break;
722         case OP_MIN:
723             stackunderflow(1);
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];
729             stptr--;
730             break;
731         case OP_MAX:
732             stackunderflow(1);
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];
738             stptr--;
739             break;
740         case OP_LIMIT:
741             stackunderflow(2);
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;
751             stptr -= 2;
752             break;
753         case OP_UN:
754             stackunderflow(0);
755             rpnstack->s[stptr] = isnan(rpnstack->s[stptr]) ? 1.0 : 0.0;
756             break;
757         case OP_ISINF:
758             stackunderflow(0);
759             rpnstack->s[stptr] = isinf(rpnstack->s[stptr]) ? 1.0 : 0.0;
760             break;
761         case OP_SQRT:
762             stackunderflow(0);
763             rpnstack->s[stptr] = sqrt(rpnstack->s[stptr]);
764             break;
765         case OP_SORT:
766             stackunderflow(0);
767             {
768                 int       spn = (int) rpnstack->s[stptr--];
769
770                 stackunderflow(spn - 1);
771                 qsort(rpnstack->s + stptr - spn + 1, spn, sizeof(double),
772                       rpn_compare_double);
773             }
774             break;
775         case OP_REV:
776             stackunderflow(0);
777             {
778                 int       spn = (int) rpnstack->s[stptr--];
779                 double   *p, *q;
780
781                 stackunderflow(spn - 1);
782
783                 p = rpnstack->s + stptr - spn + 1;
784                 q = rpnstack->s + stptr;
785                 while (p < q) {
786                     double    x = *q;
787
788                     *q-- = *p;
789                     *p++ = x;
790                 }
791             }
792             break;
793         case OP_PREDICT:
794         case OP_PREDICTSIGMA:
795             stackunderflow(2);
796             {
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
803                 if (shifts<0) {
804                     stptr--;
805                 } else {
806                     stptr-=shifts;
807                 }
808                 /* the real calculation */
809                 double val=DNAN;
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);
814
815                 /* the sums */
816                 double    sum = 0;
817                 double    sum2 = 0;
818                 int       count = 0;
819                 /* now loop for each position */
820                 int doshifts=shifts;
821                 if (shifts<0) { doshifts=-shifts; }
822                 for(int loop=0;loop<doshifts;loop++) {
823                     /* calculate shift step */
824                     int shiftstep=1;
825                     if (shifts<0) {
826                         shiftstep = loop*rpnstack->s[stptr];
827                     } else { 
828                         shiftstep = rpnstack->s[stptr+loop]; 
829                     }
830                     if(shiftstep <0) {
831                         rrd_set_error("negative shift step not allowed: %i",shiftstep);
832                         return -1;
833                     }
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)) {
841                             /* get the value */
842                             val =rpnp[rpi - 1].data[-dscount * offset];
843                             /* and handle the non NAN case only*/
844                             if (! isnan(val)) {
845                                 sum+=val;
846                                 sum2+=val*val;
847                                 count++;
848                             }
849                         }
850                     }
851                 }
852                 /* do the final calculations */
853                 val=DNAN;
854                 if (rpnp[rpi].op == OP_PREDICT) {  /* the average */
855                     if (count>0) {
856                         val = sum/(double)count;
857                     } 
858                 } else {
859                     if (count>1) { /* the sigma case */
860                         val=count*sum2-sum*sum;
861                         if (val<0) {
862                             val=DNAN;
863                         } else {
864                             val=sqrt(val/((float)count*((float)count-1.0)));
865                         }
866                     }
867                 }
868                 rpnstack->s[stptr] = val;
869             }
870             break;
871         case OP_TREND:
872         case OP_TRENDNAN:
873             stackunderflow(1);
874             if ((rpi < 2) || (rpnp[rpi - 2].op != OP_VARIABLE)) {
875                 rrd_set_error("malformed trend arguments");
876                 return -1;
877             } else {
878                 time_t    dur = (time_t) rpnstack->s[stptr];
879                 time_t    step = (time_t) rpnp[rpi - 2].step;
880
881                 if (output_idx > (int) ceil((float) dur / (float) step)) {
882                     int       ignorenan = (rpnp[rpi].op == OP_TREND);
883                     double    accum = 0.0;
884                     int       i = 0;
885                     int       count = 0;
886
887                     do {
888                         double    val =
889                             rpnp[rpi - 2].data[rpnp[rpi - 2].ds_cnt * i--];
890                         if (ignorenan || !isnan(val)) {
891                             accum += val;
892                             ++count;
893                         }
894
895                         dur -= step;
896                     } while (dur > 0);
897
898                     rpnstack->s[--stptr] =
899                         (count == 0) ? DNAN : (accum / count);
900                 } else
901                     rpnstack->s[--stptr] = DNAN;
902             }
903             break;
904         case OP_AVG:
905             stackunderflow(0);
906             {
907                 int       i = (int) rpnstack->s[stptr--];
908                 double    sum = 0;
909                 int       count = 0;
910
911                 stackunderflow(i - 1);
912                 while (i > 0) {
913                     double    val = rpnstack->s[stptr--];
914
915                     i--;
916                     if (isnan(val)) {
917                         continue;
918                     }
919                     count++;
920                     sum += val;
921                 }
922                 /* now push the result back on stack */
923                 if (count > 0) {
924                     rpnstack->s[++stptr] = sum / count;
925                 } else {
926                     rpnstack->s[++stptr] = DNAN;
927                 }
928             }
929             break;
930         case OP_ABS:
931             stackunderflow(0);
932             rpnstack->s[stptr] = fabs(rpnstack->s[stptr]);
933             break;
934         case OP_END:
935             break;
936         }
937 #undef stackunderflow
938     }
939     if (stptr != 0) {
940         rrd_set_error("RPN final stack size != 1");
941         return -1;
942     }
943
944     output[output_idx] = rpnstack->s[0];
945     return 0;
946 }
947
948 /* figure out what the local timezone offset for any point in
949    time was. Return it in seconds */
950 int tzoffset(
951     time_t now)
952 {
953     int       gm_sec, gm_min, gm_hour, gm_yday, gm_year,
954         l_sec, l_min, l_hour, l_yday, l_year;
955     struct tm t;
956     int       off;
957
958     gmtime_r(&now, &t);
959     gm_sec = t.tm_sec;
960     gm_min = t.tm_min;
961     gm_hour = t.tm_hour;
962     gm_yday = t.tm_yday;
963     gm_year = t.tm_year;
964     localtime_r(&now, &t);
965     l_sec = t.tm_sec;
966     l_min = t.tm_min;
967     l_hour = t.tm_hour;
968     l_yday = t.tm_yday;
969     l_year = t.tm_year;
970     off =
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) {
973         off += 24 * 3600;
974     } else if (l_yday < gm_yday || l_year < gm_year) {
975         off -= 24 * 3600;
976     }
977     return off;
978 }