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