Move config defaults from global into main
[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 "khatus_lib_log.h"
18 #include "khatus_lib_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 fifo list to fifo array. */
33 typedef struct Fifo Fifo;
34 struct Fifo {
35 char *name;
36 int fd;
37 int width;
38 struct timespec last_read;
39 struct timespec ttl;
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. */
43 Fifo *next;
44 };
45
46 typedef struct Config Config;
47 struct Config {
48 double interval;
49 char * separator;
50 Fifo * fifos;
51 int fifo_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 fifo_print_one(Fifo *f)
65 {
66 info("Fifo "
67 "{"
68 " name = %s,"
69 " fd = %d,"
70 " width = %d,"
71 " last_read = {tv_sec = %ld, tv_nsec = %ld}"
72 " ttl = {tv_sec = %ld, tv_nsec = %ld},"
73 " pos_init = %d,"
74 " pos_curr = %d,"
75 " pos_final = %d,"
76 " next = %p,"
77 " }\n",
78 f->name,
79 f->fd,
80 f->width,
81 f->last_read.tv_sec,
82 f->last_read.tv_nsec,
83 f->ttl.tv_sec,
84 f->ttl.tv_nsec,
85 f->pos_init,
86 f->pos_curr,
87 f->pos_final,
88 f->next
89 );
90 }
91
92 void
93 fifo_print_all(Fifo *head)
94 {
95 for (Fifo *f = head; f; f = f->next) {
96 fifo_print_one(f);
97 }
98 }
99
100 void
101 config_print(Config *cfg)
102 {
103 info(
104 "Config "
105 "{"
106 " interval = %f,"
107 " separator = %s,"
108 " fifo_count = %d,"
109 " total_width = %d,"
110 " fifos = ..."
111 " }\n",
112 cfg->interval,
113 cfg->separator,
114 cfg->fifo_count,
115 cfg->total_width
116 );
117 fifo_print_all(cfg->fifos);
118 }
119
120 int
121 is_pos_num(char *s)
122 {
123 while (*s != '\0')
124 if (!isdigit(*(s++)))
125 return 0;
126 return 1;
127 }
128
129 int
130 is_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
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 _khatus_lib_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 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 last_read.tv_sec = 0;
272 last_read.tv_nsec = 0;
273 Fifo *f = calloc(1, sizeof(struct Fifo));
274 if (f) {
275 f->name = n;
276 f->fd = -1;
277 f->width = atoi(w);
278 f->ttl = timespec_of_float(atof(t));
279 f->last_read = last_read;
280 f->pos_init = cfg->total_width;
281 f->pos_curr = f->pos_init;
282 f->pos_final = f->pos_init + f->width - 1;
283 f->next = cfg->fifos;
284
285 cfg->fifos = f;
286 cfg->total_width += f->width;
287 cfg->fifo_count++;
288 } else {
289 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 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;
319 f = next;
320 }
321 }
322
323 void
324 fifo_expire(Fifo *f, struct timespec t, char *buf)
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);
332 warn("Data source expired: \"%s\"\n", f->name);
333 }
334 }
335
336 void
337 fifo_read_error(Fifo *f, char *buf)
338 {
339 char *b;
340 int i;
341
342 b = buf + f->pos_init;
343 /* Copy as much of the error message as possible.
344 * EXCLUDING the terminating \0. */
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
352 enum read_status
353 fifo_read_one(Fifo *f, 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(f->fd, &c, 1)) {
360 case -1:
361 error("Failed to read: \"%s\". errno: %d, msg: %s\n",
362 f->name, errno, strerror(errno));
363 switch (errno) {
364 case EINTR:
365 case EAGAIN:
366 return RETRY;
367 default:
368 return FAILURE;
369 }
370 case 0:
371 debug("%s: End of FILE\n", f->name);
372 f->pos_curr = f->pos_init;
373 return END_OF_FILE;
374 case 1:
375 /* TODO: Consider making msg term char a CLI option */
376 if (c == '\n' || c == '\0') {
377 r = f->pos_final - f->pos_curr;
378 if (r > 0)
379 memset(buf + f->pos_curr, ' ', r);
380 f->pos_curr = f->pos_init;
381 f->last_read = t;
382 return END_OF_MESSAGE;
383 } else {
384 if (f->pos_curr <= f->pos_final)
385 buf[f->pos_curr++] = c;
386 /* Drop beyond available range. */
387 /*
388 * TODO Define max after which we stop reading.
389 * To ensure that a rogue large message
390 * doesn't trap us here.
391 */
392 }
393 break;
394 default:
395 assert(0);
396 }
397 }
398 }
399
400 void
401 fifo_read_all(Config *cfg, struct timespec *ti, char *buf)
402 {
403 fd_set fds;
404 int maxfd = -1;
405 int ready = 0;
406 struct stat st;
407 struct timespec t;
408
409 FD_ZERO(&fds);
410 for (Fifo *f = cfg->fifos; f; f = f->next) {
411 /* TODO: Create the FIFO if it doesn't already exist. */
412 if (lstat(f->name, &st) < 0) {
413 error(
414 "Cannot stat \"%s\". Error: %s\n",
415 f->name,
416 strerror(errno)
417 );
418 fifo_read_error(f, buf);
419 continue;
420 }
421 if (!(st.st_mode & S_IFIFO)) {
422 error("\"%s\" is not a FIFO\n", f->name);
423 fifo_read_error(f, buf);
424 continue;
425 }
426 if (f->fd < 0) {
427 debug("%s: closed. opening. fd: %d\n", f->name, f->fd);
428 f->fd = open(f->name, O_RDONLY | O_NONBLOCK);
429 } else {
430 debug("%s: already openned. fd: %d\n", f->name, f->fd);
431 }
432 if (f->fd == -1) {
433 /* TODO Consider backing off retries for failed fifos */
434 error("Failed to open \"%s\"\n", f->name);
435 fifo_read_error(f, buf);
436 continue;
437 }
438 debug("%s: open. fd: %d\n", f->name, f->fd);
439 if (f->fd > maxfd)
440 maxfd = f->fd;
441 FD_SET(f->fd, &fds);
442 }
443 debug("selecting...\n");
444 ready = pselect(maxfd + 1, &fds, NULL, NULL, ti, NULL);
445 debug("ready: %d\n", ready);
446 clock_gettime(CLOCK_MONOTONIC, &t);
447 if (ready == -1) {
448 switch (errno) {
449 case EINTR:
450 error("pselect temp failure: %d, errno: %d, msg: %s\n",
451 ready, errno, strerror(errno));
452 /* TODO: Reconsider what to do here. */
453 return;
454 default:
455 fatal("pselect failed: %d, errno: %d, msg: %s\n",
456 ready, errno, strerror(errno));
457 }
458 }
459 /* At-least-once ensures that expiries are still checked on timeouts. */
460 do {
461 for (Fifo *f = cfg->fifos; f; f = f->next) {
462 if (FD_ISSET(f->fd, &fds)) {
463 debug("reading: %s\n", f->name);
464 switch (fifo_read_one(f, t, buf)) {
465 /*
466 * ### MESSAGE LOSS ###
467 * is introduced by closing at EOM in addition
468 * to EOF, since there may be unread messages
469 * remaining in the pipe. However,
470 *
471 * ### INTER-MESSAGE PUSHBACK ###
472 * is also gained, since pipes block at the
473 * "open" call.
474 *
475 * This is an acceptable trade-off because we
476 * are a stateless reporter of a _most-recent_
477 * status, not a stateful accumulator.
478 */
479 case END_OF_MESSAGE:
480 case END_OF_FILE:
481 case FAILURE:
482 close(f->fd);
483 f->fd = -1;
484 ready--;
485 break;
486 case RETRY:
487 break;
488 default:
489 assert(0);
490 }
491 } else {
492 fifo_expire(f, t, buf);
493 }
494 }
495 } while (ready);
496 assert(ready == 0);
497 }
498
499 int
500 main(int argc, char *argv[])
501 {
502 Config cfg = {
503 .interval = 1.0,
504 .separator = "|",
505 .fifos = NULL,
506 .fifo_count = 0,
507 .total_width = 0,
508 .output_to_x_root_window = 0,
509 };
510
511 int width = 0;
512 int nfifos = 0;
513 int seplen = 0;
514 int prefix = 0;
515 int errors = 0;
516 char *buf;
517 Display *d = NULL;
518 struct stat st;
519 struct timespec
520 t0, /* time stamp. before reading fifos */
521 t1, /* time stamp. after reading fifos */
522 ti, /* time interval desired (t1 - t0) */
523 td, /* time interval measured (t1 - t0) */
524 tc; /* time interval correction (ti - td) when td < ti */
525
526 argv0 = argv[0];
527
528 opts_parse(&cfg, argc, argv);
529 debug("argv0 = %s\n", argv0);
530 config_print(&cfg);
531
532 ti = timespec_of_float(cfg.interval);
533
534 if (cfg.fifos == NULL)
535 usage("No fifo specs were given!\n");
536
537 /* 1st pass to check file existence and type */
538 for (Fifo *f = cfg.fifos; f; f = f->next) {
539 if (lstat(f->name, &st) < 0) {
540 error(
541 "Cannot stat \"%s\". Error: %s\n",
542 f->name,
543 strerror(errno)
544 );
545 errors++;
546 continue;
547 }
548 if (!(st.st_mode & S_IFIFO)) {
549 error("\"%s\" is not a FIFO\n", f->name);
550 errors++;
551 continue;
552 }
553 }
554 if (errors)
555 fatal("Encountered errors with given file paths. See log.\n");
556
557 width = cfg.total_width;
558 seplen = strlen(cfg.separator);
559
560 /* 2nd pass to make space for separators */
561 for (Fifo *f = cfg.fifos; f; f = f->next) {
562 f->pos_init += prefix;
563 f->pos_final += prefix;
564 f->pos_curr = f->pos_init;
565 prefix += seplen;
566 nfifos++;
567 }
568 width += (seplen * (nfifos - 1));
569 buf = calloc(1, width + 1);
570 if (buf == NULL)
571 fatal("[memory] Failed to allocate buffer of %d bytes", width);
572 memset(buf, ' ', width);
573 buf[width] = '\0';
574 /* 3rd pass to set the separators */
575 for (Fifo *f = cfg.fifos; f; f = f->next) {
576 if (f->pos_init) { /* Skip the first, left-most */
577 /* Copying only seplen ensures we omit the '\0' byte. */
578 strncpy(
579 buf + (f->pos_init - seplen),
580 cfg.separator,
581 seplen
582 );
583 }
584 }
585
586 if (cfg.output_to_x_root_window && !(d = XOpenDisplay(NULL)))
587 fatal("XOpenDisplay failed with: %p\n", d);
588 /* TODO: Handle signals */
589 for (;;) {
590 clock_gettime(CLOCK_MONOTONIC, &t0); // FIXME: check errors
591 fifo_read_all(&cfg, &ti, buf);
592 if (cfg.output_to_x_root_window) {
593 if (XStoreName(d, DefaultRootWindow(d), buf) < 0)
594 fatal("XStoreName failed.\n");
595 XFlush(d);
596 } else {
597 puts(buf);
598 fflush(stdout);
599 }
600 clock_gettime(CLOCK_MONOTONIC, &t1); // FIXME: check errors
601 timespecsub(&t1, &t0, &td);
602 debug(
603 "td {tv_sec = %ld, tv_nsec = %ld}\n",
604 td.tv_sec,
605 td.tv_nsec
606 );
607 if (timespeccmp(&td, &ti, <)) {
608 /* Pushback on data producers by refusing to read the
609 * pipe more frequently than the interval.
610 */
611 timespecsub(&ti, &td, &tc);
612 debug("snooze YES\n");
613 snooze(&tc);
614 } else {
615 debug("snooze NO\n");
616 }
617 }
618
619 return EXIT_SUCCESS;
620 }
This page took 0.093621 seconds and 4 git commands to generate.