aboutsummaryrefslogtreecommitdiffstats
path: root/tools/xenstat/xentop/xentop.c
blob: af9ebc86768c0e7841e5957ddc41b0a01aa217ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
/*
 *  Copyright (C) International Business Machines  Corp., 2005
 *  Author(s): Judy Fischbach <jfisch@cs.pdx.edu>
 *             David Hendricks <cro_marmot@comcast.net>
 *             Josh Triplett <josh@kernel.org>
 *    based on code from Anthony Liguori <aliguori@us.ibm.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; under version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#include <curses.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#if defined(__linux__)
#include <linux/kdev_t.h>
#endif

#include <xenstat.h>

#define XENTOP_VERSION "1.0"

#define XENTOP_DISCLAIMER \
"Copyright (C) 2005  International Business Machines  Corp\n"\
"This is free software; see the source for copying conditions.There is NO\n"\
"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
#define XENTOP_BUGSTO "Report bugs to <xen-tools@lists.xensource.com>.\n"

#define _GNU_SOURCE
#include <getopt.h>

#if !defined(__GNUC__) && !defined(__GNUG__)
#define __attribute__(arg) /* empty */
#endif

#define KEY_ESCAPE '\x1B'

#ifdef HOST_SunOS
/* Old curses library on Solaris takes non-const strings. Also, ERR interferes
 * with curse's definition.
 */
#undef ERR
#define ERR (-1)
#define curses_str_t char *
#else
#define curses_str_t const char *
#endif

/*
 * Function prototypes
 */
/* Utility functions */
static void usage(const char *);
static void version(void);
static void cleanup(void);
static void fail(const char *);
static int current_row(void);
static int lines(void);
static void print(const char *, ...) __attribute__((format(printf,1,2)));
static void attr_addstr(int attr, const char *str);
static void set_delay(char *value);
static void set_prompt(char *new_prompt, void (*func)(char *));
static int handle_key(int);
static int compare(unsigned long long, unsigned long long);
static int compare_domains(xenstat_domain **, xenstat_domain **);
static unsigned long long tot_net_bytes( xenstat_domain *, int);
static unsigned long long tot_vbd_reqs( xenstat_domain *, int);

