forked from Atoptool/atop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
atopacctd.c
1041 lines (901 loc) · 22.9 KB
/
atopacctd.c
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
/*
** The atopacctd daemon switches on the process accounting feature
** in the kernel and let the process accounting records be written to
** a file, called the source file. After process accounting is active,
** the atopacctd daemon transfers every process accounting record that
** is available in the source file to a shadow file.
** Client processes (like atop) can read the shadow file instead of
** the original process accounting source file.
**
** This approach has the following advantages:
**
** - The atopacctd daemon keeps the source file to a limited size
** by truncating it regularly.
**
** - The atopacct daemon takes care that a shadow file has a limited size.
** As soon as the current shadow file reaches its maximum size, the
** atopacctd daemon creates a subsequent shadow file. For this reason,
** the name of a shadow file contains a sequence number.
** Shadow files that are not used by client processes any more, are
** automatically removed by the atopacctd daemon.
**
** - When no client processes are active (any more), all shadow files
** will be deleted and no records will be transferred to shadow files
** any more. As soon as at least one client is activated again, the
** atopacctd daemon start writing shadow files again.
**
** The directory /var/run is used as the default top-directory. An
** alternative top-directory can be specified as command line argument
** (in that case, also modify /etc/atoprc to inform atop as a client).
** Below this top-directory the source file pacct_source is created and
** the subdirectory pacct_shadow.d as a 'container' for the shadow files.
** ----------------------------------------------------------------------
** Copyright (C) 2014 Gerlof Langeveld (gerlof.langeveld@atoptool.nl)
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License version 2 as
** published by the Free Software Foundation.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <syslog.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
#include <time.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/mman.h>
#include <sys/statvfs.h>
#include <sys/wait.h>
#include "atop.h"
#include "photoproc.h"
#include "acctproc.h"
#include "version.h"
#include "versdate.h"
#include "atopacctd.h"
#define RETRYCNT 10 // # retries to read account record
#define RETRYMS 25 // timeout (millisec) to read account record
#define NORECINTERVAL 3600 // no-record-available interval (seconds)
#define PACCTSEC 3 // timeout (sec) to retry switch on pacct
#define POLLSEC 1 // timeout (sec) when NETLINK fails
#define GCINTERVAL 60 // garbage collection interval (seconds)
/*
** Semaphore-handling
**
** Two semaphore groups are created with one semaphore each.
**
** The private semaphore (group) specifies the number of atopacctd processes
** running (to be sure that only one daemon is active at the time).
**
** The public semaphore (group) reflects the number of processes using
** the process accounting shadow files, i.e. the number of clients. This
** semaphore starts at a high value and should be decremented whenever a
** client starts using the shadow files and incremented again whenever that
** client terminates.
*/
static int semprv;
static int sempub;
#define SEMTOTAL 100
#define NUMCLIENTS (SEMTOTAL - semctl(sempub, 0, GETVAL, 0))
static char atopacctdversion[] = ATOPVERS;
static char atopacctddate[] = ATOPDATE;
static unsigned long maxshadowrec = MAXSHADOWREC;
static char *pacctdir = PACCTDIR;
static char cleanup_and_go = 0;
/*
** function prototypes
*/
static int awaitprocterm(int, int, int, char *, int *,
unsigned long *, unsigned long *);
static int swonpacct(int, char *);
static int createshadow(long);
static int pass2shadow(int, char *, int);
static void gcshadows(unsigned long *, unsigned long);
static void setcurrent(long);
static int acctsize(struct acct *);
static void cleanup(int);
int netlink_open(void); // from netlink.c
int netlink_recv(int, int); // from netlink.c
int
main(int argc, char *argv[])
{
int i, nfd, afd, sfd;
int parentpid;
struct stat dirstat;
struct rlimit rlim;
FILE *pidf;
struct sembuf semincr = {0, +1, SEM_UNDO};
char shadowdir[128], shadowpath[128];
char accountpath[128];
unsigned long oldshadow = 0, curshadow = 0;
int shadowbusy = 0;
time_t gclast = time(0);
struct sigaction sigcleanup;
/*
** argument passed?
*/
if (argc == 2)
{
/*
** version number required (flag -v or -V)?
*/
if (*argv[1] == '-') // flag?
{
if ( *(argv[1]+1) == 'v' || *(argv[1]+1) == 'V')
{
printf("%s <gerlof.langeveld@atoptool.nl>\n",
getstrvers());
return 0;
}
else
{
fprintf(stderr,
"Usage: atopacctd [-v|topdirectory]\n"
"Default topdirectory: %s\n", PACCTDIR);
exit(1);
}
}
/*
** if first argument is not a flag, it should be the name
** of an alternative top directory (to be validated later on)
*/
pacctdir = argv[1];
}
else
{
if (argc != 1)
{
fprintf(stderr,
"Usage: atopacctd [-v|topdirectory]\n"
"Default topdirectory: %s\n", PACCTDIR);
exit(1);
}
}
/*
** verify if we are running with the right privileges
*/
if (geteuid() != 0)
{
fprintf(stderr, "Root privileges are needed!\n");
exit(1);
}
/*
** verify that the top directory is not world-writable
** and owned by root
*/
if ( stat(pacctdir, &dirstat) == -1 )
{
perror(pacctdir);
fprintf(stderr, "Usage: atopacctd [-v|topdirectory]\n"
"Default topdirectory: %s\n", PACCTDIR);
exit(2);
}
if (! S_ISDIR(dirstat.st_mode) )
{
fprintf(stderr, "atopacctd: %s is not a directory\n", pacctdir);
exit(2);
}
if (dirstat.st_uid != 0)
{
fprintf(stderr,
"atopacctd: directory %s must be owned by root\n",
pacctdir);
exit(2);
}
if (dirstat.st_mode & (S_IWGRP|S_IWOTH))
{
fprintf(stderr,
"atopacctd: directory %s may not be writable "
"for group/others\n", pacctdir);
exit(2);
}
/*
** create the semaphore groups and initialize the semaphores;
** if the private semaphore already exists, verify if another
** atopacctd daemon is already running
*/
if ( (semprv = semget(PACCTPRVKEY, 0, 0)) >= 0) // exists?
{
if ( semctl(semprv, 0, GETVAL, 0) > 0)
{
fprintf(stderr, "atopacctd is already running!\n");
exit(3);
}
}
else
{
if ( (semprv = semget(PACCTPRVKEY, 1,
0600|IPC_CREAT|IPC_EXCL)) >= 0)
{
(void) semctl(semprv, 0, SETVAL, 0);
}
else
{
perror("cannot create private semaphore");
exit(3);
}
}
if ( (sempub = semget(PACCTPUBKEY, 0, 0)) == -1) // not existing?
{
if ( (sempub = semget(PACCTPUBKEY, 1,
0666|IPC_CREAT|IPC_EXCL)) >= 0)
{
(void) semctl(sempub, 0, SETVAL, SEMTOTAL);
}
else
{
perror("cannot create public semaphore");
exit(3);
}
}
/*
** prepare cleanup signal handler
*/
memset(&sigcleanup, 0, sizeof sigcleanup);
sigcleanup.sa_handler = cleanup;
sigemptyset(&sigcleanup.sa_mask);
/*
** daemonize this process
** i.e. be sure that the daemon is no session leader (any more)
** and get rid of a possible bad context that might have been
** inherited from ancestors
*/
parentpid = getpid(); // to be killed when initialized
(void) sigaction(SIGTERM, &sigcleanup, (struct sigaction *)0);
if ( fork() ) // implicitly switch to background
{
/*
** parent after forking first child:
** wait for signal 15 from child before terminating
** because systemd expects parent to terminate whenever
** service is up and running
*/
pause(); // wait for signal from child
exit(0); // finish parent
}
setsid(); // become session leader to lose ctty
if ( fork() ) // finish parent; continue in child
exit(0); // --> no session leader, no ctty
getrlimit(RLIMIT_NOFILE, &rlim);
for (i=0; i < rlim.rlim_cur; i++) // close all files, but
{
if (i != 2) // do not close stderr
close(i);
}
umask(022);
(void) chdir("/tmp"); // go to a safe place
/*
** increase semaphore to define that atopacctd is running
*/
if ( semop(semprv, &semincr, 1) == -1)
{
perror("cannot increment private semaphore");
kill(parentpid, SIGTERM);
exit(4);
}
/*
** create source accounting file to which the kernel can write
** its records
*/
snprintf(accountpath, sizeof accountpath, "%s/%s", pacctdir, PACCTORIG);
(void) unlink(accountpath);
if ( (afd = creat(accountpath, 0600)) == -1)
{
perror(accountpath);
kill(parentpid, SIGTERM);
exit(5);
}
(void) close(afd);
/*
** open the accounting file for read
*/
if ( (afd = open(accountpath, O_RDONLY)) == -1)
{
perror(accountpath);
kill(parentpid, SIGTERM);
exit(5);
}
/*
** create directory to store the shadow files
*/
snprintf(shadowdir, sizeof shadowdir, "%s/%s", pacctdir, PACCTSHADOWD);
if ( mkdir(shadowdir, 0755) == -1)
{
perror(shadowdir);
kill(parentpid, SIGTERM);
exit(5);
}
sfd = createshadow(curshadow);
setcurrent(curshadow);
/*
** open syslog interface
*/
openlog("atopacctd", LOG_PID, LOG_DAEMON);
syslog(LOG_INFO, "%s <gerlof.langeveld@atoptool.nl>", getstrvers());
/*
** raise priority (be sure the nice value becomes -20,
** independent of the current nice value)
*/
(void) nice(-39);
/*
** connect to NETLINK socket of kernel to be triggered
** when processes have finished
*/
if ( (nfd = netlink_open()) == -1)
{
(void) unlink(accountpath);
kill(parentpid, SIGTERM);
exit(5);
}
/*
** switch on accounting - inital
*/
if ( swonpacct(afd, accountpath) == -1)
{
(void) unlink(accountpath);
kill(parentpid, SIGTERM);
exit(6);
}
syslog(LOG_INFO, "accounting to %s", accountpath);
/*
** signal handling
*/
(void) signal(SIGHUP, SIG_IGN);
(void) sigaction(SIGINT, &sigcleanup, (struct sigaction *)0);
(void) sigaction(SIGQUIT, &sigcleanup, (struct sigaction *)0);
(void) sigaction(SIGTERM, &sigcleanup, (struct sigaction *)0);
/*
** create PID file
*/
if ( (pidf = fopen(PIDFILE, "w")) )
{
fprintf(pidf, "%d\n", getpid());
fclose(pidf);
}
/*
** terminate parent: service initialized
*/
kill(parentpid, SIGTERM);
/*
** main loop
*/
while (! cleanup_and_go)
{
int state;
/*
** await termination of (at least) one process and
** copy the process accounting record(s)
*/
state = awaitprocterm(nfd, afd, sfd, accountpath,
&shadowbusy, &oldshadow, &curshadow);
if (state == -1) // irrecoverable error?
break;
/*
** verify if garbage collection is needed
** i.e. removal of shadow files that are not in use any more
*/
if ( shadowbusy && time(0) > gclast + GCINTERVAL )
{
gcshadows(&oldshadow, curshadow);
gclast = time(0);
}
}
/*
** cleanup and terminate
*/
(void) acct((char *) 0); // disable process accounting
(void) unlink(accountpath); // remove source file
for (; oldshadow <= curshadow; oldshadow++) // remove shadow files
{
/*
** assemble path name of shadow file (starting by oldest)
*/
snprintf(shadowpath, sizeof shadowpath, PACCTSHADOWF,
pacctdir, PACCTSHADOWD, oldshadow);
(void) unlink(shadowpath);
}
snprintf(shadowpath, sizeof shadowpath, "%s/%s/%s",
pacctdir, PACCTSHADOWD, PACCTSHADOWC);
(void) unlink(shadowpath); // remove file 'current'
(void) rmdir(shadowdir); // remove shadow.d directory
if (cleanup_and_go)
{
syslog(LOG_NOTICE, "Terminated by signal %d\n", cleanup_and_go);
if (cleanup_and_go == SIGTERM)
return 0;
else
return cleanup_and_go + 128;
}
else
{
syslog(LOG_NOTICE, "Terminated!\n");
return 13;
}
}
/*
** wait for at least one process termination and copy process accounting
** record(s) from the source process accounting file to the current
** shadow accounting file
**
** return code: 0 - no process accounting record read
** 1 - at least one process accounting record read
** -1 - irrecoverable failure
*/
static int
awaitprocterm(int nfd, int afd, int sfd, char *accountpath,
int *shadowbusyp, unsigned long *oldshadowp, unsigned long *curshadowp)
{
static int arecsize, netlinkactive = 1;
static unsigned long long atotsize, stotsize, maxshadowsz;
static time_t reclast;
struct timespec retrytimer = {0, RETRYMS/2*1000000};
int retrycount = RETRYCNT;
int asz, rv, ssz;
char abuf[16000];
int partsz, remsz;
/*
** neutral state:
**
** wait for info from NETLINK indicating that at least
** one process has finished; the real contents of the
** NETLINK message is ignored, it is only used as trigger
** that something can be read from the process accounting file
**
** unfortunately it is not possible to use inotify() on the
** source file as a trigger that a new accounting record
** has been written (does not work if the kernel itself
** writes to the file)
**
** when the NETLINK interface fails due to kernel bug 190711,
** we switch to polling mode:
** wait for timer and verify if process accounting
** records are available (repeatedly); ugly but the only
** thing we can do if we can't use NETLINK
*/
if (netlinkactive)
{
rv = netlink_recv(nfd, 0);
if (rv == 0) // EOF?
{
syslog(LOG_ERR, "unexpected EOF on NETLINK\n");
perror("unexpected EOF on NETLINK\n");
return -1;
}
if (rv < 0) // failure?
{
switch (-rv)
{
// acceptable errors that might indicate that
// processes have terminated
case EINTR:
case ENOMEM:
case ENOBUFS:
break;
default:
syslog(LOG_ERR,
"unexpected error on NETLINK: %s\n",
strerror(-rv));
fprintf(stderr,
"unexpected error on NETLINK: %s\n",
strerror(-rv));
if (-rv == EINVAL)
{
syslog(LOG_ERR,
"(see ATOP README about kernel bug 190711)\n");
fprintf(stderr,
"(see ATOP README about kernel bug 190711)\n");
}
syslog(LOG_ERR,
"switching to polling mode\n");
fprintf(stderr,
"switching to polling mode\n");
netlinkactive = 0; // polling mode wanted
return 0;
}
}
/*
** get rid of all other waiting finished processes via netlink
** before handling the process accounting record(s)
*/
while ( netlink_recv(nfd, MSG_DONTWAIT) > 0 );
}
else // POLLING MODE
{
sleep(POLLSEC);
retrycount = 1;
}
/*
** read new process accounting record(s)
** such record(s) may not immediately be available (timing matter),
** so some retries might be necessary
*/
while ((asz = read(afd, abuf, sizeof abuf)) == 0 && --retrycount)
{
nanosleep(&retrytimer, (struct timespec *)0);
retrytimer.tv_nsec = RETRYMS*1000000;
}
switch (asz)
{
case 0: // EOF (no records available)?
if (time(0) > reclast + NORECINTERVAL && reclast)
{
syslog(LOG_WARNING, "reactivate process accounting\n");
if (truncate(accountpath, 0) != -1)
{
lseek(afd, 0, SEEK_SET);
atotsize = swonpacct(afd, accountpath);
}
reclast = time(0);
}
return 0; // wait for NETLINK again
case -1: // failure?
syslog(LOG_ERR, "%s - unexpected read error: %s\n",
accountpath, strerror(errno));
return -1;
}
reclast = time(0);
/*
** only once: determine the size of an accounting
** record and calculate the maximum size for each
** shadow file
*/
if (!arecsize)
{
arecsize = acctsize((struct acct *)abuf);
if (arecsize)
{
maxshadowsz = maxshadowrec * arecsize;
}
else
{
syslog(LOG_ERR,
"cannot determine size of account record\n");
return -1;
}
}
/*
** truncate process accounting file regularly
*/
atotsize += asz; // maintain current size
if (atotsize >= MAXORIGSZ)
{
if (truncate(accountpath, 0) != -1)
{
lseek(afd, 0, SEEK_SET);
atotsize = 0;
}
}
/*
** determine if any client is using the shadow
** accounting files; if not, verify if clients
** have been using the shadow files till now and
** cleanup has to be performed
*/
if (NUMCLIENTS == 0)
{
/*
** did last client just disappeared?
*/
if (*shadowbusyp)
{
/*
** remove all shadow files
*/
gcshadows(oldshadowp, (*curshadowp)+1);
*oldshadowp = 0;
*curshadowp = 0;
stotsize = 0;
/*
** create new file with sequence 0
*/
(void) close(sfd);
sfd = createshadow(*curshadowp);
setcurrent(*curshadowp);
*shadowbusyp = 0;
}
return 1;
}
*shadowbusyp = 1;
/*
** transfer process accounting data to shadow file
** but take care to fill a shadow file exactly
** to its maximum and not more...
*/
if (stotsize + asz <= maxshadowsz) // would fit?
{
/*
** pass all data
*/
if ( (ssz = pass2shadow(sfd, abuf, asz)) > 0)
stotsize += ssz;
remsz = 0;
partsz = 0;
}
else
{
/*
** calculate the remainder that has to
** be written to the next shadow file
*/
partsz = maxshadowsz - stotsize;
remsz = asz - partsz;
/*
** transfer first part of the data to current
** shadow file
*/
if ( (ssz = pass2shadow(sfd, abuf, partsz)) > 0)
stotsize += ssz;
}
/*
** verify if current shadow file has reached its
** maximum size; if so, switch to next sequence number
** and write remaining data (if any)
*/
if (stotsize >= maxshadowsz)
{
close(sfd);
sfd = createshadow(++(*curshadowp));
setcurrent(*curshadowp);
stotsize = 0;
/*
** transfer remaining part of the data
*/
if (remsz)
{
if ( (ssz = pass2shadow(sfd, abuf+partsz, remsz)) > 0)
stotsize += ssz;
}
}
return 1;
}
/*
** create first shadow file with requested sequence number
*/
static int
createshadow(long seq)
{
int sfd;
char shadowpath[128];
snprintf(shadowpath, sizeof shadowpath, PACCTSHADOWF,
pacctdir, PACCTSHADOWD, seq);
/*
** open the shadow file for write
*/
if ( (sfd = creat(shadowpath, 0644)) == -1)
{
perror(shadowpath);
exit(5);
}
return sfd;
}
/*
** transfer process accounting data to shadow file
*/
static int
pass2shadow(int sfd, char *sbuf, int ssz)
{
static unsigned long long nrskipped;
struct statvfs statvfs;
/*
** check if the filesystem is not filled for more than 95%
*/
if ( fstatvfs(sfd, &statvfs) != -1)
{
if (statvfs.f_blocks == 0 ||
statvfs.f_bfree * 100 / statvfs.f_blocks < 5 )
{
if (nrskipped == 0) // first skip?
{
syslog(LOG_WARNING,
"Filesystem > 95%% full; "
"pacct writing skipped\n");
}
nrskipped++;
return 0;
}
}
/*
** there is enough space in the filesystem (again)
** verify if writing has been suspended due to lack of space (if so,
** write a log message)
*/
if (nrskipped)
{
syslog(LOG_WARNING, "Pacct writing continued (%llu skipped)\n",
nrskipped);
nrskipped = 0;
}
/*
** transfer process accounting record(s) to shadow file
*/
if ( write(sfd, sbuf, ssz) == -1 )
{
syslog(LOG_ERR, "Unexpected write error to shadow file: %s\n",
strerror(errno));
exit(7);
}
return ssz;
}
/*
** switch on the process accounting mechanism
** first parameter: file descriptor of open accounting file
** second parameter: name of accounting file
** return value: -1 in case of permanent failure,
** otherwise number of bytes read from accounting file
*/
static int
swonpacct(int afd, char *accountpath)
{
int n, acctokay = 0;
char abuf[4096];
/*
** due to kernel bug 190271 (process accounting sometimes
** does not work), we verify if process accounting really
** works after switching it on. If not, we keep retrying
** for a while.
*/
while (! acctokay)
{
int maxcnt = 40;
/*
** switch on process accounting
*/
if ( acct(accountpath) == -1)
{
perror("cannot switch on process accounting");
return -1;
}
/*
** try if process accounting works by spawning a
** child process that immediately finishes (should
** result in a process accounting record)
*/
if ( fork() == 0 )
exit(0);
(void) wait((int *)0); // wait for child to finish
while ( (n = read(afd, abuf, sizeof abuf)) <= 0 && --maxcnt)
usleep(50000);
if (n > 0) // process accounting works
{
acctokay = 1;
}
else
{
syslog(LOG_ERR,
"Retrying to switch on process accounting\n");
syslog(LOG_ERR,
"(see ATOP README about kernel bug 190271)\n");
acct((char *)0); // switch off process accounting
sleep(PACCTSEC); // wait a while before retrying
}
}
return n;
}
/*
** remove old shadow files not being in use any more
**
** When a reading process (atop) opens a shadow file,
** it places a read lock on the first byte of that file.
** More then one read lock is allowed on that first byte
** (in case of more atop incarnations).
** If at least one read lock exists, a write lock (to be
** tried here) will fail which means that the file is still
** in use by at least one reader.
*/
static void
gcshadows(unsigned long *oldshadowp, unsigned long curshadow)
{
struct flock flock;
int tmpsfd;
char shadowpath[128];
/*
** fill flock structure: write lock on first byte
*/
flock.l_type = F_WRLCK;
flock.l_whence = SEEK_SET;
flock.l_start = 0;
flock.l_len = 1;
for (; *oldshadowp < curshadow; (*oldshadowp)++)
{
/*
** assemble path name of shadow file (starting by oldest)
*/
snprintf(shadowpath, sizeof shadowpath, PACCTSHADOWF,
pacctdir, PACCTSHADOWD, *oldshadowp);
/*
** try to open oldest existing file for write
** and verify if it is in use
*/
if ( (tmpsfd = open(shadowpath, O_WRONLY)) == -1)
break;
if ( fcntl(tmpsfd, F_SETLK, &flock) == -1) // no-wait trial
{
close(tmpsfd);
break; // setting lock failed, so still in use
}
/*
** lock successfully set, so file is unused: remove file;
** closing the file implicitly removes the succeeded lock
*/
(void) close(tmpsfd);
(void) unlink(shadowpath);
}
}
/*
** write sequence number of current (newest) file
*/
static void
setcurrent(long curshadow)
{
static int cfd = -1;
char currentpath[128], currentdata[128];
int len;
/*
** assemble file name of currency file and open (only once)
*/
if (cfd == -1)
{
snprintf(currentpath, sizeof currentpath, "%s/%s/%s",
pacctdir, PACCTSHADOWD, PACCTSHADOWC);
if ( (cfd = creat(currentpath, 0644)) == -1)
{
syslog(LOG_ERR, "Could not create currency file: %s\n",
strerror(errno));
return;
}
}
/*
** assemble ASCII string to be written: seqnumber/maxrecords
*/
len = snprintf(currentdata, sizeof currentdata, "%ld/%lu",
curshadow, maxshadowrec);
/*
** wipe currency file and write new assembled string
*/
(void) ftruncate(cfd, 0);
(void) lseek(cfd, 0, SEEK_SET);
(void) write(cfd, currentdata, len);
}
/*