When setting up the logging, set the event to trigger a read of a log message from...
[sahlberg/ctdb.git] / server / ctdb_logging.c
1 /* 
2    ctdb logging code
3
4    Copyright (C) Andrew Tridgell  2008
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "lib/events/events.h"
22 #include "../include/ctdb.h"
23 #include "../include/ctdb_private.h"
24 #include "system/syslog.h"
25 #include "system/time.h"
26 #include "system/filesys.h"
27
28 struct syslog_message {
29         uint32_t level;
30         uint32_t len;
31         char message[1];
32 };
33
34
35 struct ctdb_syslog_state {
36         int syslog_fd;
37         int fd[2];
38 };
39
40 static int syslogd_is_started = 0;
41
42
43 /* called when child is finished
44  * this is for the syslog daemon, we can not use DEBUG here
45  */
46 static void ctdb_syslog_handler(struct event_context *ev, struct fd_event *fde, 
47                                       uint16_t flags, void *p)
48 {
49         struct ctdb_syslog_state *state = talloc_get_type(p, struct ctdb_syslog_state);
50
51         int count;
52         char str[65536];
53         struct syslog_message *msg;
54
55         if (state == NULL) {
56                 return;
57         }
58
59         count = recv(state->syslog_fd, str, sizeof(str), 0);
60         if (count < sizeof(struct syslog_message)) {
61                 return;
62         }
63         msg = (struct syslog_message *)str;
64
65         syslog(msg->level, "%s", msg->message);
66 }
67
68
69 /* called when the pipd from the main daemon has closed
70  * this is for the syslog daemon, we can not use DEBUG here
71  */
72 static void ctdb_syslog_terminate_handler(struct event_context *ev, struct fd_event *fde, 
73                                       uint16_t flags, void *p)
74 {
75         syslog(LOG_ERR, "Shutting down SYSLOG daemon with pid:%d", (int)getpid());
76         _exit(0);
77 }
78
79
80
81 /*
82  * this is for the syslog daemon, we can not use DEBUG here
83  */
84 int start_syslog_daemon(struct ctdb_context *ctdb)
85 {
86         struct sockaddr_in syslog_sin;
87         struct ctdb_syslog_state *state;
88
89         state = talloc(ctdb, struct ctdb_syslog_state);
90         CTDB_NO_MEMORY(ctdb, state);
91
92         if (pipe(state->fd) != 0) {
93                 printf("Failed to create syslog pipe\n");
94                 talloc_free(state);
95                 return -1;
96         }
97         
98         ctdb->syslogd_pid = fork();
99         if (ctdb->syslogd_pid == (pid_t)-1) {
100                 printf("Failed to create syslog child process\n");
101                 close(state->fd[0]);
102                 close(state->fd[1]);
103                 talloc_free(state);
104                 return -1;
105         }
106
107         syslogd_is_started = 1;
108
109         if (ctdb->syslogd_pid != 0) {
110                 DEBUG(DEBUG_ERR,("Starting SYSLOG child process with pid:%d\n", (int)ctdb->syslogd_pid));
111
112                 close(state->fd[1]);
113                 set_close_on_exec(state->fd[0]);
114
115                 return 0;
116         }
117
118         talloc_free(ctdb->ev);
119         ctdb->ev = event_context_init(NULL);
120
121         syslog(LOG_ERR, "Starting SYSLOG daemon with pid:%d", (int)getpid());
122
123         close(state->fd[0]);
124         event_add_fd(ctdb->ev, state, state->fd[1], EVENT_FD_READ|EVENT_FD_AUTOCLOSE,
125                      ctdb_syslog_terminate_handler, state);
126
127         state->syslog_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
128         if (state->syslog_fd == -1) {
129                 printf("Failed to create syslog socket\n");
130                 return -1;
131         }
132
133         syslog_sin.sin_family = AF_INET;
134         syslog_sin.sin_port   = htons(CTDB_PORT);
135         syslog_sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);    
136
137         if (bind(state->syslog_fd, &syslog_sin, sizeof(syslog_sin)) == -1) {
138                 if (errno == EADDRINUSE) {
139                         /* this is ok, we already have a syslog daemon */
140                         _exit(0);
141                 }
142                 printf("syslog daemon failed to bind to socket. errno:%d(%s)\n", errno, strerror(errno));
143                 _exit(10);
144         }
145
146
147         event_add_fd(ctdb->ev, state, state->syslog_fd, EVENT_FD_READ|EVENT_FD_AUTOCLOSE,
148                      ctdb_syslog_handler, state);
149
150         event_loop_wait(ctdb->ev);
151
152         /* this should not happen */
153         _exit(10);
154 }
155
156 struct ctdb_log_state {
157         struct ctdb_context *ctdb;
158         int fd, pfd;
159         char buf[1024];
160         uint16_t buf_used;
161         bool use_syslog;
162         void (*logfn)(const char *, uint16_t, void *);
163         void *logfn_private;
164 };
165
166 /* we need this global to keep the DEBUG() syntax */
167 static struct ctdb_log_state *log_state;
168
169 /*
170   syslog logging function
171  */
172 static void ctdb_syslog_log(const char *format, va_list ap)
173 {
174         struct syslog_message *msg;
175         int level = LOG_DEBUG;
176         char *s = NULL;
177         int len, ret;
178         int syslog_fd;
179         struct sockaddr_in syslog_sin;
180
181         ret = vasprintf(&s, format, ap);
182         if (ret == -1) {
183                 return;
184         }
185
186         switch (this_log_level) {
187         case DEBUG_EMERG: 
188                 level = LOG_EMERG; 
189                 break;
190         case DEBUG_ALERT: 
191                 level = LOG_ALERT; 
192                 break;
193         case DEBUG_CRIT: 
194                 level = LOG_CRIT; 
195                 break;
196         case DEBUG_ERR: 
197                 level = LOG_ERR; 
198                 break;
199         case DEBUG_WARNING: 
200                 level = LOG_WARNING; 
201                 break;
202         case DEBUG_NOTICE: 
203                 level = LOG_NOTICE;
204                 break;
205         case DEBUG_INFO: 
206                 level = LOG_INFO;
207                 break;
208         default:
209                 level = LOG_DEBUG;
210                 break;          
211         }
212
213         len = offsetof(struct syslog_message, message) + strlen(s) + 1;
214         msg = malloc(len);
215         if (msg == NULL) {
216                 free(s);
217                 return;
218         }
219         msg->level = level;
220         msg->len   = strlen(s);
221         strcpy(msg->message, s);
222
223         if (syslogd_is_started == 0) {
224                 syslog(msg->level, "%s", msg->message);
225         } else {
226                 syslog_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
227                 if (syslog_fd == -1) {
228                         printf("Failed to create syslog socket\n");
229                         free(s);
230                         free(msg);
231                         return;
232                 }
233
234                 syslog_sin.sin_family = AF_INET;
235                 syslog_sin.sin_port   = htons(CTDB_PORT);
236                 syslog_sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);    
237
238        
239                 ret = sendto(syslog_fd, msg, len, 0, &syslog_sin, sizeof(syslog_sin));
240                 /* no point in checking here since we cant log an error */
241
242                 close(syslog_fd);
243         }
244
245         free(s);
246         free(msg);
247 }
248
249
250 /*
251   log file logging function
252  */
253 static void ctdb_logfile_log(const char *format, va_list ap)
254 {
255         struct timeval t;
256         char *s = NULL;
257         struct tm *tm;
258         char tbuf[100];
259         char *s2 = NULL;
260         int ret;
261
262         ret = vasprintf(&s, format, ap);
263         if (ret == -1) {
264                 const char *errstr = "vasprintf failed\n";
265
266                 write(log_state->fd, errstr, strlen(errstr));
267                 return;
268         }
269
270         t = timeval_current();
271         tm = localtime(&t.tv_sec);
272
273         strftime(tbuf,sizeof(tbuf)-1,"%Y/%m/%d %H:%M:%S", tm);
274
275         ret = asprintf(&s2, "%s.%06u [%5u]: %s",
276                  tbuf, (unsigned)t.tv_usec, (unsigned)getpid(), s);
277         free(s);
278         if (ret == -1) {
279                 const char *errstr = "asprintf failed\n";
280                 write(log_state->fd, errstr, strlen(errstr));
281                 return;
282         }
283         if (s2) {
284                 write(log_state->fd, s2, strlen(s2));
285                 free(s2);
286         }
287 }
288
289 static void ctdb_logfile_log_add(const char *format, va_list ap)
290 {
291         char *s = NULL;
292         int ret;
293
294         ret = vasprintf(&s, format, ap);
295         if (ret == -1) {
296                 const char *errstr = "vasprintf failed\n";
297
298                 write(log_state->fd, errstr, strlen(errstr));
299                 return;
300         }
301
302         if (s) {
303                 write(log_state->fd, s, strlen(s));
304                 free(s);
305         }
306 }
307
308
309
310 /*
311   choose the logfile location
312 */
313 int ctdb_set_logfile(struct ctdb_context *ctdb, const char *logfile, bool use_syslog)
314 {
315         int ret;
316
317         ctdb->log = talloc_zero(ctdb, struct ctdb_log_state);
318         if (ctdb->log == NULL) {
319                 printf("talloc_zero failed\n");
320                 abort();
321         }
322
323         ctdb->log->ctdb = ctdb;
324         log_state = ctdb->log;
325
326         if (use_syslog) {
327                 do_debug_v = ctdb_syslog_log;
328                 do_debug_add_v = ctdb_syslog_log;
329                 ctdb->log->use_syslog = true;
330         } else if (logfile == NULL || strcmp(logfile, "-") == 0) {
331                 do_debug_v = ctdb_logfile_log;
332                 do_debug_add_v = ctdb_logfile_log_add;
333                 ctdb->log->fd = 1;
334                 /* also catch stderr of subcommands to stdout */
335                 ret = dup2(1, 2);
336                 if (ret == -1) {
337                         printf("dup2 failed: %s\n", strerror(errno));
338                         abort();
339                 }
340         } else {
341                 do_debug_v = ctdb_logfile_log;
342                 do_debug_add_v = ctdb_logfile_log_add;
343
344                 ctdb->log->fd = open(logfile, O_WRONLY|O_APPEND|O_CREAT, 0666);
345                 if (ctdb->log->fd == -1) {
346                         printf("Failed to open logfile %s\n", logfile);
347                         abort();
348                 }
349         }
350
351         return 0;
352 }
353
354 /* Note that do_debug always uses the global log state. */
355 static void write_to_log(struct ctdb_log_state *log,
356                          const char *buf, unsigned int len)
357 {
358         if (script_log_level <= LogLevel) {
359                 do_debug("%*.*s\n", len, len, buf);
360                 /* log it in the eventsystem as well */
361                 if (log->logfn)
362                         log->logfn(log->buf, len, log->logfn_private);
363         }
364 }
365
366 /*
367   called when log data comes in from a child process
368  */
369 static void ctdb_log_handler(struct event_context *ev, struct fd_event *fde, 
370                              uint16_t flags, void *private)
371 {
372         struct ctdb_log_state *log = talloc_get_type(private, struct ctdb_log_state);
373         char *p;
374         int n;
375
376         if (!(flags & EVENT_FD_READ)) {
377                 return;
378         }
379         
380         n = read(log->pfd, &log->buf[log->buf_used],
381                  sizeof(log->buf) - log->buf_used);
382         if (n > 0) {
383                 log->buf_used += n;
384         } else if (n == 0) {
385                 talloc_free(log);
386                 return;
387         }
388
389         this_log_level = script_log_level;
390
391         while (log->buf_used > 0 &&
392                (p = memchr(log->buf, '\n', log->buf_used)) != NULL) {
393                 int n1 = (p - log->buf)+1;
394                 int n2 = n1 - 1;
395                 /* swallow \r from child processes */
396                 if (n2 > 0 && log->buf[n2-1] == '\r') {
397                         n2--;
398                 }
399                 write_to_log(log, log->buf, n2);
400                 memmove(log->buf, p+1, sizeof(log->buf) - n1);
401                 log->buf_used -= n1;
402         }
403
404         /* the buffer could have completely filled - unfortunately we have
405            no choice but to dump it out straight away */
406         if (log->buf_used == sizeof(log->buf)) {
407                 write_to_log(log, log->buf, log->buf_used);
408                 log->buf_used = 0;
409         }
410 }
411
412 static int log_context_destructor(struct ctdb_log_state *log)
413 {
414         /* Flush buffer in case it wasn't \n-terminated. */
415         if (log->buf_used > 0) {
416                 this_log_level = script_log_level;
417                 write_to_log(log, log->buf, log->buf_used);
418         }
419         return 0;
420 }
421
422 /*
423    fork(), redirecting child output to logging and specified callback.
424 */
425 struct ctdb_log_state *ctdb_fork_with_logging(TALLOC_CTX *mem_ctx,
426                                               struct ctdb_context *ctdb,
427                                               void (*logfn)(const char *, uint16_t, void *),
428                                               void *logfn_private, pid_t *pid)
429 {
430         int p[2];
431         int old_stdout, old_stderr;
432         int saved_errno;
433         struct ctdb_log_state *log;
434
435         log = talloc_zero(mem_ctx, struct ctdb_log_state);
436         CTDB_NO_MEMORY_NULL(ctdb, log);
437         log->ctdb = ctdb;
438         log->logfn = logfn;
439         log->logfn_private = (void *)logfn_private;
440
441         if (pipe(p) != 0) {
442                 DEBUG(DEBUG_ERR,(__location__ " Failed to setup for child logging pipe\n"));
443                 goto free_log;
444         }
445
446         /* We'll fail if stderr/stdout not already open; it's simpler. */
447         old_stdout = dup(STDOUT_FILENO);
448         old_stderr = dup(STDERR_FILENO);
449         if (dup2(p[1], STDOUT_FILENO) < 0 || dup2(p[1], STDERR_FILENO) < 0) {
450                 DEBUG(DEBUG_ERR,(__location__ " Failed to setup output for child\n"));
451                 goto close_pipe;
452         }
453         close(p[1]);
454
455         *pid = fork();
456
457         /* Child? */
458         if (*pid == 0) {
459                 close(old_stdout);
460                 close(old_stderr);
461                 close(p[0]);
462                 return log;
463         }
464
465         saved_errno = errno;
466         dup2(STDOUT_FILENO, old_stdout);
467         dup2(STDERR_FILENO, old_stderr);
468         close(old_stdout);
469         close(old_stderr);
470
471         /* We failed? */
472         if (*pid < 0) {
473                 DEBUG(DEBUG_ERR, (__location__ " fork failed for child process\n"));
474                 close(p[0]);
475                 errno = saved_errno;
476                 goto free_log;
477         }
478
479         log->pfd = p[0];
480         talloc_set_destructor(log, log_context_destructor);
481         event_add_fd(ctdb->ev, log, log->pfd, EVENT_FD_READ,
482                      ctdb_log_handler, log);
483         return log;
484
485 close_pipe:
486         close(p[0]);
487         close(p[1]);
488 free_log:
489         talloc_free(log);
490         return NULL;
491 }
492
493 /*
494   setup for logging of child process stdout
495 */
496 int ctdb_set_child_logging(struct ctdb_context *ctdb)
497 {
498         int p[2];
499         int ret;
500
501         if (ctdb->log->fd == 1) {
502                 /* not needed for stdout logging */
503                 return 0;
504         }
505
506         /* setup a pipe to catch IO from subprocesses */
507         if (pipe(p) != 0) {
508                 DEBUG(DEBUG_ERR,(__location__ " Failed to setup for child logging pipe\n"));
509                 return -1;
510         }
511
512         event_add_fd(ctdb->ev, ctdb->log, p[0], EVENT_FD_READ, 
513                      ctdb_log_handler, ctdb->log);
514         set_close_on_exec(p[0]);
515         ctdb->log->pfd = p[0];
516
517         DEBUG(DEBUG_NOTICE, (__location__ " Created PIPE FD:%d for logging\n", p[0]));
518
519         close(1);
520         close(2);
521         if (p[1] != 1) {
522                 ret = dup2(p[1], 1);
523                 if (ret == -1) {
524                         printf("dup2 failed: %s\n", strerror(errno));
525                         return -1;
526                 }
527                 close(p[1]);
528         }
529         /* also catch stderr of subcommands to the log */
530         ret = dup2(1, 2);
531         if (ret == -1) {
532                 printf("dup2 failed: %s\n", strerror(errno));
533                 return -1;
534         }
535
536         return 0;
537 }
538
539
540
541
542