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 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
|
/*
* sadc: system activity data collector
* (C) 1999-2016 by Sebastien GODARD (sysstat <at> orange.fr)
*
***************************************************************************
* 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; either version 2 of the License, or (at your *
* option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without 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., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA *
***************************************************************************
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <dirent.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include "version.h"
#include "sa.h"
#include "rd_stats.h"
#include "common.h"
#include "ioconf.h"
#ifdef USE_NLS
#include <locale.h>
#include <libintl.h>
#define _(string) gettext(string)
#else
#define _(string) (string)
#endif
#ifdef HAVE_SENSORS
#include "sensors/sensors.h"
#include "sensors/error.h"
#endif
long interval = 0;
unsigned int flags = 0;
int dis;
int optz = 0;
char timestamp[2][TIMESTAMP_LEN];
struct file_header file_hdr;
struct record_header record_hdr;
char comment[MAX_COMMENT_LEN];
unsigned int id_seq[NR_ACT];
unsigned int vol_id_seq[NR_ACT];
extern struct activity *act[];
extern __nr_t (*f_count[]) (struct activity *);
struct sigaction alrm_act, int_act;
int sigint_caught = 0;
/*
***************************************************************************
* Print usage and exit.
*
* IN:
* @progname Name of sysstat command
***************************************************************************
*/
void usage(char *progname)
{
fprintf(stderr, _("Usage: %s [ options ] [ <interval> [ <count> ] ] [ <outfile> ]\n"),
progname);
fprintf(stderr, _("Options are:\n"
"[ -C <comment> ] [ -D ] [ -F ] [ -L ] [ -V ]\n"
"[ -S { INT | DISK | IPV6 | POWER | SNMP | XDISK | ALL | XALL } ]\n"));
exit(1);
}
/*
***************************************************************************
* Collect all activities belonging to a group.
*
* IN:
* @group_id Group identification number.
* @opt_f Optionnal flag to set.
***************************************************************************
*/
void collect_group_activities(unsigned int group_id, unsigned int opt_f)
{
int i;
for (i = 0; i < NR_ACT; i++) {
if (act[i]->group & group_id) {
act[i]->options |= AO_COLLECTED;
if (opt_f) {
act[i]->opt_flags |= opt_f;
}
}
}
}
/*
***************************************************************************
* Parse option -S, indicating which activities are to be collected.
*
* IN:
* @argv Arguments list.
* @opt Index in list of arguments.
***************************************************************************
*/
void parse_sadc_S_option(char *argv[], int opt)
{
char *p;
int i;
for (p = strtok(argv[opt], ","); p; p = strtok(NULL, ",")) {
if (!strcmp(p, K_INT)) {
/* Select group of interrupt activities */
collect_group_activities(G_INT, AO_F_NULL);
}
else if (!strcmp(p, K_DISK)) {
/* Select group of disk activities */
collect_group_activities(G_DISK, AO_F_NULL);
}
else if (!strcmp(p, K_XDISK)) {
/* Select group of disk and partition/filesystem activities */
collect_group_activities(G_DISK + G_XDISK, AO_F_DISK_PART);
}
else if (!strcmp(p, K_SNMP)) {
/* Select group of SNMP activities */
collect_group_activities(G_SNMP, AO_F_NULL);
}
else if (!strcmp(p, K_IPV6)) {
/* Select group of IPv6 activities */
collect_group_activities(G_IPV6, AO_F_NULL);
}
else if (!strcmp(p, K_POWER)) {
/* Select group of activities related to power management */
collect_group_activities(G_POWER, AO_F_NULL);
}
else if (!strcmp(p, K_ALL) || !strcmp(p, K_XALL)) {
/* Select all activities */
for (i = 0; i < NR_ACT; i++) {
if (!strcmp(p, K_ALL) && (act[i]->group & G_XDISK))
/*
* Don't select G_XDISK activities
* when option -S ALL is used.
*/
continue;
act[i]->options |= AO_COLLECTED;
}
if (!strcmp(p, K_XALL)) {
/* Tell sadc to also collect partition statistics */
collect_group_activities(G_DISK + G_XDISK, AO_F_DISK_PART);
}
}
else if (strspn(p, DIGITS) == strlen(p)) {
/*
* Although undocumented, option -S followed by a numerical value
* enables the user to select each activity that should be
* collected. "-S 0" unselects all activities but CPU.
* A value greater than 255 enables the user to select groups
* of activities.
*/
int act_id;
act_id = atoi(p);
if (act_id > 255) {
act_id >>= 8;
for (i = 0; i < NR_ACT; i++) {
if (act[i]->group & act_id) {
act[i]->options |= AO_COLLECTED;
}
}
}
else if ((act_id < 0) || (act_id > NR_ACT)) {
usage(argv[0]);
}
else if (!act_id) {
/* Unselect all activities but CPU */
for (i = 0; i < NR_ACT; i++) {
act[i]->options &= ~AO_COLLECTED;
}
COLLECT_ACTIVITY(A_CPU);
}
else {
/* Select chosen activity */
COLLECT_ACTIVITY(act_id);
}
}
else {
usage(argv[0]);
}
}
}
/*
***************************************************************************
* SIGALRM signal handler. No need to reset handler here.
*
* IN:
* @sig Signal number.
***************************************************************************
*/
void alarm_handler(int sig)
{
alarm(interval);
}
/*
***************************************************************************
* SIGINT signal handler.
*
* IN:
* @sig Signal number.
***************************************************************************
*/
void int_handler(int sig)
{
pid_t ppid = getppid();
sigint_caught = 1;
if (!optz || (ppid == 1)) {
/* sadc hasn't been called by sar or sar process is already dead */
exit(1);
}
/*
* When starting sar then pressing ctrl/c, SIGINT is received
* by sadc, not sar. So send SIGINT to sar so that average stats
* can be displayed.
*/
if (kill(ppid, SIGINT) < 0) {
exit(1);
}
}
/*
***************************************************************************
* Display an error message.
***************************************************************************
*/
void p_write_error(void)
{
fprintf(stderr, _("Cannot write data to system activity file: %s\n"),
strerror(errno));
exit(2);
}
/*
***************************************************************************
* Init structures. All of them are init'ed first when they are allocated
* (done by SREALLOC() macro in sa_sys_init() function).
* Then, they are init'ed again each time before reading the various system
* stats to make sure that no stats from a previous reading will remain (eg.
* if some network interfaces or block devices have been unregistered).
***************************************************************************
*/
void reset_stats(void)
{
int i;
for (i = 0; i < NR_ACT; i++) {
if ((act[i]->nr > 0) && act[i]->_buf0) {
memset(act[i]->_buf0, 0,
(size_t) act[i]->msize * (size_t) act[i]->nr * (size_t) act[i]->nr2);
}
}
}
/*
***************************************************************************
* Allocate and init structures, according to system state.
***************************************************************************
*/
void sa_sys_init(void)
{
int i, idx;
__nr_t f_count_results[NR_F_COUNT];
/* Init array. Means that no items have been counted yet */
for (i = 0; i < NR_F_COUNT; i++) {
f_count_results[i] = -1;
}
for (i = 0; i < NR_ACT; i++) {
idx = act[i]->f_count_index;
if (idx >= 0) {
/* Number of items is not a constant and should be calculated */
if (f_count_results[idx] >= 0) {
act[i]->nr = f_count_results[idx];
}
else {
act[i]->nr = (f_count[idx])(act[i]);
f_count_results[idx] = act[i]->nr;
}
}
if (act[i]->nr > 0) {
if (act[i]->f_count2) {
act[i]->nr2 = (*act[i]->f_count2)(act[i]);
}
/* else act[i]->nr2 is a constant and doesn't need to be calculated */
if (!act[i]->nr2) {
act[i]->nr = 0;
}
}
if (act[i]->nr > 0) {
/* Allocate structures for current activity */
SREALLOC(act[i]->_buf0, void,
(size_t) act[i]->msize * (size_t) act[i]->nr * (size_t) act[i]->nr2);
}
else {
/* No items found: Invalidate current activity */
act[i]->options &= ~AO_COLLECTED;
}
/* Set default activity list */
id_seq[i] = act[i]->id;
}
}
/*
***************************************************************************
* Free structures.
***************************************************************************
*/
void sa_sys_free(void)
{
int i;
for (i = 0; i < NR_ACT; i++) {
if (act[i]->nr > 0) {
if (act[i]->_buf0) {
free(act[i]->_buf0);
act[i]->_buf0 = NULL;
}
}
}
}
/*
***************************************************************************
* Write data to file. If the write() call was interrupted by a signal, try
* again so that the whole buffer can be written.
*
* IN:
* @fd Output file descriptor.
* @buf Data buffer.
* @nr_bytes Number of bytes to write.
*
* RETURNS:
* Number of bytes written to file, or -1 on error.
***************************************************************************
*/
int write_all(int fd, const void *buf, int nr_bytes)
{
int block, offset = 0;
char *buffer = (char *) buf;
while (nr_bytes > 0) {
block = write(fd, &buffer[offset], nr_bytes);
if (block < 0) {
if (errno == EINTR)
continue;
return block;
}
if (block == 0)
return offset;
offset += block;
nr_bytes -= block;
}
return offset;
}
/*
***************************************************************************
* If -L option used, request a non-blocking, exclusive lock on the file.
* If lock would block, then another process (possibly sadc) has already
* opened that file => exit.
*
* IN:
* @fd Output file descriptor.
* @fatal Indicate if failing to lock file should be fatal or not.
* If it's not fatal then we'll wait for next iteration and
* try again.
*
* RETURNS:
* 0 on success, or 1 if file couldn't be locked.
***************************************************************************
*/
int ask_for_flock(int fd, int fatal)
{
/* Option -L may be used only if an outfile was specified on the command line */
if (LOCK_FILE(flags)) {
/*
* Yes: Try to lock file. To make code portable, check for both EWOULDBLOCK
* and EAGAIN return codes, and treat them the same (glibc documentation).
* Indeed, some Linux ports (e.g. hppa-linux) do not equate EWOULDBLOCK and
* EAGAIN like every other Linux port.
*/
if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
if ((((errno == EWOULDBLOCK) || (errno == EAGAIN)) && (fatal == FATAL)) ||
((errno != EWOULDBLOCK) && (errno != EAGAIN))) {
perror("flock");
exit(1);
}
/* Was unable to lock file: Lock would have blocked... */
return 1;
}
else {
/* File successfully locked */
flags |= S_F_FILE_LOCKED;
}
}
return 0;
}
/*
***************************************************************************
* Fill system activity file magic header.
*
* IN:
* @file_magic System activity file magic header.
***************************************************************************
*/
void fill_magic_header(struct file_magic *file_magic)
{
memset(file_magic, 0, FILE_MAGIC_SIZE);
file_magic->header_size = FILE_HEADER_SIZE;
file_magic->sysstat_magic = SYSSTAT_MAGIC;
file_magic->format_magic = FORMAT_MAGIC;
enum_version_nr(file_magic);
}
/*
***************************************************************************
* Fill system activity file header, then write it (or print it if stdout).
*
* IN:
* @fd Output file descriptor. May be stdout.
***************************************************************************
*/
void setup_file_hdr(int fd)
{
int i, p;
struct tm rectime;
struct utsname header;
struct file_magic file_magic;
struct file_activity file_act;
/* Fill then write file magic header */
fill_magic_header(&file_magic);
if (write_all(fd, &file_magic, FILE_MAGIC_SIZE) != FILE_MAGIC_SIZE)
goto write_error;
/* First reset the structure */
memset(&file_hdr, 0, FILE_HEADER_SIZE);
/* Then get current date */
file_hdr.sa_ust_time = get_time(&rectime, 0);
/* OK, now fill the header */
file_hdr.sa_act_nr = get_activity_nr(act, AO_COLLECTED, COUNT_ACTIVITIES);
file_hdr.sa_vol_act_nr = get_activity_nr(act, AO_COLLECTED + AO_VOLATILE,
COUNT_ACTIVITIES);
file_hdr.sa_day = rectime.tm_mday;
file_hdr.sa_month = rectime.tm_mon;
file_hdr.sa_year = rectime.tm_year;
file_hdr.sa_sizeof_long = sizeof(long);
/*
* This is a new file (or stdout): Field sa_last_cpu_nr is set to the number
* of CPU items of the machine (1 .. CPU_NR + 1).
* A_CPU activity is always collected, hence its number of items is
* always counted (in sa_sys_init()).
*/
file_hdr.sa_last_cpu_nr = act[get_activity_position(act, A_CPU, EXIT_IF_NOT_FOUND)]->nr;
/* Get system name, release number, hostname and machine architecture */
uname(&header);
strncpy(file_hdr.sa_sysname, header.sysname, UTSNAME_LEN);
file_hdr.sa_sysname[UTSNAME_LEN - 1] = '\0';
strncpy(file_hdr.sa_nodename, header.nodename, UTSNAME_LEN);
file_hdr.sa_nodename[UTSNAME_LEN - 1] = '\0';
strncpy(file_hdr.sa_release, header.release, UTSNAME_LEN);
file_hdr.sa_release[UTSNAME_LEN - 1] = '\0';
strncpy(file_hdr.sa_machine, header.machine, UTSNAME_LEN);
file_hdr.sa_machine[UTSNAME_LEN - 1] = '\0';
/* Write file header */
if (write_all(fd, &file_hdr, FILE_HEADER_SIZE) != FILE_HEADER_SIZE)
goto write_error;
/* Write activity list */
for (i = 0; i < NR_ACT; i++) {
/*
* Activity sequence given by id_seq array.
* Sequence must be the same for stdout as for output file.
*/
if (!id_seq[i])
continue;
if ((p = get_activity_position(act, id_seq[i], RESUME_IF_NOT_FOUND)) < 0)
continue;
if (IS_COLLECTED(act[p]->options)) {
file_act.id = act[p]->id;
file_act.magic = act[p]->magic;
file_act.nr = act[p]->nr;
file_act.nr2 = act[p]->nr2;
file_act.size = act[p]->fsize;
if (write_all(fd, &file_act, FILE_ACTIVITY_SIZE)
!= FILE_ACTIVITY_SIZE)
goto write_error;
/* Create sequence of volatile activities */
if (IS_VOLATILE(act[p]->options)) {
vol_id_seq[i] = act[p]->id;
}
}
}
return;
write_error:
fprintf(stderr, _("Cannot write system activity file header: %s\n"),
strerror(errno));
exit(2);
}
/*
***************************************************************************
* Write the volatile activity structures following each restart mark.
* sa_vol_act_nr structures have to be written.
* Note that volatile activities written after the restart marks may be
* different within the same file if different versions of sysstat have been
* used to create the file and then to append data to it.
*
* IN:
* @ofd Output file descriptor.
***************************************************************************
*/
void write_vol_act_structures(int ofd)
{
struct file_activity file_act;
int i, p;
memset(&file_act, 0, FILE_ACTIVITY_SIZE);
for (i = 0; i < file_hdr.sa_vol_act_nr; i++) {
if (!vol_id_seq[i]) {
/*
* Write an empty structure when current sysstat
* version knows fewer volatile activities than
* the number saved in file's header.
*/
file_act.id = file_act.nr = 0;
}
else {
p = get_activity_position(act, vol_id_seq[i], EXIT_IF_NOT_FOUND);
/*
* All the fields in file_activity structure are not used.
* In particular, act[p]->nr2 is left unmodified.
*/
file_act.id = act[p]->id;
file_act.nr = act[p]->nr;
}
if (write_all(ofd, &file_act, FILE_ACTIVITY_SIZE) != FILE_ACTIVITY_SIZE) {
p_write_error();
}
}
}
/*
***************************************************************************
* sadc called with interval and count parameters not set:
* Write a dummy record notifying a system restart, or insert a comment in
* binary data file if option -C has been used.
* Writing a dummy record should typically be done at boot time,
* before the cron daemon is started to avoid conflict with sa1/sa2 scripts.
*
* IN:
* @ofd Output file descriptor.
* @rtype Record type to write (dummy or comment).
***************************************************************************
*/
void write_special_record(int ofd, int rtype)
{
struct tm rectime = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL};
/* Check if file is locked */
if (!FILE_LOCKED(flags)) {
ask_for_flock(ofd, FATAL);
}
/* Reset the structure (not compulsory, but a bit cleaner) */
memset(&record_hdr, 0, RECORD_HEADER_SIZE);
/* Set record type */
record_hdr.record_type = rtype;
/* Save time */
record_hdr.ust_time = get_time(&rectime, 0);
record_hdr.hour = rectime.tm_hour;
record_hdr.minute = rectime.tm_min;
record_hdr.second = rectime.tm_sec;
/* Write record now */
if (write_all(ofd, &record_hdr, RECORD_HEADER_SIZE) != RECORD_HEADER_SIZE) {
p_write_error();
}
if (rtype == R_RESTART) {
/* Also write the volatile activities structures */
write_vol_act_structures(ofd);
}
else if (rtype == R_COMMENT) {
/* Also write the comment */
if (write_all(ofd, comment, MAX_COMMENT_LEN) != MAX_COMMENT_LEN) {
p_write_error();
}
}
}
/*
***************************************************************************
* Write stats (or print them if stdout).
*
* IN:
* @ofd Output file descriptor. May be stdout.
***************************************************************************
*/
void write_stats(int ofd)
{
int i, p;
/* Try to lock file */
if (!FILE_LOCKED(flags)) {
if (ask_for_flock(ofd, NON_FATAL))
/*
* Unable to lock file:
* Wait for next iteration to try again to save data.
*/
return;
}
/* Write record header */
if (write_all(ofd, &record_hdr, RECORD_HEADER_SIZE) != RECORD_HEADER_SIZE) {
p_write_error();
}
/* Then write all statistics */
for (i = 0; i < NR_ACT; i++) {
if (!id_seq[i])
continue;
if ((p = get_activity_position(act, id_seq[i], RESUME_IF_NOT_FOUND)) < 0)
continue;
if (IS_COLLECTED(act[p]->options)) {
if (write_all(ofd, act[p]->_buf0, act[p]->fsize * act[p]->nr * act[p]->nr2) !=
(act[p]->fsize * act[p]->nr * act[p]->nr2)) {
p_write_error();
}
}
}
}
/*
***************************************************************************
* Rewrite file's header. Done when number of CPU has changed.
*
* IN:
* @ofd Output file descriptor.
* @fpos Position in file where header structure has to be written.
* @file_magic File magic structure.
***************************************************************************
*/
void rewrite_file_hdr(int *ofd, off_t fpos, struct file_magic *file_magic)
{
int n;
/* Remove O_APPEND status flag */
if (fcntl(*ofd, F_SETFL, 0) < 0) {
perror("fcntl");
exit(2);
}
/* Now rewrite file's header with its new CPU number value */
if (lseek(*ofd, fpos, SEEK_SET) < fpos) {
perror("lseek");
exit(2);
}
n = MINIMUM(file_magic->header_size, FILE_HEADER_SIZE);
if (write_all(*ofd, &file_hdr, n) != n) {
p_write_error();
}
/* Restore O_APPEND status flag */
if (fcntl(*ofd, F_SETFL, O_APPEND) < 0) {
perror("fcntl");
exit(2);
}
}
/*
***************************************************************************
* Create a system activity daily data file.
*
* IN:
* @ofile Name of output file.
*
* OUT:
* @ofd Output file descriptor.
***************************************************************************
*/
void create_sa_file(int *ofd, char *ofile)
{
if ((*ofd = open(ofile, O_CREAT | O_WRONLY,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0) {
fprintf(stderr, _("Cannot open %s: %s\n"), ofile, strerror(errno));
exit(2);
}
/* Try to lock file */
ask_for_flock(*ofd, FATAL);
/* Truncate file */
if (ftruncate(*ofd, 0) < 0) {
fprintf(stderr, _("Cannot open %s: %s\n"), ofile, strerror(errno));
exit(2);
}
/* Write file header */
setup_file_hdr(*ofd);
}
/*
***************************************************************************
* Get descriptor for stdout.
*
* IN:
* @stdfd A value >= 0 indicates that stats data should also
* be written to stdout.
*
* OUT:
* @stdfd Stdout file descriptor.
***************************************************************************
*/
void open_stdout(int *stdfd)
{
if (*stdfd >= 0) {
if ((*stdfd = dup(STDOUT_FILENO)) < 0) {
perror("dup");
exit(4);
}
/* Write file header on STDOUT */
setup_file_hdr(*stdfd);
}
}
/*
***************************************************************************
* Get descriptor for output file and write its header.
* We may enter this function several times (when we rotate a file).
*
* IN:
* @ofile Name of output file.
* @restart_mark TRUE if sadc called with interval (and count) not
* set, and no comment given (so we are going to insert
* a restart mark into the file).
*
* OUT:
* @ofd Output file descriptor.
***************************************************************************
*/
void open_ofile(int *ofd, char ofile[], int restart_mark)
{
struct file_magic file_magic;
struct file_activity file_act[NR_ACT];
struct tm rectime = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL};
void *buffer = NULL;
ssize_t sz, n;
off_t fpos;
int i, j, p;
if (!ofile[0])
return;
/* Try to open file and check that data can be appended to it */
if ((*ofd = open(ofile, O_APPEND | O_RDWR)) < 0) {
if (errno == ENOENT) {
/* File doesn't exist: Create it */
create_sa_file(ofd, ofile);
return;
}
fprintf(stderr, _("Cannot open %s: %s\n"), ofile, strerror(errno));
exit(2);
}
/* Read file magic header */
sz = read(*ofd, &file_magic, FILE_MAGIC_SIZE);
if (!sz) {
close(*ofd);
/* This is an empty file: Create it again */
create_sa_file(ofd, ofile);
return;
}
if ((sz != FILE_MAGIC_SIZE) ||
(file_magic.sysstat_magic != SYSSTAT_MAGIC) ||
(file_magic.format_magic != FORMAT_MAGIC) ||
(file_magic.header_size > MAX_FILE_HEADER_SIZE)) {
if (FORCE_FILE(flags)) {
close(*ofd);
/* -F option used: Truncate file */
create_sa_file(ofd, ofile);
return;
}
/* Display error message and exit */
handle_invalid_sa_file(ofd, &file_magic, ofile, sz);
}
SREALLOC(buffer, char, file_magic.header_size);
/*
* Save current file position.
* Needed later to update sa_last_cpu_nr.
*/
if ((fpos = lseek(*ofd, 0, SEEK_CUR)) < 0) {
perror("lseek");
exit(2);
}
/* Read file standard header */
n = read(*ofd, buffer, file_magic.header_size);
memcpy(&file_hdr, buffer, MINIMUM(file_magic.header_size, FILE_HEADER_SIZE));
free(buffer);
if (n != file_magic.header_size) {
/* Display error message and exit */
handle_invalid_sa_file(ofd, &file_magic, ofile, 0);
}
/*
* If we are using the standard daily data file (file specified
* as "-" on the command line) and it is from a past month,
* then overwrite (truncate) it.
*/
get_time(&rectime, 0);
if (((file_hdr.sa_month != rectime.tm_mon) ||
(file_hdr.sa_year != rectime.tm_year)) &&
WANT_SA_ROTAT(flags)) {
close(*ofd);
create_sa_file(ofd, ofile);
return;
}
/* OK: It's a true system activity file */
if (!file_hdr.sa_act_nr || (file_hdr.sa_act_nr > NR_ACT) ||
(file_hdr.sa_vol_act_nr > NR_ACT))
/*
* No activities at all or at least one unknown activity,
* or too many volatile activities:
* Cannot append data to such a file.
*/
goto append_error;
for (i = 0; i < file_hdr.sa_act_nr; i++) {
/* Read current activity in list */
if (read(*ofd, &file_act[i], FILE_ACTIVITY_SIZE) != FILE_ACTIVITY_SIZE) {
handle_invalid_sa_file(ofd, &file_magic, ofile, 0);
}
p = get_activity_position(act, file_act[i].id, RESUME_IF_NOT_FOUND);
if ((p < 0) || (act[p]->fsize != file_act[i].size) ||
(act[p]->magic != file_act[i].magic))
/*
* Unknown activity in list or item size has changed or
* unknown activity format: Cannot append data to such a file.
*/
goto append_error;
if ((file_act[i].nr <= 0) || (file_act[i].nr2 <= 0) ||
(file_act[i].nr > act[p]->nr_max) ||
(file_act[i].nr2 > NR2_MAX)) {
/*
* Number of items and subitems should never be zero (or negative)
* or greater than their upper limit.
*/
goto append_error;
}
}
/*
* OK: (Almost) all tests successfully passed.
* List of activities from the file prevails over that of the user.
* So unselect all of them. And reset activity sequence.
*/
for (i = 0; i < NR_ACT; i++) {
act[i]->options &= ~AO_COLLECTED;
id_seq[i] = 0;
}
j = 0;
for (i = 0; i < file_hdr.sa_act_nr; i++) {
p = get_activity_position(act, file_act[i].id, EXIT_IF_NOT_FOUND);
/*
* Force number of items (serial lines, network interfaces...)
* and sub-items to that of the file, and reallocate structures.
* Exceptions are volatile activities, for which number of items
* is kept unmodified unless its value was zero (in this case,
* it is also forced to the value of the file).
* Also keep in mind that the file cannot contain more than
* sa_vol_act_nr volatile activities.
*/
if (!IS_VOLATILE(act[p]->options) || !act[p]->nr || (j >= file_hdr.sa_vol_act_nr)) {
act[p]->nr = file_act[i].nr;
}
else {
vol_id_seq[j++] = file_act[i].id;
}
act[p]->nr2 = file_act[i].nr2;
SREALLOC(act[p]->_buf0, void,
(size_t) act[p]->msize * (size_t) act[p]->nr * (size_t) act[p]->nr2);
/* Save activity sequence */
id_seq[i] = file_act[i].id;
act[p]->options |= AO_COLLECTED;
}
while (j < file_hdr.sa_vol_act_nr) {
vol_id_seq[j++] = 0;
}
p = get_activity_position(act, A_CPU, EXIT_IF_NOT_FOUND);
if (!IS_COLLECTED(act[p]->options)) {
/* A_CPU activity should always exist in file */
goto append_error;
}
if (act[p]->nr != file_hdr.sa_last_cpu_nr) {
if (restart_mark) {
/*
* We are inserting a restart mark, and current machine
* has a different number of CPU than that saved in file,
* so update sa_last_cpu_nr in file's header and rewrite it.
*/
file_hdr.sa_last_cpu_nr = act[p]->nr;
rewrite_file_hdr(ofd, fpos, &file_magic);
}
else {
/*
* Current number of cpu items (for current system)
* doesn't match number of cpu items of the last sample
* saved in file.
*/
goto append_error;
}
}
return;
append_error:
close(*ofd);
if (FORCE_FILE(flags)) {
/* Truncate file */
create_sa_file(ofd, ofile);
}
else {
fprintf(stderr, _("Cannot append data to that file (%s)\n"), ofile);
exit(1);
}
}
/*
***************************************************************************
* Read statistics from various system files.
***************************************************************************
*/
void read_stats(void)
{
int i;
__nr_t cpu_nr = act[get_activity_position(act, A_CPU, EXIT_IF_NOT_FOUND)]->nr;
/*
* Init uptime0. So if /proc/uptime cannot fill it,
* this will be done by /proc/stat.
* If cpu_nr = 2, force /proc/stat to fill it.
* If cpu_nr = 1, uptime0 and uptime are equal.
* NB: uptime0 is always filled.
* Remember that cpu_nr = 1 means one CPU and no SMP kernel
* (one structure for CPU "all") and cpu_nr = 2 means one CPU
* and an SMP kernel (two structures for CPUs "all" and "0").
*/
record_hdr.uptime0 = 0;
if (cpu_nr > 2) {
read_uptime(&(record_hdr.uptime0));
}
for (i = 0; i < NR_ACT; i++) {
if (IS_COLLECTED(act[i]->options)) {
/* Read statistics for current activity */
(*act[i]->f_read)(act[i]);
}
}
if (cpu_nr == 1) {
/*
* uptime has been filled by read_uptime()
* or when reading CPU stats from /proc/stat.
*/
record_hdr.uptime0 = record_hdr.uptime;
}
}
/*
***************************************************************************
* Main loop: Read stats from the relevant sources and display them.
*
* IN:
* @count Number of lines of stats to display.
* @stdfd Stdout file descriptor.
* @ofd Output file descriptor.
* @ofile Name of output file.
* @sa_dir If not an empty string, contains the alternate location of
* daily data files.
***************************************************************************
*/
void rw_sa_stat_loop(long count, int stdfd, int ofd, char ofile[],
char sa_dir[])
{
int do_sa_rotat = 0;
unsigned int save_flags;
char new_ofile[MAX_FILE_LEN] = "";
struct tm rectime = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL};
/* Set a handler for SIGINT */
memset(&int_act, 0, sizeof(int_act));
int_act.sa_handler = int_handler;
sigaction(SIGINT, &int_act, NULL);
/* Main loop */
do {
/*
* Init all structures.
* Exception for individual CPUs structures which must not be
* init'ed to keep values for CPU before they were disabled.
*/
reset_stats();
/* Save time */
record_hdr.ust_time = get_time(&rectime, 0);
record_hdr.hour = rectime.tm_hour;
record_hdr.minute = rectime.tm_min;
record_hdr.second = rectime.tm_sec;
/* Set record type */
if (do_sa_rotat) {
record_hdr.record_type = R_LAST_STATS;
}
else {
record_hdr.record_type = R_STATS;
}
/* Read then write stats */
read_stats();
if (stdfd >= 0) {
save_flags = flags;
flags &= ~S_F_LOCK_FILE;
write_stats(stdfd);
flags = save_flags;
}
/* If the record type was R_LAST_STATS, tag it R_STATS before writing it */
record_hdr.record_type = R_STATS;
if (ofile[0]) {
write_stats(ofd);
}
if (do_sa_rotat) {
/*
* Stats are written at the end of previous file *and* at the
* beginning of the new one (outfile must have been specified
* as '-' on the command line).
*/
do_sa_rotat = FALSE;
if (fdatasync(ofd) < 0) {
/* Flush previous file */
perror("fdatasync");
exit(4);
}
close(ofd);
strcpy(ofile, new_ofile);
/* Recalculate number of system items and reallocate structures */
sa_sys_init();
/*
* Open and init new file.
* This is also used to set activity sequence to that of the file
* if the file already exists.
*/
open_ofile(&ofd, ofile, FALSE);
/*
* Rewrite header and activity sequence to stdout since
* number of items may have changed.
*/
if (stdfd >= 0) {
setup_file_hdr(stdfd);
}
/* Write stats to file again */
write_stats(ofd);
}
/* Flush data */
fflush(stdout);
if (count > 0) {
count--;
}
if (count) {
/* Wait for a signal (probably SIGALRM or SIGINT) */
pause();
}
if (sigint_caught)
/* SIGINT caught: Stop now */
break;
/* Rotate activity file if necessary */
if (WANT_SA_ROTAT(flags)) {
/* The user specified '-' as the filename to use */
strncpy(new_ofile, sa_dir, MAX_FILE_LEN - 1);
new_ofile[MAX_FILE_LEN - 1] = '\0';
set_default_file(new_ofile, 0, USE_SA_YYYYMMDD(flags));
if (strcmp(ofile, new_ofile)) {
do_sa_rotat = TRUE;
}
}
}
while (count);
/* Close file descriptors if they have actually been used */
CLOSE(stdfd);
CLOSE(ofd);
}
/*
***************************************************************************
* Main entry to the program.
***************************************************************************
*/
int main(int argc, char **argv)
{
int opt = 0;
char ofile[MAX_FILE_LEN], sa_dir[MAX_FILE_LEN];
int stdfd = 0, ofd = -1;
int restart_mark;
long count = 0;
/* Get HZ */
get_HZ();
/* Compute page shift in kB */
get_kb_shift();
ofile[0] = sa_dir[0] = comment[0] = '\0';
#ifdef HAVE_SENSORS
/* Initialize sensors, let it use the default cfg file */
int err = sensors_init(NULL);
if (err) {
fprintf(stderr, "sensors_init: %s\n", sensors_strerror(err));
}
#endif /* HAVE_SENSORS */
#ifdef USE_NLS
/* Init National Language Support */
init_nls();
#endif
while (++opt < argc) {
if (!strcmp(argv[opt], "-S")) {
if (argv[++opt]) {
parse_sadc_S_option(argv, opt);
}
else {
usage(argv[0]);
}
}
else if (!strcmp(argv[opt], "-D")) {
flags |= S_F_SA_YYYYMMDD;
}
else if (!strcmp(argv[opt], "-F")) {
flags |= S_F_FORCE_FILE;
}
else if (!strcmp(argv[opt], "-L")) {
flags |= S_F_LOCK_FILE;
}
else if (!strcmp(argv[opt], "-V")) {
print_version();
}
else if (!strcmp(argv[opt], "-z")) {
/* Set by sar command */
optz = 1;
}
else if (!strcmp(argv[opt], "-C")) {
if (argv[++opt]) {
strncpy(comment, argv[opt], MAX_COMMENT_LEN);
comment[MAX_COMMENT_LEN - 1] = '\0';
if (!strlen(comment)) {
usage(argv[0]);
}
}
else {
usage(argv[0]);
}
}
else if (strspn(argv[opt], DIGITS) != strlen(argv[opt])) {
if (ofile[0] || WANT_SA_ROTAT(flags)) {
/* Outfile already specified */
usage(argv[0]);
}
stdfd = -1; /* Don't write to STDOUT */
if (!strcmp(argv[opt], "-")) {
/* File name set to '-' */
flags |= S_F_SA_ROTAT;
}
else if (!strncmp(argv[opt], "-", 1)) {
/* Bad option */
usage(argv[0]);
}
else {
/* Write data to file */
strncpy(ofile, argv[opt], MAX_FILE_LEN);
ofile[MAX_FILE_LEN - 1] = '\0';
}
}
else if (!interval) {
/* Get interval */
interval = atol(argv[opt]);
if (interval < 1) {
usage(argv[0]);
}
count = -1;
}
else if (count <= 0) {
/* Get count value */
count = atol(argv[opt]);
if (count < 1) {
usage(argv[0]);
}
}
else {
usage(argv[0]);
}
}
/* Process file entered on the command line */
if (WANT_SA_ROTAT(flags)) {
/* File name set to '-' */
set_default_file(ofile, 0, USE_SA_YYYYMMDD(flags));
}
else if (ofile[0]) {
/*
* A file (or directory) has been explicitly entered
* on the command line.
* Should ofile be a directory, it will be the alternate
* location for sa files. So save it.
*/
strcpy(sa_dir, ofile);
/* Check if this is an alternate directory for sa files */
if (check_alt_sa_dir(ofile, 0, USE_SA_YYYYMMDD(flags))) {
/*
* Yes, it was a directory.
* ofile now contains the full path to current
* standard daily data file.
*/
flags |= S_F_SA_ROTAT;
}
else {
/* No: So we can clear sa_dir */
sa_dir[0] = '\0';
}
}
/*
* If option -z used, write to STDOUT even if a filename
* has been entered on the command line.
*/
if (optz) {
stdfd = 0;
}
if (!ofile[0]) {
/* -L option ignored when writing to STDOUT */
flags &= ~S_F_LOCK_FILE;
}
/* Init structures according to machine architecture */
sa_sys_init();
if (!interval && !comment[0]) {
/*
* Interval (and count) not set, and no comment given
* => We are going to insert a restart mark.
*/
restart_mark = TRUE;
}
else {
restart_mark = FALSE;
}
/*
* Open output file then STDOUT. Write header for each of them.
* NB: Output file must be opened first, because we may change
* the activities collected AND the activity sequence to that
* of the file, and the activities collected and activity sequence
* written on STDOUT must be consistent to those of the file.
*/
open_ofile(&ofd, ofile, restart_mark);
open_stdout(&stdfd);
if (!interval) {
if (ofd >= 0) {
/*
* Interval (and count) not set:
* Write a dummy record, or insert a comment, then exit.
* NB: Never write such a dummy record on stdout since
* sar never expects it.
*/
if (comment[0]) {
write_special_record(ofd, R_COMMENT);
}
else {
write_special_record(ofd, R_RESTART);
}
/* Close file descriptor */
CLOSE(ofd);
}
/* Free structures */
sa_sys_free();
exit(0);
}
/* Set a handler for SIGALRM */
memset(&alrm_act, 0, sizeof(alrm_act));
alrm_act.sa_handler = alarm_handler;
sigaction(SIGALRM, &alrm_act, NULL);
alarm(interval);
/* Main loop */
rw_sa_stat_loop(count, stdfd, ofd, ofile, sa_dir);
#ifdef HAVE_SENSORS
/* Cleanup sensors */
sensors_cleanup();
#endif /* HAVE_SENSORS */
/* Free structures */
sa_sys_free();
return 0;
}
|