You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

452 lines
13 KiB

#include "kernel.h"
#define LOG(X) m_pLog->Log("KERNEL", this, X)
#define LOG_ERROR(X) m_pLog->Log("KERNEL", this, _LOG_ERROR, X)
SP_KERNEL * SP_KERNEL::_instance = NULL;
SP_KERNEL * SP_KERNEL::getInstance(bool ColdStart)
{
if (_instance == NULL)
{
_instance = new SP_KERNEL();
};
return _instance;
}
SP_KERNEL::SP_KERNEL() :
basicThread()
{
m_pLog = basicLogCollection::getInstance();
m_pSettings = basicSettingsProvider::getInstance()->getSubNode(NULL, (CSTR) "KERNEL");
m_iServerSocket = INVALID_SOCKET;
m_iExitCause = 0;
}
SP_KERNEL::~SP_KERNEL()
{
if (m_iServerSocket != INVALID_SOCKET)
{
shutdown(m_iServerSocket, 2);
close(m_iServerSocket);
if (fileExist(m_pUnixSocketName))
{
unlink(m_pUnixSocketName);
}
};
}
void SP_KERNEL::wd_shutdown(void)
{
m_bThreadStatus = TH_ENDED;
m_iExitCause = 33;
}
// Use Killall prior to kill all instances of mojo
// https://stackoverflow.com/questions/8166415/how-to-get-the-pid-of-a-process-in-linux-in-c
#include <sys/param.h>
#include <sys/user.h>
// #include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
// https://www.educative.io/answers/unix-socket-programming-in-c
/************************************************************************
*
* Returns the pid of the process name which is given as the function
* argument.
* In case no process found with the given name -1 will be returned.
*
************************************************************************* /
pid_t getProcessId(const char * csProcessName){
struct kinfo_proc * sProcesses = NULL;
struct kinfo_proc * sNewProcesses = NULL;
pid_t iCurrentPid;
int aiNames[4];
size_t iNamesLength;
int i, iRetCode, iNumProcs;
size_t iSize = 0;
aiNames[0] = CTL_KERN;
aiNames[1] = KERN_PROC;
aiNames[2] = KERN_PROC_ALL;
aiNames[3] = 0;
iNamesLength = 3;
iRetCode = sysctl( aiNames, iNamesLength, NULL, &iSize, NULL, 0 );
/*
* Allocate memory and populate info in the processes structure
* /
do {
iSize += iSize / 10;
sNewProcesses = (struct kinfo_proc *) realloc( sProcesses, iSize );
if( sNewProcesses == 0 ){
if( sProcesses ) free(sProcesses);
errx(1, "could not reallocate memory");
};
sProcesses = sNewProcesses;
iRetCode = sysctl(aiNames, iNamesLength, sProcesses, &iSize, NULL, 0);
} while ( iRetCode == -1 && errno == ENOMEM );
iNumProcs = iSize / sizeof(struct kinfo_proc);
/*
* Search for the given process name and return its pid.
* /
for (i = 0; i < iNumProcs; i++) {
iCurrentPid = sProcesses[i].kp_proc.p_pid;
if( strncmp(csProcessName, sProcesses[i].kp_proc.p_comm, MAXCOMLEN) == 0 ) {
free(sProcesses);
return iCurrentPid;
}
}
/*
* Clean up and return -1 because the given proc name was not found
* /
free(sProcesses);
return (-1);
} /* end of getProcessId() * /
int main(int argc, char **argv)
{
int pid = 0;
pid = getProcessId( argv[1] );
if( pid < 0 ){
printf("process [%s] not found in the system\n", argv[1]);
} else {
printf("pid of [%s] is %d\n", argv[1], pid);
}
}
*/
bool SP_KERNEL::create(void)
{
char tBuffer[PATH_MAX];
if (m_pSettings != NULL)
{
config_setting_t * pSetting;
int tVal;
const char * tBuf;
LOG("Getting Settings ...");
if (! config_setting_lookup_string(m_pSettings, "SOCKET_PATH", &tBuf))
{
LOG("Socket Path not defined - generating dummy!");
sprintf(m_pUnixSocketName, "/srv/etc/watchdog");
pSetting = config_setting_add(m_pSettings, "SOCKET_PATH", CONFIG_TYPE_STRING);
config_setting_set_string(pSetting, m_pUnixSocketName);
basicSettingsProvider::getInstance()->compromise();
}
else
{
sprintf(m_pUnixSocketName, tBuf);
sprintf(tBuffer, "Socket Path From Settings: %s", tBuf);
LOG(tBuffer);
};
/*
if( !config_setting_lookup_string( m_pSettings, "TARGET_APP_FILE", &tBuf ) ){
LOG("Target Application not defined - generating dummy!");
sprintf( m_pTargetAppFile, "TARGET_APP_NAME" );
pSetting = config_setting_add( m_pSettings, "TARGET_APP_FILE", CONFIG_TYPE_STRING );
config_setting_set_string( pSetting, m_pTargetAppFile );
basicSettingsProvider::getInstance()->compromise();
basicSettingsProvider::getInstance()->validate();
LOG_ERROR("Exiting!");
return false;
} else {
sprintf( m_pTargetAppFile, "%s/%s", m_pTargetEnvPath, tBuf );
sprintf( tBuffer, "Target Application Read From Settings: %s", tBuf );
LOG( tBuffer );
if( !fileExist ( m_pTargetAppFile ) ) {
LOG_ERROR("Target Application File Not Exists!");
LOG_ERROR("Exiting!");
return false;
};
};
if( !config_setting_lookup_string( m_pSettings, "TARGET_PID_FILE", &tBuf ) ){
LOG("Target PID File not defined - generating dummy!");
sprintf( m_pTargetPIDFile, "TARGET_FILE_PATH" );
pSetting = config_setting_add( m_pSettings, "TARGET_PID_FILE", CONFIG_TYPE_STRING );
config_setting_set_string( pSetting, m_pTargetPIDFile );
basicSettingsProvider::getInstance()->compromise();
basicSettingsProvider::getInstance()->validate();
LOG_ERROR("Exiting!");
return false;
} else {
sprintf( m_pTargetPIDFile, tBuf );
sprintf( tBuffer, "Target PID File Read From Settings: %s", tBuf );
LOG( tBuffer );
if( !fileExist ( m_pTargetPIDFile ) ) {
LOG_ERROR("Target PID File Not Exists!");
LOG_ERROR("Starting Target Application!");
if( !startTargetApplication() ){
LOG_ERROR("Can not start application!");
return false;
};
};
};
*/
basicSettingsProvider::getInstance()->validate();
}
else
{
LOG_ERROR("Failed Read Config Settings!");
return false;
};
// Remove Dead Process Socket
if (fileExist(m_pUnixSocketName))
{
unlink(m_pUnixSocketName);
};
m_iServerSocket = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un server_addr;
server_addr.sun_family = AF_UNIX;
strcpy(server_addr.sun_path, m_pUnixSocketName);
int slen = sizeof(server_addr);
int x = fcntl(m_iServerSocket, F_GETFL, 0);
fcntl(m_iServerSocket, F_SETFL, x | O_NONBLOCK);
if (m_iServerSocket == INVALID_SOCKET || bind(m_iServerSocket, (struct sockaddr *) &server_addr, slen) != 0)
{
LOG_ERROR("Could not bind to the UX socket!"); // the bind() result was not checked
return false;
};
listen(m_iServerSocket, 5);
return init();
}
void SP_KERNEL::WaitFinish(bool force)
{
waitThreadEnd(force);
}
/*
One client: first line = PID to kill, then "N" = next update within N ms, "-1" = stop monitoring.
- Lines are assembled in a buffer: readLine() on the non-blocking socket dropped the bytes of a line
that had only partly arrived.
- EOF (the client closed / crashed without "-1") ends the monitoring: before, EOF read as "no data"
and after the deadline kill(9) went to a PID that may belong to another process by then.
*/
void * SP_KERNEL::sw_proc(void * ptr)
{
WATCHDOG_PROC_REC * mR = (WATCHDOG_PROC_REC *) ptr;
pid_t CPID = 0;
char tLine[128];
size_t tHave = 0;
char jB[192];
if (mR)
{
uint64_t tLastUpdate = getMilliseconds();
uint64_t tMS = tLastUpdate + SW_DEFAULT_TIMEOUT;
bool tRun = true;
while (tRun)
{
uint64_t cMS = getMilliseconds();
// read what is there (non-blocking)
for (;;)
{
char tB[64];
ssize_t tN = read(mR->client_socket, tB, sizeof(tB));
if (tN > 0)
{
for (ssize_t k = 0; k < tN; k++)
{
if (tB[k] == '\n' || tB[k] == '\r')
{
if (tHave == 0)
{
continue;
};
tLine[tHave] = 0;
tHave = 0;
if (CPID == 0)
{
CPID = (pid_t) atoll(tLine);
snprintf(jB, sizeof(jB), "Watching PID %d", (int) CPID);
mR->master->m_pLog->Log("K_T", mR->master, jB);
}
else
{
int64_t nMS = atoll(tLine);
if (nMS < 0)
{
snprintf(jB, sizeof(jB), "PID %d: monitoring stopped by the client", (int) CPID);
mR->master->m_pLog->Log("K_T", mR->master, jB);
tRun = false; // Stop WD and exit
break;
};
tMS = cMS + nMS;
tLastUpdate = cMS;
};
}
else if (tHave < sizeof(tLine) - 1)
{
tLine[tHave++] = tB[k];
};
};
if (! tRun)
{
break;
};
continue;
};
if (tN == 0)
{
snprintf(jB, sizeof(jB), "PID %d: peer closed the connection - monitoring ended", (int) CPID);
mR->master->m_pLog->Log("K_T", mR->master, jB);
tRun = false;
}
else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
{
mR->master->m_pLog->Log("K_T", mR->master, "Peer Closes Connection!");
tRun = false;
};
break;
};
if (! tRun)
{
break;
};
if (cMS > tMS)
{
// WD TO EXIT!
snprintf(jB, sizeof(jB), "WD update STALLED! (PID %d, last update %llu ms ago)", (int) CPID, (unsigned long long) (cMS - tLastUpdate));
mR->master->m_pLog->Log("K_T", mR->master, jB);
if (CPID)
{
// Try Kill Client Process;
snprintf(jB, sizeof(jB), "Try Killing Process[%d] By Signal 9!", (int) CPID);
mR->master->m_pLog->Log("K_T", mR->master, jB);
kill(CPID, 9);
}
else
{
mR->master->wd_shutdown();
};
break; //-----> exit thread
};
SLEEP(SW_TIMEOUT_PERCISION);
};
shutdown(mR->client_socket, 2);
close(mR->client_socket);
mR->client_socket = -1;
mR->finished = true;
};
pthread_exit(NULL);
return NULL;
}
void SP_KERNEL::m_fThreadProc(void)
{
struct sockaddr_un client_addr;
unsigned int clen = sizeof(client_addr);
int ClientSocket;
m_bThreadStatus = TH_WORKING;
while (m_bThreadStatus < TH_ENDED)
{
ClientSocket = accept(m_iServerSocket, (struct sockaddr *) &client_addr, &clen);
if (ClientSocket < 0)
{
switch (errno)
{
case EAGAIN:
{
// Checkup client disconnection: join and free finished handlers
// (erase() inside the for loop skipped the next handler; the records were never freed)
for (WATCHDOG_PROCS_VECTOR::iterator index = m_vWPV.begin(); index != m_vWPV.end();)
{
if ((*index)->finished)
{
pthread_join((*index)->handler, NULL);
LOG("WD Procedure Removed");
free(*index);
index = m_vWPV.erase(index);
}
else
{
++index;
};
};
SLEEP(10);
continue;
};
// case EWOULDBLOCK: me->Log(" The socket is marked non-blocking and no connections are present to be accepted."); break;
case EBADF : LOG_ERROR("The descriptor is invalid."); break;
case ECONNABORTED: LOG_ERROR("A connection has been aborted."); break;
case EINTR : LOG_ERROR("The system call was interrupted by a signal that was caught before a valid connection arrived."); break;
case EINVAL : LOG_ERROR("Socket is not listening for connections, or addrlen is invalid (e.g., is negative)."); break;
case EMFILE : LOG_ERROR("The per-process limit of open file descriptors has been reached."); break;
case ENFILE : LOG_ERROR("The system limit on the total number of open files has been reached."); break;
case ENOTSOCK : LOG_ERROR("The descriptor references a file, not a socket."); break;
case EOPNOTSUPP : LOG_ERROR("The referenced socket is not of type SOCK_STREAM."); break;
case EFAULT : LOG_ERROR("The addr argument is not in a writable part of the user address space."); break;
case ENOBUFS :
case ENOMEM : LOG_ERROR("Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory."); break;
case EPROTO : LOG_ERROR("Protocol error."); break;
case EPERM : LOG_ERROR("Firewall rules forbid connection."); break;
case ENOSR:
#ifdef __linux__
case ESOCKTNOSUPPORT:
#endif
case EPROTONOSUPPORT:
case ETIMEDOUT : LOG_ERROR(" Unusual error in Kernel (Timeout, No Socket Support in Kernel, Unsupported Protocol)"); break;
// case ERESTARTSYS: me->Log(" Unusual error by Kernel"); break;
default: LOG_ERROR(" Unhandled error in Kernel"); break;
};
m_bThreadStatus = TH_ENDED;
}
else
{
WATCHDOG_PROC_REC * tPRC = (WATCHDOG_PROC_REC *) malloc(sizeof(WATCHDOG_PROC_REC));
if (tPRC)
{
int x = fcntl(ClientSocket, F_GETFL, 0);
fcntl(ClientSocket, F_SETFL, x | O_NONBLOCK);
memset(tPRC, 0, sizeof(WATCHDOG_PROC_REC)); // finished was uninitialized (malloc): a live handler
// could be joined - the accept loop blocked
tPRC->client_socket = ClientSocket;
tPRC->master = this;
tPRC->finished = false;
int RetVal = pthread_create(&tPRC->handler, NULL, sw_proc, (void *) tPRC);
if (RetVal != 0) // pthread_create returns an error number, not -1
{
LOG_ERROR("No Client Thread Created!");
shutdown(ClientSocket, 2);
close(ClientSocket);
free(tPRC);
}
else
{
LOG("New Handler Created");
m_vWPV.push_back(tPRC);
};
}
else
{
LOG_ERROR("No Client Handler Created!");
shutdown(ClientSocket, 2);
close(ClientSocket);
};
};
};
}
#undef LOG_ERROR
#undef LOG