]> mj.ucw.cz Git - libucw.git/blob - ucw/shell/ucw-logoutput.c
Merge branch 'dev-api' into dev-package
[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 uns 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_UNS("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   uns 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 uns
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 ((uns)(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           uns 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     write(2, usage, sizeof(usage));
320     return (help == 1) ? 0 : 1;
321   }
322
323   if (register_default) {
324     if (loginput) {
325       add_level_fd(0, L_INFO);
326     } else {
327       add_level_fd(1, L_INFO);
328       add_level_fd(2, L_WARN);
329     }
330   }
331
332   if (loginput) {
333     /* Just check, that we don't want open stderr for reading. */
334     CLIST_FOR_EACH(struct fds *, fd, filedescriptors) {
335       if (fd->fdnum == 2)
336         die("Stderr is reserved for output");
337     }
338   } else {
339     /* Open all filedescriptors and their duplicates. */
340     CLIST_FOR_EACH(struct fds *, fd, filedescriptors) {
341       CLIST_FOR_EACH(struct fds *, fdcheck, filedescriptors) {
342         /* We do a dummy check for collisions of filedescriptors. */
343         if (fdcheck == fd)
344           break;
345         if (fdcheck->fdnum == fd->fdnum) {
346           die("Duplicate filedescriptor %i", fd->fdnum);
347         }
348         xdupavoid(fdcheck->pipe + 0, fd->fdnum);
349         xdupavoid(fdcheck->pipe + 1, fd->fdnum);
350       }
351       if (pipe(fd->pipe) == -1)
352         die("Cannot create pipe: %m");
353       DBG("Pipe [%i, %i] for %i", fd->pipe[0], fd->pipe[1], fd->fdnum);
354       xdupavoid(fd->pipe + 0, fd->fdnum);
355
356       if (fd->fdnum == 2) {
357         stderrfd = fd; //We need to redirect stderr later.
358       } else {
359         xdupto(fd->pipe + 1, fd->fdnum);
360       }
361       DBG("---> [%i, %i] for %i", fd->pipe[0], fd->pipe[1], fd->fdnum);
362       set_cloexec_flag(fd->pipe[0], 1);
363       set_cloexec_flag(fd->pipe[1], 0);
364     }
365   }
366
367   /* Initialize main loop. */
368   main_init();
369
370   CLIST_FOR_EACH(struct fds *, fd, filedescriptors) {
371     /* Our pipe is created, let fd->fdnum be the reading end. */
372     if (!loginput)
373       fd->fdnum = fd->pipe[0];
374     fd->rio.read_rec_max = max_line + 1;
375     rec_io_add(&fd->rio, fd->fdnum);
376   }
377
378   int pid = -1;
379   if (!loginput) {
380     /* Launch the child and close filedescriptors. */
381     pid = fork();
382     if (pid == -1)
383       die("Cannot fork: %m");
384     if (pid == 0 ) {
385       /* Child */
386
387       /* Move stderr where it should be. */
388       if (stderrfd)
389         xdupto(stderrfd->pipe + 1, 2);
390
391       execvp(argv[optind], argv + optind);
392       if (stderrfd) {
393         /* We translate stderr, just print. */
394         perror("Cannot exec child");
395         return 127;
396       }
397       /* No stderr translation: use logging function. */
398       die("Cannot exec child: %m");
399     }
400
401     /* Close writing filedescriptors. */
402     CLIST_FOR_EACH(struct fds *, fd, filedescriptors) {
403       close(fd->pipe[1]);
404     }
405   }
406
407   /* Open logfile or stderr. */
408   if (logfile) {
409     log_file(logfile);
410     close(2);
411   }
412
413   if (!loginput) {
414     /* Inform about launching of the command. */
415     int buflen = 0;
416     for (int i = optind; i < argc; i++) buflen += strlen(argv[i]) + 1;
417     char *buf = xmalloc(buflen);
418     char *buf2 = buf;
419     for (int i = optind; i < argc; i++) {
420       strcpy(buf2, argv[i]);
421       buf2 += strlen(argv[i]);
422       buf2[0] = ' ';
423       buf2++;
424     }
425     buf2[-1] = 0;
426
427     if (launch_finish_messages)
428       msg(L_INFO, "Launching command: %s", buf);
429   }
430
431   /* Set logname. */
432   if (logname)
433     log_init(logname);
434   else if (!loginput)
435     log_init(argv[optind]);
436
437   /* Start reading from pipes. */
438   CLIST_FOR_EACH(struct fds *, fd, filedescriptors)
439     rec_io_start_read(&fd->rio);
440   main_loop();
441
442   if (!loginput) {
443     /* Unset logname. */
444     log_init("ucw-logoutput");
445
446     /* Wait for status of the child and inform about finish. */
447     int status;
448     char buf[256];
449
450     while (waitpid(pid, &status, 0) == -1) {
451       if (errno != EINTR)
452         die("Cannot wait for child: %m");
453     }
454
455     if (format_exit_status(buf, status)) {
456       if (nonzero_status_message)
457         msg(L_WARN, "Child %s", buf);
458       return WIFEXITED(status) ? WEXITSTATUS(status) : 127;
459     } else {
460       if (launch_finish_messages)
461         msg(L_INFO, "Child terminated successfully.");
462       return 0;
463     }
464   }
465
466   return 0;
467 }