Flush stderr after each log statement
[khatus.git] / x5 / khatus.c
1 #include <sys/select.h>
2 #include <sys/stat.h>
3
4 #include <assert.h>
5 #include <ctype.h>
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <time.h>
12 #include <unistd.h>
13
14 #include <X11/Xlib.h>
15
16 #include "bsdtimespec.h"
17
18 #define debug(args...) {fprintf(stderr, "[debug] " args); fflush(stderr);}
19 #define info( args...) {fprintf(stderr, "[info] " args); fflush(stderr);}
20 #define error(args...) {fprintf(stderr, "[error] " args); fflush(stderr);}
21 #define fatal(args...) {fprintf(stderr, "[fatal] " args); exit(EXIT_FAILURE);}
22 #define usage(args...) {print_usage(); fatal("[usage] " args);}
23
24 #define ERRMSG "ERROR"
25
26 static const char errmsg[] = ERRMSG;
27 static const int errlen = sizeof(ERRMSG) - 1;
28
29 char *argv0;
30
31 /* TODO: Convert fifo list to fifo array. */
32 typedef struct Fifo Fifo;
33 struct Fifo {
34 char *name;
35 int fd;
36 int width;
37 int last_read;
38 int ttl;
39 int pos; /* Position on the output buffer. */
40 Fifo *next;
41 };
42
43 typedef struct Config Config;
44 struct Config {
45 int interval;
46 char * separator;
47 Fifo * fifos;
48 int fifo_count;
49 int total_width;
50 int output_to_x_root_window;
51 } defaults = {
52 .interval = 1,
53 .separator = "|",
54 .fifos = NULL,
55 .fifo_count = 0,
56 .total_width = 0,
57 .output_to_x_root_window = 0,
58 };
59
60 void
61 fifo_print_one(Fifo *f)
62 {
63 debug(
64 "Fifo "
65 "{"
66 " name = %s,"
67 " fd = %d,"
68 " width = %d,"
69 " last_read = %d,"
70 " ttl = %d,"
71 " pos = %d,"
72 " next = %p,"
73 " }\n",
74 f->name,
75 f->fd,
76 f->width,
77 f->last_read,
78 f->ttl,
79 f->pos,
80 f->next
81 );
82 }
83
84 void
85 fifo_print_all(Fifo *head)
86 {
87 for (Fifo *f = head; f; f = f->next) {
88 fifo_print_one(f);
89 }
90 }
91
92 void
93 config_print(Config *c)
94 {
95 debug(
96 "Config "
97 "{"
98 " interval = %d,"
99 " separator = %s,"
100 " fifo_count = %d,"
101 " total_width = %d,"
102 " fifos = ..."
103 " }\n",
104 c->interval,
105 c->separator,
106 c->fifo_count,
107 c->total_width
108 );
109 fifo_print_all(c->fifos);
110 }
111
112 int
113 is_pos_num(char *s)
114 {
115 while (*s != '\0')
116 if (!isdigit(*(s++)))
117 return 0;
118 return 1;
119 }
120
121 void
122 print_usage()
123 {
124 assert(argv0);
125 fprintf(
126 stderr,
127 "\n"
128 "Usage: %s [OPTION ...] SPEC [SPEC ...]\n"
129 "\n"
130 " SPEC = FILE_PATH DATA_WIDTH DATA_TTL\n"
131 " FILE_PATH = string\n"
132 " DATA_WIDTH = int (* (positive) number of characters *)\n"
133 " DATA_TTL = int (* (positive) number of seconds *)\n"
134 " OPTION = -i INTERVAL\n"
135 " | -s SEPARATOR\n"
136 " SEPARATOR = string\n"
137 " INTERVAL = int (* (positive) number of seconds *)\n"
138 "\n",
139 argv0
140 );
141 fprintf(
142 stderr,
143 "Example: %s -i 1 /dev/shm/khatus/khatus_sensor_x 4 10\n"
144 "\n",
145 argv0
146 );
147 }
148
149 void opts_parse_any(Config *, int, char *[], int); /* For mutually-recursive calls. */
150
151 void
152 parse_opts_opt_i(Config *cfg, int argc, char *argv[], int i)
153 {
154 if (i < argc) {
155 char *param = argv[i++];
156
157 if (is_pos_num(param)) {
158 cfg->interval = atoi(param);
159 opts_parse_any(cfg, argc, argv, i);
160 } else {
161 usage("Option -i parameter is invalid: \"%s\"\n", param);
162 }
163 } else {
164 usage("Option -i parameter is missing.\n");
165 }
166 }
167
168 void
169 parse_opts_opt_s(Config *cfg, int argc, char *argv[], int i)
170 {
171 if (i < argc) {
172 cfg->separator = calloc((strlen(argv[i]) + 1), sizeof(char));
173 strcpy(cfg->separator, argv[i]);
174 opts_parse_any(cfg, argc, argv, ++i);
175 } else {
176 usage("Option -s parameter is missing.\n");
177 }
178 }
179
180 void
181 parse_opts_opt(Config *cfg, int argc, char *argv[], int i)
182 {
183 switch (argv[i][1]) {
184 case 'i':
185 /* TODO: Generic set_int */
186 parse_opts_opt_i(cfg, argc, argv, ++i);
187 break;
188 case 's':
189 /* TODO: Generic set_str */
190 parse_opts_opt_s(cfg, argc, argv, ++i);
191 break;
192 case 'x':
193 cfg->output_to_x_root_window = 1;
194 opts_parse_any(cfg, argc, argv, ++i);
195 break;
196 default :
197 usage("Option \"%s\" is invalid\n", argv[i]);
198 }
199 }
200
201 void
202 parse_opts_spec(Config *cfg, int argc, char *argv[], int i)
203 {
204 if ((i + 3) > argc)
205 usage("[spec] Parameter(s) missing for fifo \"%s\".\n", argv[i]);
206
207 char *n = argv[i++];
208 char *w = argv[i++];
209 char *t = argv[i++];
210
211 if (!is_pos_num(w))
212 usage("[spec] Invalid width: \"%s\", for fifo \"%s\"\n", w, n);
213 if (!is_pos_num(t))
214 usage("[spec] Invalid TTL: \"%s\", for fifo \"%s\"\n", t, n);
215 Fifo *f = calloc(1, sizeof(struct Fifo));
216 if (f) {
217 f->name = n;
218 f->fd = -1;
219 f->width = atoi(w);
220 f->ttl = atoi(t);
221 f->last_read = 0;
222 f->pos = cfg->total_width;
223 f->next = cfg->fifos;
224
225 cfg->fifos = f;
226 cfg->total_width += f->width;
227 cfg->fifo_count++;
228 } else {
229 fatal("[memory] Allocation failure.");
230 }
231 opts_parse_any(cfg, argc, argv, i);
232 }
233
234 void
235 opts_parse_any(Config *cfg, int argc, char *argv[], int i)
236 {
237 if (i < argc) {
238 switch (argv[i][0]) {
239 case '-':
240 parse_opts_opt(cfg, argc, argv, i);
241 break;
242 default :
243 parse_opts_spec(cfg, argc, argv, i);
244 }
245 }
246 }
247
248 void
249 opts_parse(Config *cfg, int argc, char *argv[])
250 {
251 opts_parse_any(cfg, argc, argv, 1);
252
253 Fifo *last = cfg->fifos;
254 cfg->fifos = NULL;
255 for (Fifo *f = last; f; ) {
256 Fifo *next = f->next;
257 f->next = cfg->fifos;
258 cfg->fifos = f;
259 f = next;
260 }
261 }
262
263 void
264 fifo_read_error(Fifo *f, char *buf)
265 {
266 char *b;
267 int i;
268
269 b = buf + f->pos;
270 /* Copy as much of the error message as possible.
271 * EXCLUDING the reminating \0. */
272 for (i = 0; i < errlen && i < f->width; i++)
273 b[i] = errmsg[i];
274 /* Any remaining slots: */
275 for (; i < f->width; i++)
276 b[i] = '_';
277 }
278
279 void
280 fifo_read_one(Fifo *f, char *buf)
281 {
282 ssize_t current;
283 ssize_t total;
284 char *b;
285 char c;
286
287 current = 0;
288 total = 0;
289 c = '\0';
290 b = buf + f->pos;
291 while ((current = read(f->fd, &c, 1)) && c != '\n' && c != '\0' && total++ < f->width)
292 *b++ = c;
293 if (current == -1) {
294 error("Failed to read: \"%s\". Error: %s\n", f->name, strerror(errno));
295 fifo_read_error(f, buf);
296 } else
297 while (total++ < f->width)
298 *b++ = ' ';
299 /* TODO Record timestamp read */
300 close(f->fd);
301 f->fd = -1;
302 }
303
304 void
305 fifo_read_all(Config *cfg, char *buf)
306 {
307 fd_set fds;
308 int maxfd = -1;
309 int ready;
310 struct stat st;
311
312 FD_ZERO(&fds);
313 for (Fifo *f = cfg->fifos; f; f = f->next) {
314 /* TODO: Create the FIFO if it doesn't already exist. */
315 if (lstat(f->name, &st) < 0) {
316 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
317 fifo_read_error(f, buf);
318 continue;
319 }
320 if (!(st.st_mode & S_IFIFO)) {
321 error("\"%s\" is not a FIFO\n", f->name);
322 fifo_read_error(f, buf);
323 continue;
324 }
325 debug("opening: %s\n", f->name);
326 if (f->fd < 0)
327 f->fd = open(f->name, O_RDONLY | O_NONBLOCK);
328 if (f->fd == -1) {
329 /* TODO: Consider backing off retries for failed fifos. */
330 error("Failed to open \"%s\"\n", f->name);
331 fifo_read_error(f, buf);
332 continue;
333 }
334 if (f->fd > maxfd)
335 maxfd = f->fd;
336 FD_SET(f->fd, &fds);
337 }
338 debug("selecting...\n");
339 ready = select(maxfd + 1, &fds, NULL, NULL, NULL);
340 debug("ready: %d\n", ready);
341 assert(ready != 0);
342 if (ready < 0)
343 fatal("%s", strerror(errno));
344 for (Fifo *f = cfg->fifos; f; f = f->next) {
345 if (FD_ISSET(f->fd, &fds)) {
346 debug("reading: %s\n", f->name);
347 fifo_read_one(f, buf);
348 }
349 }
350 }
351
352 void
353 snooze(struct timespec *t)
354 {
355 struct timespec remainder;
356 int result;
357
358 result = nanosleep(t, &remainder);
359
360 if (result < 0) {
361 if (errno == EINTR) {
362 info(
363 "nanosleep interrupted. Remainder: "
364 "{ tv_sec = %ld, tv_nsec = %ld }",
365 remainder.tv_sec, remainder.tv_nsec);
366 /* No big deal if we occasionally sleep less,
367 * so not attempting to correct after an interruption.
368 */
369 } else {
370 fatal("nanosleep: %s\n", strerror(errno));
371 }
372 }
373 }
374
375 int
376 main(int argc, char *argv[])
377 {
378 int width = 0;
379 int nfifos = 0;
380 int seplen = 0;
381 int prefix = 0;
382 int errors = 0;
383 char *buf;
384 Config cfg0 = defaults;
385 Config *cfg = &cfg0;
386 Display *display = NULL;
387 struct stat st;
388 struct timespec
389 t0, /* time stamp. before reading fifos */
390 t1, /* time stamp. after reading fifos */
391 ti, /* time interval desired (t1 - t0) */
392 td, /* time interval measured (t1 - t0) */
393 tc; /* time interval correction (ti - td) when td < ti */
394
395 argv0 = argv[0];
396
397 opts_parse(cfg, argc, argv);
398 debug("argv0 = %s\n", argv0);
399 config_print(cfg);
400
401 /* TODO: Support interval < 1. i.e. implement timespec_of_float */
402 ti.tv_sec = cfg->interval;
403 ti.tv_nsec = 0;
404
405 if (cfg->fifos == NULL)
406 usage("No fifo specs were given!\n");
407
408 /* 1st pass to check file existence and type */
409 for (Fifo *f = cfg->fifos; f; f = f->next) {
410 if (lstat(f->name, &st) < 0) {
411 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
412 errors++;
413 continue;
414 }
415 if (!(st.st_mode & S_IFIFO)) {
416 error("\"%s\" is not a FIFO\n", f->name);
417 errors++;
418 continue;
419 }
420 }
421 if (errors)
422 fatal("Encountered errors with the given file paths. See log.\n");
423
424 width = cfg->total_width;
425 seplen = strlen(cfg->separator);
426
427 /* 2nd pass to make space for separators */
428 for (Fifo *f = cfg->fifos; f; f = f->next) {
429 f->pos += prefix;
430 prefix += seplen;
431 nfifos++;
432 }
433 width += (seplen * (nfifos - 1));
434 buf = calloc(1, width + 1);
435 if (buf == NULL)
436 fatal("[memory] Failed to allocate buffer of %d bytes", width);
437 memset(buf, ' ', width);
438 buf[width] = '\0';
439 /* 3rd pass to set the separators */
440 for (Fifo *f = cfg->fifos; f; f = f->next) {
441 if (f->pos) { /* Skip the first, left-most */
442 /* Copying only seplen ensures we omit the '\0' byte. */
443 strncpy(buf + (f->pos - seplen), cfg->separator, seplen);
444 }
445 }
446
447 if (cfg->output_to_x_root_window && !(display = XOpenDisplay(NULL)))
448 fatal("XOpenDisplay failed with: %p\n", display);
449 /* TODO: Handle signals */
450 for (;;) {
451 clock_gettime(CLOCK_MONOTONIC, &t0); // FIXME: check errors
452 /* TODO: Cache expiration. i.e. use the TTL */
453 /* TODO: How to trigger TTL check? On select? Alarm signal? */
454 /* TODO: Set timeout on fifo_read_all based on diff of last time of
455 * fifo_read_all and desired time of next TTL check.
456 */
457 /* TODO: How long to wait on IO? Max TTL? */
458 fifo_read_all(cfg, buf);
459 if (cfg->output_to_x_root_window) {
460 if (XStoreName(display, DefaultRootWindow(display), buf) < 0)
461 fatal("XStoreName failed.\n");
462 XFlush(display);
463 } else {
464 puts(buf);
465 fflush(stdout);
466 }
467 clock_gettime(CLOCK_MONOTONIC, &t1); // FIXME: check errors
468 timespecsub(&t1, &t0, &td);
469 debug("td {tv_sec = %ld, tv_nsec = %ld}\n", td.tv_sec, td.tv_nsec);
470 if (timespeccmp(&td, &ti, <)) {
471 /* Pushback on data producers by refusing to read the
472 * pipe more frequently than the interval.
473 */
474 timespecsub(&ti, &td, &tc);
475 debug("snooze YES\n");
476 snooze(&tc);
477 } else
478 debug("snooze NO\n");
479 }
480
481 return EXIT_SUCCESS;
482 }
This page took 0.119387 seconds and 4 git commands to generate.