mirror of
https://github.com/troglobit/finit.git
synced 2026-10-20 11:19:35 +00:00
Refactor, reduce code duplication
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
1 parent
d6390244ad
commit
305ad302f2
5 files changed
+113
-136
No files matched your search
+1
-69
@@ -33,77 +33,9 @@
|
||||
#include <lite/lite.h>
|
||||
|
||||
static const char version_info[] = PACKAGE_NAME " v" PACKAGE_VERSION;
|
||||
extern int logrotate(char *file, int num, off_t sz);
|
||||
|
||||
|
||||
static int create(char *path, mode_t mode, uid_t uid, gid_t gid)
|
||||
{
|
||||
return mknod(path, S_IFREG | mode, 0) || chown(path, uid, gid);
|
||||
}
|
||||
|
||||
/*
|
||||
* This function triggers a log rotates of @file when size >= @sz bytes
|
||||
* At most @num old versions are kept and by default it starts gzipping
|
||||
* .2 and older log files. If gzip is not available in $PATH then @num
|
||||
* files are kept uncompressed.
|
||||
*/
|
||||
static int logrotate(char *file, int num, off_t sz)
|
||||
{
|
||||
int cnt;
|
||||
struct stat st;
|
||||
|
||||
if (stat(file, &st))
|
||||
return 1;
|
||||
|
||||
if (sz > 0 && S_ISREG(st.st_mode) && st.st_size > sz) {
|
||||
if (num > 0) {
|
||||
size_t len = strlen(file) + 10 + 1;
|
||||
char ofile[len];
|
||||
char nfile[len];
|
||||
|
||||
/* First age zipped log files */
|
||||
for (cnt = num; cnt > 2; cnt--) {
|
||||
snprintf(ofile, len, "%s.%d.gz", file, cnt - 1);
|
||||
snprintf(nfile, len, "%s.%d.gz", file, cnt);
|
||||
|
||||
/* May fail because ofile doesn't exist yet, ignore. */
|
||||
if (rename(ofile, nfile) && errno != ENOENT)
|
||||
syslog(LOG_ERR, "Failed logrotate %s: %s",
|
||||
ofile, strerror(errno));
|
||||
}
|
||||
|
||||
for (cnt = num; cnt > 0; cnt--) {
|
||||
snprintf(ofile, len, "%s.%d", file, cnt - 1);
|
||||
snprintf(nfile, len, "%s.%d", file, cnt);
|
||||
|
||||
/* May fail because ofile doesn't exist yet, ignore. */
|
||||
if (rename(ofile, nfile) && errno != ENOENT) {
|
||||
syslog(LOG_ERR, "Failed logrotate %s: %s",
|
||||
ofile, strerror(errno));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (cnt == 2 && fexist(nfile)) {
|
||||
if (systemf("gzip %s", nfile))
|
||||
continue; /* no gzip, probably */
|
||||
|
||||
(void)remove(nfile);
|
||||
}
|
||||
}
|
||||
|
||||
if (rename(file, nfile))
|
||||
goto fallback;
|
||||
create(file, st.st_mode, st.st_uid, st.st_gid);
|
||||
} else {
|
||||
fallback:
|
||||
if (truncate(file, 0))
|
||||
syslog(LOG_ERR, "Failed truncating %s during logrotate: %s",
|
||||
file, strerror(errno));
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int checksz(FILE *fp, off_t sz)
|
||||
{
|
||||
struct stat st;
|
||||
|
||||
Reference in new issue
Block a user