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