vacuum: fix an abundance of indentation white spaces in ctdb_vacuum_db()
[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/tevent/tevent.h"
22 #include "../include/ctdb_client.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         struct tevent_fd *fde;
89
90         state = talloc(ctdb, struct ctdb_syslog_state);
91         CTDB_NO_MEMORY(ctdb, state);
92
93         if (pipe(state->fd) != 0) {
94                 printf("Failed to create syslog pipe\n");
95                 talloc_free(state);
96                 return -1;
97         }
98         
99         ctdb->syslogd_pid = ctdb_fork(ctdb);
100         if (ctdb->syslogd_pid == (pid_t)-1) {
101                 printf("Failed to create syslog child process\n");
102                 close(state->fd[0]);
103                 close(state->fd[1]);
104                 talloc_free(state);
105                 return -1;
106         }
107
108         syslogd_is_started = 1;
109
110         if (ctdb->syslogd_pid != 0) {
111                 DEBUG(DEBUG_ERR,("Starting SYSLOG child process with pid:%d\n", (int)ctdb->syslogd_pid));
112
113                 close(state->fd[1]);
114                 set_close_on_exec(state->fd[0]);
115
116                 return 0;
117         }
118
119         debug_extra = talloc_asprintf(NULL, "syslogd:");
120         talloc_free(ctdb->ev);
121         ctdb->ev = event_context_init(NULL);
122         tevent_loop_allow_nesting(ctdb->ev);
123
124         syslog(LOG_ERR, "Starting SYSLOG daemon with pid:%d", (int)getpid());
125
126         close(state->fd[0]);
127         set_close_on_exec(state->fd[1]);
128         fde = event_add_fd(ctdb->ev, state, state->fd[1], EVENT_FD_READ,
129                      ctdb_syslog_terminate_handler, state);
130         tevent_fd_set_auto_close(fde);
131
132         state->syslog_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
133         if (state->syslog_fd == -1) {
134                 printf("Failed to create syslog socket\n");
135                 return -1;
136         }
137
138         set_close_on_exec(state->syslog_fd);
139
140         syslog_sin.sin_family = AF_INET;
141         syslog_sin.sin_port   = htons(CTDB_PORT);
142         syslog_sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);    
143
144         if (bind(state->syslog_fd, (struct sockaddr *)&syslog_sin,
145                  sizeof(syslog_sin)) == -1)
146         {
147                 if (errno == EADDRINUSE) {
148                         /* this is ok, we already have a syslog daemon */
149                         _exit(0);
150                 }
151                 printf("syslog daemon failed to bind to socket. errno:%d(%s)\n", errno, strerror(errno));
152                 _exit(10);
153         }
154
155
156         fde = event_add_fd(ctdb->ev, state, state->syslog_fd, EVENT_FD_READ,
157                      ctdb_syslog_handler, state);
158         tevent_fd_set_auto_close(fde);
159
160         event_loop_wait(ctdb->ev);
161
162         /* this should not happen */
163         _exit(10);
164 }
165
166 struct ctdb_log_state {
167         struct ctdb_context *ctdb;
168         const char *prefix;
169         int fd, pfd;
170         char buf[1024];
171         uint16_t buf_used;
172         bool use_syslog;
173         void (*logfn)(const char *, uint16_t, void *);
174         void *logfn_private;
175 };
176
177 /* we need this global to keep the DEBUG() syntax */
178 static struct ctdb_log_state *log_state;
179
180 /*
181   syslog logging function
182  */
183 static void ctdb_syslog_log(const char *format, va_list ap)
184 {
185         struct syslog_message *msg;
186         int level = LOG_DEBUG;
187         char *s = NULL;
188         int len, ret;
189         int syslog_fd;
190         struct sockaddr_in syslog_sin;
191
192         ret = vasprintf(&s, format, ap);
193         if (ret == -1) {
194                 return;
195         }
196
197         switch (this_log_level) {
198         case DEBUG_EMERG: 
199                 level = LOG_EMERG; 
200                 break;
201         case DEBUG_ALERT: 
202                 level = LOG_ALERT; 
203                 break;
204         case DEBUG_CRIT: 
205                 level = LOG_CRIT; 
206                 break;
207         case DEBUG_ERR: 
208                 level = LOG_ERR; 
209                 break;
210         case DEBUG_WARNING: 
211                 level = LOG_WARNING; 
212                 break;
213         case DEBUG_NOTICE: 
214                 level = LOG_NOTICE;
215                 break;
216         case DEBUG_INFO: 
217                 level = LOG_INFO;
218                 break;
219         default:
220                 level = LOG_DEBUG;
221                 break;          
222         }
223
224         len = offsetof(struct syslog_message, message) + strlen(debug_extra) + strlen(s) + 1;
225         msg = malloc(len);
226         if (msg == NULL) {
227                 free(s);
228                 return;
229         }
230         msg->level = level;
231         msg->len   = strlen(debug_extra) + strlen(s);
232         strcpy(msg->message, debug_extra);
233         strcat(msg->message, s);
234
235         if (syslogd_is_started == 0) {
236                 syslog(msg->level, "%s", msg->message);
237         } else {
238                 syslog_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
239                 if (syslog_fd == -1) {
240                         printf("Failed to create syslog socket\n");
241                         free(s);
242                         free(msg);
243                         return;
244                 }
245
246                 syslog_sin.sin_family = AF_INET;
247                 syslog_sin.sin_port   = htons(CTDB_PORT);
248                 syslog_sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
249
250                 ret = sendto(syslog_fd, msg, len, 0,
251                              (struct sockaddr *)&syslog_sin,
252                              sizeof(syslog_sin));
253                 /* no point in checking here since we cant log an error */
254
255                 close(syslog_fd);
256         }
257
258         free(s);
259         free(msg);
260 }
261
262
263 /*
264   log file logging function
265  */
266 static void ctdb_logfile_log(const char *format, va_list ap)
267 {
268         struct timeval t;
269         char *s = NULL;
270         struct tm *tm;
271         char tbuf[100];
272         char *s2 = NULL;
273         int ret;
274
275         ret = vasprintf(&s, format, ap);
276         if (ret == -1) {
277                 const char *errstr = "vasprintf failed\n";
278
279                 write(log_state->fd, errstr, strlen(errstr));
280                 return;
281         }
282
283         t = timeval_current();
284         tm = localtime(&t.tv_sec);
285
286         strftime(tbuf,sizeof(tbuf)-1,"%Y/%m/%d %H:%M:%S", tm);
287
288         ret = asprintf(&s2, "%s.%06u [%s%5u]: %s",
289                        tbuf, (unsigned)t.tv_usec,
290                        debug_extra, (unsigned)getpid(), s);
291         free(s);
292         if (ret == -1) {
293                 const char *errstr = "asprintf failed\n";
294                 write(log_state->fd, errstr, strlen(errstr));
295                 return;
296         }
297         if (s2) {
298                 write(log_state->fd, s2, strlen(s2));
299                 free(s2);
300         }
301 }
302
303 static void ctdb_logfile_log_add(const char *format, va_list ap)
304 {
305         char *s = NULL;
306         int ret;
307
308         ret = vasprintf(&s, format, ap);
309         if (ret == -1) {
310                 const char *errstr = "vasprintf failed\n";
311
312                 write(log_state->fd, errstr, strlen(errstr));
313                 return;
314         }
315
316         if (s) {
317                 write(log_state->fd, s, strlen(s));
318                 free(s);
319         }
320 }
321
322
323
324 /*
325   choose the logfile location
326 */
327 int ctdb_set_logfile(struct ctdb_context *ctdb, const char *logfile, bool use_syslog)
328 {
329         int ret;
330
331         ctdb->log = talloc_zero(ctdb, struct ctdb_log_state);
332         if (ctdb->log == NULL) {
333                 printf("talloc_zero failed\n");
334                 abort();
335         }
336
337         ctdb->log->ctdb = ctdb;
338         log_state = ctdb->log;
339
340         if (use_syslog) {
341                 do_debug_v = ctdb_syslog_log;
342                 do_debug_add_v = ctdb_syslog_log;
343                 ctdb->log->use_syslog = true;
344         } else if (logfile == NULL || strcmp(logfile, "-") == 0) {
345                 do_debug_v = ctdb_logfile_log;
346                 do_debug_add_v = ctdb_logfile_log_add;
347                 ctdb->log->fd = 1;
348                 /* also catch stderr of subcommands to stdout */
349                 ret = dup2(1, 2);
350                 if (ret == -1) {
351                         printf("dup2 failed: %s\n", strerror(errno));
352                         abort();
353                 }
354         } else {
355                 do_debug_v = ctdb_logfile_log;
356                 do_debug_add_v = ctdb_logfile_log_add;
357
358                 ctdb->log->fd = open(logfile, O_WRONLY|O_APPEND|O_CREAT, 0666);
359                 if (ctdb->log->fd == -1) {
360                         printf("Failed to open logfile %s\n", logfile);
361                         abort();
362                 }
363         }
364
365         return 0;
366 }
367
368 /* Note that do_debug always uses the global log state. */
369 static void write_to_log(struct ctdb_log_state *log,
370                          const char *buf, unsigned int len)
371 {
372         if (script_log_level <= LogLevel) {
373                 if (log != NULL && log->prefix != NULL) {
374                         do_debug("%s: %*.*s\n", log->prefix, len, len, buf);
375                 } else {
376                         do_debug("%*.*s\n", len, len, buf);
377                 }
378                 /* log it in the eventsystem as well */
379                 if (log->logfn)
380                         log->logfn(log->buf, len, log->logfn_private);
381         }
382 }
383
384 /*
385   called when log data comes in from a child process
386  */
387 static void ctdb_log_handler(struct event_context *ev, struct fd_event *fde, 
388                              uint16_t flags, void *private)
389 {
390         struct ctdb_log_state *log = talloc_get_type(private, struct ctdb_log_state);
391         char *p;
392         int n;
393
394         if (!(flags & EVENT_FD_READ)) {
395                 return;
396         }
397
398         n = read(log->pfd, &log->buf[log->buf_used],
399                  sizeof(log->buf) - log->buf_used);
400         if (n > 0) {
401                 log->buf_used += n;
402         } else if (n == 0) {
403                 if (log != log_state) {
404                         talloc_free(log);
405                 }
406                 return;
407         }
408
409         this_log_level = script_log_level;
410
411         while (log->buf_used > 0 &&
412                (p = memchr(log->buf, '\n', log->buf_used)) != NULL) {
413                 int n1 = (p - log->buf)+1;
414                 int n2 = n1 - 1;
415                 /* swallow \r from child processes */
416                 if (n2 > 0 && log->buf[n2-1] == '\r') {
417                         n2--;
418                 }
419                 write_to_log(log, log->buf, n2);
420                 memmove(log->buf, p+1, sizeof(log->buf) - n1);
421                 log->buf_used -= n1;
422         }
423
424         /* the buffer could have completely filled - unfortunately we have
425            no choice but to dump it out straight away */
426         if (log->buf_used == sizeof(log->buf)) {
427                 write_to_log(log, log->buf, log->buf_used);
428                 log->buf_used = 0;
429         }
430 }
431
432 static int log_context_destructor(struct ctdb_log_state *log)
433 {
434         /* Flush buffer in case it wasn't \n-terminated. */
435         if (log->buf_used > 0) {
436                 this_log_level = script_log_level;
437                 write_to_log(log, log->buf, log->buf_used);
438         }
439         return 0;
440 }
441
442 /*
443    fork(), redirecting child output to logging and specified callback.
444 */
445 struct ctdb_log_state *ctdb_fork_with_logging(TALLOC_CTX *mem_ctx,
446                                               struct ctdb_context *ctdb,
447                                               const char *log_prefix,
448                                               void (*logfn)(const char *, uint16_t, void *),
449                                               void *logfn_private, pid_t *pid)
450 {
451         int p[2];
452         struct ctdb_log_state *log;
453         struct tevent_fd *fde;
454
455         log = talloc_zero(mem_ctx, struct ctdb_log_state);
456         CTDB_NO_MEMORY_NULL(ctdb, log);
457         log->ctdb = ctdb;
458         log->prefix = log_prefix;
459         log->logfn = logfn;
460         log->logfn_private = (void *)logfn_private;
461
462         if (pipe(p) != 0) {
463                 DEBUG(DEBUG_ERR,(__location__ " Failed to setup for child logging pipe\n"));
464                 goto free_log;
465         }
466
467         *pid = ctdb_fork(ctdb);
468
469         /* Child? */
470         if (*pid == 0) {
471                 close(STDOUT_FILENO);
472                 close(STDERR_FILENO);
473                 dup2(p[1], STDOUT_FILENO);
474                 dup2(p[1], STDERR_FILENO);
475                 close(p[0]);
476                 close(p[1]);
477                 return log;
478         }
479         close(p[1]);
480
481         /* We failed? */
482         if (*pid < 0) {
483                 DEBUG(DEBUG_ERR, (__location__ " fork failed for child process\n"));
484                 close(p[0]);
485                 goto free_log;
486         }
487
488         log->pfd = p[0];
489         set_close_on_exec(log->pfd);
490         talloc_set_destructor(log, log_context_destructor);
491         fde = event_add_fd(ctdb->ev, log, log->pfd,
492                            EVENT_FD_READ, ctdb_log_handler, log);
493         tevent_fd_set_auto_close(fde);
494
495         return log;
496
497 free_log:
498         talloc_free(log);
499         return NULL;
500 }
501
502 /*
503   setup for logging of child process stdout
504 */
505 int ctdb_set_child_logging(struct ctdb_context *ctdb)
506 {
507         int p[2];
508         int old_stdout, old_stderr;
509         struct tevent_fd *fde;
510
511         if (ctdb->log->fd == STDOUT_FILENO) {
512                 /* not needed for stdout logging */
513                 return 0;
514         }
515
516         /* setup a pipe to catch IO from subprocesses */
517         if (pipe(p) != 0) {
518                 DEBUG(DEBUG_ERR,(__location__ " Failed to setup for child logging pipe\n"));
519                 return -1;
520         }
521
522         /* We'll fail if stderr/stdout not already open; it's simpler. */
523         old_stdout = dup(STDOUT_FILENO);
524         old_stderr = dup(STDERR_FILENO);
525         if (dup2(p[1], STDOUT_FILENO) < 0 || dup2(p[1], STDERR_FILENO) < 0) {
526                 int saved_errno = errno;
527                 dup2(old_stdout, STDOUT_FILENO);
528                 dup2(old_stderr, STDERR_FILENO);
529                 close(old_stdout);
530                 close(old_stderr);
531                 close(p[0]);
532                 close(p[1]);
533                 errno = saved_errno;
534
535                 printf(__location__ " dup2 failed: %s\n",
536                         strerror(errno));
537                 return -1;
538         }
539         close(p[1]);
540         close(old_stdout);
541         close(old_stderr);
542
543         /* Is this correct for STDOUT and STDERR ? */
544         set_close_on_exec(STDOUT_FILENO);
545         set_close_on_exec(STDERR_FILENO);
546         set_close_on_exec(p[0]);
547
548         fde = event_add_fd(ctdb->ev, ctdb->log, p[0],
549                            EVENT_FD_READ, ctdb_log_handler, ctdb->log);
550         tevent_fd_set_auto_close(fde);
551
552         ctdb->log->pfd = p[0];
553
554         DEBUG(DEBUG_DEBUG, (__location__ " Created PIPE FD:%d for logging\n", p[0]));
555
556         return 0;
557 }
558
559
560 /*
561  * set up a log handler to catch logging from TEVENT
562  */
563 static void ctdb_tevent_logging(void *private_data,
564                                 enum tevent_debug_level level,
565                                 const char *fmt,
566                                 va_list ap)
567 {
568         enum debug_level lvl = DEBUG_EMERG;
569
570         switch (level) {
571         case TEVENT_DEBUG_FATAL:
572                 lvl = DEBUG_EMERG;
573                 break;
574         case TEVENT_DEBUG_ERROR:
575                 lvl = DEBUG_ERR;
576                 break;
577         case TEVENT_DEBUG_WARNING:
578                 lvl = DEBUG_WARNING;
579                 break;
580         case TEVENT_DEBUG_TRACE:
581                 lvl = DEBUG_DEBUG;
582                 break;
583         }
584
585         if (lvl <= LogLevel) {
586                 this_log_level = lvl;
587                 do_debug_v(fmt, ap);
588         }
589 }
590
591 int ctdb_init_tevent_logging(struct ctdb_context *ctdb)
592 {
593         int ret;
594
595         ret = tevent_set_debug(ctdb->ev,
596                         ctdb_tevent_logging,
597                         ctdb);
598         return ret;
599 }
600
601
602