]> mj.ucw.cz Git - libucw.git/blob - ucw/shell/ucw-logoutput.c
Merge branch 'master' into table
[libucw.git] / ucw / shell / ucw-logoutput.c
1 /*
2  *      UCW Library Utilities -- A Simple Logger for use in shell scripts
3  *
4  *      (c) 2001--2009 Martin Mares <mj@ucw.cz>
5  *      (c) 2011 Tomas Ebenlendr <ebik@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #undef LOCAL_DEBUG
12
13 #include <ucw/lib.h>
14 #include <ucw/log.h>
15 #include <ucw/mainloop.h>
16 #include <ucw/clists.h>
17 #include <ucw/getopt.h>
18 #include <ucw/conf.h>
19 #include <ucw/process.h>
20
21 #include <stdio.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 #include <errno.h>
28
29 static uint max_line = 1024;
30 static int launch_finish_messages = 1;
31 static int nonzero_status_message = 1;
32
33 static struct cf_section cfsec_logoutput = {
34   CF_ITEMS {
35     CF_UINT("LineMax", &max_line),
36     CF_END
37   }
38 };
39
40 static clist filedescriptors;
41
42 struct fds {
43   cnode node;
44   int pipe[2];
45   int fdnum;
46   uint level;
47   int long_continue;
48   struct main_rec_io rio;
49 };
50
51 static void
52 close_fd(struct fds *fd)
53 {
54   rec_io_del(&fd->rio);
55   close(fd->fdnum);
56   clist_remove(&fd->node);
57   if (clist_empty(&filedescriptors))
58     main_shut_down();
59 }
60
61
62 static void
63 do_msg (struct fds *fd, char *l_msg, int long_continue)
64 {
65   msg(fd->level, "%s%s", (fd->long_continue ? "... " : ""), l_msg);
66   fd->long_continue = long_continue;
67 }
68
69 static uint
70 handle_read(struct main_rec_io *r)
71 {
72   char buf[max_line + 5];
73   byte *eol = memchr((char *)r->read_rec_start + r->read_prev_avail, '\n', r->read_avail - r->read_prev_avail);
74   if (eol == NULL) {
75     if (r->read_avail >= max_line) {
76       memcpy(buf, r->read_rec_start, max_line);
77       memcpy(buf + max_line, " ...", 5);
78       do_msg(r->data, buf, 1);
79       return max_line;
80     } else
81       return 0;
82   }
83   *eol = 0;
84   byte *b = r->read_rec_start;
85   while ((uint)(eol - b) > max_line) {
86     char cc = b[max_line];
87     b[max_line]=0;
88     do_msg(r->data, b, 1);
89     b[max_line]=cc;
90     b+=max_line;
91   }
92   do_msg(r->data, (char *)b, 0);
93   return eol - r->read_rec_start + 1;
94 }
95
96 static int
97 handle_notify(struct main_rec_io *r, int status)
98 {
99   struct fds *fd = r->data;
100   switch (status) {
101     case RIO_ERR_READ:
102     case RIO_EVENT_EOF:
103       if (r->read_avail) {
104         char buf[max_line + 10];
105         memcpy(buf, r->read_rec_start, r->read_avail);
106         memcpy(buf + r->read_avail, " [no eol]", 10);
107         do_msg(r->data, buf, 0);
108       } else if (fd->long_continue) {
109         do_msg(r->data, "[no eol]", 0);
110       }
111       close_fd(fd);
112       return HOOK_DONE;
113     default:
114       ASSERT(0);
115   }
116   return HOOK_IDLE;
117 }
118
119
120 static void
121 add_level_fd(int fdnum, int level)
122 {
123   struct fds *fd = xmalloc_zero(sizeof(*fd));
124   fd->level = level;
125   fd->pipe[0] = -1;
126   fd->pipe[1] = -1;
127   fd->fdnum = fdnum;
128   fd->rio.read_handler = handle_read;
129   fd->rio.data = fd;
130   fd->rio.notify_handler = handle_notify;
131   fd->long_continue = 0;
132   clist_add_tail(&filedescriptors, &fd->node);
133 }
134
135 static int
136 xdup(int fd)
137 {
138   int rfd = dup(fd);
139   if (rfd == -1)
140     die("Cannot dup(): %m");
141   DBG("  Dup(%i) -> %i", fd, rfd);
142   return rfd;
143 }
144
145 static int
146 xdup2(int fd1, int fd2)
147 {
148   int rfd = dup2(fd1, fd2);
149   if (rfd == -1)
150     die("Cannot dup2(): %m");
151   DBG("  Dup2(%i, %i) -> %i", fd1, fd2, rfd);
152   return rfd;
153 }
154
155 static void
156 xdupavoid(int *fd1, int fd2)
157 {
158   DBG("Dupavoid: !%i -> %i", fd2, *fd1);
159   int ofd = *fd1;
160   if (ofd == fd2) {
161     *fd1 = xdup(ofd);
162     DBG("  Close: %i", ofd);
163     close(ofd);
164   }
165 }
166
167 static void
168 xdupto(int *fd1, int fd2)
169 {
170   DBG("Dupto: %i -> %i", *fd1, fd2);
171   if (*fd1 == fd2)
172     return;
173   DBG("  Close: %i", fd2);
174   close(fd2);
175   xdup2(*fd1, fd2);
176   DBG("  Close: %i", *fd1);
177   close(*fd1);
178   *fd1 = fd2;
179 }
180
181 static void
182 set_cloexec_flag(int fd, int value)
183 {
184   int flags = fcntl(fd, F_GETFD, 0);
185   if (flags < 0)
186     die("fcntl(..., F_GETFD, ...) : %m");
187   flags = (value) ? flags | FD_CLOEXEC : flags & ~FD_CLOEXEC;
188   if (fcntl(fd, F_SETFD, flags) < 0)
189     die("fcntl(..., F_SETFD, ...) : %m");
190 }
191
192 /* The "+" stands for end at first argument (i.e. do not parse options after
193    first argument.) */
194 #define MY_SHORT_OPTS "+" CF_SHORT_OPTS "f:n:l:ih"
195 const struct option my_long_opts[] = {
196   CF_LONG_OPTS
197   { "help", 0, 0, 'h'},
198   { "input", 0, 0, 'i'},
199   { "logfile", 1, 0, 'f'},
200   { "logname", 1, 0, 'n'},
201   { "descriptor", 1, 0, 'l'},
202   { "nv", 0, 0, 'q'},
203   { "nonverbose", 0, 0, 'q'},
204   { "non-verbose", 0, 0, 'q'},
205   { "non_verbose", 0, 0, 'q'},
206   { "silent", 0, 0, 's'},
207   { NULL, 0, 0, 0}
208 };
209
210 #undef CF_USAGE_TAB
211 #define CF_USAGE_TAB "\t   "
212 static char usage[] =
213   "Usage:\n"
214   "ucw-logoutput -h|--help\t\t   This help.\n"
215   "ucw-logoutput <options> -i|--input   Read file descriptors and log them.\n"
216   "\t\t\t\t   default: stdin at level I.\n"
217   "ucw-logoutput <opts> [--] <cmd> [arguments for cmd ...]\n"
218   "\t\t\t\t   Open file descriptors for writing for command <cmd> and log them.\n"
219   "\t\t\t\t   default: stdout:I, stderr:W.\n\n"
220   "Options:\n"
221   CF_USAGE
222   "-n, --logname <name>\t\t   Use <name> as program name in logs.\n"
223   "-l, --descriptor <fdnum>:<level>   Open file descriptor <fdnum> and log it at level <level> (replaces defaults).\n"
224   "-f, --logfile <logfile>\t\t   Log to file <logfile>.\n"
225   "-q, --nv, --nonverbose\t\t   Suppress launching and successful finish messages.\n"
226   "-s, --silent\t\t\t   Suppress launching message and all finish messages.\n"
227   "\t\t\t\t   (i.e., no warning if it terminates with a nonzero exit code or by a signal)\n";
228
229 int
230 main(int argc, char **argv)
231 {
232   int register_default = 1;
233   int loginput = 0;
234   char *logfile = NULL;
235   char *logname = NULL;
236   struct fds *stderrfd = NULL;
237   int help = 0;
238
239   log_init("ucw-logoutput");
240   clist_init(&filedescriptors);
241   cf_declare_section("LogOutput", &cfsec_logoutput, 0);
242
243   while (1) {
244     int opt = cf_getopt(argc, argv, MY_SHORT_OPTS, my_long_opts, NULL);
245     switch (opt) {
246       case -1:
247         goto opt_done;
248
249       case 'h':
250         help = 1;
251         break;
252
253       case 'i':
254         loginput = 1;
255         break;
256
257       case 'f':
258         logfile = optarg;
259         break;
260
261       case 'n':
262         logname = optarg;
263         break;
264
265       case 'l':
266         {
267           char *c = optarg;
268
269           register_default = 0;
270           int fdnum = 0;
271           int parseerror = 0;
272           if ( (c[0]<'0') || (c[0] > '9') )
273             parseerror = 1;
274           while ( (!parseerror) && (c[0] >= '0') && (c[0] <= '9') )
275             { fdnum = fdnum*10 + c[0] - '0'; c++; }
276           if ( (!parseerror) && (c[0] != ':') )
277             parseerror = 1;
278           c++;
279           if ( (!parseerror) && (c[0] == 0) )
280             parseerror = 1;
281           if ( (!parseerror) && (c[1] != 0) )
282             parseerror = 1;
283           if (parseerror) die("Bad argument `%s' to -l, expects number:letter.", optarg);
284
285           uint level = 0;
286           while (level < L_MAX && LS_LEVEL_LETTER(level) != c[0])
287             level++;
288           if (level >= L_MAX)
289             die("Unknown logging level `%s'", c);
290
291           add_level_fd(fdnum, level);
292         }
293         break;
294
295       case 's':
296         nonzero_status_message = 0;
297         /* fallthrough */
298       case 'q':
299         launch_finish_messages = 0;
300         break;
301
302       default:
303         optind--;
304         goto opt_done;
305     }
306   }
307 opt_done:
308
309   if (!help) {
310     if (loginput && (optind < argc))
311       die("No cmd is allowed for -i. Use -h for help.");
312
313     if ((!loginput) && (optind >= argc)) {
314       msg(L_FATAL, "Either command or --input expected.");
315       help = 2;
316     }
317   }
318   if (help) {
319     if (write(2, usage, sizeof(usage)) < 0) {
320     }
321     return (help == 1) ? 0 : 1;
322   }
323
324   if (register_default) {
325     if (loginput) {
326       add_level_fd(0, L_INFO);
327     } else {
328       add_level_fd(1, L_INFO);
329       add_level_fd(2, L_WARN);
330     }
331   }
332
333   if (loginput) {
334     /* Just check, that we don't want open stderr for reading. */
335     CLIST_FOR_EACH(struct fds *, fd, filedescriptors) {
336       if (fd->fdnum == 2)
337         die("Stderr is reserved for output");
338     }
339   } else {
340     /* Open all filedescriptors and their duplicates. */
341     CLIST_FOR_EACH(struct fds *, fd, filedescriptors) {
342       CLIST_FOR_EACH(struct fds *, fdcheck, filedescriptors) {
343         /* We do a dummy check for collisions of filedescriptors. */
344         if (fdcheck == fd)
345           break;
346         if (fdcheck->fdnum == fd->fdnum) {
347           die("Duplicate filedescriptor %i", fd->fdnum);
348         }
349         xdupavoid(fdcheck->pipe + 0, fd->fdnum);
350         xdupavoid(fdcheck->pipe + 1, fd->fdnum);
351       }
352       if (pipe(fd->pipe) == -1)
353         die("Cannot create pipe: %m");
354       DBG("Pipe [%i, %i] for %i", fd->pipe[0], fd->pipe[1], fd->fdnum);
355       xdupavoid(fd->pipe + 0, fd->fdnum);
356
357       if (fd->fdnum == 2) {
358         stderrfd = fd; //We need to redirect stderr later.
359       } else {
360         xdupto(fd->pipe + 1, fd->fdnum);
361       }
362       DBG("---> [%i, %i] for %i", fd->pipe[0], fd->pipe[1], fd->fdnum);
363       set_cloexec_flag(fd->pipe[0], 1);
364       set_cloexec_flag(fd->pipe[1], 0);
365     }
366   }
367
368   /* Initialize main loop. */
369   main_init();
370
371   CLIST_FOR_EACH(struct fds *, fd, filedescriptors) {
372     /* Our pipe is created, let fd->fdnum be the reading end. */
373     if (!loginput)
374       fd->fdnum = fd->pipe[0];
375     fd->rio.read_rec_max = max_line + 1;
376     rec_io_add(&fd->rio, fd->fdnum);
377   }
378
379   int pid = -1;
380   if (!loginput) {
381     /* Launch the child and close filedescriptors. */
382     pid = fork();
383     if (pid == -1)
384       die("Cannot fork: %m");
385     if (pid == 0 ) {
386       /* Child */
387
388       /* Move stderr where it should be. */
389       if (stderrfd)
390         xdupto(stderrfd->pipe + 1, 2);
391
392       execvp(argv[optind], argv + optind);
393       if (stderrfd) {
394         /* We translate stderr, just print. */
395         perror("Cannot exec child");
396         return 127;
397       }
398       /* No stderr translation: use logging function. */
399       die("Cannot exec child: %m");
400     }
401
402     /* Close writing filedescriptors. */
403     CLIST_FOR_EACH(struct fds *, fd, filedescriptors) {
404       close(fd->pipe[1]);
405     }
406   }
407
408   /* Open logfile or stderr. */
409   if (logfile) {
410     log_file(logfile);
411     close(2);
412   }
413
414   if (!loginput) {
415     /* Inform about launching of the command. */
416     int buflen = 0;
417     for (int i = optind; i < argc; i++) buflen += strlen(argv[i]) + 1;
418     char *buf = xmalloc(buflen);
419     char *buf2 = buf;
420     for (int i = optind; i < argc; i++) {
421       strcpy(buf2, argv[i]);
422       buf2 += strlen(argv[i]);
423       buf2[0] = ' ';
424       buf2++;
425     }
426     buf2[-1] = 0;
427
428     if (launch_finish_messages)
429       msg(L_INFO, "Launching command: %s", buf);
430   }
431
432   /* Set logname. */
433   if (logname)
434     log_init(logname);
435   else if (!loginput)
436     log_init(argv[optind]);
437
438   /* Start reading from pipes. */
439   CLIST_FOR_EACH(struct fds *, fd, filedescriptors)
440     rec_io_start_read(&fd->rio);
441   main_loop();
442
443   if (!loginput) {
444     /* Unset logname. */
445     log_init("ucw-logoutput");
446
447     /* Wait for status of the child and inform about finish. */
448     int status;
449     char buf[256];
450
451     while (waitpid(pid, &status, 0) == -1) {
452       if (errno != EINTR)
453         die("Cannot wait for child: %m");
454     }
455
456     if (format_exit_status(buf, status)) {
457       if (nonzero_status_message)
458         msg(L_WARN, "Child %s", buf);
459       return WIFEXITED(status) ? WEXITSTATUS(status) : 127;
460     } else {
461       if (launch_finish_messages)
462         msg(L_INFO, "Child terminated successfully.");
463       return 0;
464     }
465   }
466
467   return 0;
468 }