Fix character filling for ok, error and expiry reads
[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 #include "khlib_log.h"
18 #include "khlib_time.h"
19
20 #define usage(...) { \
21 print_usage(); \
22 fprintf(stderr, "Error:\n " __VA_ARGS__); \
23 exit(EXIT_FAILURE); \
24 }
25 #define ERRMSG "ERROR"
26
27
28 static const char errmsg[] = ERRMSG;
29 static const int errlen = sizeof(ERRMSG) - 1;
30
31 char *argv0;
32
33 /* TODO: Convert slot list to slot array. */
34 typedef struct Slot Slot;
35 struct Slot {
36 char *in_fifo;
37 int in_fd;
38 struct timespec in_last_read;
39 struct timespec out_ttl;
40 int out_width;
41 int out_pos_lo; /* Lowest position on the output buffer. */
42 int out_pos_cur; /* Current position on the output buffer. */
43 int out_pos_hi; /* Highest position on the output buffer. */
44 Slot *next;
45 };
46
47 typedef struct Config Config;
48 struct Config {
49 double interval;
50 char * separator;
51 Slot * slots;
52 int slot_count;
53 int total_width;
54 int output_to_x_root_window;
55 };
56
57 enum read_status {
58 END_OF_FILE,
59 END_OF_MESSAGE,
60 RETRY,
61 FAILURE
62 };
63
64 Slot *
65 slots_rev(Slot *old)
66 {
67 Slot *tmp = NULL;
68 Slot *new = NULL;
69
70 while (old) {
71 tmp = old->next;
72 old->next = new;
73 new = old;
74 old = tmp;
75 }
76 return new;
77 }
78
79 void
80 slot_print(Slot *s)
81 {
82 khlib_info("Slot "
83 "{"
84 " in_fifo = %s,"
85 " in_fd = %d,"
86 " out_width = %d,"
87 " in_last_read = {tv_sec = %ld, tv_nsec = %ld}"
88 " out_ttl = {tv_sec = %ld, tv_nsec = %ld},"
89 " out_pos_lo = %d,"
90 " out_pos_cur = %d,"
91 " out_pos_hi = %d,"
92 " next = %p,"
93 " }\n",
94 s->in_fifo,
95 s->in_fd,
96 s->out_width,
97 s->in_last_read.tv_sec,
98 s->in_last_read.tv_nsec,
99 s->out_ttl.tv_sec,
100 s->out_ttl.tv_nsec,
101 s->out_pos_lo,
102 s->out_pos_cur,
103 s->out_pos_hi,
104 s->next
105 );
106 }
107
108 void
109 slots_print(Slot *head)
110 {
111 for (Slot *s = head; s; s = s->next) {
112 slot_print(s);
113 }
114 }
115
116 void
117 slot_expire(Slot *s, struct timespec t, char *buf)
118 {
119 struct timespec td;
120
121 timespecsub(&t, &(s->in_last_read), &td);
122 if (timespeccmp(&td, &(s->out_ttl), >=)) {
123 /* TODO: Maybe configurable expiry character. */
124 memset(buf + s->out_pos_lo, '_', s->out_width);
125 khlib_warn("Slot expired: \"%s\"\n", s->in_fifo);
126 }
127 }
128
129 void
130 slot_set_error(Slot *s, char *buf)
131 {
132 char *b;
133 int i;
134
135 s->in_fd = -1;
136 b = buf + s->out_pos_lo;
137 /* Copy as much of the error message as possible.
138 * EXCLUDING the terminating \0. */
139 for (i = 0; i < errlen && i < s->out_width; i++)
140 b[i] = errmsg[i];
141 /* Any remaining positions: */
142 memset(b + i, '_', s->out_width - i);
143 }
144
145 enum read_status
146 slot_read(Slot *s, struct timespec t, char *buf)
147 {
148 char c; /* Character read. */
149 int r; /* Remaining unused positions in buffer range. */
150
151 for (;;) {
152 switch (read(s->in_fd, &c, 1)) {
153 case -1:
154 khlib_error(
155 "Failed to read: \"%s\". errno: %d, msg: %s\n",
156 s->in_fifo,
157 errno,
158 strerror(errno)
159 );
160 switch (errno) {
161 case EINTR:
162 case EAGAIN:
163 return RETRY;
164 default:
165 return FAILURE;
166 }
167 case 0:
168 khlib_debug("%s: End of FILE\n", s->in_fifo);
169 s->out_pos_cur = s->out_pos_lo;
170 return END_OF_FILE;
171 case 1:
172 /* TODO: Consider making msg term char a CLI option */
173 if (c == '\n' || c == '\0') {
174 r = (s->out_pos_hi - s->out_pos_cur) + 1;
175 if (r > 0)
176 memset(buf + s->out_pos_cur, ' ', r);
177 s->out_pos_cur = s->out_pos_lo;
178 s->in_last_read = t;
179 return END_OF_MESSAGE;
180 } else {
181 if (s->out_pos_cur <= s->out_pos_hi)
182 buf[s->out_pos_cur++] = c;
183 /* Drop beyond available range. */
184 /*
185 * TODO Define max after which we stop reading.
186 * To ensure that a rogue large message
187 * doesn't trap us here.
188 */
189 }
190 break;
191 default:
192 assert(0);
193 }
194 }
195 }
196
197 void
198 slots_read(Config *cfg, struct timespec *ti, char *buf)
199 {
200 fd_set fds;
201 int maxfd = -1;
202 int ready = 0;
203 struct stat st;
204 struct timespec t;
205 Slot *s;
206
207 FD_ZERO(&fds);
208 for (s = cfg->slots; s; s = s->next) {
209 /* TODO: Create the FIFO if it doesn't already exist. */
210 if (lstat(s->in_fifo, &st) < 0) {
211 khlib_error(
212 "Cannot stat \"%s\". Error: %s\n",
213 s->in_fifo,
214 strerror(errno)
215 );
216 slot_set_error(s, buf);
217 continue;
218 }
219 if (!(st.st_mode & S_IFIFO)) {
220 khlib_error("\"%s\" is not a FIFO\n", s->in_fifo);
221 slot_set_error(s, buf);
222 continue;
223 }
224 if (s->in_fd < 0) {
225 khlib_debug(
226 "%s: closed. opening. in_fd: %d\n",
227 s->in_fifo,
228 s->in_fd
229 );
230 s->in_fd = open(s->in_fifo, O_RDONLY | O_NONBLOCK);
231 } else {
232 khlib_debug(
233 "%s: already openned. in_fd: %d\n",
234 s->in_fifo,
235 s->in_fd
236 );
237 }
238 if (s->in_fd == -1) {
239 /* TODO Consider backing off retries for failed slots */
240 khlib_error("Failed to open \"%s\"\n", s->in_fifo);
241 slot_set_error(s, buf);
242 continue;
243 }
244 khlib_debug("%s: open. in_fd: %d\n", s->in_fifo, s->in_fd);
245 if (s->in_fd > maxfd)
246 maxfd = s->in_fd;
247 FD_SET(s->in_fd, &fds);
248 }
249 khlib_debug("selecting...\n");
250 ready = pselect(maxfd + 1, &fds, NULL, NULL, ti, NULL);
251 khlib_debug("ready: %d\n", ready);
252 clock_gettime(CLOCK_MONOTONIC, &t);
253 if (ready == -1) {
254 switch (errno) {
255 case EINTR:
256 khlib_error(
257 "pselect temp failure: %d, errno: %d, msg: %s\n",
258 ready,
259 errno,
260 strerror(errno)
261 );
262 /* TODO: Reconsider what to do here. */
263 return;
264 default:
265 khlib_fatal(
266 "pselect failed: %d, errno: %d, msg: %s\n",
267 ready,
268 errno,
269 strerror(errno)
270 );
271 }
272 }
273 /* At-least-once ensures that expiries are still checked on timeouts. */
274 do {
275 for (s = cfg->slots; s; s = s->next) {
276 if (s->in_fd < 0)
277 continue;
278 if (FD_ISSET(s->in_fd, &fds)) {
279 khlib_debug("reading: %s\n", s->in_fifo);
280 switch (slot_read(s, t, buf)) {
281 /*
282 * ### MESSAGE LOSS ###
283 * is introduced by closing at EOM in addition
284 * to EOF, since there may be unread messages
285 * remaining in the pipe. However,
286 *
287 * ### INTER-MESSAGE PUSHBACK ###
288 * is also gained, since pipes block at the
289 * "open" call.
290 *
291 * This is an acceptable trade-off because we
292 * are a stateless reporter of a _most-recent_
293 * status, not a stateful accumulator.
294 */
295 case END_OF_MESSAGE:
296 case END_OF_FILE:
297 case FAILURE:
298 close(s->in_fd);
299 s->in_fd = -1;
300 ready--;
301 break;
302 case RETRY:
303 break;
304 default:
305 assert(0);
306 }
307 } else {
308 slot_expire(s, t, buf);
309 }
310 }
311 } while (ready);
312 assert(ready == 0);
313 }
314
315 void
316 config_print(Config *cfg)
317 {
318 khlib_info(
319 "Config "
320 "{"
321 " interval = %f,"
322 " separator = %s,"
323 " slot_count = %d,"
324 " total_width = %d,"
325 " slots = ..."
326 " }\n",
327 cfg->interval,
328 cfg->separator,
329 cfg->slot_count,
330 cfg->total_width
331 );
332 slots_print(cfg->slots);
333 }
334
335 int
336 is_pos_num(char *str)
337 {
338 while (*str != '\0')
339 if (!isdigit(*(str++)))
340 return 0;
341 return 1;
342 }
343
344 int
345 is_decimal(char *str)
346 {
347 char c;
348 int seen = 0;
349
350 while ((c = *(str++)) != '\0')
351 if (!isdigit(c)) {
352 if (c == '.' && !seen++)
353 continue;
354 else
355 return 0;
356 }
357 return 1;
358 }
359
360 void
361 print_usage()
362 {
363 assert(argv0);
364 fprintf(
365 stderr,
366 "\n"
367 "Usage: %s [OPTION ...] SPEC [SPEC ...]\n"
368 "\n"
369 " SPEC = FILE_PATH DATA_WIDTH DATA_TTL\n"
370 " FILE_PATH = string\n"
371 " DATA_WIDTH = int (* (positive) number of characters *)\n"
372 " DATA_TTL = float (* (positive) number of seconds *)\n"
373 " OPTION = -i INTERVAL\n"
374 " | -s SEPARATOR\n"
375 " | -x (* Output to X root window *)\n"
376 " | -l LOG_LEVEL\n"
377 " SEPARATOR = string\n"
378 " INTERVAL = float (* (positive) number of seconds *)\n"
379 " LOG_LEVEL = int (* %d through %d *)\n"
380 "\n",
381 argv0,
382 Nothing,
383 Debug
384 );
385 fprintf(
386 stderr,
387 "Example: %s -i 1 /dev/shm/khatus/khatus_sensor_x 4 10\n"
388 "\n",
389 argv0
390 );
391 }
392
393 /* For mutually-recursive calls. */
394 void opts_parse_any(Config *, int, char *[], int);
395
396 void
397 parse_opts_opt_i(Config *cfg, int argc, char *argv[], int i)
398 {
399 char *param;
400
401 if (i >= argc)
402 usage("Option -i parameter is missing.\n");
403 param = argv[i++];
404 if (!is_decimal(param))
405 usage("Option -i parameter is invalid: \"%s\"\n", param);
406 cfg->interval = atof(param);
407 opts_parse_any(cfg, argc, argv, i);
408 }
409
410 void
411 parse_opts_opt_s(Config *cfg, int argc, char *argv[], int i)
412 {
413 if (i >= argc)
414 usage("Option -s parameter is missing.\n");
415 cfg->separator = calloc((strlen(argv[i]) + 1), sizeof(char));
416 strcpy(cfg->separator, argv[i]);
417 opts_parse_any(cfg, argc, argv, ++i);
418 }
419
420 void
421 parse_opts_opt_l(Config *cfg, int argc, char *argv[], int i)
422 {
423 char *param;
424 int log_level;
425
426 if (i >= argc)
427 usage("Option -l parameter is missing.\n");
428 param = argv[i++];
429 if (!is_pos_num(param))
430 usage("Option -l parameter is invalid: \"%s\"\n", param);
431 log_level = atoi(param);
432 if (log_level > Debug)
433 usage(
434 "Option -l value (%d) exceeds maximum (%d)\n",
435 log_level,
436 Debug
437 );
438 _khlib_log_level = log_level;
439 opts_parse_any(cfg, argc, argv, i);
440 }
441
442 void
443 parse_opts_opt(Config *cfg, int argc, char *argv[], int i)
444 {
445 switch (argv[i][1]) {
446 case 'i':
447 /* TODO: Generic set_int */
448 parse_opts_opt_i(cfg, argc, argv, ++i);
449 break;
450 case 's':
451 /* TODO: Generic set_str */
452 parse_opts_opt_s(cfg, argc, argv, ++i);
453 break;
454 case 'x':
455 cfg->output_to_x_root_window = 1;
456 opts_parse_any(cfg, argc, argv, ++i);
457 break;
458 case 'l':
459 /* TODO: Generic set_int */
460 parse_opts_opt_l(cfg, argc, argv, ++i);
461 break;
462 default :
463 usage("Option \"%s\" is invalid\n", argv[i]);
464 }
465 }
466
467 void
468 parse_opts_spec(Config *cfg, int argc, char *argv[], int i)
469 {
470 char *n;
471 char *w;
472 char *t;
473 struct timespec in_last_read;
474 Slot *s;
475
476 if ((i + 3) > argc)
477 usage(
478 "[spec] Parameter(s) missing for fifo \"%s\".\n",
479 argv[i]
480 );
481
482 n = argv[i++];
483 w = argv[i++];
484 t = argv[i++];
485
486 if (!is_pos_num(w))
487 usage("[spec] Invalid width: \"%s\", for fifo \"%s\"\n", w, n);
488 if (!is_decimal(t))
489 usage("[spec] Invalid TTL: \"%s\", for fifo \"%s\"\n", t, n);
490
491 in_last_read.tv_sec = 0;
492 in_last_read.tv_nsec = 0;
493 s = calloc(1, sizeof(struct Slot));
494
495 if (s) {
496 s->in_fifo = n;
497 s->in_fd = -1;
498 s->out_width = atoi(w);
499 s->out_ttl = khlib_timespec_of_float(atof(t));
500 s->in_last_read = in_last_read;
501 s->out_pos_lo = cfg->total_width;
502 s->out_pos_cur = s->out_pos_lo;
503 s->out_pos_hi = s->out_pos_lo + s->out_width - 1;
504 s->next = cfg->slots;
505
506 cfg->slots = s;
507 cfg->total_width += s->out_width;
508 cfg->slot_count++;
509 } else {
510 khlib_fatal("[memory] Allocation failure.");
511 }
512 opts_parse_any(cfg, argc, argv, i);
513 }
514
515 void
516 opts_parse_any(Config *cfg, int argc, char *argv[], int i)
517 {
518 if (i < argc) {
519 switch (argv[i][0]) {
520 case '-':
521 parse_opts_opt(cfg, argc, argv, i);
522 break;
523 default :
524 parse_opts_spec(cfg, argc, argv, i);
525 }
526 }
527 }
528
529 void
530 opts_parse(Config *cfg, int argc, char *argv[])
531 {
532 opts_parse_any(cfg, argc, argv, 1);
533 cfg->slots = slots_rev(cfg->slots);
534 }
535
536 int
537 main(int argc, char *argv[])
538 {
539 Config cfg = {
540 .interval = 1.0,
541 .separator = "|",
542 .slots = NULL,
543 .slot_count = 0,
544 .total_width = 0,
545 .output_to_x_root_window = 0,
546 };
547
548 int width = 0;
549 int nslots = 0;
550 int seplen = 0;
551 int prefix = 0;
552 int errors = 0;
553 char *buf;
554 Display *d = NULL;
555 struct stat st;
556 struct timespec
557 t0, /* time stamp. before reading slots */
558 t1, /* time stamp. after reading slots */
559 ti, /* time interval desired (t1 - t0) */
560 td, /* time interval measured (t1 - t0) */
561 tc; /* time interval correction (ti - td) when td < ti */
562 Slot *s;
563
564 argv0 = argv[0];
565
566 opts_parse(&cfg, argc, argv);
567 khlib_debug("argv0 = %s\n", argv0);
568 config_print(&cfg);
569
570 ti = khlib_timespec_of_float(cfg.interval);
571
572 if (cfg.slots == NULL)
573 usage("No slot specs were given!\n");
574
575 /* 1st pass to check file existence and type */
576 for (s = cfg.slots; s; s = s->next) {
577 if (lstat(s->in_fifo, &st) < 0) {
578 khlib_error(
579 "Cannot stat \"%s\". Error: %s\n",
580 s->in_fifo,
581 strerror(errno)
582 );
583 errors++;
584 continue;
585 }
586 if (!(st.st_mode & S_IFIFO)) {
587 khlib_error("\"%s\" is not a FIFO\n", s->in_fifo);
588 errors++;
589 continue;
590 }
591 }
592 if (errors)
593 khlib_fatal(
594 "Encountered errors with given file paths. See log.\n"
595 );
596
597 width = cfg.total_width;
598 seplen = strlen(cfg.separator);
599
600 /* 2nd pass to make space for separators */
601 for (s = cfg.slots; s; s = s->next) {
602 s->out_pos_lo += prefix;
603 s->out_pos_hi += prefix;
604 s->out_pos_cur = s->out_pos_lo;
605 prefix += seplen;
606 nslots++;
607 }
608 width += (seplen * (nslots - 1));
609 buf = calloc(1, width + 1);
610 if (buf == NULL)
611 khlib_fatal(
612 "[memory] Failed to allocate buffer of %d bytes",
613 width
614 );
615 memset(buf, ' ', width);
616 buf[width] = '\0';
617 /* 3rd pass to set the separators */
618 for (s = cfg.slots; s; s = s->next) {
619 if (s->out_pos_lo) { /* Skip the first, left-most */
620 /* Copying only seplen ensures we omit the '\0' byte. */
621 strncpy(
622 buf + (s->out_pos_lo - seplen),
623 cfg.separator,
624 seplen
625 );
626 }
627 }
628
629 if (cfg.output_to_x_root_window && !(d = XOpenDisplay(NULL)))
630 khlib_fatal("XOpenDisplay failed with: %p\n", d);
631 /* TODO: Handle signals */
632 for (;;) {
633 clock_gettime(CLOCK_MONOTONIC, &t0); // FIXME: check errors
634 slots_read(&cfg, &ti, buf);
635 if (cfg.output_to_x_root_window) {
636 if (XStoreName(d, DefaultRootWindow(d), buf) < 0)
637 khlib_fatal("XStoreName failed.\n");
638 XFlush(d);
639 } else {
640 puts(buf);
641 fflush(stdout);
642 }
643 clock_gettime(CLOCK_MONOTONIC, &t1); // FIXME: check errors
644 timespecsub(&t1, &t0, &td);
645 khlib_debug(
646 "td {tv_sec = %ld, tv_nsec = %ld}\n",
647 td.tv_sec,
648 td.tv_nsec
649 );
650 if (timespeccmp(&td, &ti, <)) {
651 /*
652 * Pushback on data producers by refusing to read the
653 * pipe more frequently than the interval.
654 */
655 timespecsub(&ti, &td, &tc);
656 khlib_sleep(&tc);
657 }
658 }
659 return EXIT_SUCCESS;
660 }
This page took 0.147293 seconds and 4 git commands to generate.