(Trivial) Fix spellling in a comment.
[metze/wireshark/wip.git] / epan / stats_tree.c
1 /* stats_tree.c
2  * API for a counter tree for Wireshark
3  * 2004, Luis E. G. Ontanon
4  *
5  * $Id$
6  *
7  * Wireshark - Network traffic analyzer
8  * By Gerald Combs <gerald@wireshark.org>
9  * Copyright 1998 Gerald Combs
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24  */
25
26  /* stats_tree modifications by Deon van der Westhuysen, November 2013
27   * support for
28   *  - sorting by column,
29   *  - calculation of average values
30   *  - calculation of burst rate
31   *  - export to text, CSV or XML file
32   */
33
34 #include "config.h"
35
36 #include <glib.h>
37 #include <glib/gprintf.h>
38
39 #include <stdlib.h>
40
41 #include <epan/stats_tree_priv.h>
42 #include <epan/prefs.h>
43 #include <math.h>
44 #include <string.h>
45
46 #include "strutil.h"
47 #include "stats_tree.h"
48
49 enum _stat_tree_columns {
50         COL_NAME,
51         COL_COUNT,
52         COL_AVERAGE,
53         COL_MIN,
54         COL_MAX,
55         COL_RATE,
56         COL_PERCENT,
57         COL_BURSTRATE,
58         COL_BURSTTIME,
59         N_COLUMNS
60 };
61
62 /* used to contain the registered stat trees */
63 static GHashTable *registry = NULL;
64
65 /* a text representation of a node
66 if buffer is NULL returns a newly allocated string */
67 extern gchar*
68 stats_tree_node_to_str(const stat_node *node, gchar *buffer, guint len)
69 {
70         if (buffer) {
71                 g_snprintf(buffer,len,"%s: %i",node->name, node->counter);
72                 return buffer;
73         } else {
74                 return g_strdup_printf("%s: %i",node->name, node->counter);
75         }
76 }
77
78 extern guint
79 stats_tree_branch_max_namelen(const stat_node *node, guint indent)
80 {
81         stat_node *child;
82         guint maxlen = 0;
83         guint len;
84
85         indent = indent > INDENT_MAX ? INDENT_MAX : indent;
86
87         if (node->children) {
88                 for (child = node->children; child; child = child->next ) {
89                         len = stats_tree_branch_max_namelen(child,indent+1);
90                         maxlen = len > maxlen ? len : maxlen;
91                 }
92         }
93
94         if (node->st_flags&ST_FLG_ROOTCHILD) {
95                 gchar *display_name= stats_tree_get_displayname(node->name);
96                 len = (guint) strlen(display_name) + indent;
97                 g_free(display_name);
98         }
99         else {
100         len = (guint) strlen(node->name) + indent;
101         }
102         maxlen = len > maxlen ? len : maxlen;
103
104         return maxlen;
105 }
106
107 /* frees the resources allocated by a stat_tree node */
108 static void
109 free_stat_node(stat_node *node)
110 {
111         stat_node *child;
112         stat_node *next;
113         burst_bucket *bucket;
114
115         if (node->children) {
116         for (child = node->children; child; child = next ) {
117                 /* child->next will be gone after free_stat_node, so cache it here */
118                 next = child->next;
119                 free_stat_node(child);
120         }
121         }
122
123         if(node->st->cfg->free_node_pr) node->st->cfg->free_node_pr(node);
124
125         if (node->hash) g_hash_table_destroy(node->hash);
126
127         while (node->bh) {
128                 bucket = node->bh;
129                 node->bh = bucket->next;
130                 g_free(bucket);
131         }
132
133         g_free(node->rng);
134         g_free(node->name);
135         g_free(node);
136 }
137
138 /* destroys the whole tree instance */
139 extern void
140 stats_tree_free(stats_tree *st)
141 {
142         stat_node *child;
143         stat_node *next;
144
145         g_free(st->filter);
146         g_hash_table_destroy(st->names);
147         g_ptr_array_free(st->parents,TRUE);
148         g_free(st->display_name);
149
150         for (child = st->root.children; child; child = next ) {
151                 /* child->next will be gone after free_stat_node, so cache it here */
152                 next = child->next;
153                 free_stat_node(child);
154         }
155
156         if (st->cfg->free_tree_pr)
157                 st->cfg->free_tree_pr(st);
158
159         if (st->cfg->cleanup)
160                 st->cfg->cleanup(st);
161
162         g_free(st);
163 }
164
165
166 /* reset a node to its original state */
167 static void
168 reset_stat_node(stat_node *node)
169 {
170         stat_node *child;
171         burst_bucket *bucket;
172
173         node->counter = 0;
174         node->total = 0;
175         node->minvalue = G_MAXINT;
176         node->maxvalue = G_MININT;
177         node->st_flags = 0;
178
179         while (node->bh) {
180                 bucket = node->bh;
181                 node->bh = bucket->next;
182                 g_free(bucket);
183         }
184         node->bh = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
185         node->bt = node->bh;
186         node->bcount = 0;
187         node->max_burst = 0;
188         node->burst_time = -1.0;
189
190         if (node->children) {
191                 for (child = node->children; child; child = child->next )
192                         reset_stat_node(child);
193         }
194
195         if(node->st->cfg->reset_node) {
196                 node->st->cfg->reset_node(node);
197         }
198
199 }
200
201 /* reset the whole stats_tree */
202 extern void
203 stats_tree_reset(void *p)
204 {
205         stats_tree *st = (stats_tree *)p;
206
207         st->start = -1.0;
208         st->elapsed = 0.0;
209         st->now = - 1.0;
210
211         reset_stat_node(&st->root);
212
213         if (st->cfg->reset_tree) {
214                 st->cfg->reset_tree(st);
215         }
216 }
217
218 extern void
219 stats_tree_reinit(void *p)
220 {
221         stats_tree *st = (stats_tree *)p;
222         stat_node *child;
223         stat_node *next;
224
225         for (child = st->root.children; child; child = next) {
226                 /* child->next will be gone after free_stat_node, so cache it here */
227                 next = child->next;
228                 free_stat_node(child);
229         }
230
231         st->root.children = NULL;
232         st->root.counter = 0;
233         st->root.total = 0;
234         st->root.minvalue = G_MAXINT;
235         st->root.maxvalue = G_MININT;
236         st->root.st_flags = 0;
237
238         st->root.bh = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
239         st->root.bt = st->root.bh;
240         st->root.bcount = 0;
241         st->root.max_burst = 0;
242         st->root.burst_time = -1.0;
243
244         /* No more stat_nodes left in tree - clean out hash, array */
245         g_hash_table_remove_all(st->names);
246         if (st->parents->len>1) {
247                 g_ptr_array_remove_range(st->parents, 1, st->parents->len-1);
248         }
249
250         /* Do not update st_flags for the tree (sorting) - leave as was */
251         st->num_columns = N_COLUMNS;
252         g_free(st->display_name);
253         st->display_name= stats_tree_get_displayname(st->cfg->name);
254
255         if (st->cfg->init) {
256                 st->cfg->init(st);
257         }
258 }
259
260 /* register a new stats_tree */
261 extern void
262 stats_tree_register_with_group(const char *tapname, const char *abbr, const char *name,
263                     guint flags,
264                     stat_tree_packet_cb packet, stat_tree_init_cb init,
265                     stat_tree_cleanup_cb cleanup, register_stat_group_t stat_group)
266 {
267         stats_tree_cfg *cfg = (stats_tree_cfg *)g_malloc( sizeof(stats_tree_cfg) );
268
269         /* at the very least the abbrev and the packet function should be given */
270         g_assert( tapname && abbr && packet );
271
272         cfg->plugin = FALSE;
273         cfg->tapname = g_strdup(tapname);
274         cfg->abbr = g_strdup(abbr);
275         cfg->name = name ? g_strdup(name) : g_strdup(abbr);
276         cfg->stat_group = stat_group;
277
278         cfg->packet = packet;
279         cfg->init = init;
280         cfg->cleanup = cleanup;
281
282         cfg->flags = flags&~ST_FLG_MASK;
283         cfg->st_flags = flags&ST_FLG_MASK;
284
285         /* these have to be filled in by implementations */
286         cfg->setup_node_pr = NULL;
287         cfg->new_tree_pr = NULL;
288         cfg->free_node_pr = NULL;
289         cfg->free_tree_pr = NULL;
290         cfg->draw_node = NULL;
291         cfg->draw_tree = NULL;
292         cfg->reset_node = NULL;
293         cfg->reset_tree = NULL;
294
295         if (!registry) registry = g_hash_table_new(g_str_hash,g_str_equal);
296
297         g_hash_table_insert(registry,cfg->abbr,cfg);
298 }
299
300 /* register a new stats_tree with default group REGISTER_STAT_GROUP_UNSORTED */
301 extern void
302 stats_tree_register(const char *tapname, const char *abbr, const char *name,
303                     guint flags,
304                     stat_tree_packet_cb packet, stat_tree_init_cb init,
305                     stat_tree_cleanup_cb cleanup)
306 {
307         stats_tree_register_with_group(tapname, abbr, name,
308                     flags,
309                     packet, init,
310                     cleanup, REGISTER_STAT_GROUP_UNSORTED);
311 }
312
313 /* register a new stat_tree with default group REGISTER_STAT_GROUP_UNSORTED from a plugin */
314 extern void
315 stats_tree_register_plugin(const char *tapname, const char *abbr, const char *name,
316                     guint flags,
317                     stat_tree_packet_cb packet, stat_tree_init_cb init,
318                     stat_tree_cleanup_cb cleanup)
319 {
320         stats_tree_cfg *cfg;
321
322         stats_tree_register(tapname, abbr, name,
323                     flags,
324                     packet, init,
325                     cleanup);
326         cfg = stats_tree_get_cfg_by_abbr(abbr);
327         cfg->plugin = TRUE;
328 }
329
330 extern stats_tree*
331 stats_tree_new(stats_tree_cfg *cfg, tree_pres *pr, const char *filter)
332 {
333         stats_tree *st = (stats_tree *)g_malloc(sizeof(stats_tree));
334
335         st->cfg = cfg;
336         st->pr = pr;
337
338         st->names = g_hash_table_new(g_str_hash,g_str_equal);
339         st->parents = g_ptr_array_new();
340         st->filter = g_strdup(filter);
341
342         st->start = -1.0;
343         st->elapsed = 0.0;
344
345         st->root.counter = 0;
346         st->root.total = 0;
347         st->root.minvalue = G_MAXINT;
348         st->root.maxvalue = G_MININT;
349         st->root.st_flags = 0;
350
351         st->root.bh = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
352         st->root.bt = st->root.bh;
353         st->root.bcount = 0;
354         st->root.max_burst = 0;
355         st->root.burst_time = -1.0;
356
357         st->root.name = stats_tree_get_displayname(cfg->name);
358         st->root.st = st;
359         st->root.parent = NULL;
360         st->root.children = NULL;
361         st->root.next = NULL;
362         st->root.hash = NULL;
363         st->root.pr = NULL;
364
365         st->st_flags = st->cfg->st_flags;
366
367         if (!(st->st_flags&ST_FLG_SRTCOL_MASK)) {
368                 /* No default sort specified - use preferences */
369                 st->st_flags |= prefs.st_sort_defcolflag<<ST_FLG_SRTCOL_SHIFT;
370                 if (prefs.st_sort_defdescending) {
371                         st->st_flags |= ST_FLG_SORT_DESC;
372                 }
373         }
374         st->num_columns = N_COLUMNS;
375         st->display_name= stats_tree_get_displayname(st->cfg->name);
376
377         g_ptr_array_add(st->parents,&st->root);
378
379         return st;
380 }
381
382 /* will be the tap packet cb */
383 extern int
384 stats_tree_packet(void *p, packet_info *pinfo, epan_dissect_t *edt, const void *pri)
385 {
386         stats_tree *st = (stats_tree *)p;
387
388         st->now = nstime_to_msec(&pinfo->rel_ts);
389         if (st->start < 0.0) st->start = st->now;
390
391         st->elapsed = st->now - st->start;
392
393         if (st->cfg->packet)
394                 return st->cfg->packet(st,pinfo,edt,pri);
395         else
396                 return 0;
397 }
398
399 extern stats_tree_cfg*
400 stats_tree_get_cfg_by_abbr(const char *abbr)
401 {
402         return (stats_tree_cfg *)g_hash_table_lookup(registry,abbr);
403 }
404
405 extern GList*
406 stats_tree_get_cfg_list(void)
407 {
408         return g_hash_table_get_values(registry);
409 }
410
411 struct _stats_tree_pres_cbs {
412         void (*setup_node_pr)(stat_node*);
413         void (*free_node_pr)(stat_node*);
414         void (*draw_node)(stat_node*);
415         void (*reset_node)(stat_node*);
416         tree_pres *(*new_tree_pr)(stats_tree*);
417         void (*free_tree_pr)(stats_tree*);
418         void (*draw_tree)(stats_tree*);
419         void (*reset_tree)(stats_tree*);
420 };
421
422 static void
423 setup_tree_presentation(gpointer k _U_, gpointer v, gpointer p)
424 {
425         stats_tree_cfg *cfg = (stats_tree_cfg *)v;
426         struct _stats_tree_pres_cbs *d = (struct _stats_tree_pres_cbs *)p;
427
428         cfg->in_use = FALSE;
429         cfg->setup_node_pr = d->setup_node_pr;
430         cfg->new_tree_pr = d->new_tree_pr;
431         cfg->free_node_pr = d->free_node_pr;
432         cfg->free_tree_pr = d->free_tree_pr;
433         cfg->draw_node = d->draw_node;
434         cfg->draw_tree = d->draw_tree;
435         cfg->reset_node = d->reset_node;
436         cfg->reset_tree = d->reset_tree;
437
438 }
439
440 extern void
441 stats_tree_presentation(void (*registry_iterator)(gpointer,gpointer,gpointer),
442                         void (*setup_node_pr)(stat_node*),
443                         void (*free_node_pr)(stat_node*),
444                         void (*draw_node)(stat_node*),
445                         void (*reset_node)(stat_node*),
446                         tree_pres *(*new_tree_pr)(stats_tree*),
447                         void (*free_tree_pr)(stats_tree*),
448                         void (*draw_tree)(stats_tree*),
449                         void (*reset_tree)(stats_tree*),
450                         void *data)
451 {
452         static struct _stats_tree_pres_cbs d;
453
454         d.setup_node_pr = setup_node_pr;
455         d.new_tree_pr = new_tree_pr;
456         d.free_node_pr = free_node_pr;
457         d.free_tree_pr = free_tree_pr;
458         d.draw_node = draw_node;
459         d.draw_tree = draw_tree;
460         d.reset_node = reset_node;
461         d.reset_tree = reset_tree;
462
463         if (registry) g_hash_table_foreach(registry,setup_tree_presentation,&d);
464
465         if (registry_iterator && registry)
466                 g_hash_table_foreach(registry,registry_iterator,data);
467
468 }
469
470
471 /* creates a stat_tree node
472 *    name: the name of the stats_tree node
473 *    parent_name: the name of the ALREADY REGISTERED parent
474 *    with_hash: whether or not it should keep a hash with its children names
475 *    as_named_node: whether or not it has to be registered in the root namespace
476 */
477 static stat_node*
478 new_stat_node(stats_tree *st, const gchar *name, int parent_id,
479               gboolean with_hash, gboolean as_parent_node)
480 {
481
482         stat_node *node = (stat_node *)g_malloc (sizeof(stat_node));
483         stat_node *last_chld = NULL;
484
485         node->counter = 0;
486         node->total = 0;
487         node->minvalue = G_MAXINT;
488         node->maxvalue = G_MININT;
489         node->st_flags = parent_id?0:ST_FLG_ROOTCHILD;
490
491         node->bh = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
492         node->bt = node->bh;
493         node->bcount = 0;
494         node->max_burst = 0;
495         node->burst_time = -1.0;
496
497         node->name = g_strdup(name);
498         node->children = NULL;
499         node->next = NULL;
500         node->st = (stats_tree*) st;
501         node->hash = with_hash ? g_hash_table_new(g_str_hash,g_str_equal) : NULL;
502         node->parent = NULL;
503         node->rng  =  NULL;
504
505         if (as_parent_node) {
506                 g_hash_table_insert(st->names,
507                                                         node->name,
508                                                         node);
509
510                 g_ptr_array_add(st->parents,node);
511
512                 node->id = st->parents->len - 1;
513         } else {
514                 node->id = -1;
515         }
516
517         if (parent_id >= 0 && parent_id < (int) st->parents->len ) {
518                 node->parent = (stat_node *)g_ptr_array_index(st->parents,parent_id);
519         } else {
520                 /* ??? should we set the parent to be root ??? */
521                 g_assert_not_reached();
522         }
523
524         if (node->parent->children) {
525                 /* insert as last child */
526
527                 for (last_chld = node->parent->children;
528                          last_chld->next;
529                          last_chld = last_chld->next ) ;
530
531                 last_chld->next = node;
532
533         } else {
534                 /* insert as first child */
535                 node->parent->children = node;
536         }
537
538         if(node->parent->hash) {
539                 g_hash_table_insert(node->parent->hash,node->name,node);
540         }
541
542         if (st->cfg->setup_node_pr) {
543                 st->cfg->setup_node_pr(node);
544         } else {
545                 node->pr = NULL;
546         }
547
548         return node;
549 }
550 /***/
551
552 extern int
553 stats_tree_create_node(stats_tree *st, const gchar *name, int parent_id, gboolean with_hash)
554 {
555         stat_node *node = new_stat_node(st,name,parent_id,with_hash,TRUE);
556
557         if (node)
558                 return node->id;
559         else
560                 return 0;
561 }
562
563 /* XXX: should this be a macro? */
564 extern int
565 stats_tree_create_node_by_pname(stats_tree *st, const gchar *name,
566                                 const gchar *parent_name, gboolean with_children)
567 {
568         return stats_tree_create_node(st,name,stats_tree_parent_id_by_name(st,parent_name),with_children);
569 }
570
571 /* Internal function to update the burst calculation data - add entry to bucket */
572 static void
573 update_burst_calc(stat_node *node, gint value)
574 {
575         double current_bucket;
576         double burstwin;
577
578         burst_bucket *bn;
579
580         if (!prefs.st_enable_burstinfo) {
581                 return;
582         }
583
584         /* NB thebucket list should always contain at least one node - even if it is */
585         /* the dummy created at init time. Head and tail should never be NULL!       */
586         current_bucket= floor(node->st->now/prefs.st_burst_resolution);
587         burstwin= prefs.st_burst_windowlen/prefs.st_burst_resolution;
588         if (current_bucket>node->bt->bucket_no) {
589                 /* Must add a new bucket at the burst list tail */
590                 bn = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
591                 bn->count = value;
592                 bn->bucket_no = current_bucket;
593                 bn->start_time = node->st->now;
594                 bn->prev = node->bt;
595                 node->bt->next = bn;
596                 node->bt = bn;
597                 /* And add value to the current burst count for node */
598                 node->bcount += value;
599                 /* Check if bucket list head is now too old and must be removed */
600                 while (current_bucket>=(node->bh->bucket_no+burstwin)) {
601                         /* off with its head! */
602                         bn = node->bh;
603                         node->bh = bn->next;
604                         node->bh->prev = NULL;
605                         node->bcount -= bn->count;
606                         g_free(bn);
607                 }
608         }
609         else if (current_bucket<node->bh->bucket_no) {
610                 /* Packet must be added at head of burst list - check if not too old */
611                 if ((current_bucket+burstwin)>node->bt->bucket_no) {
612                         /* packet still within the window */
613                         bn = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
614                         bn->count = value;
615                         bn->bucket_no = current_bucket;
616                         bn->start_time = node->st->now;
617                         bn->next = node->bh;
618                         node->bh->prev = bn;
619                         node->bh = bn;
620                         /* And add value to the current burst count for node */
621                         node->bcount += value;
622                 }
623         }
624         else
625         {
626                 /* Somewhere in the middle... */
627                 burst_bucket *search = node->bt;
628                 while (current_bucket<search->bucket_no) {
629                         search = search->prev;
630                 }
631                 if (current_bucket==search->bucket_no) {
632                         /* found existing bucket, increase value */
633                         search->count += value;
634                         if (search->start_time>node->st->now) {
635                                 search->start_time = node->st->now;
636                         }
637                 }
638                 else {
639                         /* must add a new bucket after bn. */
640                         bn = (burst_bucket*)g_malloc0(sizeof(burst_bucket));
641                         bn->count = value;
642                         bn->bucket_no = current_bucket;
643                         bn->start_time = node->st->now;
644                         bn->prev = search;
645                         bn->next = search->next;
646                         search->next = bn;
647                         bn->next->prev = bn;
648                 }
649                 node->bcount += value;
650         }
651         if (node->bcount>node->max_burst) {
652                 /* new record burst */
653                 node->max_burst = node->bcount;
654                 node->burst_time = node->bh->start_time;
655         }
656 }
657
658 /*
659  * Increases by delta the counter of the node whose name is given
660  * if the node does not exist yet it's created (with counter=1)
661  * using parent_name as parent node.
662  * with_hash=TRUE to indicate that the created node will have a parent
663  */
664 extern int
665 stats_tree_manip_node(manip_node_mode mode, stats_tree *st, const char *name,
666                       int parent_id, gboolean with_hash, gint value)
667 {
668         stat_node *node = NULL;
669         stat_node *parent = NULL;
670
671         g_assert( parent_id >= 0 && parent_id < (int) st->parents->len );
672
673         parent = (stat_node *)g_ptr_array_index(st->parents,parent_id);
674
675         if( parent->hash ) {
676                 node = (stat_node *)g_hash_table_lookup(parent->hash,name);
677         } else {
678                 node = (stat_node *)g_hash_table_lookup(st->names,name);
679         }
680
681         if ( node == NULL )
682                 node = new_stat_node(st,name,parent_id,with_hash,with_hash);
683
684         switch (mode) {
685                 case MN_INCREASE:
686                                 node->counter += value;
687                                 update_burst_calc(node, value);
688                                 break;
689                 case MN_SET: node->counter = value; break;
690                 case MN_AVERAGE:
691                                 node->counter++;
692                                 update_burst_calc(node, 1);
693                                 /* fall through to average code */
694                 case MN_AVERAGE_NOTICK:
695                                 node->total += value;
696                                 if (node->minvalue > value) {
697                                         node->minvalue = value;
698                                 }
699                                 if (node->maxvalue < value) {
700                                         node->maxvalue = value;
701                                 }
702                                 node->st_flags |= ST_FLG_AVERAGE;
703                                 break;
704                 case MN_SET_FLAGS:
705                                 node->st_flags |= value;
706                                 break;
707                 case MN_CLEAR_FLAGS:
708                                 node->st_flags &= ~value;
709                                 break;
710         }
711
712         if (node)
713                 return node->id;
714         else
715                 return -1;
716 }
717
718
719 extern char*
720 stats_tree_get_abbr(const char *opt_arg)
721 {
722         guint i;
723
724         /* XXX: this fails when tshark is given any options
725            after the -z */
726         g_assert(opt_arg != NULL);
727
728         for (i=0; opt_arg[i] && opt_arg[i] != ','; i++);
729
730         if (opt_arg[i] == ',') {
731                 return g_strndup(opt_arg,i);
732         } else {
733                 return NULL;
734         }
735 }
736
737
738 /*
739  * This function accepts an input string which should define a long integer range.
740  * The normal result is a struct containing the floor and ceil value of this
741  * range.
742  *
743  * It is allowed to define a range string in the following ways :
744  *
745  * "0-10" -> { 0, 10 }
746  * "-0" -> { G_MININT, 0 }
747  * "0-" -> { 0, G_MAXINT }
748  * "-" -> { G_MININT, G_MAXINT }
749  *
750  * Note that this function is robust to buggy input string. If in some cases it
751  * returns NULL, it but may also return a pair with undefined values.
752  *
753  */
754 static range_pair_t*
755 get_range(char *rngstr)
756 {
757         gchar **split;
758         range_pair_t *rng;
759
760         split = g_strsplit((gchar*)rngstr,"-",2);
761
762         /* empty string */
763         if (split[0] == NULL) {
764                 g_strfreev(split);
765                 return NULL;
766         }
767
768         rng = (range_pair_t *)g_malloc(sizeof(range_pair_t));
769
770         if (split[1] == NULL) {
771                 /* means we have a non empty string with no delimiter
772                  * so it must be a single number */
773                 rng->floor = (gint)strtol(split[0],NULL,10);
774                 rng->ceil = rng->floor;
775         } else {
776           /* string == "X-?" */
777                 if (*(split[0]) != '\0') {
778                         rng->floor = (gint)strtol(split[0],NULL,10);
779                 } else
780                 /* string == "-?" */
781                 rng->floor = G_MININT;
782
783                 /* string != "?-" */
784         if (*(split[1]) != '\0') {
785                         rng->ceil  = (gint)strtol(split[1],NULL,10);
786         } else
787                 /* string == "?-" */
788                 rng->ceil = G_MAXINT;
789         }
790         g_strfreev(split);
791
792         return rng;
793 }
794
795
796 extern int
797 stats_tree_create_range_node(stats_tree *st, const gchar *name, int parent_id, ...)
798 {
799         va_list list;
800         gchar *curr_range;
801         stat_node *rng_root = new_stat_node(st, name, parent_id, FALSE, TRUE);
802         stat_node *range_node = NULL;
803
804         va_start( list, parent_id );
805         while (( curr_range = va_arg(list, gchar*) )) {
806                 range_node = new_stat_node(st, curr_range, rng_root->id, FALSE, FALSE);
807                 range_node->rng = get_range(curr_range);
808         }
809         va_end( list );
810
811         return rng_root->id;
812 }
813
814 extern int 
815 stats_tree_create_range_node_string(stats_tree *st, const gchar *name,
816                                     int parent_id, int num_str_ranges,
817                                     gchar** str_ranges)
818 {
819         int i;
820         stat_node *rng_root = new_stat_node(st, name, parent_id, FALSE, TRUE);
821         stat_node *range_node = NULL;
822
823         for (i = 0; i < num_str_ranges; i++) {
824                 range_node = new_stat_node(st, str_ranges[i], rng_root->id, FALSE, FALSE);
825                 range_node->rng = get_range(str_ranges[i]);
826         }
827
828         return rng_root->id;
829 }
830
831 /****/
832 extern int
833 stats_tree_parent_id_by_name(stats_tree *st, const gchar *parent_name)
834 {
835         stat_node *node = (stat_node *)g_hash_table_lookup(st->names,parent_name);
836
837         if (node)
838                 return node->id;
839         else
840                 return 0; /* XXX: this is the root shoud we return -1 instead?*/
841 }
842
843
844 extern int
845 stats_tree_range_node_with_pname(stats_tree *st, const gchar *name,
846                                  const gchar *parent_name, ...)
847 {
848         va_list list;
849         gchar *curr_range;
850         stat_node *range_node = NULL;
851         int parent_id = stats_tree_parent_id_by_name(st,parent_name);
852         stat_node *rng_root = new_stat_node(st, name, parent_id, FALSE, TRUE);
853
854         va_start( list, parent_name );
855         while (( curr_range = va_arg(list, gchar*) )) {
856                 range_node = new_stat_node(st, curr_range, rng_root->id, FALSE, FALSE);
857                 range_node->rng = get_range(curr_range);
858         }
859         va_end( list );
860
861         return rng_root->id;
862 }
863
864
865 extern int
866 stats_tree_tick_range(stats_tree *st, const gchar *name, int parent_id,
867                       int value_in_range)
868 {
869
870         stat_node *node = NULL;
871         stat_node *parent = NULL;
872         stat_node *child = NULL;
873         gint stat_floor, stat_ceil;
874
875         if (parent_id >= 0 && parent_id < (int) st->parents->len) {
876                 parent = (stat_node *)g_ptr_array_index(st->parents,parent_id);
877         } else {
878                 g_assert_not_reached();
879         }
880
881         if( parent->hash ) {
882                 node = (stat_node *)g_hash_table_lookup(parent->hash,name);
883         } else {
884                 node = (stat_node *)g_hash_table_lookup(st->names,name);
885         }
886
887         if ( node == NULL )
888                 g_assert_not_reached();
889
890         /* update stats for container node. counter should already be ticked so we only update total and min/max */
891         node->total += value_in_range;
892         if (node->minvalue > value_in_range) {
893                 node->minvalue = value_in_range;
894         }
895         if (node->maxvalue < value_in_range) {
896                 node->maxvalue = value_in_range;
897         }
898         node->st_flags |= ST_FLG_AVERAGE;
899
900         for ( child = node->children; child; child = child->next) {
901                 stat_floor =  child->rng->floor;
902                 stat_ceil = child->rng->ceil;
903
904                 if ( value_in_range >= stat_floor && value_in_range <= stat_ceil ) {
905                         child->counter++;
906                         child->total += value_in_range;
907                         if (child->minvalue > value_in_range) {
908                                 child->minvalue = value_in_range;
909                         }
910                         if (child->maxvalue < value_in_range) {
911                                 child->maxvalue = value_in_range;
912                         }
913                         child->st_flags |= ST_FLG_AVERAGE;
914                         update_burst_calc(child, 1);
915                         return node->id;
916                 }
917         }
918
919         return node->id;
920 }
921
922 extern int
923 stats_tree_create_pivot(stats_tree *st, const gchar *name, int parent_id)
924 {
925         stat_node *node = new_stat_node(st,name,parent_id,TRUE,TRUE);
926
927         if (node)
928                 return node->id;
929         else
930                 return 0;
931 }
932
933 extern int
934 stats_tree_create_pivot_by_pname(stats_tree *st, const gchar *name,
935                                  const gchar *parent_name)
936 {
937         int parent_id = stats_tree_parent_id_by_name(st,parent_name);
938         stat_node *node;
939
940         node = new_stat_node(st,name,parent_id,TRUE,TRUE);
941
942         if (node)
943                 return node->id;
944         else
945                 return 0;
946 }
947
948 extern int
949 stats_tree_tick_pivot(stats_tree *st, int pivot_id, const gchar *pivot_value)
950 {
951         stat_node *parent = (stat_node *)g_ptr_array_index(st->parents,pivot_id);
952
953         parent->counter++;
954         update_burst_calc(parent, 1);
955         stats_tree_manip_node( MN_INCREASE, st, pivot_value, pivot_id, FALSE, 1);
956
957         return pivot_id;
958 }
959
960 extern gchar*
961 stats_tree_get_displayname (gchar* fullname)
962 {
963         gchar *buf = g_strdup(fullname);
964         gchar *sep;
965
966         if (prefs.st_sort_showfullname) {
967                 return buf; /* unmodifed */
968         }
969
970         sep = buf;
971         while ((sep = strchr(sep,'/')) != NULL) {
972                 if (*(++sep)=='/') {  /* escapeded slash - two slash characters after each other */
973                         memmove(sep,sep+1,strlen(sep));
974                 }
975                 else {
976                         /* we got a new path separator */
977                         memmove(buf,sep,strlen(sep)+1);
978                         sep = buf;
979                 }
980         }
981
982         return buf;
983 }
984
985 extern gint
986 stats_tree_get_default_sort_col (stats_tree *st)
987 {
988         switch ((st->st_flags&ST_FLG_SRTCOL_MASK)>>ST_FLG_SRTCOL_SHIFT) {
989                 case ST_SORT_COL_NAME:          return COL_NAME;
990                 case ST_SORT_COL_COUNT:         return COL_COUNT;
991                 case ST_SORT_COL_AVG:           return COL_AVERAGE;
992                 case ST_SORT_COL_MIN:           return COL_MIN;
993                 case ST_SORT_COL_MAX:           return COL_MAX;
994                 case ST_SORT_COL_BURSTRATE:     return COL_BURSTRATE;
995         }
996         return COL_COUNT;       /* nothing specific set */
997 }
998
999 extern gboolean
1000 stats_tree_is_default_sort_DESC (stats_tree *st)
1001 {
1002         return st->st_flags&ST_FLG_SORT_DESC;
1003 }
1004
1005 extern const gchar*
1006 stats_tree_get_column_name (gint col_index)
1007 {
1008         switch (col_index) {
1009                 case COL_NAME:          return "Topic / Item";
1010                 case COL_COUNT:         return "Count";
1011                 case COL_AVERAGE:       return "Average";
1012                 case COL_MIN:           return "Min val";
1013                 case COL_MAX:           return "Max val";
1014                 case COL_RATE:          return "Rate (ms)";
1015                 case COL_PERCENT:       return "Percent";
1016                 case COL_BURSTRATE:     return prefs.st_burst_showcount?"Burst count":"Burst rate";
1017                 case COL_BURSTTIME:     return "Burst start";
1018                 default:                return "(Unknown)";
1019         }
1020 }
1021
1022 extern gint
1023 stats_tree_get_column_size (gint col_index)
1024 {
1025         if (col_index==COL_NAME) {
1026                 return 36;              /* but caller should really call stats_tree_branch_max_namelen() */
1027         }
1028         if (col_index<N_COLUMNS) {
1029                 return 12;              /* all numerical values are this size */
1030         }
1031         return 0;                       /* invalid column */
1032 }
1033
1034 extern gchar**
1035 stats_tree_get_values_from_node (const stat_node* node)
1036 {
1037         gchar **values = (gchar**) g_malloc0(sizeof(gchar*)*(node->st->num_columns));
1038
1039         values[COL_NAME]= (node->st_flags&ST_FLG_ROOTCHILD)?stats_tree_get_displayname(node->name):g_strdup(node->name);
1040         values[COL_COUNT]= g_strdup_printf("%u",node->counter);
1041         values[COL_AVERAGE]= ((node->st_flags&ST_FLG_AVERAGE)||node->rng)?
1042                                 (node->counter?g_strdup_printf("%.2f",((float)node->total)/node->counter):g_strdup("-")):
1043                                 g_strdup("");
1044         values[COL_MIN]= ((node->st_flags&ST_FLG_AVERAGE)||node->rng)?
1045                                 (node->counter?g_strdup_printf("%u",node->minvalue):g_strdup("-")):
1046                                 g_strdup("");
1047         values[COL_MAX]= ((node->st_flags&ST_FLG_AVERAGE)||node->rng)?
1048                                 (node->counter?g_strdup_printf("%u",node->maxvalue):g_strdup("-")):
1049                                 g_strdup("");
1050         values[COL_RATE]= (node->st->elapsed)?g_strdup_printf("%.4f",((float)node->counter)/node->st->elapsed):g_strdup("");
1051         values[COL_PERCENT]= ((node->parent)&&(node->parent->counter))?
1052                                 g_strdup_printf("%.2f%%",(node->counter*100.0)/node->parent->counter):
1053                                 (node->parent==&(node->st->root)?g_strdup("100%"):g_strdup(""));
1054         if (node->st->num_columns>COL_BURSTTIME) {
1055                 values[COL_BURSTRATE]= (!prefs.st_enable_burstinfo)?g_strdup(""):
1056                                 (node->max_burst?(prefs.st_burst_showcount?
1057                                                                 g_strdup_printf("%d",node->max_burst):
1058                                                                 g_strdup_printf("%.4f",((double)node->max_burst)/prefs.st_burst_windowlen)):
1059                                 g_strdup("-"));
1060                 values[COL_BURSTTIME]= (!prefs.st_enable_burstinfo)?g_strdup(""):
1061                                 (node->max_burst?g_strdup_printf("%.3f",((double)node->burst_time/1000.0)):g_strdup("-"));
1062         }
1063         return values;
1064 }
1065
1066 extern gint
1067 stats_tree_sort_compare (const stat_node *a, const stat_node *b, gint sort_column,
1068                                         gboolean sort_descending)
1069 {
1070         int     result = 0;
1071         float avg_a, avg_b;
1072
1073         if  (prefs.st_sort_rng_nameonly&&(a->rng&&b->rng)) {
1074                 /* always sort ranges by range name */
1075                 result = a->rng->floor - b->rng->floor;
1076                 if (sort_descending&&(!prefs.st_sort_rng_fixorder)) {
1077                         result= -result;
1078                 }
1079                 return result;
1080         }
1081
1082         switch (sort_column)
1083         {
1084                 case COL_NAME:          if  (a->rng&&b->rng) {
1085                                                                 result = a->rng->floor - b->rng->floor;
1086                                                         }
1087                                                         else if (prefs.st_sort_casesensitve) {
1088                                                                 result = strcmp(a->name,b->name);
1089                                                         }
1090                                                         else {
1091                                                                 result = g_ascii_strcasecmp(a->name,b->name);
1092                                                         }
1093                                                         break;
1094
1095                 case COL_RATE:
1096                 case COL_PERCENT:
1097                 case COL_COUNT:         result = a->counter - b->counter;
1098                                                         break;
1099
1100                 case COL_AVERAGE:       if (a->counter) {
1101                                                                 result= 1;              /* assume a>b */
1102                                                                 if (b->counter) {
1103                                                                         avg_a= ((float)a->total)/a->counter;
1104                                                                         avg_b= ((float)b->total)/b->counter;
1105                                                                         result= (avg_a>avg_b)?1:((avg_a<avg_b)?-1:0);
1106                                                                 }
1107                                                         }
1108                                                         else {
1109                                                                 result= -1;             /* let b>a */
1110                                                         }
1111                                                         break;
1112
1113                 case COL_MIN:           result = a->minvalue - b->minvalue;
1114                                                         break;
1115
1116                 case COL_MAX:           result = a->maxvalue - b->maxvalue;
1117                                                         break;
1118
1119                 case COL_BURSTRATE:     result = a->max_burst - b->max_burst;
1120                                                         break;
1121
1122                 case COL_BURSTTIME:     result = (a->burst_time>b->burst_time)?1:((a->burst_time<b->burst_time)?-1:0);
1123                                                         break;
1124
1125                 default:
1126                                         /* no sort comparison found for column - must update this switch statement */
1127                                         g_assert_not_reached();
1128         }
1129
1130         /* break tie between items with same primary search result */
1131         if (!result) {
1132                 if (sort_column==COL_NAME) {
1133                         result = a->counter - b->counter;
1134                 }
1135                 else {
1136                         if  (a->rng&&b->rng) {
1137                                 result = a->rng->floor - b->rng->floor;
1138                         }
1139                         else if (prefs.st_sort_casesensitve) {
1140                                 result = strcmp(a->name,b->name);
1141                         }
1142                         else {
1143                                 result = g_ascii_strcasecmp(a->name,b->name);
1144                         }
1145                 }
1146         }
1147
1148         /* take into account sort order */
1149         if (sort_descending) {
1150                 result= -result;
1151         }
1152
1153         if ((a->st_flags&ST_FLG_SORT_TOP)!=(b->st_flags&ST_FLG_SORT_TOP)) {
1154                 /* different sort groups top vs non-top */
1155                 result= (a->st_flags&ST_FLG_SORT_TOP)?-1:1;
1156         }
1157         return result;
1158 }
1159
1160 extern GString*
1161 stats_tree_format_as_str(const stats_tree* st, st_format_type format_type,
1162                                         gint sort_column, gboolean sort_descending)
1163 {
1164         int maxnamelen= stats_tree_branch_max_namelen(&st->root,0);
1165         stat_node *child;
1166         GString *s;
1167         int count;
1168         gchar *separator = NULL;
1169
1170         switch(format_type)
1171         {
1172         case ST_FORMAT_YAML:
1173                 s = g_string_new("---\n");
1174                 break;
1175         case ST_FORMAT_XML:
1176                 s = g_string_new("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
1177                 break;
1178         case ST_FORMAT_CSV:
1179                 s = g_string_new("\"level\",\"parent\",");
1180                 for (count = 0; count<st->num_columns; count++) {
1181                         g_string_append_printf(s,"\"%s\",",stats_tree_get_column_name(count));
1182                 }
1183                 g_string_append (s,"\n");
1184                 break;
1185         case ST_FORMAT_PLAIN:
1186                 {
1187                 char fmt[16];
1188                 int sep_length;
1189
1190                 sep_length= maxnamelen;
1191                 for (count = 1; count<st->num_columns; count++) {
1192                         sep_length += stats_tree_get_column_size(count)+2;
1193                 }
1194                 separator = (gchar *)g_malloc(sep_length+1);
1195                 memset (separator, '=', sep_length);
1196                 separator[sep_length] = 0;
1197
1198                 s = g_string_new("\n");
1199                 g_string_append(s,separator);
1200                 g_string_append_printf(s,"\n%s:\n",st->cfg->name);
1201                 g_sprintf (fmt,"%%-%us",maxnamelen);
1202                 g_string_append_printf(s,fmt,stats_tree_get_column_name(0));
1203                 for (count = 1; count<st->num_columns; count++) {
1204                         g_sprintf (fmt," %%-%us",stats_tree_get_column_size(count)+1);
1205                         g_string_append_printf(s,fmt,stats_tree_get_column_name(count));
1206                 }
1207                 memset (separator, '-', sep_length);
1208                 g_string_append_printf(s,"\n%s\n",separator);
1209                 }
1210                 break;
1211         default:
1212                 return g_string_new("unknown format for stats_tree\n");
1213         }
1214
1215         for (child = st->root.children; child; child = child->next ) {
1216                 stats_tree_format_node_as_str(child,s,format_type,0,"",maxnamelen,sort_column,sort_descending);
1217
1218         }
1219
1220         if (format_type==ST_FORMAT_PLAIN) {
1221                 g_string_append_printf(s,"\n%s\n",separator);
1222                 g_free(separator);
1223         }
1224
1225         return s;
1226 }
1227
1228 typedef struct {
1229         gint sort_column;
1230         gboolean sort_descending;
1231 }       sortinfo;
1232
1233 /* Function to compare elements for child array sort. a and b are children, user_data
1234 points to a st_flags value */
1235 extern gint
1236 stat_node_array_sortcmp (gconstpointer a, gconstpointer b, gpointer user_data)
1237 {
1238         /* user_data is *guint value to st_flags */
1239         return stats_tree_sort_compare (*(const stat_node**)a,*(const stat_node**)b,
1240                                         ((sortinfo*)user_data)->sort_column,((sortinfo*)user_data)->sort_descending);
1241 }
1242
1243 static gchar*
1244 clean_for_xml_tag (gchar *str)
1245 {
1246         gchar *s = str;
1247         while ((s=strpbrk(s,"!\"#$%%&'()*+,/;<=>?@[\\]^`{|}~ ")) != NULL) {
1248                 *(s++) = '-';
1249         }
1250         return str;
1251 }
1252
1253 /** helper funcation to add note to formatted stats_tree */
1254 WS_DLL_PUBLIC void stats_tree_format_node_as_str(const stat_node *node,
1255                                                  GString *s,
1256                                                  st_format_type format_type,
1257                                                  guint indent,
1258                                                  const gchar *path,
1259                                                  gint maxnamelen,
1260                                                  gint sort_column,
1261                                                  gboolean sort_descending)
1262 {
1263         int count;
1264         int num_columns= node->st->num_columns;
1265         gchar **values= stats_tree_get_values_from_node(node);
1266         stat_node *child;
1267         sortinfo si;
1268         gchar *full_path;
1269         char fmt[16];
1270
1271         switch(format_type)
1272         {
1273         case ST_FORMAT_YAML:
1274                 if (indent) {
1275                         g_sprintf(fmt, "%%%ds%%s%%s", indent*4-2);
1276                 }
1277                 else {
1278                         strcpy(fmt, "%s%s%s");
1279                 }
1280                 g_string_append_printf(s, fmt, "", indent?"- ":"", "Description");
1281                 g_string_append_printf(s, ": \"%s\"\n", values[0]);
1282
1283                 for (count = 1; count<num_columns; count++) {
1284                         if (*values[count]) {
1285                                 g_string_append_printf(s, fmt, "", indent?"  ":"",
1286                                                                                 stats_tree_get_column_name(count));
1287                                 g_string_append_printf(s, ": %s\n", values[count]);
1288                         }
1289                 }
1290                 if (node->children) {
1291                         g_string_append_printf(s, fmt, "", indent?"  ":"", "Items:\n");
1292                 }
1293                 break;
1294         case ST_FORMAT_XML:
1295                 {
1296                 char *itemname = xml_escape(values[0]);
1297                 g_string_append_printf(s,"<stat-node name=\"%s\"%s>\n",itemname,
1298                                 node->rng?" isrange=\"true\"":"");
1299                 g_free(itemname);
1300                 for (count = 1; count<num_columns; count++) {
1301                         gchar *colname= g_strdup(stats_tree_get_column_name(count));
1302                         g_string_append_printf(s,"<%s>",clean_for_xml_tag(colname));
1303                         g_string_append_printf(s,"%s</%s>\n",values[count],colname);
1304                         g_free(colname);
1305                 }
1306                 }
1307                 break;
1308         case ST_FORMAT_CSV:
1309                 g_string_append_printf(s,"%d,\"%s\",\"%s\"",indent,path,values[0]);
1310                 for (count = 1; count<num_columns; count++) {
1311                         g_string_append_printf(s,",%s",values[count]);
1312                 }
1313                 g_string_append (s,"\n");
1314                 break;
1315         case ST_FORMAT_PLAIN:
1316                 g_sprintf (fmt,"%%%ds%%-%us",indent,maxnamelen-indent);
1317                 g_string_append_printf(s,fmt,"",values[0]);
1318                 for (count = 1; count<num_columns; count++) {
1319                         g_sprintf (fmt," %%-%us",stats_tree_get_column_size(count)+1);
1320                         g_string_append_printf(s,fmt,values[count]);
1321                 }
1322                 g_string_append (s,"\n");
1323                 break;
1324         }
1325
1326         indent++;
1327         indent = indent > INDENT_MAX ? INDENT_MAX : indent;
1328         full_path= g_strdup_printf ("%s/%s",path,values[0]);
1329
1330         for (count = 0; count<num_columns; count++) {
1331                 g_free(values[count]);
1332         }
1333         g_free(values);
1334
1335         if (node->children) {
1336                 GArray *Children= g_array_new(FALSE,FALSE,sizeof(child));
1337                 for (child = node->children; child; child = child->next ) {
1338                         g_array_append_val(Children,child);
1339                 }
1340                 si.sort_column = sort_column;
1341                 si.sort_descending = sort_descending;
1342                 g_array_sort_with_data(Children,stat_node_array_sortcmp,&si);
1343                 for (count = 0; count<((int)Children->len); count++) {
1344                         stats_tree_format_node_as_str(g_array_index(Children,stat_node*,count), s, format_type,
1345                                         indent, full_path, maxnamelen, sort_column, sort_descending);
1346                 }
1347                 g_array_free(Children,FALSE);
1348         }
1349         g_free(full_path);
1350
1351         if (format_type==ST_FORMAT_XML) {
1352                 g_string_append(s,"</stat-node>\n");
1353         }
1354 }
1355
1356 /*
1357  * Editor modelines
1358  *
1359  * Local Variables:
1360  * c-basic-offset: 4
1361  * tab-width: 8
1362  * indent-tabs-mode: t
1363  * End:
1364  *
1365  * vi: ex: set shiftwidth=4 tabstop=8 noexpandtab:
1366  * :indentSize=4:tabSize=8:noTabs=false:
1367  */