Change logging in netdaemon, add command for reboot

This commit is contained in:
Edward Emelianov 2020-08-24 18:02:20 +03:00
parent d97273f177
commit 722645aa16
15 changed files with 107 additions and 72 deletions

0
STM32/2sensors_logging/tsys01.bin Executable file → Normal file
View File

0
STM32/TSYS_controller/tsys01.bin Normal file → Executable file
View File

0
STM32/Tcalc/tsys01.bin Executable file → Normal file
View File

0
STM32/Tcalc_screen/tsys01.bin Executable file → Normal file
View File

0
STM32/Tcalc_screen_ver2/tcalc_screen.bin Executable file → Normal file
View File

0
STM32/inc/gen042 Executable file → Normal file
View File

0
STM32/src4multiplexer/tsys01.bin Executable file → Normal file
View File

View File

@ -94,7 +94,7 @@ static void gnuplot(char *path, char *fname){
DBG("Run %s", buf); DBG("Run %s", buf);
if(system(buf)){ if(system(buf)){
WARNX(_("Can't run `%s`"), buf); WARNX(_("Can't run `%s`"), buf);
}else putlog("created chart %s", fname); }else LOG("created chart %s", fname);
} }
void plot(double data[2][NCHANNEL_MAX+1][NCTRLR_MAX+1], char *savepath){ void plot(double data[2][NCHANNEL_MAX+1][NCTRLR_MAX+1], char *savepath){

View File

@ -19,8 +19,10 @@
* MA 02110-1301, USA. * MA 02110-1301, USA.
*/ */
#include <signal.h> #include <signal.h>
#include <sys/wait.h> // wait
#include <sys/prctl.h> //prctl #include <sys/prctl.h> //prctl
#include <sys/types.h>
#include <sys/wait.h> // wait
#include "checkfile.h" #include "checkfile.h"
#include "cmdlnopts.h" #include "cmdlnopts.h"
#include "socket.h" #include "socket.h"
@ -36,8 +38,8 @@ void signals(int signo){
restore_tty(); restore_tty();
if(childpid){ if(childpid){
const char *s = signum_to_signame(signo); const char *s = signum_to_signame(signo);
if(s) putlog("exit with status %d (or by signal %s)", signo, s); if(s) LOG("exit with status %d (or by signal %s)", signo, s);
else putlog("exit with status %d", signo); else LOG("exit with status %d", signo);
} }
exit(signo); exit(signo);
} }
@ -52,10 +54,10 @@ static void repsig(int signo){
static void refreshAdj(_U_ int signo){ static void refreshAdj(_U_ int signo){
DBG("refresh adj"); DBG("refresh adj");
if(childpid){ // I am a master if(childpid){ // I am a master
putlog("Force child %d to re-read adj-file", childpid); LOG("Force child %d to re-read adj-file", childpid);
kill(childpid, SIGUSR1); kill(childpid, SIGUSR1);
}else{ // I am a child }else{ // I am a child
putlog("Re-read adj-file"); LOG("Re-read adj-file");
read_adj_file(G->adjfilename); read_adj_file(G->adjfilename);
} }
} }
@ -63,9 +65,9 @@ static void refreshAdj(_U_ int signo){
static void logT(_U_ int signo){ static void logT(_U_ int signo){
for(int i = 0; i < 3; ++i){ for(int i = 0; i < 3; ++i){
const char *s = gotstr(i); const char *s = gotstr(i);
if(s && *s) putlog("Sensors group #%d:\n%s", i, s); if(s && *s) LOG("Sensors group #%d:\n%s", i, s);
} }
putlog("Turn sensors off"); LOG("Turn sensors off");
TurnOFF(); TurnOFF();
} }
@ -94,7 +96,7 @@ int main(int argc, char **argv){
} }
if(runningproc) ERRX("Found running process, pid=%d.", runningproc); if(runningproc) ERRX("Found running process, pid=%d.", runningproc);
if(G->rest_pars_num) if(G->rest_pars_num)
openlogfile(G->rest_pars[0]); Cl_createlog(G->rest_pars[0]);
// ignore almost all possible signals // ignore almost all possible signals
for(int sig = 0; sig < 256; ++sig) signal(sig, repsig); for(int sig = 0; sig < 256; ++sig) signal(sig, repsig);
signal(SIGTERM, signals); // kill (-15) - quit signal(SIGTERM, signals); // kill (-15) - quit
@ -113,7 +115,7 @@ int main(int argc, char **argv){
while(1){ // guard for dead processes while(1){ // guard for dead processes
childpid = fork(); childpid = fork();
if(childpid){ if(childpid){
putlog("create child with PID %d\n", childpid); LOG("create child with PID %d\n", childpid);
DBG("Created child with PID %d\n", childpid); DBG("Created child with PID %d\n", childpid);
while(childpid != waitpid(childpid, NULL, 0)); while(childpid != waitpid(childpid, NULL, 0));
WARNX("Child %d died\n", childpid); WARNX("Child %d died\n", childpid);
@ -128,9 +130,9 @@ int main(int argc, char **argv){
DBG("dev: %s", G->device); DBG("dev: %s", G->device);
try_connect(G->device); try_connect(G->device);
if(check_sensors()){ if(check_sensors()){
putlog("No CAN-controllers detected"); LOG("No CAN-controllers detected");
if(!poll_sensors(0)){ // there's not main controller connected to given terminal if(!poll_sensors(0)){ // there's not main controller connected to given terminal
putlog("Opened device is not main controller"); LOG("Opened device is not main controller");
if(!G->terminal) signals(15); if(!G->terminal) signals(15);
} }
} }

0
src/netdaemon/plot Executable file → Normal file
View File

View File

@ -294,13 +294,13 @@ cont:
if(fabs(Tadj[i]) > DBL_EPSILON){ if(fabs(Tadj[i]) > DBL_EPSILON){
printf("\tTadj[%02d] = %g\n", i, Tadj[i]); printf("\tTadj[%02d] = %g\n", i, Tadj[i]);
} }
if(fabs(sensors[i].Tadj - Tadj[i]) > 0.001) putlog("Tadj[%d] = %g", i, Tadj[i]); if(fabs(sensors[i].Tadj - Tadj[i]) > 0.001) LOG("Tadj[%d] = %g", i, Tadj[i]);
sensors[i].Tadj = Tadj[i]; sensors[i].Tadj = Tadj[i];
} }
return 0; return 0;
reperr: reperr:
red("Error in string %d:\n", strnum); red("Error in string %d:\n", strnum);
printf("%s\n", adjf); printf("%s\n", adjf);
putlog("Erroneous log file %s in line %d", fname, strnum); LOG("Erroneous adjustment file %s in line %d", fname, strnum);
return 1; return 1;
} }

View File

@ -143,15 +143,21 @@ static char* stringscan(char *str, char *needle){
if(e) *e = 0; if(e) *e = 0;
return a; return a;
} }
typedef struct{
int sockn;
char *host;
} conn;
static void *handle_socket(void *asock){ static void *handle_socket(void *asock){
FNAME(); FNAME();
if(!asock) return NULL; if(!asock) return NULL;
int sock = *((int*)asock); conn C = *((conn*)asock);
int sock = C.sockn; //*((int*)asock);
int webquery = 0; // whether query is web or regular int webquery = 0; // whether query is web or regular
char buff[BUFLEN]; char buff[BUFLEN];
char tbuf[128];
int Nsens = -1; int Nsens = -1;
ssize_t rd; ssize_t rd, L;
double t0 = dtime(); double t0 = dtime();
while(dtime() - t0 < SOCKET_TIMEOUT){ while(dtime() - t0 < SOCKET_TIMEOUT){
if(!waittoread(sock)){ // no data incoming if(!waittoread(sock)){ // no data incoming
@ -176,23 +182,31 @@ static void *handle_socket(void *asock){
// web query have format GET /some.resource // web query have format GET /some.resource
} }
// here we can process user data // here we can process user data
printf("user send: %s\nfound=%s", buff,found); //printf("user send: %s\nfound=%s", buff,found);
if(strlen(found) == 2 && found[0] == 'T'){ if(strlen(found) < 5 && found[0] == 'T'){
Nsens = found[1] - '0'; Nsens = found[1] - '0';
if(Nsens < 0 || Nsens > 2) break; // wrong query if(Nsens < 0 || Nsens > 2){
L = write(sock, "Only T0, T1 and T2 available\n", 29);
break; // wrong query
}
pthread_mutex_lock(&mutex); pthread_mutex_lock(&mutex);
if(!send_data(sock, webquery, Nsens)){ if(!send_data(sock, webquery, Nsens)){
putlog("can't send data, some error occured"); LOG("can't send data, some error occured");
} }
pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&mutex);
}else if(strncmp("Tmean", found, 5) == 0){ // send user meanT }else if(strncmp("Tmean", found, 5) == 0){ // send user meanT
char tbuf[10]; L = snprintf(tbuf, 128, "%.2f\n", meanT);
ssize_t L = snprintf(tbuf, 10, "%.2f", meanT);
if(L != write(sock, tbuf, L)) WARN("write()"); if(L != write(sock, tbuf, L)) WARN("write()");
} // here can be more parsers }else if(strncmp("ReBoOt", found, 6) == 0){
LOG("Reboot command from %s", C.host);
L = write(sock, "Reboot system\n", 14);
if(0 != system("sudo reboot")) WARN("Can't reboot");
// here can be more parsers
}else L = write(sock, "Unrecognized command\n", 21);
break; break;
} }
close(sock); close(sock);
FREE(C.host);
pthread_exit(NULL); pthread_exit(NULL);
return NULL; return NULL;
} }
@ -200,7 +214,7 @@ static void *handle_socket(void *asock){
// main socket server // main socket server
static void *server(void *asock){ static void *server(void *asock){
if(!asock) return NULL; if(!asock) return NULL;
//putlog("server(): getpid: %d, pthread_self: %lu, tid: %lu",getpid(), pthread_self(), syscall(SYS_gettid)); //LOG("server(): getpid: %d, pthread_self: %lu, tid: %lu",getpid(), pthread_self(), syscall(SYS_gettid));
int sock = *((int*)asock); int sock = *((int*)asock);
if(listen(sock, BACKLOG) == -1){ if(listen(sock, BACKLOG) == -1){
WARN("listen()"); WARN("listen()");
@ -220,17 +234,19 @@ static void *server(void *asock){
struct in_addr ipAddr = pV4Addr->sin_addr; struct in_addr ipAddr = pV4Addr->sin_addr;
char str[INET_ADDRSTRLEN]; char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ipAddr, str, INET_ADDRSTRLEN); inet_ntop(AF_INET, &ipAddr, str, INET_ADDRSTRLEN);
//putlog("get connection from %s", str); //LOG("get connection from %s", str);
red("Got connection from %s\n", str); red("Got connection from %s\n", str);
pthread_t handler_thread; pthread_t handler_thread;
if(pthread_create(&handler_thread, NULL, handle_socket, (void*) &newsock)){ conn C = {.sockn = newsock};
C.host = strdup(str);
if(pthread_create(&handler_thread, NULL, handle_socket, (void*)&C)){
WARN("pthread_create()"); WARN("pthread_create()");
}else{ }else{
DBG("Thread created, detouch"); DBG("Thread created, detouch");
pthread_detach(handler_thread); // don't care about thread state pthread_detach(handler_thread); // don't care about thread state
} }
} }
putlog("server(): UNREACHABLE CODE REACHED!"); LOG("server(): UNREACHABLE CODE REACHED!");
} }
typedef double Item; typedef double Item;
@ -412,7 +428,7 @@ static void daemon_(int sock){
memcpy(strT, bufs, sizeof(strT)); memcpy(strT, bufs, sizeof(strT));
pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&mutex);
}while(1); }while(1);
putlog("daemon_(): UNREACHABLE CODE REACHED!"); LOG("daemon_(): UNREACHABLE CODE REACHED!");
} }
/** /**
@ -458,7 +474,7 @@ void daemonize(char *port){
freeaddrinfo(res); freeaddrinfo(res);
daemon_(sock); daemon_(sock);
close(sock); close(sock);
putlog("daemonize(): UNREACHABLE CODE REACHED!"); LOG("daemonize(): UNREACHABLE CODE REACHED!");
signals(0); signals(0);
} }

View File

@ -78,7 +78,7 @@ void try_connect(char *device){
fflush(stdout); fflush(stdout);
tty_init(device); tty_init(device);
read_tty(tmpbuf, 4096); // clear rbuf read_tty(tmpbuf, 4096); // clear rbuf
putlog("Connected to %s", device); LOG("Connected to %s", device);
} }
/** /**
@ -238,7 +238,7 @@ int check_sensors(){
if(i == ans[sizeof(ANS_PONG)-1] - '0'){ if(i == ans[sizeof(ANS_PONG)-1] - '0'){
++found; ++found;
green(_("Found controller #%d\n"), i); green(_("Found controller #%d\n"), i);
putlog("Found controller #%d", i); LOG("Found controller #%d", i);
break; break;
} }
} }

View File

@ -388,54 +388,66 @@ int str2double(double *num, const char *str){
return TRUE; return TRUE;
} }
FILE *Flog = NULL; // log file descriptor //////////// logging
char *logname = NULL;
time_t log_open_time = 0; static Cl_log log = {0};
/** /**
* Try to open log file * @brief Cl_createlog - create log file: init mutex, test file open ability
* if failed show warning message * @param log - log structure
* @return 0 if all OK
*/ */
void openlogfile(char *name){ int Cl_createlog(char *logname){
if(!name){ if(log.logpath){
WARNX(_("Need filename")); FREE(log.logpath);
return; pthread_mutex_destroy(&log.mutex);
} }
green(_("Try to open log file %s in append mode\n"), name); FILE *logfd = fopen(logname, "a");
if(!(Flog = fopen(name, "a"))){ if(!logfd){
WARN(_("Can't open log file")); WARN("Can't open log file");
return; return 2;
} }
log_open_time = time(NULL); log.logpath = strdup(logname);
logname = name; fclose(logfd);
if(pthread_mutex_init(&log.mutex, NULL)){
WARN("Can't init log mutes");
return 3;
}
return 0;
} }
/** /**
* Save message to log file, rotate logs every 24 hours * @brief Cl_putlog - put message to log file with/without timestamp
* @param timest - ==1 to put timestamp
* @param log - pointer to log structure
* @param lvl - message loglevel (if lvl > loglevel, message won't be printed)
* @param fmt - format and the rest part of message
* @return amount of symbols saved in file
*/ */
int putlog(const char *fmt, ...){ int Cl_putlogt(const char *fmt, ...){
if(!Flog) return 0; if(pthread_mutex_lock(&log.mutex)){
time_t t_now = time(NULL); WARN("Can't lock log mutex");
if(t_now - log_open_time > 86400){ // rotate log return 0;
fprintf(Flog, "\n\t\t%sRotate log\n", ctime(&t_now));
fclose(Flog);
char newname[PATH_MAX];
snprintf(newname, PATH_MAX, "%s.old", logname);
if(rename(logname, newname)) WARN("rename()");
openlogfile(logname);
if(!Flog) return 0;
} }
int i = fprintf(Flog, "\n\t\t%s", ctime(&t_now)); int i = 0;
FILE *logfd = fopen(log.logpath, "a");
if(!logfd) goto rtn;
char strtm[128];
time_t t = time(NULL);
struct tm *curtm = localtime(&t);
strftime(strtm, 128, "%Y/%m/%d-%H:%M:%S", curtm);
i = fprintf(logfd, "%s\t", strtm);
va_list ar; va_list ar;
va_start(ar, fmt); va_start(ar, fmt);
i = vfprintf(Flog, fmt, ar); i += vfprintf(logfd, fmt, ar);
va_end(ar); va_end(ar);
fprintf(Flog, "\n"); i += fprintf(logfd, "\n");
fflush(Flog); fclose(logfd);
rtn:
pthread_mutex_unlock(&log.mutex);
return i; return i;
} }
/* /*
* Copyright (c) 1988, 1993, 1994, 2017 * Copyright (c) 1988, 1993, 1994, 2017
* The Regents of the University of California. All rights reserved. * The Regents of the University of California. All rights reserved.

View File

@ -45,12 +45,13 @@
#define _(String) (String) #define _(String) (String)
#define N_(String) (String) #define N_(String) (String)
#endif #endif
#include <pthread.h>
#include <stdint.h>
#include <stdlib.h> #include <stdlib.h>
#include <termios.h>
#include <termio.h> #include <termio.h>
#include <termios.h>
#include <sys/time.h> #include <sys/time.h>
#include <sys/types.h> #include <sys/types.h>
#include <stdint.h>
// unused arguments with -Wall -Werror // unused arguments with -Wall -Werror
@ -76,11 +77,11 @@
*/ */
extern int globErr; extern int globErr;
extern void signals(int sig); extern void signals(int sig);
#define ERR(...) do{globErr=errno; putlog(__VA_ARGS__); _WARN(__VA_ARGS__); signals(9);}while(0) #define ERR(...) do{globErr=errno; Cl_putlogt(__VA_ARGS__); _WARN(__VA_ARGS__); signals(9);}while(0)
#define ERRX(...) do{globErr=0; putlog(__VA_ARGS__); _WARN(__VA_ARGS__); signals(9);}while(0) #define ERRX(...) do{globErr=0; Cl_putlogt(__VA_ARGS__); _WARN(__VA_ARGS__); signals(9);}while(0)
#define WARN(...) do{globErr=errno; putlog(__VA_ARGS__); _WARN(__VA_ARGS__);}while(0) #define WARN(...) do{globErr=errno; Cl_putlogt(__VA_ARGS__); _WARN(__VA_ARGS__);}while(0)
#define WARNX(...) do{globErr=0; putlog(__VA_ARGS__); _WARN(__VA_ARGS__);}while(0) #define WARNX(...) do{globErr=0; Cl_putlogt(__VA_ARGS__); _WARN(__VA_ARGS__);}while(0)
#define LOG(...) do{Cl_putlogt(__VA_ARGS__); }while(0)
/* /*
* print function name, debug messages * print function name, debug messages
* debug mode, -DEBUG * debug mode, -DEBUG
@ -134,9 +135,13 @@ int write_tty(char *buff, size_t length);
int str2double(double *num, const char *str); int str2double(double *num, const char *str);
void openlogfile(char *name); typedef struct{
int putlog(const char *fmt, ...); char *logpath; // full path to logfile
pthread_mutex_t mutex; // log mutex
} Cl_log;
int Cl_createlog(char *logname);
int Cl_putlogt(const char *fmt, ...);
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
const char *signum_to_signame(int signum); const char *signum_to_signame(int signum);