9c84a7b56bb81c33462ce6a9cf8514b6b32aaff9
[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 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 = %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 switch (errno) {
344 case EAGAIN:
345 return RETRY;
346 default:
347 return FAILURE;
348 }
349 case 0:
350 debug("%s: End of FILE\n", f->name);
351 f->pos_curr = f->pos_init;
352 return END_OF_FILE;
353 case 1:
354 /* TODO: Consider making msg term char a CLI option */
355 if (c == '\n' || c == '\0') {
356 r = f->pos_final - f->pos_curr;
357 if (r > 0)
358 memset(buf + f->pos_curr, ' ', r);
359 f->pos_curr = f->pos_init;
360 return END_OF_MESSAGE;
361 } else {
362 if (f->pos_curr <= f->pos_final)
363 buf[f->pos_curr++] = c;
364 /* Drop beyond available range. */
365 }
366 break;
367 default:
368 assert(0);
369 }
370 }
371 /* TODO Record timestamp read */
372 }
373
374 void
375 fifo_read_all(Config *cfg, char *buf)
376 {
377 fd_set fds;
378 int maxfd = -1;
379 int ready;
380 struct stat st;
381
382 FD_ZERO(&fds);
383 for (Fifo *f = cfg->fifos; f; f = f->next) {
384 /* TODO: Create the FIFO if it doesn't already exist. */
385 if (lstat(f->name, &st) < 0) {
386 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
387 fifo_read_error(f, buf);
388 continue;
389 }
390 if (!(st.st_mode & S_IFIFO)) {
391 error("\"%s\" is not a FIFO\n", f->name);
392 fifo_read_error(f, buf);
393 continue;
394 }
395 if (f->fd < 0) {
396 debug("%s: closed. opening. fd: %d\n", f->name, f->fd);
397 f->fd = open(f->name, O_RDONLY | O_NONBLOCK);
398 } else {
399 debug("%s: already openned. fd: %d\n", f->name, f->fd);
400 }
401 if (f->fd == -1) {
402 /* TODO: Consider backing off retries for failed fifos. */
403 error("Failed to open \"%s\"\n", f->name);
404 fifo_read_error(f, buf);
405 continue;
406 }
407 debug("%s: open. fd: %d\n", f->name, f->fd);
408 if (f->fd > maxfd)
409 maxfd = f->fd;
410 FD_SET(f->fd, &fds);
411 }
412 debug("selecting...\n");
413 ready = select(maxfd + 1, &fds, NULL, NULL, NULL);
414 debug("ready: %d\n", ready);
415 assert(ready != 0);
416 if (ready < 0)
417 fatal("%s", strerror(errno));
418 for (Fifo *f = cfg->fifos; f; f = f->next) {
419 if (FD_ISSET(f->fd, &fds)) {
420 debug("reading: %s\n", f->name);
421 switch (fifo_read_one(f, buf)) {
422 case END_OF_FILE:
423 case FAILURE:
424 close(f->fd);
425 f->fd = -1;
426 break;
427 case END_OF_MESSAGE:
428 case RETRY:
429 break;
430 default:
431 assert(0);
432 }
433 }
434 }
435 }
436
437 int
438 main(int argc, char *argv[])
439 {
440 int width = 0;
441 int nfifos = 0;
442 int seplen = 0;
443 int prefix = 0;
444 int errors = 0;
445 char *buf;
446 Config cfg0 = defaults;
447 Config *cfg = &cfg0;
448 Display *display = NULL;
449 struct stat st;
450 struct timespec
451 t0, /* time stamp. before reading fifos */
452 t1, /* time stamp. after reading fifos */
453 ti, /* time interval desired (t1 - t0) */
454 td, /* time interval measured (t1 - t0) */
455 tc; /* time interval correction (ti - td) when td < ti */
456
457 argv0 = argv[0];
458
459 opts_parse(cfg, argc, argv);
460 debug("argv0 = %s\n", argv0);
461 config_print(cfg);
462
463 ti = timespec_of_float(cfg->interval);
464
465 if (cfg->fifos == NULL)
466 usage("No fifo specs were given!\n");
467
468 /* 1st pass to check file existence and type */
469 for (Fifo *f = cfg->fifos; f; f = f->next) {
470 if (lstat(f->name, &st) < 0) {
471 error("Cannot stat \"%s\". Error: %s\n", f->name, strerror(errno));
472 errors++;
473 continue;
474 }
475 if (!(st.st_mode & S_IFIFO)) {
476 error("\"%s\" is not a FIFO\n", f->name);
477 errors++;
478 continue;
479 }
480 }
481 if (errors)
482 fatal("Encountered errors with the given file paths. See log.\n");
483
484 width = cfg->total_width;
485 seplen = strlen(cfg->separator);
486
487 /* 2nd pass to make space for separators */
488 for (Fifo *f = cfg->fifos; f; f = f->next) {
489 f->pos_init += prefix;
490 f->pos_final += prefix;
491 f->pos_curr = f->pos_init;
492 prefix += seplen;
493 nfifos++;
494 }
495 width += (seplen * (nfifos - 1));
496 buf = calloc(1, width + 1);
497 if (buf == NULL)
498 fatal("[memory] Failed to allocate buffer of %d bytes", width);
499 memset(buf, ' ', width);
500 buf[width] = '\0';
501 /* 3rd pass to set the separators */
502 for (Fifo *f = cfg->fifos; f; f = f->next) {
503 if (f->pos_init) { /* Skip the first, left-most */
504 /* Copying only seplen ensures we omit the '\0' byte. */
505 strncpy(buf + (f->pos_init - seplen), cfg->separator, seplen);
506 }
507 }
508
509 if (cfg->output_to_x_root_window && !(display = XOpenDisplay(NULL)))
510 fatal("XOpenDisplay failed with: %p\n", display);
511 /* TODO: Handle signals */
512 for (;;) {
513 clock_gettime(CLOCK_MONOTONIC, &t0); // FIXME: check errors
514 /* TODO: Cache expiration. i.e. use the TTL */
515 /* TODO: How to trigger TTL check? On select? Alarm signal? */
516 /* TODO: Set timeout on fifo_read_all based on diff of last time of
517 * fifo_read_all and desired time of next TTL check.
518 */
519 /* TODO: How long to wait on IO? Max TTL? */
520 fifo_read_all(cfg, buf);
521 if (cfg->output_to_x_root_window) {
522 if (XStoreName(display, DefaultRootWindow(display), buf) < 0)
523 fatal("XStoreName failed.\n");
524 XFlush(display);
525 } else {
526 puts(buf);
527 fflush(stdout);
528 }
529 clock_gettime(CLOCK_MONOTONIC, &t1); // FIXME: check errors
530 timespecsub(&t1, &t0, &td);
531 debug("td {tv_sec = %ld, tv_nsec = %ld}\n", td.tv_sec, td.tv_nsec);
532 if (timespeccmp(&td, &ti, <)) {
533 /* Pushback on data producers by refusing to read the
534 * pipe more frequently than the interval.
535 */
536 timespecsub(&ti, &td, &tc);
537 debug("snooze YES\n");
538 snooze(&tc);
539 } else {
540 debug("snooze NO\n");
541 }
542 }
543
544 return EXIT_SUCCESS;
545 }
This page took 0.118708 seconds and 3 git commands to generate.