Co-locate all slot functions
[khatus.git] / x5 / khatus.c
CommitLineData
77c76070 1#include <sys/select.h>
bec93767 2#include <sys/stat.h>
4d66492f 3
9b5ebc12
SK
4#include <assert.h>
5#include <ctype.h>
77c76070 6#include <errno.h>
c5d1af8c 7#include <fcntl.h>
9b5ebc12
SK
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
b7487ec5 11#include <time.h>
c5d1af8c
SK
12#include <unistd.h>
13
14#include <X11/Xlib.h>
9b5ebc12 15
b7487ec5 16#include "bsdtimespec.h"
1084633a
SK
17#include "khlib_log.h"
18#include "khlib_time.h"
b7487ec5 19
544b0835
SK
20#define usage(...) { \
21 print_usage(); \
22 fprintf(stderr, "Error:\n " __VA_ARGS__); \
23 exit(EXIT_FAILURE); \
24}
e6c523cd
SK
25#define ERRMSG "ERROR"
26
ca7a3d6c 27
e6c523cd
SK
28static const char errmsg[] = ERRMSG;
29static const int errlen = sizeof(ERRMSG) - 1;
30
4d66492f 31char *argv0;
9b5ebc12 32
900b9a6b
SK
33/* TODO: Convert slot list to slot array. */
34typedef struct Slot Slot;
35struct 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;
9b5ebc12
SK
45};
46
4d66492f
SK
47typedef struct Config Config;
48struct Config {
348d5f36 49 double interval;
4d66492f 50 char * separator;
900b9a6b
SK
51 Slot * slots;
52 int slot_count;
4d66492f 53 int total_width;
fabb8771 54 int output_to_x_root_window;
9b5ebc12
SK
55};
56
efa97b71 57enum read_status {
e6441710
SK
58 END_OF_FILE,
59 END_OF_MESSAGE,
60 RETRY,
61 FAILURE
efa97b71
SK
62};
63
ca7a3d6c
SK
64Slot *
65slots_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
77c76070 79void
ca7a3d6c 80slot_print(Slot *s)
77c76070 81{
900b9a6b 82 khlib_info("Slot "
a6b13fa2 83 "{"
900b9a6b
SK
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,"
a6b13fa2
SK
92 " next = %p,"
93 " }\n",
900b9a6b
SK
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
77c76070
SK
105 );
106}
107
108void
ca7a3d6c 109slots_print(Slot *head)
77c76070 110{
900b9a6b 111 for (Slot *s = head; s; s = s->next) {
ca7a3d6c 112 slot_print(s);
77c76070
SK
113 }
114}
115
4bfac488
SK
116void
117slot_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_pos_hi - s->out_pos_lo);
125 khlib_warn("Slot expired: \"%s\"\n", s->in_fifo);
126 }
127}
128
129void
130slot_read_error(Slot *s, char *buf)
131{
132 char *b;
133 int i;
134
135 b = buf + s->out_pos_lo;
136 /* Copy as much of the error message as possible.
137 * EXCLUDING the terminating \0. */
138 for (i = 0; i < errlen && i < s->out_width; i++)
139 b[i] = errmsg[i];
140 /* Any remaining positions: */
141 for (; i < s->out_width; i++)
142 b[i] = '_';
143}
144
145enum read_status
146slot_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;
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
197void
198slots_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_read_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_read_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_read_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 (FD_ISSET(s->in_fd, &fds)) {
277 khlib_debug("reading: %s\n", s->in_fifo);
278 switch (slot_read(s, t, buf)) {
279 /*
280 * ### MESSAGE LOSS ###
281 * is introduced by closing at EOM in addition
282 * to EOF, since there may be unread messages
283 * remaining in the pipe. However,
284 *
285 * ### INTER-MESSAGE PUSHBACK ###
286 * is also gained, since pipes block at the
287 * "open" call.
288 *
289 * This is an acceptable trade-off because we
290 * are a stateless reporter of a _most-recent_
291 * status, not a stateful accumulator.
292 */
293 case END_OF_MESSAGE:
294 case END_OF_FILE:
295 case FAILURE:
296 close(s->in_fd);
297 s->in_fd = -1;
298 ready--;
299 break;
300 case RETRY:
301 break;
302 default:
303 assert(0);
304 }
305 } else {
306 slot_expire(s, t, buf);
307 }
308 }
309 } while (ready);
310 assert(ready == 0);
311}
312
77c76070 313void
b6316e94 314config_print(Config *cfg)
77c76070 315{
1084633a 316 khlib_info(
a6b13fa2
SK
317 "Config "
318 "{"
348d5f36 319 " interval = %f,"
a6b13fa2 320 " separator = %s,"
900b9a6b 321 " slot_count = %d,"
a6b13fa2 322 " total_width = %d,"
900b9a6b 323 " slots = ..."
a6b13fa2
SK
324 " }\n",
325 cfg->interval,
326 cfg->separator,
900b9a6b 327 cfg->slot_count,
17a27e48 328 cfg->total_width
77c76070 329 );
ca7a3d6c 330 slots_print(cfg->slots);
77c76070 331}
9b5ebc12
SK
332
333int
900b9a6b 334is_pos_num(char *str)
9b5ebc12 335{
900b9a6b
SK
336 while (*str != '\0')
337 if (!isdigit(*(str++)))
9b5ebc12
SK
338 return 0;
339 return 1;
340}
341
348d5f36 342int
900b9a6b 343is_decimal(char *str)
348d5f36
SK
344{
345 char c;
346 int seen = 0;
347
900b9a6b 348 while ((c = *(str++)) != '\0')
348d5f36
SK
349 if (!isdigit(c)) {
350 if (c == '.' && !seen++)
351 continue;
352 else
353 return 0;
354 }
355 return 1;
356}
357
9b5ebc12
SK
358void
359print_usage()
360{
4d66492f 361 assert(argv0);
9b5ebc12 362 fprintf(
a6b13fa2
SK
363 stderr,
364 "\n"
365 "Usage: %s [OPTION ...] SPEC [SPEC ...]\n"
366 "\n"
367 " SPEC = FILE_PATH DATA_WIDTH DATA_TTL\n"
368 " FILE_PATH = string\n"
369 " DATA_WIDTH = int (* (positive) number of characters *)\n"
0a01172a 370 " DATA_TTL = float (* (positive) number of seconds *)\n"
a6b13fa2
SK
371 " OPTION = -i INTERVAL\n"
372 " | -s SEPARATOR\n"
373 " | -x (* Output to X root window *)\n"
374 " | -l LOG_LEVEL\n"
375 " SEPARATOR = string\n"
0a01172a 376 " INTERVAL = float (* (positive) number of seconds *)\n"
a6b13fa2
SK
377 " LOG_LEVEL = int (* %d through %d *)\n"
378 "\n",
379 argv0,
380 Nothing,
381 Debug
9b5ebc12
SK
382 );
383 fprintf(
a6b13fa2
SK
384 stderr,
385 "Example: %s -i 1 /dev/shm/khatus/khatus_sensor_x 4 10\n"
386 "\n",
387 argv0
9b5ebc12
SK
388 );
389}
390
544b0835
SK
391/* For mutually-recursive calls. */
392void opts_parse_any(Config *, int, char *[], int);
9b5ebc12
SK
393
394void
4d66492f 395parse_opts_opt_i(Config *cfg, int argc, char *argv[], int i)
9b5ebc12 396{
4c438cef
SK
397 char *param;
398
399 if (i >= argc)
9b5ebc12 400 usage("Option -i parameter is missing.\n");
4c438cef 401 param = argv[i++];
348d5f36 402 if (!is_decimal(param))
4c438cef 403 usage("Option -i parameter is invalid: \"%s\"\n", param);
348d5f36 404 cfg->interval = atof(param);
4c438cef 405 opts_parse_any(cfg, argc, argv, i);
9b5ebc12
SK
406}
407
408void
4d66492f
SK
409parse_opts_opt_s(Config *cfg, int argc, char *argv[], int i)
410{
4c438cef 411 if (i >= argc)
4d66492f 412 usage("Option -s parameter is missing.\n");
4c438cef
SK
413 cfg->separator = calloc((strlen(argv[i]) + 1), sizeof(char));
414 strcpy(cfg->separator, argv[i]);
415 opts_parse_any(cfg, argc, argv, ++i);
4d66492f
SK
416}
417
b6316e94
SK
418void
419parse_opts_opt_l(Config *cfg, int argc, char *argv[], int i)
420{
4c438cef 421 char *param;
b6316e94
SK
422 int log_level;
423
4c438cef 424 if (i >= argc)
b6316e94 425 usage("Option -l parameter is missing.\n");
4c438cef
SK
426 param = argv[i++];
427 if (!is_pos_num(param))
428 usage("Option -l parameter is invalid: \"%s\"\n", param);
429 log_level = atoi(param);
430 if (log_level > Debug)
544b0835
SK
431 usage(
432 "Option -l value (%d) exceeds maximum (%d)\n",
433 log_level,
434 Debug
435 );
1084633a 436 _khlib_log_level = log_level;
4c438cef 437 opts_parse_any(cfg, argc, argv, i);
b6316e94
SK
438}
439
4d66492f
SK
440void
441parse_opts_opt(Config *cfg, int argc, char *argv[], int i)
9b5ebc12
SK
442{
443 switch (argv[i][1]) {
ce552549
SK
444 case 'i':
445 /* TODO: Generic set_int */
446 parse_opts_opt_i(cfg, argc, argv, ++i);
447 break;
448 case 's':
449 /* TODO: Generic set_str */
450 parse_opts_opt_s(cfg, argc, argv, ++i);
451 break;
452 case 'x':
453 cfg->output_to_x_root_window = 1;
454 opts_parse_any(cfg, argc, argv, ++i);
455 break;
456 case 'l':
457 /* TODO: Generic set_int */
458 parse_opts_opt_l(cfg, argc, argv, ++i);
459 break;
460 default :
461 usage("Option \"%s\" is invalid\n", argv[i]);
9b5ebc12
SK
462 }
463}
464
465void
4d66492f 466parse_opts_spec(Config *cfg, int argc, char *argv[], int i)
9b5ebc12 467{
ca7a3d6c
SK
468 char *n;
469 char *w;
470 char *t;
471 struct timespec in_last_read;
472 Slot *s;
473
9b5ebc12 474 if ((i + 3) > argc)
544b0835
SK
475 usage(
476 "[spec] Parameter(s) missing for fifo \"%s\".\n",
477 argv[i]
478 );
9b5ebc12 479
ca7a3d6c
SK
480 n = argv[i++];
481 w = argv[i++];
482 t = argv[i++];
0a01172a 483
9b5ebc12 484 if (!is_pos_num(w))
1872c5c1 485 usage("[spec] Invalid width: \"%s\", for fifo \"%s\"\n", w, n);
0a01172a 486 if (!is_decimal(t))
1872c5c1 487 usage("[spec] Invalid TTL: \"%s\", for fifo \"%s\"\n", t, n);
ca7a3d6c 488
900b9a6b
SK
489 in_last_read.tv_sec = 0;
490 in_last_read.tv_nsec = 0;
ca7a3d6c
SK
491 s = calloc(1, sizeof(struct Slot));
492
900b9a6b
SK
493 if (s) {
494 s->in_fifo = n;
495 s->in_fd = -1;
ca7a3d6c
SK
496 s->out_width = atoi(w);
497 s->out_ttl = khlib_timespec_of_float(atof(t));
900b9a6b 498 s->in_last_read = in_last_read;
ca7a3d6c 499 s->out_pos_lo = cfg->total_width;
900b9a6b 500 s->out_pos_cur = s->out_pos_lo;
ca7a3d6c
SK
501 s->out_pos_hi = s->out_pos_lo + s->out_width - 1;
502 s->next = cfg->slots;
900b9a6b
SK
503
504 cfg->slots = s;
505 cfg->total_width += s->out_width;
506 cfg->slot_count++;
9b5ebc12 507 } else {
1084633a 508 khlib_fatal("[memory] Allocation failure.");
9b5ebc12 509 }
4d66492f 510 opts_parse_any(cfg, argc, argv, i);
9b5ebc12
SK
511}
512
513void
4d66492f 514opts_parse_any(Config *cfg, int argc, char *argv[], int i)
9b5ebc12
SK
515{
516 if (i < argc) {
517 switch (argv[i][0]) {
ce552549
SK
518 case '-':
519 parse_opts_opt(cfg, argc, argv, i);
520 break;
521 default :
522 parse_opts_spec(cfg, argc, argv, i);
4d66492f
SK
523 }
524 }
525}
526
527void
5400b86f 528opts_parse(Config *cfg, int argc, char *argv[])
4d66492f
SK
529{
530 opts_parse_any(cfg, argc, argv, 1);
ca7a3d6c 531 cfg->slots = slots_rev(cfg->slots);
4d66492f
SK
532}
533
9b5ebc12 534int
4d66492f 535main(int argc, char *argv[])
9b5ebc12 536{
16e0239d
SK
537 Config cfg = {
538 .interval = 1.0,
539 .separator = "|",
900b9a6b
SK
540 .slots = NULL,
541 .slot_count = 0,
16e0239d
SK
542 .total_width = 0,
543 .output_to_x_root_window = 0,
544 };
545
f277f405 546 int width = 0;
900b9a6b 547 int nslots = 0;
f277f405 548 int seplen = 0;
4d66492f 549 int prefix = 0;
e6c523cd 550 int errors = 0;
4d66492f 551 char *buf;
544b0835 552 Display *d = NULL;
e6c523cd 553 struct stat st;
b7487ec5 554 struct timespec
900b9a6b
SK
555 t0, /* time stamp. before reading slots */
556 t1, /* time stamp. after reading slots */
b7487ec5
SK
557 ti, /* time interval desired (t1 - t0) */
558 td, /* time interval measured (t1 - t0) */
559 tc; /* time interval correction (ti - td) when td < ti */
ca7a3d6c 560 Slot *s;
4d66492f
SK
561
562 argv0 = argv[0];
563
16e0239d 564 opts_parse(&cfg, argc, argv);
1084633a 565 khlib_debug("argv0 = %s\n", argv0);
16e0239d 566 config_print(&cfg);
b7487ec5 567
1084633a 568 ti = khlib_timespec_of_float(cfg.interval);
b7487ec5 569
900b9a6b
SK
570 if (cfg.slots == NULL)
571 usage("No slot specs were given!\n");
4d66492f 572
e6c523cd 573 /* 1st pass to check file existence and type */
ca7a3d6c 574 for (s = cfg.slots; s; s = s->next) {
900b9a6b 575 if (lstat(s->in_fifo, &st) < 0) {
1084633a 576 khlib_error(
544b0835 577 "Cannot stat \"%s\". Error: %s\n",
900b9a6b 578 s->in_fifo,
544b0835
SK
579 strerror(errno)
580 );
e6c523cd
SK
581 errors++;
582 continue;
583 }
584 if (!(st.st_mode & S_IFIFO)) {
900b9a6b 585 khlib_error("\"%s\" is not a FIFO\n", s->in_fifo);
e6c523cd
SK
586 errors++;
587 continue;
588 }
589 }
590 if (errors)
1084633a
SK
591 khlib_fatal(
592 "Encountered errors with given file paths. See log.\n"
593 );
e6c523cd 594
16e0239d
SK
595 width = cfg.total_width;
596 seplen = strlen(cfg.separator);
4d66492f 597
e6c523cd 598 /* 2nd pass to make space for separators */
ca7a3d6c 599 for (s = cfg.slots; s; s = s->next) {
900b9a6b
SK
600 s->out_pos_lo += prefix;
601 s->out_pos_hi += prefix;
602 s->out_pos_cur = s->out_pos_lo;
4d66492f 603 prefix += seplen;
900b9a6b 604 nslots++;
4d66492f 605 }
900b9a6b 606 width += (seplen * (nslots - 1));
3c836bfd 607 buf = calloc(1, width + 1);
4d66492f 608 if (buf == NULL)
1084633a
SK
609 khlib_fatal(
610 "[memory] Failed to allocate buffer of %d bytes",
611 width
612 );
4d66492f
SK
613 memset(buf, ' ', width);
614 buf[width] = '\0';
e6c523cd 615 /* 3rd pass to set the separators */
ca7a3d6c 616 for (s = cfg.slots; s; s = s->next) {
900b9a6b 617 if (s->out_pos_lo) { /* Skip the first, left-most */
77c76070 618 /* Copying only seplen ensures we omit the '\0' byte. */
544b0835 619 strncpy(
900b9a6b 620 buf + (s->out_pos_lo - seplen),
16e0239d 621 cfg.separator,
544b0835
SK
622 seplen
623 );
4d66492f
SK
624 }
625 }
626
16e0239d 627 if (cfg.output_to_x_root_window && !(d = XOpenDisplay(NULL)))
1084633a 628 khlib_fatal("XOpenDisplay failed with: %p\n", d);
805f0d22 629 /* TODO: Handle signals */
4d66492f 630 for (;;) {
b7487ec5 631 clock_gettime(CLOCK_MONOTONIC, &t0); // FIXME: check errors
ca7a3d6c 632 slots_read(&cfg, &ti, buf);
16e0239d 633 if (cfg.output_to_x_root_window) {
544b0835 634 if (XStoreName(d, DefaultRootWindow(d), buf) < 0)
1084633a 635 khlib_fatal("XStoreName failed.\n");
544b0835 636 XFlush(d);
fabb8771
SK
637 } else {
638 puts(buf);
639 fflush(stdout);
640 }
b7487ec5
SK
641 clock_gettime(CLOCK_MONOTONIC, &t1); // FIXME: check errors
642 timespecsub(&t1, &t0, &td);
1084633a 643 khlib_debug(
544b0835
SK
644 "td {tv_sec = %ld, tv_nsec = %ld}\n",
645 td.tv_sec,
646 td.tv_nsec
647 );
a415999c 648 if (timespeccmp(&td, &ti, <)) {
ca7a3d6c
SK
649 /*
650 * Pushback on data producers by refusing to read the
b7487ec5
SK
651 * pipe more frequently than the interval.
652 */
653 timespecsub(&ti, &td, &tc);
1084633a 654 khlib_sleep(&tc);
574a4bff 655 }
4d66492f 656 }
3d7e82a8 657 return EXIT_SUCCESS;
9b5ebc12 658}
This page took 0.100559 seconds and 4 git commands to generate.