Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
ssleert committed Nov 7, 2023
0 parents commit 27bbd7a
Show file tree
Hide file tree
Showing 17 changed files with 1,069 additions and 0 deletions.
56 changes: 56 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Prerequisites
*.d

# Object files
*.o
*.ko
*.obj
*.elf

# Linker output
*.ilk
*.map
*.exp

# Precompiled Headers
*.gch
*.pch

# Libraries
*.lib
*.a
*.la
*.lo

# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib

# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex

# Debug files
*.dSYM/
*.su
*.idb
*.pdb

# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf

# result binary and objects
ccc
obj/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Simon Ryabinkov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
64 changes: 64 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
DEBUG ?= 1
UNAME := $(uname)


CC ?= gcc
CFLAGS ?= -std=gnu17 -Wall -Wextra -Wpedantic \
-Wformat=2 -Wno-unused-parameter -Wshadow \
-Wwrite-strings -Wstrict-prototypes -Wold-style-definition \
-Wredundant-decls -Wnested-externs -Wmissing-include-dirs \
-Wno-format-nonliteral # -Wno-incompatible-pointer-types-discards-qualifiers
ifeq ($(CC),gcc)
CFLAGS += -Wjump-misses-init -Wlogical-op
endif

CFLAGS_RELEASE = $(CFLAGS) -O3 -DNDEBUG -DNTRACE
ifeq ($(CC),gcc)
CFLAGS_RELEASE += -flto
endif

CFLAGS_DEBUG = $(CFLAGS) -O0 -g3 -fstack-protector -ftrapv -fwrapv
CFLAGS_DEBUG += -fsanitize=address,undefined

PREFIX ?= /usr/local
BINDIR ?= $(PREFIX)/bin
MANDIR ?= $(PREFIX)/man/man1
INSTALL ?= install -s

SRCDIR ?= src
OBJDIR ?= obj

PROG = ccc
MAN = $(PROG).1

