source: MondoRescue/branches/stable/monitas/common.c@ 352

Last change on this file since 352 was 352, checked in by bcornec, 18 years ago

monitas v0.1a

File size: 15.8 KB
Line 
1/* common.c - functions common to server.c and client.c
2
3
4
506/19
6- fixed silly bug in create_and_watch_fifo_for_commands()
7
806/16
9- added program_still_running()
10
1106/14
12- added create_and_watch_fifo_for_commands() from server.c
13- if log_it(fatal,...) then call terminate_daemon()
14
1506/11
16- added register_pid(), set_signals()
17- commented code a bit
18
1906/10
20- create function to call external executable in background
21- create function to wait for it to terminate & to grab its result
22- put them in common.c
23
24
25
26*/
27
28#include "structs.h"
29
30
31extern char g_command_fifo[MAX_STR_LEN+1];
32extern char g_logfile[MAX_STR_LEN+1];
33extern char *call_program_and_get_last_line_of_output(char*);
34extern int call_program_and_log_output (char *);
35extern bool does_file_exist (char *);
36extern int make_hole_for_file (char *outfile_fname);
37extern int process_incoming_command(char*);
38extern void terminate_daemon(int);
39
40
41void call_program_in_background(pthread_t*, char*);
42void *call_prog_in_bkgd_SUB(void*);
43int create_and_watch_fifo_for_commands(char*);
44int get_bkgd_prog_result(pthread_t*);
45void log_it_SUB(char*, t_loglevel, char*);
46bool program_still_running(char*);
47int receive_file_from_socket(FILE*fout, int socket_fd);
48void register_pid(pid_t, char*);
49void set_signals(bool);
50char *tmsg_to_string(t_msg msg_type);
51int read_block_from_fd(int, char*, int);
52void termination_in_progress(int sig);
53int transmit_file_to_socket(FILE*fin, int socket_fd);
54
55
56
57/*-----------------------------------------------------------*/
58
59
60
61void call_program_in_background(pthread_t *thread, char*command)
62/*
63Purpose:Execute external binary in a background thread created
64 specially for this purpose. Return. Leave binary running.
65Params: thread - [returned] thread running in background
66 command - binary call to be executed
67Return: 0 if prog started ok; nonzero if failure
68NB: Use get_bkgd_prog_result() to wait for binary to terminate
69 and to get binary's result (zero or nonzero)
70*/
71{
72 int res;
73
74 res = pthread_create(thread, NULL, call_prog_in_bkgd_SUB, (void*)command);
75 if (res) { log_it(fatal, "Unable to call program in background - thread creation failure"); }
76 log_it(debug, "Done creating pthread. Will continue now.");
77}
78
79
80
81/*-----------------------------------------------------------*/
82
83
84
85void *call_prog_in_bkgd_SUB(void*cmd)
86{
87/*
88Purpose:Subroutine of call_program_in_background()
89Params: cmd - binary call to be executed
90Return: None
91*/
92 char*command;
93 int res;
94 char tmp[MAX_STR_LEN+1];
95 static char result_str[MAX_STR_LEN+1];
96
97 command=(char*)cmd;
98 sprintf(tmp, "Calling '%s' in background pthread", command);
99 log_it(debug, tmp);
100 res = system(command);
101 sprintf(tmp, "'%s' is returning from bkgd process - res=%d", command, res);
102 log_it(debug, tmp);
103 sprintf(result_str, "%d", res);
104 pthread_exit((void*)result_str);
105}
106
107
108
109/*-----------------------------------------------------------*/
110
111
112
113int create_and_watch_fifo_for_commands(char*devpath)
114/*
115Purpose:Create a FIFO (device). Open it. Read commands from it
116 if/when they're echoed to it (e.g. backup, restore, ...)
117Params: devpath - path+filename of FIFO to create
118Return: result (nonzero=failure; else, infinite loop & notional 0)
119*/
120{
121 char tmp[MAX_STR_LEN+1], incoming[MAX_STR_LEN+1];
122 int res=0, fd, len, pos=0;
123
124 res = make_hole_for_file(devpath) + mkfifo(devpath, 700);
125 if (res) { log_it(error, "Unable to prepare command FIFO"); return(res); }
126 strncpy(g_command_fifo, devpath, MAX_STR_LEN);
127 if (!(fd = open(g_command_fifo, O_RDONLY))) { log_it(error, "Unable to openin command FIFO"); return(1); }
128// log_it(info, "Awaiting commands from FIFO");
129 for(;;)
130 {
131 len=read(fd, incoming+pos, 1);
132 if (len==0) { usleep(1000); continue; }
133 pos+=len;
134 incoming[pos]='\0';
135 if (incoming[pos-1]=='\n' || pos>=MAX_STR_LEN)
136 {
137 incoming[pos-1]='\0';
138 len=pos=0;
139 res=process_incoming_command(incoming);
140 if (res)
141 {
142 sprintf(tmp, "%s <-- errors occurred during processing", incoming);
143 log_it(error, tmp);
144 }
145 else
146 {
147 sprintf(tmp, "%s <-- command received OK", incoming);
148 log_it(info, tmp);
149 }
150 }
151 } // forever
152 return(0);
153}
154
155
156/*-----------------------------------------------------------*/
157
158
159
160int get_bkgd_prog_result(pthread_t *thread)
161/*
162Purpose:Wait for external binary (running in background) to terminate.
163 Discover how it ended (w/success or w/failure?).
164Params: thread - thread running in background
165Return: result (0=success, nonzero=failure)
166NB: Binary was executed by call_program_in_background(). This
167 subroutine should be called sometime after that call.
168*/
169{
170 void*vp;
171 void**pvp;
172 int res;
173 char tmp[MAX_STR_LEN+1], *p, result_str[MAX_STR_LEN+1];
174
175 pvp=&vp;
176 vp=(void*)result_str;
177 strcpy(result_str, "(uninitialized)");
178 log_it(debug, "Waiting for bkgd prog to finish, so that we can get its result");
179 if (pthread_join(*thread, pvp)) { log_it(fatal, "pthread_join failed"); }
180 p = result_str;
181 p = (char*)vp;
182 res = atoi(p);
183 sprintf(tmp, "pthread res = %d ('%s')", res, p);
184 log_it(debug, tmp);
185 *thread = 0;
186 return(res);
187}
188
189
190
191/*-----------------------------------------------------------*/
192
193
194
195void log_it_SUB(char *logfile, t_loglevel level, char *sz_message)
196/*
197Purpose:Log event and its level of severity.
198Params: level - level of severity (debug/info/warn/error/fatal)
199 sz_message - message/event [string]
200Return: None
201*/
202{
203 char sz_outstr[MAX_STR_LEN], sz_level[MAX_STR_LEN], sz_time[MAX_STR_LEN];
204 time_t time_rec;
205 FILE*fout;
206
207 time(&time_rec);
208 switch(level)
209 {
210 case debug: strcpy(sz_level, "DEBUG"); break;
211 case info: strcpy(sz_level, "INFO "); break;
212 case warn: strcpy(sz_level, "WARN "); break;
213 case error: strcpy(sz_level, "ERROR"); break;
214 case fatal: strcpy(sz_level, "FATAL"); break;
215 default: strcpy(sz_level, "UNKWN"); break;
216 }
217 sprintf(sz_time, ctime(&time_rec));
218 sz_time[strlen(sz_time)-6] = '\0';
219 sprintf(sz_outstr, "%s %s: %s", sz_time+11, sz_level, sz_message);
220 if ((int)level >= LOG_THESE_AND_HIGHER)
221 {
222 while (!(fout=fopen(logfile,"a"))) { usleep((int)(random()%32768)); }
223 fprintf(fout, "%s\n",sz_outstr);
224 fclose(fout);
225 }
226 if (level==fatal)
227 {
228 fprintf(stderr, "Aborting now. See %s for more information.\n", g_logfile);
229 terminate_daemon(0);
230 exit(1);
231 }
232}
233
234
235
236/*-----------------------------------------------------------*/
237
238
239
240bool program_still_running(char*command)
241{
242 char comm_sub[MAX_STR_LEN+1],
243 tmp[MAX_STR_LEN+1];
244 strncpy(comm_sub, command, 40);
245 comm_sub[40] = '\0';
246 sprintf(tmp, "ps ax | grep \"%s\" | grep -v \"ps ax\" | grep -v \"grep \"", comm_sub);
247 if (call_program_and_log_output(tmp))
248 { return(false); }
249 else
250 { return(true); }
251}
252
253
254
255/*-----------------------------------------------------------*/
256
257
258
259int read_block_from_fd(int socket_fd, char*buf, int len_to_read)
260/*
261Purpose:Read N bytes from socket, into buffer
262Params: socket_fd - socket to be read from
263 buf - buffer where incoming data will be stored
264 len_to_read - bytes to be read from socket
265Return: bytes read
266NB: if bytes read < len_to_read then there is
267 probably something wrong (e.g. EOF of pipe)
268*/
269{
270 int length, noof_tries, i=0;
271 char tmp[MAX_STR_LEN+1];
272
273// log_it(debug, "Reading from pipe");
274 for(length=noof_tries=0; length<len_to_read && noof_tries<10; length+=i)
275 {
276 i = read(socket_fd, buf+length, len_to_read-length);
277 if (i==0) { noof_tries++; }
278 if (i<0) { log_it(error, "Error while reading from fd"); return(-1); }
279 }
280 if (length != len_to_read) { log_it(error, "Unable to continue reading from fd"); }
281 sprintf(tmp, "%d of %d bytes read from fd", length, len_to_read);
282 return(length);
283}
284
285
286
287/*-----------------------------------------------------------*/
288
289
290
291int receive_file_from_socket(FILE*fout, int socket_fd)
292/*
293Purpose:Receive file from socket and save to disk / stream.
294Params: socket_fd - file descriptor of socket
295 fout - file descriptor of output file
296Return: result (0=success, nonzero=failure)
297NB: socket_fd was created with open() but
298 fopen was created with fopen(). Different, see? Nyah.
299*/
300{
301 int res=0, length, rotor=0, incoming_len;
302 char tmp[MAX_STR_LEN+1], buf[XFER_BUF_SIZE];
303 bool done;
304 long long total_length=0;
305
306 signal(SIGPIPE, SIG_IGN);
307
308 length=99999;
309// sleep(1);
310 for(done=false; !done; )
311 {
312 // usleep(1000);
313 length = read_block_from_fd(socket_fd, buf, 3);
314 if (length<3) { log_it(debug, "Failed to read header block from fd"); res++; done=true; continue; }
315 rotor=(rotor%127)+1;
316 sprintf(tmp, "Rotor is %d (I was expecting %d)", buf[0], rotor);
317 if (buf[0]==0 && buf[1]==0x7B && buf[2]==0x21) { log_it(debug, "OK, end of stream. Cool."); done=true; continue; }
318// log_it(debug, tmp);
319 if (buf[0]!=rotor) { log_it(debug, "Rotors do not match"); res++; break; }
320 incoming_len = buf[2];
321 if (incoming_len < 0) { incoming_len += 256; }
322 incoming_len += buf[1] * 256;
323 // memcpy((char*)&incoming_len, buf+1, 2);
324 sprintf(tmp, "Expecting %d bytes in block #%d", incoming_len, rotor);
325// log_it(debug, tmp);
326 length = read_block_from_fd(socket_fd, buf, incoming_len);
327/*
328 for(length=0,i=0; length<incoming_len; length+=i)
329 {
330 i = read(socket_fd, buf+length, incoming_len-length);
331 if (length<0) { log_it(debug, "Unable to read block in from socket_fd"); done=true; }
332 else if (length==0) { log_it(debug, "Zero-length block arrived from socket"); }
333 sprintf(tmp, "Read %d bytes from socket", i);
334// log_it(debug, tmp);
335 }
336*/
337 if (length != incoming_len) { log_it(debug, "Error reading from socket"); res++; }
338 if (fwrite(buf, 1, length, fout)!=length) { log_it(debug, "Error writing data to output file"); res++; }
339 sprintf(tmp, "Written %d bytes to output stream", length);
340 total_length += length;
341// log_it(debug, tmp);
342 }
343 if (total_length==0) { res++; log_it(debug, "Zero-length file received. Silly. I say that's an error."); }
344
345 signal(SIGPIPE, terminate_daemon);
346
347 return(res);
348}
349
350
351
352
353/*-----------------------------------------------------------*/
354
355
356
357void register_pid(pid_t pid, char*name_str)
358/*
359Purpose:Register executable's PID in /var/run/monitas-[name_str].pid;
360 store [pid] in data file
361Params: pid - process ID to be stored in data file
362 name_str - name (e.g. "client" or "server") to be included
363 in the data file name of the PID locking file
364Return: None
365NB: Use pid=0 to delete the lock file and unregister the PID
366*/
367{
368 char tmp[MAX_STR_LEN+1], lockfile_fname[MAX_STR_LEN+1];
369 int res;
370 FILE*fin;
371
372 sprintf(lockfile_fname, "/var/run/monitas-%s.pid", name_str);
373 if (!pid)
374 {
375 log_it(debug, "Unregistering PID");
376 if (unlink(lockfile_fname)) { log_it(error, "Error unregistering PID"); }
377 return;
378 }
379 if (does_file_exist(lockfile_fname))
380 {
381 tmp[0]='\0';
382 if ((fin=fopen(lockfile_fname,"r"))) { fgets(tmp, MAX_STR_LEN, fin); fclose(fin); }
383 pid = atol(tmp);
384 sprintf(tmp, "ps %ld", (long int)pid);
385 res = call_program_and_log_output(tmp);
386 if (!res)
387 {
388 sprintf(tmp, "I believe the daemon is already running. If it isn't, please delete %s and try again.", lockfile_fname);
389 log_it(fatal, tmp);
390 }
391 }
392 sprintf(tmp, "echo %ld > %s", (long int)getpid(), lockfile_fname);
393 if (system(tmp)) { log_it(fatal, "Cannot register PID"); }
394}
395
396
397
398/*-----------------------------------------------------------*/
399
400
401
402void set_signals(bool on)
403/*
404Purpose:Turn on/off signal-trapping
405Params: on - turn on or off (true=on, false=off)
406Return: None
407*/
408{
409 int signals[]= { SIGKILL, SIGPIPE, SIGTERM, SIGHUP, SIGTRAP, SIGABRT, SIGINT, SIGSTOP, 0 };
410 int i;
411 for (i=0; signals[i]; i++)
412 {
413 if (on)
414 { signal(signals[i], terminate_daemon); }
415 else
416 { signal(signals[i], termination_in_progress); }
417 }
418}
419
420
421
422/*-----------------------------------------------------------*/
423
424
425
426void termination_in_progress(int sig)
427{
428 log_it(debug, "Termination in progress");
429 usleep(1000);
430 pthread_exit(0);
431}
432
433
434
435/*-----------------------------------------------------------*/
436
437
438
439char *tmsg_to_string(t_msg msg_type)
440/*
441Purpose:turn msg_type struct variable into a string
442Params: msg_type - type of message
443Return: pointer to static string containing text version of msg_type
444*/
445{
446 static char sz_msg[MAX_STR_LEN];
447 switch(msg_type)
448 {
449 case unused : strcpy(sz_msg, "unused"); break;
450 case login : strcpy(sz_msg, "login"); break;
451 case logout : strcpy(sz_msg, "logout"); break;
452 case login_ok:strcpy(sz_msg, "login_ok"); break;
453 case logout_ok:strcpy(sz_msg, "logout_ok"); break;
454 case ping : strcpy(sz_msg, "ping"); break;
455 case pong : strcpy(sz_msg, "pong"); break;
456 case login_fail : strcpy(sz_msg, "login_fail"); break;
457 case logout_fail: strcpy(sz_msg, "logout_fail"); break;
458 case trigger_backup: strcpy(sz_msg, "trigger_backup"); break;
459 case trigger_compare:strcpy(sz_msg, "trigger_compare"); break;
460 case trigger_restore:strcpy(sz_msg, "trigger_restore"); break;
461 case begin_stream: strcpy(sz_msg, "begin_stream"); break;
462 case end_stream: strcpy(sz_msg, "end_stream"); break;
463 case backup_ok: strcpy(sz_msg, "backup_ok"); break;
464 case backup_fail: strcpy(sz_msg, "backup_fail"); break;
465 case compare_ok: strcpy(sz_msg, "compare_ok"); break;
466 case compare_fail: strcpy(sz_msg, "compare_fail"); break;
467 case restore_ok: strcpy(sz_msg, "restore_ok"); break;
468 case restore_fail: strcpy(sz_msg, "restore_fail"); break;
469 case user_req: strcpy(sz_msg, "user_req"); break;
470 case progress_rpt: strcpy(sz_msg, "progress_rpt"); break;
471 default: strcpy(sz_msg, "(Fix tmsg_to_string please)"); break;
472 }
473 return(sz_msg);
474}
475
476
477
478/*-----------------------------------------------------------*/
479
480
481
482int transmit_file_to_socket(FILE*fin, int socket_fd)
483/*
484Purpose:Transmit file to socket, from disk / stream.
485Params: socket_fd - file descriptor of socket
486 fin - file descriptor of input file
487Return: result (0=success, nonzero=failure)
488NB: socket_fd was created with open() but
489 fopen was created with fopen(). Different, see? Nyah.
490*/
491{
492 char tmp[MAX_STR_LEN+1], buf[XFER_BUF_SIZE];
493 int length, retval=0, rotor=0;
494 bool done;
495
496 signal(SIGPIPE, SIG_IGN);
497 for(done=false; !done; )
498 {
499 if (feof(fin))
500 {
501 log_it(debug, "eof(fin) - OK, stopped reading from mondoarchive");
502 done=true;
503 continue;
504 }
505// log_it(debug, "Reading from mondoarchive");
506 length = fread(buf, 1, XFER_BUF_SIZE, fin); /* read from fifo (i.e. mondoarchive) */
507// sprintf(tmp, "%d bytes read from mondoarchive", length); log_it(debug, tmp);
508 if (length > 0)
509 {
510 tmp[0] = (char)(rotor=(rotor%127)+1);
511 tmp[1] = (char)(length / 256);
512 tmp[2] = (char)(length % 256);
513 if (write(socket_fd, tmp, 3)!=3) { log_it(debug, "Failed to write rotor and block_len to socket"); retval++; done=true; continue; }
514// else { log_it(debug, "rotor and block_len written to socket"); }
515 if (write(socket_fd, buf, length)!=length) { log_it(debug, "Failed to write block read from mondoarchive to socket"); retval++; done=true; continue; }
516 else
517 {
518 sprintf(tmp, "Block #%d (%d bytes) written to socket", rotor, length);
519// log_it(debug, tmp);
520 }
521 }
522 else if (length < 0)
523 { log_it(warn, "I had trouble reading from FIFO while calling mondoarchive"); }
524 }
525 if (retval==0)
526 {
527// log_it(debug, "Writing final rotor (the 'end of stream' one) to socket");
528 tmp[0]=0;
529 tmp[1]=0x7B;
530 tmp[2]=0x21;
531 if (write(socket_fd, tmp, 3)!=3) { log_it(debug, "Failed to write end-of-stream rotor to socket"); retval++; }
532 }
533 log_it(debug, "Closed fopen() to tempdev");
534// fclose(fin);
535 signal(SIGPIPE, terminate_daemon);
536 return(retval);
537}
538
539
540
541
542
543
544
545
Note: See TracBrowser for help on using the repository browser.