/* Field functions */
static int compare_state(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_state(xenstat_domain *domain);
static int compare_cpu(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_cpu(xenstat_domain *domain);
static int compare_cpu_pct(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_cpu_pct(xenstat_domain *domain);
static int compare_mem(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_mem(xenstat_domain *domain);
static void print_mem_pct(xenstat_domain *domain);
static int compare_maxmem(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_maxmem(xenstat_domain *domain);
static void print_max_pct(xenstat_domain *domain);
static int compare_vcpus(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_vcpus(xenstat_domain *domain);
static int compare_nets(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_nets(xenstat_domain *domain);
static int compare_net_tx(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_net_tx(xenstat_domain *domain);
static int compare_net_rx(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_net_rx(xenstat_domain *domain);
static int compare_ssid(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_ssid(xenstat_domain *domain);
static int compare_name(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_name(xenstat_domain *domain);
static int compare_vbds(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_vbds(xenstat_domain *domain);
static int compare_vbd_oo(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_vbd_oo(xenstat_domain *domain);
static int compare_vbd_rd(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_vbd_rd(xenstat_domain *domain);
static int compare_vbd_wr(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_vbd_wr(xenstat_domain *domain);
static int compare_vbd_rsect(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_vbd_rsect(xenstat_domain *domain);
static int compare_vbd_wsect(xenstat_domain *domain1, xenstat_domain *domain2);
static void print_vbd_wsect(xenstat_domain *domain);


/* Section printing functions */
static void do_summary(void);
static void do_header(void);
static void do_bottom_line(void);
static void do_domain(xenstat_domain *);
static void do_vcpu(xenstat_domain *);
static void do_network(xenstat_domain *);
static void do_vbd(xenstat_domain *);
static void top(void);

/* Field types */
typedef enum field_id {
	FIELD_DOMID,
	FIELD_NAME,
	FIELD_STATE,
	FIELD_CPU,
	FIELD_CPU_PCT,
	FIELD_MEM,
	FIELD_MEM_PCT,
	FIELD_MAXMEM,
	FIELD_MAX_PCT,
	FIELD_VCPUS,
	FIELD_NETS,
	FIELD_NET_TX,
	FIELD_NET_RX,
	FIELD_VBDS,
	FIELD_VBD_OO,
	FIELD_VBD_RD,
	FIELD_VBD_WR,
	FIELD_VBD_RSECT,
	FIELD_VBD_WSECT,
	FIELD_SSID
} field_id;

typedef struct field {
	field_id num;
	const char *header;
	unsigned int default_width;
	int (*compare)(xenstat_domain *domain1, xenstat_domain *domain2);
	void (*print)(xenstat_domain *domain);
} field;

field fields[] = {
	{ FIELD_NAME,      "NAME",      10, compare_name,      print_name    },
	{ FIELD_STATE,     "STATE",      6, compare_state,     print_state   },
	{ FIELD_CPU,       "CPU(sec)",  10, compare_cpu,       print_cpu     },
	{ FIELD_CPU_PCT,   "CPU(%)",     6, compare_cpu_pct,   print_cpu_pct },
	{ FIELD_MEM,       "MEM(k)",    10, compare_mem,       print_mem     },
	{ FIELD_MEM_PCT,   "MEM(%)",     6, compare_mem,       print_mem_pct },
	{ FIELD_MAXMEM,    "MAXMEM(k)", 10, compare_maxmem,    print_maxmem  },
	{ FIELD_MAX_PCT,   "MAXMEM(%)",  9, compare_maxmem,    print_max_pct },
	{ FIELD_VCPUS,     "VCPUS",      5, compare_vcpus,     print_vcpus   },
	{ FIELD_NETS,      "NETS",       4, compare_nets,      print_nets    },
	{ FIELD_NET_TX,    "NETTX(k)",   8, compare_net_tx,    print_net_tx  },
	{ FIELD_NET_RX,    "NETRX(k)",   8, compare_net_rx,    print_net_rx  },
	{ FIELD_VBDS,      "VBDS",       4, compare_vbds,      print_vbds    },
	{ FIELD_VBD_OO,    "VBD_OO",     8, compare_vbd_oo,    print_vbd_oo  },
	{ FIELD_VBD_RD,    "VBD_RD",     8, compare_vbd_rd,    print_vbd_rd  },
	{ FIELD_VBD_WR,    "VBD_WR",     8, compare_vbd_wr,    print_vbd_wr  },
	{ FIELD_VBD_RSECT, "VBD_RSECT", 10, compare_vbd_rsect, print_vbd_rsect  },
	{ FIELD_VBD_WSECT, "VBD_WSECT", 10, compare_vbd_wsect, print_vbd_wsect  },
	{ FIELD_SSID,      "SSID",       4, compare_ssid,      print_ssid    }
};

const unsigned int NUM_FIELDS = sizeof(fields)/sizeof(field);

/* Globals */
struct timeval curtime, oldtime;
xenstat_handle *xhandle = NULL;
xenstat_node *prev_node = NULL;
xenstat_node *cur_node = NULL;
field_id sort_field = FIELD_DOMID;
unsigned int first_domain_index = 0;
unsigned int delay = 3;
unsigned int batch = 0;
unsigned int loop = 1;
unsigned int iterations = 0;
int show_vcpus = 0;
int show_networks = 0;
int show_vbds = 0;
int repeat_header = 0;
int show_full_name = 0;
#define PROMPT_VAL_LEN 80
char *prompt = NULL;
char prompt_val[PROMPT_VAL_LEN];
int prompt_val_len = 0;
void (*prompt_complete_func)(char *);

static WINDOW *cwin;

/*
 * Function definitions
 */

/* Utility functions */

/* Print usage message, using given program name */
static void usage(const char *program)
{
	printf("Usage: %s [OPTION]\n"
	       "Displays ongoing information about xen vm resources \n\n"
	       "-h, --help           display this help and exit\n"
	       "-V, --version        output version information and exit\n"
	       "-d, --delay=SECONDS  seconds between updates (default 3)\n"
	       "-n, --networks       output vif network data\n"
	       "-x, --vbds           output vbd block device data\n"
	       "-r, --repeat-header  repeat table header before each domain\n"
	       "-v, --vcpus          output vcpu data\n"
	       "-b, --batch	     output in batch mode, no user input accepted\n"
	       "-i, --iterations     number of iterations before exiting\n"
	       "-f, --full-name      output the full domain name (not truncated)\n"
	       "\n" XENTOP_BUGSTO,
	       program);
	return;
}

/* Print program version information */
static void version(void)
{
	printf("xentop " XENTOP_VERSION "\n"
	       "Written by Judy Fischbach, David Hendricks, Josh Triplett\n"
	       "\n" XENTOP_DISCLAIMER);
}

/* Clean up any open resources */
static void cleanup(void)
{
	if(cwin != NULL && !isendwin())
		endwin();
	if(prev_node != NULL)
		xenstat_free_node(prev_node);
	if(cur_node != NULL)
		xenstat_free_node(cur_node);
	if(xhandle != NULL)
		xenstat_uninit(xhandle);
}

/* Display the given message and gracefully exit */
static void fail(const char *str)
{
	if(cwin != NULL && !isendwin())
		endwin();
	fprintf(stderr, "%s", str);
	exit(1);
}

/* Return the row containing the cursor. */
static int current_row(void)
{
	int y, x;
	getyx(stdscr, y, x);
	return y;
}

/* Return the number of lines on the screen. */
static int lines(void)
{
	int y, x;
	getmaxyx(stdscr, y, x);
	return y;
}

/* printf-style print function which calls printw, but only if the cursor is
 * not on the last line. */
static void print(const char *fmt, ...)
{
	va_list args;

	if (!batch) {
		if((current_row() < lines()-1)) {
			va_start(args, fmt);
			vwprintw(stdscr, (curses_str_t)fmt, args);
			va_end(args);
		}
	} else {
		va_start(args, fmt);
		vprintf(fmt, args);
		va_end(args);
	}
}

static void xentop_attron(int attr)
{
	if (!batch)
		attron(attr);
}

static void xentop_attroff(int attr)
{
	if (!batch)
		attroff(attr);
}

/* Print a string with the given attributes set. */
static void attr_addstr(int attr, const char *str)
{
	xentop_attron(attr);
	addstr((curses_str_t)str);
	xentop_attroff(attr);
}

/* Handle setting the delay from the user-supplied value in prompt_val */
static void set_delay(char *value)
{
	int new_delay;
	new_delay = atoi(value);
	if(new_delay > 0)
		delay = new_delay;
}

/* Enable prompting mode with the given prompt string; call the given function
 * when a value is available. */
static void set_prompt(char *new_prompt, void (*func)(char *))
{
	prompt = new_prompt;
	prompt_val[0] = '\0';
	prompt_val_len = 0;
	prompt_complete_func = func;
}

/* Handle user input, return 0 if the program should quit, or 1 if not */
static int handle_key(int ch)
{
	if(prompt == NULL) {
		/* Not prompting for input; handle interactive commands */
		switch(ch) {
		case 'n': case 'N':
			show_networks ^= 1;
			break;
		case 'b': case 'B':
			show_vbds ^= 1;
			break;
		case 'r': case 'R':
			repeat_header ^= 1;
			break;
		case 's': case 'S':
			sort_field = (sort_field + 1) % NUM_FIELDS;
			break;
		case 'v': case 'V':
			show_vcpus ^= 1;
			break;
		case KEY_DOWN:
			first_domain_index++;
			break;
		case KEY_UP:
			if(first_domain_index > 0)
				first_domain_index--;
			break;
		case 'd': case 'D':
			set_prompt("Delay(sec)", set_delay);
			break;
		case 'q': case 'Q': case KEY_ESCAPE:
			return 0;
		}
	} else {
		/* Prompting for input; handle line editing */
		switch(ch) {
		case '\r':
			prompt_complete_func(prompt_val);
			set_prompt(NULL, NULL);
			break;
		case KEY_ESCAPE:
			set_prompt(NULL, NULL);
			break;
		case KEY_BACKSPACE:
			if(prompt_val_len > 0)
				prompt_val[--prompt_val_len] = '\0';
		default:
			if((prompt_val_len+1) < PROMPT_VAL_LEN
			   && isprint(ch)) {
				prompt_val[prompt_val_len++] = (char)ch;
				prompt_val[prompt_val_len] = '\0';
			}
		}
	}

	return 1;
}

/* Compares two integers, returning -1,0,1 for <,=,> */
static int compare(unsigned long long i1, unsigned long long i2)
{
	if(i1 < i2)
		return -1;
	if(i1 > i2)
		return 1;
	return 0;
}

/* Comparison function for use with qsort.  Compares two domains using the
 * current sort field. */
static int compare_domains(xenstat_domain **domain1, xenstat_domain **domain2)
{
	return fields[sort_field].compare(*domain1, *domain2);
}

/* Field functions */

/* Compare domain names, returning -1,0,1 for <,=,> */
int compare_name(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return strcasecmp(xenstat_domain_name(domain1), xenstat_domain_name(domain2));
}

/* Prints domain name */
void print_name(xenstat_domain *domain)
{
	if(show_full_name)
		print("%10s", xenstat_domain_name(domain));
	else
		print("%10.10s", xenstat_domain_name(domain));
}

struct {
	unsigned int (*get)(xenstat_domain *);
	char ch;
} state_funcs[] = {
	{ xenstat_domain_dying,    'd' },
	{ xenstat_domain_shutdown, 's' },
	{ xenstat_domain_blocked,  'b' },
	{ xenstat_domain_crashed,  'c' },
	{ xenstat_domain_paused,   'p' },
	{ xenstat_domain_running,  'r' }
};
const unsigned int NUM_STATES = sizeof(state_funcs)/sizeof(*state_funcs);

/* Compare states of two domains, returning -1,0,1 for <,=,> */
static int compare_state(xenstat_domain *domain1, xenstat_domain *domain2)
{
	unsigned int i, d1s, d2s;
	for(i = 0; i < NUM_STATES; i++) {
		d1s = state_funcs[i].get(domain1);
		d2s = state_funcs[i].get(domain2);
		if(d1s && !d2s)
			return -1;
		if(d2s && !d1s)
			return 1;
	}
	return 0;
}

/* Prints domain state in abbreviated letter format */
static void print_state(xenstat_domain *domain)
{
	unsigned int i;
	for(i = 0; i < NUM_STATES; i++)
		print("%c", state_funcs[i].get(domain) ? state_funcs[i].ch
		                                       : '-');
}

/* Compares cpu usage of two domains, returning -1,0,1 for <,=,> */
static int compare_cpu(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(xenstat_domain_cpu_ns(domain1),
			xenstat_domain_cpu_ns(domain2));
}

/* Prints domain cpu usage in seconds */
static void print_cpu(xenstat_domain *domain)
{
	print("%10llu", xenstat_domain_cpu_ns(domain)/1000000000);
}

/* Computes the CPU percentage used for a specified domain */
static double get_cpu_pct(xenstat_domain *domain)
{
	xenstat_domain *old_domain;
	double us_elapsed;

	/* Can't calculate CPU percentage without a previous sample. */
	if(prev_node == NULL)
		return 0.0;

	old_domain = xenstat_node_domain(prev_node, xenstat_domain_id(domain));
	if(old_domain == NULL)
		return 0.0;

	/* Calculate the time elapsed in microseconds */
	us_elapsed = ((curtime.tv_sec-oldtime.tv_sec)*1000000.0
		      +(curtime.tv_usec - oldtime.tv_usec));

	/* In the following, nanoseconds must be multiplied by 1000.0 to
	 * convert to microseconds, then divided by 100.0 to get a percentage,
	 * resulting in a multiplication by 10.0 */
	return ((xenstat_domain_cpu_ns(domain)
		 -xenstat_domain_cpu_ns(old_domain))/10.0)/us_elapsed;
}

static int compare_cpu_pct(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(get_cpu_pct(domain1), get_cpu_pct(domain2));
}

/* Prints cpu percentage statistic */
static void print_cpu_pct(xenstat_domain *domain)
{
	print("%6.1f", get_cpu_pct(domain));
}

/* Compares current memory of two domains, returning -1,0,1 for <,=,> */
static int compare_mem(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(xenstat_domain_cur_mem(domain1),
	                xenstat_domain_cur_mem(domain2));
}

/* Prints current memory statistic */
static void print_mem(xenstat_domain *domain)
{
	print("%10llu", xenstat_domain_cur_mem(domain)/1024);
}

/* Prints memory percentage statistic, ratio of current domain memory to total
 * node memory */
static void print_mem_pct(xenstat_domain *domain)
{
	print("%6.1f", (double)xenstat_domain_cur_mem(domain) /
	               (double)xenstat_node_tot_mem(cur_node) * 100);
}

/* Compares maximum memory of two domains, returning -1,0,1 for <,=,> */
static int compare_maxmem(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(xenstat_domain_max_mem(domain1),
	                xenstat_domain_max_mem(domain2));
}

/* Prints maximum domain memory statistic in KB */
static void print_maxmem(xenstat_domain *domain)
{
	unsigned long long max_mem = xenstat_domain_max_mem(domain);
	if(max_mem == ((unsigned long long)-1))
		print("%10s", "no limit");
	else
		print("%10llu", max_mem/1024);
}

/* Prints memory percentage statistic, ratio of current domain memory to total
 * node memory */
static void print_max_pct(xenstat_domain *domain)
{
	if (xenstat_domain_max_mem(domain) == (unsigned long long)-1)
		print("%9s", "n/a");
	else
		print("%9.1f", (double)xenstat_domain_max_mem(domain) /
		               (double)xenstat_node_tot_mem(cur_node) * 100);
}

/* Compares number of virtual CPUs of two domains, returning -1,0,1 for
 * <,=,> */
static int compare_vcpus(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(xenstat_domain_num_vcpus(domain1),
	                xenstat_domain_num_vcpus(domain2));
}

/* Prints number of virtual CPUs statistic */
static void print_vcpus(xenstat_domain *domain)
{
	print("%5u", xenstat_domain_num_vcpus(domain));
}

/* Compares number of virtual networks of two domains, returning -1,0,1 for
 * <,=,> */
static int compare_nets(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(xenstat_domain_num_networks(domain1),
	                xenstat_domain_num_networks(domain2));
}

/* Prints number of virtual networks statistic */
static void print_nets(xenstat_domain *domain)
{
	print("%4u", xenstat_domain_num_networks(domain));
}

/* Compares number of total network tx bytes of two domains, returning -1,0,1
 * for <,=,> */
static int compare_net_tx(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(tot_net_bytes(domain1, FALSE),
	                tot_net_bytes(domain2, FALSE));
}

/* Prints number of total network tx bytes statistic */
static void print_net_tx(xenstat_domain *domain)
{
	print("%8llu", tot_net_bytes(domain, FALSE)/1024);
}

/* Compares number of total network rx bytes of two domains, returning -1,0,1
 * for <,=,> */
static int compare_net_rx(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(tot_net_bytes(domain1, TRUE),
	                tot_net_bytes(domain2, TRUE));
}

/* Prints number of total network rx bytes statistic */
static void print_net_rx(xenstat_domain *domain)
{
	print("%8llu", tot_net_bytes(domain, TRUE)/1024);
}

/* Gets number of total network bytes statistic, if rx true, then rx bytes
 * otherwise tx bytes
 */
static unsigned long long tot_net_bytes(xenstat_domain *domain, int rx_flag)
{
	int i = 0;
	xenstat_network *network;
	unsigned num_networks = 0;
	unsigned long long total = 0;

	/* How many networks? */
	num_networks = xenstat_domain_num_networks(domain);

	/* Dump information for each network */
	for (i=0; i < num_networks; i++) {
		/* Next get the network information */
		network = xenstat_domain_network(domain,i);
		if (rx_flag)
			total += xenstat_network_rbytes(network);
		else
			total += xenstat_network_tbytes(network);
	}

	return total;
}

/* Compares number of virtual block devices of two domains,
   returning -1,0,1 for * <,=,> */
static int compare_vbds(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(xenstat_domain_num_vbds(domain1),
	                xenstat_domain_num_vbds(domain2));
}

/* Prints number of virtual block devices statistic */
static void print_vbds(xenstat_domain *domain)
{
	print("%4u", xenstat_domain_num_vbds(domain));
}

/* Compares number of total VBD OO requests of two domains,
   returning -1,0,1 * for <,=,> */
static int compare_vbd_oo(xenstat_domain *domain1, xenstat_domain *domain2)
{
  return -compare(tot_vbd_reqs(domain1, FIELD_VBD_OO),
		  tot_vbd_reqs(domain2, FIELD_VBD_OO));
}

/* Prints number of total VBD OO requests statistic */
static void print_vbd_oo(xenstat_domain *domain)
{
	print("%8llu", tot_vbd_reqs(domain, FIELD_VBD_OO));
}

/* Compares number of total VBD READ requests of two domains,
   returning -1,0,1 * for <,=,> */
static int compare_vbd_rd(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(tot_vbd_reqs(domain1, FIELD_VBD_RD),
			tot_vbd_reqs(domain2, FIELD_VBD_RD));
}

/* Prints number of total VBD READ requests statistic */
static void print_vbd_rd(xenstat_domain *domain)
{
	print("%8llu", tot_vbd_reqs(domain, FIELD_VBD_RD));
}

/* Compares number of total VBD WRITE requests of two domains,
   returning -1,0,1 * for <,=,> */
static int compare_vbd_wr(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(tot_vbd_reqs(domain1, FIELD_VBD_WR),
			tot_vbd_reqs(domain2, FIELD_VBD_WR));
}

/* Prints number of total VBD WRITE requests statistic */
static void print_vbd_wr(xenstat_domain *domain)
{
	print("%8llu", tot_vbd_reqs(domain, FIELD_VBD_WR));
}

/* Compares number of total VBD READ sectors of two domains,
   returning -1,0,1 * for <,=,> */
static int compare_vbd_rsect(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(tot_vbd_reqs(domain1, FIELD_VBD_RSECT),
			tot_vbd_reqs(domain2, FIELD_VBD_RSECT));
}

/* Prints number of total VBD READ sectors statistic */
static void print_vbd_rsect(xenstat_domain *domain)
{
	print("%10llu", tot_vbd_reqs(domain, FIELD_VBD_RSECT));
}

/* Compares number of total VBD WRITE sectors of two domains,
   returning -1,0,1 * for <,=,> */
static int compare_vbd_wsect(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return -compare(tot_vbd_reqs(domain1, FIELD_VBD_WSECT),
			tot_vbd_reqs(domain2, FIELD_VBD_WSECT));
}

/* Prints number of total VBD WRITE sectors statistic */
static void print_vbd_wsect(xenstat_domain *domain)
{
	print("%10llu", tot_vbd_reqs(domain, FIELD_VBD_WSECT));
}


/* Gets number of total VBD requests statistic, 
 *   if flag is FIELD_VBD_OO, then OO requests,
 *   if flag is FIELD_VBD_RD, then READ requests,
 *   if flag is FIELD_VBD_WR, then WRITE requests,
 *   if flag is FIELD_VBD_RSECT, then READ sectors,
 *   if flag is FIELD_VBD_WSECT, then WRITE sectors.
 */
static unsigned long long tot_vbd_reqs(xenstat_domain *domain, int flag)
{
	int i = 0;
	xenstat_vbd *vbd;
	unsigned num_vbds = 0;
	unsigned long long total = 0;
	
	num_vbds = xenstat_domain_num_vbds(domain);
	
	for ( i=0 ; i < num_vbds ; i++) {
		vbd = xenstat_domain_vbd(domain,i);
		switch(flag) {
		case FIELD_VBD_OO:
			total += xenstat_vbd_oo_reqs(vbd);
			break;
		case FIELD_VBD_RD:
			total += xenstat_vbd_rd_reqs(vbd);
			break;
		case FIELD_VBD_WR:
			total += xenstat_vbd_wr_reqs(vbd);
			break;
		case FIELD_VBD_RSECT:
			total += xenstat_vbd_rd_sects(vbd);
			break;
		case FIELD_VBD_WSECT:
			total += xenstat_vbd_wr_sects(vbd);
			break;
		default:
			break;
		}
	}
	
	return total;
}

/* Compares security id (ssid) of two domains, returning -1,0,1 for <,=,> */
static int compare_ssid(xenstat_domain *domain1, xenstat_domain *domain2)
{
	return compare(xenstat_domain_ssid(domain1),
		       xenstat_domain_ssid(domain2));
}

/* Prints ssid statistic */
static void print_ssid(xenstat_domain *domain)
{
	print("%4u", xenstat_domain_ssid(domain));
}

/* Section printing functions */
/* Prints the top summary, above the domain table */
void do_summary(void)
{
#define TIME_STR_LEN 9
	const char *TIME_STR_FORMAT = "%H:%M:%S";
	char time_str[TIME_STR_LEN];
	const char *ver_str;
	unsigned run = 0, block = 0, pause = 0,
	         crash = 0, dying = 0, shutdown = 0;
	unsigned i, num_domains = 0;
	unsigned long long used = 0;
	long freeable_mb = 0;
	xenstat_domain *domain;
	time_t curt;

	/* Print program name, current time, and number of domains */
	curt = curtime.tv_sec;
	strftime(time_str, TIME_STR_LEN, TIME_STR_FORMAT, localtime(&curt));
	num_domains = xenstat_node_num_domains(cur_node);
	ver_str = xenstat_node_xen_version(cur_node);
	print("xentop - %s   Xen %s\n", time_str, ver_str);

	/* Tabulate what states domains are in for summary */
	for (i=0; i < num_domains; i++) {
		domain = xenstat_node_domain_by_index(cur_node,i);
		if (xenstat_domain_running(domain)) run++;
		else if (xenstat_domain_blocked(domain)) block++;
		else if (xenstat_domain_paused(domain)) pause++;
		else if (xenstat_domain_shutdown(domain)) shutdown++;
		else if (xenstat_domain_crashed(domain)) crash++;
		else if (xenstat_domain_dying(domain)) dying++;
	}

	print("%u domains: %u running, %u blocked, %u paused, "
	      "%u crashed, %u dying, %u shutdown \n",
	      num_domains, run, block, pause, crash, dying, shutdown);

	used = xenstat_node_tot_mem(cur_node)-xenstat_node_free_mem(cur_node);
	freeable_mb = xenstat_node_freeable_mb(cur_node);

	/* Dump node memory and cpu information */
	if ( freeable_mb <= 0 )
	     print("Mem: %lluk total, %lluk used, %lluk free    ",
	      xenstat_node_tot_mem(cur_node)/1024, used/1024,
	      xenstat_node_free_mem(cur_node)/1024);
	else
	     print("Mem: %lluk total, %lluk used, %lluk free, %ldk freeable, ",
	      xenstat_node_tot_mem(cur_node)/1024, used/1024,
	      xenstat_node_free_mem(cur_node)/1024, freeable_mb*1024);
	print("CPUs: %u @ %lluMHz\n",
	      xenstat_node_num_cpus(cur_node),
	      xenstat_node_cpu_hz(cur_node)/1000000);
}

/* Display the top header for the domain table */
void do_header(void)
{
	field_id i;

	/* Turn on REVERSE highlight attribute for headings */
	xentop_attron(A_REVERSE);
	for(i = 0; i < NUM_FIELDS; i++) {
		if (i != 0)
			print(" ");
		/* The BOLD attribute is turned on for the sort column */
		if (i == sort_field)
			xentop_attron(A_BOLD);
		print("%*s", fields[i].default_width, fields[i].header);
		if (i == sort_field)
			xentop_attroff(A_BOLD);
	}
	xentop_attroff(A_REVERSE);
	print("\n");
}

/* Displays bottom status line or current prompt */
void do_bottom_line(void)
{
	move(lines()-1, 2);

	if (prompt != NULL) {
		printw("%s: %s", prompt, prompt_val);
	} else {
		addch(A_REVERSE | 'D'); addstr("elay  ");

		/* network */
		addch(A_REVERSE | 'N');
		attr_addstr(show_networks ? COLOR_PAIR(1) : 0, "etworks");
		addstr("  ");
		
		/* VBDs */
		attr_addstr(show_vbds ? COLOR_PAIR(1) : 0, "v");
		addch(A_REVERSE | 'B');
		attr_addstr(show_vbds ? COLOR_PAIR(1) : 0, "ds");
		addstr("  ");


		/* vcpus */
		addch(A_REVERSE | 'V');
		attr_addstr(show_vcpus ? COLOR_PAIR(1) : 0, "CPUs");
		addstr("  ");

		/* repeat */
		addch(A_REVERSE | 'R');
		attr_addstr(repeat_header ? COLOR_PAIR(1) : 0, "epeat header");
		addstr("  ");

		/* sort order */
		addch(A_REVERSE | 'S'); addstr("ort order  ");

		addch(A_REVERSE | 'Q'); addstr("uit  ");
	}
}

/* Prints Domain information */
void do_domain(xenstat_domain *domain)
{
	unsigned int i;
	for (i = 0; i < NUM_FIELDS; i++) {
		if (i != 0)
			print(" ");
		if (i == sort_field)
			xentop_attron(A_BOLD);
		fields[i].print(domain);
		if (i == sort_field)
			xentop_attroff(A_BOLD);
	}
	print("\n");
}

/* Output all vcpu information */
void do_vcpu(xenstat_domain *domain)
{
	int i = 0;
	unsigned num_vcpus = 0;
	xenstat_vcpu *vcpu;

	print("VCPUs(sec): ");

	num_vcpus = xenstat_domain_num_vcpus(domain);

	/* for all online vcpus dump out values */
	for (i=0; i< num_vcpus; i++) {
		vcpu = xenstat_domain_vcpu(domain,i);

		if (xenstat_vcpu_online(vcpu) > 0) {
			if (i != 0 && (i%5)==0)
				print("\n        ");
			print(" %2u: %10llus", i, 
					xenstat_vcpu_ns(vcpu)/1000000000);
		}
	}
	print("\n");
}

/* Output all network information */
void do_network(xenstat_domain *domain)
{
	int i = 0;
	xenstat_network *network;
	unsigned num_networks = 0;

	/* How many networks? */
	num_networks = xenstat_domain_num_networks(domain);

	/* Dump information for each network */
	for (i=0; i < num_networks; i++) {
		/* Next get the network information */
		network = xenstat_domain_network(domain,i);

		print("Net%d RX: %8llubytes %8llupkts %8lluerr %8lludrop  ",
		      i,
		      xenstat_network_rbytes(network),
		      xenstat_network_rpackets(network),
		      xenstat_network_rerrs(network),
		      xenstat_network_rdrop(network));

		print("TX: %8llubytes %8llupkts %8lluerr %8lludrop\n",
		      xenstat_network_tbytes(network),
		      xenstat_network_tpackets(network),
		      xenstat_network_terrs(network),
		      xenstat_network_tdrop(network));
	}
}


/* Output all VBD information */
void do_vbd(xenstat_domain *domain)
{
	int i = 0;
	xenstat_vbd *vbd;
	unsigned num_vbds = 0;

	const char *vbd_type[] = {
		"Unidentified",           /* number 0 */
		"BlkBack",           /* number 1 */
		"BlkTap",            /* number 2 */
	};
	
	num_vbds = xenstat_domain_num_vbds(domain);

	for (i=0 ; i< num_vbds; i++) {
		char details[20];

		vbd = xenstat_domain_vbd(domain,i);

#if !defined(__linux__)
		details[0] = '\0';
#else
		snprintf(details, 20, "[%2x:%2x] ",
			 MAJOR(xenstat_vbd_dev(vbd)),
			 MINOR(xenstat_vbd_dev(vbd)));
#endif

		print("VBD %s %4d %s OO: %8llu   RD: %8llu   WR: %8llu   RSECT: %10llu   WSECT: %10llu\n",
		      vbd_type[xenstat_vbd_type(vbd)],
		      xenstat_vbd_dev(vbd), details,
		      xenstat_vbd_oo_reqs(vbd),
		      xenstat_vbd_rd_reqs(vbd),
		      xenstat_vbd_wr_reqs(vbd),
		      xenstat_vbd_rd_sects(vbd),
		      xenstat_vbd_wr_sects(vbd));
	}
}

static void top(void)
{
	xenstat_domain **domains;
	unsigned int i, num_domains = 0;

	/* Now get the node information */
	if (prev_node != NULL)
		xenstat_free_node(prev_node);
	prev_node = cur_node;
	cur_node = xenstat_get_node(xhandle, XENSTAT_ALL);
	if (cur_node == NULL)
		fail("Failed to retrieve statistics from libxenstat\n");

	/* dump summary top information */
	if (!batch)
		do_summary();

	/* Count the number of domains for which to report data */
	num_domains = xenstat_node_num_domains(cur_node);

	domains = calloc(num_domains, sizeof(xenstat_domain *));
	if(domains == NULL)
		fail("Failed to allocate memory\n");

	for (i=0; i < num_domains; i++)
		domains[i] = xenstat_node_domain_by_index(cur_node, i);

	/* Sort */
	qsort(domains, num_domains, sizeof(xenstat_domain *),
	      (int(*)(const void *, const void *))compare_domains);

	if(first_domain_index >= num_domains)
		first_domain_index = num_domains-1;

	for (i = first_domain_index; i < num_domains; i++) {
		if(!batch && current_row() == lines()-1)
			break;
		if (i == first_domain_index || repeat_header)
			do_header();
		do_domain(domains[i]);
		if (show_vcpus)
			do_vcpu(domains[i]);
		if (show_networks)
			do_network(domains[i]);
		if (show_vbds)
			do_vbd(domains[i]);
	}

	if (!batch)
		do_bottom_line();

	free(domains);
}

static int signal_exit;

static void signal_exit_handler(int sig)
{
	signal_exit = 1;
}

int main(int argc, char **argv)
{
	int opt, optind = 0;
	int ch = ERR;

	struct option lopts[] = {
		{ "help",          no_argument,       NULL, 'h' },
		{ "version",       no_argument,       NULL, 'V' },
		{ "networks",      no_argument,       NULL, 'n' },
		{ "vbds",          no_argument,       NULL, 'x' },
		{ "repeat-header", no_argument,       NULL, 'r' },
		{ "vcpus",         no_argument,       NULL, 'v' },
		{ "delay",         required_argument, NULL, 'd' },
		{ "batch",	   no_argument,	      NULL, 'b' },
		{ "iterations",	   required_argument, NULL, 'i' },
		{ "full-name",     no_argument,       NULL, 'f' },
		{ 0, 0, 0, 0 },
	};
	const char *sopts = "hVnxrvd:bi:f";

	if (atexit(cleanup) != 0)
		fail("Failed to install cleanup handler.\n");

	while ((opt = getopt_long(argc, argv, sopts, lopts, &optind)) != -1) {
		switch (opt) {
		default:
			usage(argv[0]);
			exit(1);
		case '?':
		case 'h':
			usage(argv[0]);
			exit(0);
		case 'V':
			version();
			exit(0);
		case 'n':
			show_networks = 1;
			break;
		case 'x':
			show_vbds = 1;
			break;
		case 'r':
			repeat_header = 1;
			break;
		case 'v':
			show_vcpus = 1;
			break;
		case 'd':
			delay = atoi(optarg);
			break;
		case 'b':
			batch = 1;
			break;
		case 'i':
			iterations = atoi(optarg);
			loop = 0;
			break;
		case 'f':
			show_full_name = 1;
			break;
		}
	}

	/* Get xenstat handle */
	xhandle = xenstat_init();
	if (xhandle == NULL)
		fail("Failed to initialize xenstat library\n");

	if (!batch) {
		/* Begin curses stuff */
		cwin = initscr();
		start_color();
		cbreak();
		noecho();
		nonl();
		keypad(stdscr, TRUE);
		halfdelay(5);
#ifndef __sun__
		use_default_colors();
#endif
		init_pair(1, -1, COLOR_YELLOW);

		do {
			gettimeofday(&curtime, NULL);
			if(ch != ERR || (curtime.tv_sec - oldtime.tv_sec) >= delay) {
				clear();
				top();
				oldtime = curtime;
				refresh();
				if ((!loop) && !(--iterations))
					break;
			}
			ch = getch();
		} while (handle_key(ch));
	} else {
		struct sigaction sa = {
			.sa_handler = signal_exit_handler,
			.sa_flags = 0
		};
		sigemptyset(&sa.sa_mask);
		sigaction(SIGINT, &sa, NULL);
		sigaction(SIGTERM, &sa, NULL);

		do {
			gettimeofday(&curtime, NULL);
			top();
			fflush(stdout);
			oldtime = curtime;
			if ((!loop) && !(--iterations))
				break;
			sleep(delay);
		} while (!signal_exit);
	}

	/* Cleanup occurs in cleanup(), so no work to do here. */

	return 0;
}