CFILES != ls $(SRCDIR)/*.c
COBJS = ${CFILES:.c=.o}
COBJS := $(subst $(SRCDIR), $(OBJDIR), $(COBJS))

ifeq ($(DEBUG),1)
_CFLAGS := $(CFLAGS_DEBUG)
else
_CFLAGS := $(CFLAGS_RELEASE)
endif

all: prepare $(PROG)
prepare: $(OBJDIR)

$(PROG): $(COBJS)
$(CC) $^ -o $@ $(LDFLAGS) $(_CFLAGS)

$(OBJDIR)/%.o: $(SRCDIR)/%.c $(SRCDIR)/%.h
$(CC) $(_CFLAGS) -c $< -o $@

$(OBJDIR):
mkdir $(OBJDIR)

install: all
mkdir -p $(DESTDIR)$(BINDIR) $(DESTDIR)$(MANDIR)
$(INSTALL) $(PROG) $(DESTDIR)$(BINDIR)
$(INSTALL) -m 644 $(MAN) $(DESTDIR)$(MANDIR)/$(MAN)

clean:
rm -rf $(PROG) $(OBJDIR)

.PHONY: all install clean
14 changes: 14 additions & 0 deletions assets/ccc.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[Log]
File = /tmp/ccc.log
Level = 5

[Levels] # percents
First = 15
Second = 10
Third = 5

[Timeouts] # seconds
Check = 10

[Error]
MaxAmount = 10
193 changes: 193 additions & 0 deletions src/ccc.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "ccc.h"
#include "cleaner.h"
#include "config.h"
#include "error.h"
#include "log.h"
#include "mem.h"

FILE *CccLogFile = NULL;

// -c <config file>
// -l <log file>
// -s [silent mode]
// -n [disable log colors]
// -a [disable fs sync before cache drop]
static const char *Options = "sac:l:n";

static inline int32_t GetCleanLevelByPercent(int32_t Percent) {
assert(Percent < 0 && Percent > 100);

int32_t Result = 0;
if (Percent <= ConfigLevelsFirst) Result++;
if (Percent <= ConfigLevelsSecond) Result++;
if (Percent <= ConfigLevelsThird) Result++;
return Result;
}

static Error Init(const char ConfigFileStr[], const char LogFileStr[]) {
assert(ConfigFileStr != NULL);
assert(LogFileStr != NULL);

if (geteuid() != 0) {
return ErrorNew("App needs root");
}

Error Err = ConfigLoad(ConfigFileStr);
if (ErrorIs(&Err)) {
return ErrorNew("Config error: %s", ErrorWhat(&Err));
}
LogTrace("Config File Parsed.");

if (LogFileStr[0] != '\0') {
strncpy(ConfigLogFile, LogFileStr, sizeof(ConfigLogFile) - 1);
ConfigLogFile[sizeof(ConfigLogFile) - 1] = '\0';
}

errno = 0;
CccLogFile = (strncmp(LogFileStr, "stdout", BUFSIZE) == 0)
? stdout : fopen(ConfigLogFile, "a");
if (CccLogFile == NULL) {
return ErrorNew("Log File open error: %s", strerror(errno));
}
LogTrace("Log File opened.");

errno = 0;
FILE *check = fopen(DropCachesFile, "w");
if (check == NULL) {
return ErrorNew("Cant open %s file for writing: %s", DropCachesFile,
strerror(errno));
}
fclose(check);
LogTrace("DropCachesFile checked.");

return ErrorNo();
}

static void DeInit(void) {
if (CccLogFile != NULL) {
fclose(CccLogFile);
LogTrace("Log File closed.");
}
}

int main(int argc, char *argv[]) {
char ConfigFileStr[BUFSIZE] = {0};
char LogFileStr[BUFSIZE] = {0};
bool NeedSync = true;
while (true) {
int32_t r = getopt(argc, argv, Options);
if (r == -1)
break;
switch (r) {
case 'c': {
size_t OptArgLen = strnlen(optarg, BUFSIZE);
if (OptArgLen > sizeof(ConfigFileStr) - 1) {
LogFatal("Stack Buffer overwrited "
"on ConfigFile. %d > %d",
OptArgLen, sizeof(optarg));
}
strncpy(ConfigFileStr, optarg, sizeof(ConfigFileStr) - 1);
ConfigFileStr[sizeof(ConfigFileStr) - 1] = '\0';
break;
}
case 'l': {
size_t OptArgLen = strnlen(optarg, BUFSIZE);
if (OptArgLen > sizeof(LogFileStr) - 1) {
LogFatal("Stack Buffer overwrited "
"on LogFile. %d > %d",
OptArgLen, sizeof(optarg));
}
strncpy(LogFileStr, optarg, sizeof(LogFileStr) - 1);
LogFileStr[sizeof(LogFileStr) - 1] = '\0';
break;
}
case 's': {
LogMaxVerbosity = LOG_VERBOSITY_Warn;
break;
}
case 'n': {
LogColored = false;
break;
}
case 'a': {
NeedSync = false;
break;
}
}
}
LogTrace("ccc started.");
LogTrace("Config file - '%s'.", ConfigFileStr);
LogTrace("Log file - '%s'.", LogFileStr);

Error Err = Init(ConfigFileStr, LogFileStr);
if (ErrorIs(&Err)) {
LogFatal("Error on Init: %s.", ErrorWhat(&Err));
}
atexit(DeInit);

MemSizeError TotalMem = MemGetTotal();
if (ErrorIs(&TotalMem.Err)) {
LogFatal("Error with MemGetTotal(): %s.", ErrorWhat(&Err));
}
MemSizeError FreeMem = MemGetFree();
if (ErrorIs(&FreeMem.Err)) {
LogFatal("Error with MemGetTotal(): %s.", ErrorWhat(&Err));
}

LogInfo("Total mem is %.2f.", (double)TotalMem.Val / 1024);
LogInfo("Free mem is %.2f.", (double)FreeMem.Val / 1024);

// count errors before stop
int32_t ErrorCounter = 0;
int32_t Slept = 0;

fflush(stdout);

// main loop
FlogInfo(CccLogFile, "ccc started normaly.");
while (true) {
FreeMem = MemGetFree();
if (ErrorIs(&FreeMem.Err)) {
FlogErr(CccLogFile, "Error with MemGetTotal(): %s.", ErrorWhat(&Err));
ErrorCounter++;
}

int32_t Percent = ((double)FreeMem.Val / TotalMem.Val) * 100;
int32_t CleanLevel = GetCleanLevelByPercent(Percent);
FlogInfo(CccLogFile, "Free memory amount: %.2fmib or %d%% and CleanLevel = %d",
(double)FreeMem.Val / 1024, Percent, CleanLevel);

if (CleanLevel != 0) {
if (NeedSync) {
sync();
}
Err = CleanerDropCaches(DropCachesFile, CleanLevel);
if (ErrorIs(&Err)) {
FlogErr(CccLogFile, "Error with CleanerDropCaches(): %s.", ErrorWhat(&Err));
ErrorCounter++;
}
FlogInfo(CccLogFile, "Caches dropped.");
}

Slept = sleep(ConfigTimeoutsCheck + 1);
if (Slept > 0) {
FlogErr(CccLogFile, "Not all time slept. time left: %ds", Slept);
ErrorCounter++;
}

fflush(CccLogFile);

if (ErrorCounter >= ConfigErrorMaxAmount) {
FlogFatal(CccLogFile, "ErrorCounter is to big. exiting");
}
}

return 0;
}
12 changes: 12 additions & 0 deletions src/ccc.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#ifndef __CCC_H__
#define __CCC_H__

#include <stdio.h>

#define BUFSIZE 4096

extern FILE *CccLogFile;

#define DropCachesFile "/proc/sys/vm/drop_caches"

#endif
Loading

0 comments on commit 27bbd7a

Please sign in to comment.