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