Handle fifo read errors and ends of messages
[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 int last_read;
35 int 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 FAIL_FINAL = -2,
61 FAIL_TMP = -1,
62 END_OF_FILE = 0,
63 END_OF_MESSAGE = 1
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 = %d,"
75 " ttl = %d,"
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,
85 f->ttl,
86 f->pos_init,
87 f->pos_curr,
88 f->pos_final,
89 f->next
90 );
91 }
92
93 void
94 fifo_print_all(Fifo *head)
95 {
96 for (Fifo *f = head; f; f = f->next) {
97 fifo_print_one(f);
98 }
99 }
100
101 void
102 config_print(Config *cfg)
103 {
104 info(
105 "Config "
106 "{"
107 " interval = %f,"
108 " separator = %s,"
109 " fifo_count = %d,"
110 " total_width = %d,"
111 " fifos = ..."
112 " }\n",
113 cfg->interval,
114 cfg->separator,
115 cfg->fifo_count,
116 cfg->total_width
117 );
118 fifo_print_all(cfg->fifos);
119 }
120
121 int
122 is_pos_num(char *s)
123 {
124 while (*s != '\0')
125 if (!isdigit(*(s++)))
126 return 0;
127 return 1;
128 }
129
130 int
131 is_decimal(char *s)
132 {
133 char c;
134 int seen = 0;
135
136 while ((c = *(s++)) != '\0')
137 if (!isdigit(c)) {
138 if (c == '.' && !seen++)
139 continue;
140 else
141 return 0;
142 }
143 return 1;
144 }
145
146 void
147 print_usage()
148 {
149 assert(argv0);
150 fprintf(
151 stderr,
152 "\n"
153 "Usage: %s [OPTION ...] SPEC [SPEC ...]\n"
154 "\n"
155 " SPEC = FILE_PATH DATA_WIDTH DATA_TTL\n"
156 " FILE_PATH = string\n"
157 " DATA_WIDTH = int (* (positive) number of characters *)\n"
158 " DATA_TTL = int (* (positive) number of seconds *)\n"
159 " OPTION = -i INTERVAL\n"
160 " | -s SEPARATOR\n"
161 " | -x (* Output to X root window *)\n"
162 " | -l LOG_LEVEL\n"
163 " SEPARATOR = string\n"
164 " INTERVAL = int (* (positive) number of seconds *)\n"
165 " LOG_LEVEL = int (* %d through %d *)\n"
166 "\n",
167 argv0,
168 Nothing,
169 Debug
170 );
171 fprintf(
172 stderr,
173 "Example: %s -i 1 /dev/shm/khatus/khatus_sensor_x 4 10\n"
174 "\n",
175 argv0
176 );
177 }
178
179 void opts_parse_any(Config *, int, char *[], int); /* For mutually-recursive calls. */
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("Option -l value (%d) exceeds maximum (%d)\n", log_level, Debug);
219 _khatus_lib_log_level = log_level;
220 opts_parse_any(cfg, argc, argv, i);
221 }
222
223 void
224 parse_opts_opt(Config *cfg, int argc, char *argv[], int i)
225 {
226 switch (argv[i][1]) {
227 case 'i':
228 /* TODO: Generic set_int */
229 parse_opts_opt_i(cfg, argc, argv, ++i);
230 break;
231 case 's':
232 /* TODO: Generic set_str */
233 parse_opts_opt_s(cfg, argc, argv, ++i);
234 break;
235 case 'x':
236 cfg->output_to_x_root_window = 1;
237 opts_parse_any(cfg, argc, argv, ++i);
238 break;
239 case 'l':
240 /* TODO: Generic set_int */
241 parse_opts_opt_l(cfg, argc, argv, ++i);
242 break;
243 default :
244 usage("Option \"%s\" is invalid\n", argv[i]);
245 }
246 }
247
248 void
249 parse_opts_spec(Config *cfg, int argc, char *argv[], int i)
250 {
251 if ((i + 3) > argc)
252 usage("[spec] Parameter(s) missing for fifo \"%s\".\n", argv[i]);
253
254 char *n = argv[i++];
255 char *w = argv[i++];
256 char *t = argv[i++];
257
258 if (!is_pos_num(w))
259 usage("[spec] Invalid width: \"%s\", for fifo \"%s\"\n", w, n);
260 if (!is_pos_num(t))
261 usage("[spec] Invalid TTL: \"%s\", for fifo \"%s\"\n", t, n);
262 Fifo *f = calloc(1, sizeof(struct Fifo));
263 if (f) {
264 f->name = n;
265 f->fd = -1;
266 f->width = atoi(w);
267 f->ttl = atoi(t);
268 f->last_read = 0;
269 f->pos_init = cfg->total_width;
270 f->pos_curr = f->pos_init;
271 f->pos_final = f->pos_init + f->width - 1;
272 f->next = cfg->fifos;
273
274 cfg->fifos = f;
275 cfg->total_width += f->width;
276 cfg->fifo_count++;
277 } else {
278 fatal("[memory] Allocation failure.");
279 }
280 opts_parse_any(cfg, argc, argv, i);
281 }
282
283 void
284 opts_parse_any(Config *cfg, int argc, char *argv[], int i)
285 {
286 if (i < argc) {
287 switch (argv[i][0]) {
288 case '-':
289 parse_opts_opt(cfg, argc, argv, i);
290 break;
291 default :
292 parse_opts_spec(cfg, argc, argv, i);
293 }
294 }
295 }
296
297 void
298 opts_parse(Config *cfg, int argc, char *argv[])
299 {
300 opts_parse_any(cfg, argc, argv, 1);
301
302 Fifo *last = cfg->fifos;
303 cfg->fifos = NULL;
304 for (Fifo *f = last; f; ) {
305 Fifo *next = f->next;
306 f->next = cfg->fifos;
307 cfg->fifos = f;
308 f = next;
309 }
310 }
311
312 void
313 fifo_read_error(Fifo *f, char *buf)
314 {
315 char *b;
316 int i;
317
318 b = buf + f->pos_init;
319 /* Copy as much of the error message as possible.
320 * EXCLUDING the reminating \0. */
321 for (i = 0; i < errlen && i < f->width; i++)
322 b[i] = errmsg[i];
323 /* Any remaining slots: */
324 for (; i < f->width; i++)
325 b[i] = '_';
326 }
327
328 enum read_status
329 fifo_read_one(Fifo *f, char *buf)
330 {
331 /* Initialize all to an impossible value: */
332 ssize_t n = -5; /* Number of bytes read. */
333 char c = -1; /* Character read. */
334 int r = -1; /* Remaining unused slots in buffer range. */
335
336 for (;;) {
337 n = read(f->fd, &c, 1);
338 assert(n >= -1 && n <= 1);
339 switch (n) {
340 case -1:
341 error("Failed to read: \"%s\". errno: %d, msg: %s\n",
342 f->name, errno, strerror(errno));
343 if (errno == 11)
344 return FAIL_TMP;
345 else
346 return FAIL_FINAL;
347 case 0:
348 debug("%s: End of FILE\n", f->name);
349 f->pos_curr = f->pos_init;
350 return END_OF_FILE;
351 case 1:
352 /* TODO: Consider making msg term char a CLI option */
353 if (c == '\n' || c == '\0') {
354 r = f->pos_final - f->pos_curr;
355 if (r > 0)
356 memset(buf + f->pos_curr, ' ', r);
357 f->pos_curr = f->pos_init;
358 return END_OF_MESSAGE;
359 } else {
360 if (f->pos_curr <= f->pos_final)
361 buf[f->pos_curr++] = c;
362 /* Drop beyond available range. */
363 }
364 break;
365 default:
366 assert(0);
367 }
368 }
369 /* TODO Record timestamp read */
370 }
371
372 void
373 fifo_read_all(Config *cfg, char *buf)
374 {
375 fd_set fds;
376 int maxfd = -1;
377 int ready;
378 struct stat st;
379
380 FD_ZERO(&fds);
381 for (Fifo *f = cfg->fifos; f; f = f->next) {
382 /* TODO: Create the FIFO if it doesn't already exist. */
383 if (lstat(f->name, &st) < 0) {
384 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
385 fifo_read_error(f, buf);
386 continue;
387 }
388 if (!(st.st_mode & S_IFIFO)) {
389 error("\"%s\" is not a FIFO\n", f->name);
390 fifo_read_error(f, buf);
391 continue;
392 }
393 if (f->fd < 0) {
394 debug("%s: closed. opening. fd: %d\n", f->name, f->fd);
395 f->fd = open(f->name, O_RDONLY | O_NONBLOCK);
396 } else {
397 debug("%s: already openned. fd: %d\n", f->name, f->fd);
398 }
399 if (f->fd == -1) {
400 /* TODO: Consider backing off retries for failed fifos. */
401 error("Failed to open \"%s\"\n", f->name);
402 fifo_read_error(f, buf);
403 continue;
404 }
405 debug("%s: open. fd: %d\n", f->name, f->fd);
406 if (f->fd > maxfd)
407 maxfd = f->fd;
408 FD_SET(f->fd, &fds);
409 }
410 debug("selecting...\n");
411 ready = select(maxfd + 1, &fds, NULL, NULL, NULL);
412 debug("ready: %d\n", ready);
413 assert(ready != 0);
414 if (ready < 0)
415 fatal("%s", strerror(errno));
416 for (Fifo *f = cfg->fifos; f; f = f->next) {
417 if (FD_ISSET(f->fd, &fds)) {
418 debug("reading: %s\n", f->name);
419 switch (fifo_read_one(f, buf)) {
420 case END_OF_FILE:
421 case FAIL_FINAL:
422 close(f->fd);
423 f->fd = -1;
424 break;
425 case END_OF_MESSAGE:
426 case FAIL_TMP:
427 break;
428 default:
429 assert(0);
430 }
431 }
432 }
433 }
434
435 int
436 main(int argc, char *argv[])
437 {
438 int width = 0;
439 int nfifos = 0;
440 int seplen = 0;
441 int prefix = 0;
442 int errors = 0;
443 char *buf;
444 Config cfg0 = defaults;
445 Config *cfg = &cfg0;
446 Display *display = NULL;
447 struct stat st;
448 struct timespec
449 t0, /* time stamp. before reading fifos */
450 t1, /* time stamp. after reading fifos */
451 ti, /* time interval desired (t1 - t0) */
452 td, /* time interval measured (t1 - t0) */
453 tc; /* time interval correction (ti - td) when td < ti */
454
455 argv0 = argv[0];
456
457 opts_parse(cfg, argc, argv);
458 debug("argv0 = %s\n", argv0);
459 config_print(cfg);
460
461 ti = timespec_of_float(cfg->interval);
462
463 if (cfg->fifos == NULL)
464 usage("No fifo specs were given!\n");
465
466 /* 1st pass to check file existence and type */
467 for (Fifo *f = cfg->fifos; f; f = f->next) {
468 if (lstat(f->name, &st) < 0) {
469 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
470 errors++;
471 continue;
472 }
473 if (!(st.st_mode & S_IFIFO)) {
474 error("\"%s\" is not a FIFO\n", f->name);
475 errors++;
476 continue;
477 }
478 }
479 if (errors)
480 fatal("Encountered errors with the given file paths. See log.\n");
481
482 width = cfg->total_width;
483 seplen = strlen(cfg->separator);
484
485 /* 2nd pass to make space for separators */
486 for (Fifo *f = cfg->fifos; f; f = f->next) {
487 f->pos_init += prefix;
488 f->pos_final += prefix;
489 f->pos_curr = f->pos_init;
490 prefix += seplen;
491 nfifos++;
492 }
493 width += (seplen * (nfifos - 1));
494 buf = calloc(1, width + 1);
495 if (buf == NULL)
496 fatal("[memory] Failed to allocate buffer of %d bytes", width);
497 memset(buf, ' ', width);
498 buf[width] = '\0';
499 /* 3rd pass to set the separators */
500 for (Fifo *f = cfg->fifos; f; f = f->next) {
501 if (f->pos_init) { /* Skip the first, left-most */
502 /* Copying only seplen ensures we omit the '\0' byte. */
503 strncpy(buf + (f->pos_init - seplen), cfg->separator, seplen);
504 }
505 }
506
507 if (cfg->output_to_x_root_window && !(display = XOpenDisplay(NULL)))
508 fatal("XOpenDisplay failed with: %p\n", display);
509 /* TODO: Handle signals */
510 for (;;) {
511 clock_gettime(CLOCK_MONOTONIC, &t0); // FIXME: check errors
512 /* TODO: Cache expiration. i.e. use the TTL */
513 /* TODO: How to trigger TTL check? On select? Alarm signal? */
514 /* TODO: Set timeout on fifo_read_all based on diff of last time of
515 * fifo_read_all and desired time of next TTL check.
516 */
517 /* TODO: How long to wait on IO? Max TTL? */
518 fifo_read_all(cfg, buf);
519 if (cfg->output_to_x_root_window) {
520 if (XStoreName(display, DefaultRootWindow(display), buf) < 0)
521 fatal("XStoreName failed.\n");
522 XFlush(display);
523 } else {
524 puts(buf);
525 fflush(stdout);
526 }
527 clock_gettime(CLOCK_MONOTONIC, &t1); // FIXME: check errors
528 timespecsub(&t1, &t0, &td);
529 debug("td {tv_sec = %ld, tv_nsec = %ld}\n", td.tv_sec, td.tv_nsec);
530 if (timespeccmp(&td, &ti, <)) {
531 /* Pushback on data producers by refusing to read the
532 * pipe more frequently than the interval.
533 */
534 timespecsub(&ti, &td, &tc);
535 debug("snooze YES\n");
536 snooze(&tc);
537 } else {
538 debug("snooze NO\n");
539 }
540 }
541
542 return EXIT_SUCCESS;
543 }
This page took 0.097649 seconds and 4 git commands to generate.