923b092eca755af466f7c66bae6cfe8907c829ce
[fio.git] / client.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <errno.h>
5 #include <fcntl.h>
6 #include <poll.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <sys/socket.h>
10 #include <sys/un.h>
11 #include <netinet/in.h>
12 #include <arpa/inet.h>
13 #include <netdb.h>
14 #include <signal.h>
15 #ifdef CONFIG_ZLIB
16 #include <zlib.h>
17 #endif
18
19 #include "fio.h"
20 #include "client.h"
21 #include "server.h"
22 #include "flist.h"
23 #include "hash.h"
24 #include "verify-state.h"
25
26 static void handle_du(struct fio_client *client, struct fio_net_cmd *cmd);
27 static void handle_ts(struct fio_client *client, struct fio_net_cmd *cmd);
28 static void handle_gs(struct fio_client *client, struct fio_net_cmd *cmd);
29 static void handle_probe(struct fio_client *client, struct fio_net_cmd *cmd);
30 static void handle_text(struct fio_client *client, struct fio_net_cmd *cmd);
31 static void handle_stop(struct fio_client *client);
32 static void handle_start(struct fio_client *client, struct fio_net_cmd *cmd);
33
34 static void convert_text(struct fio_net_cmd *cmd);
35 static void client_display_thread_status(struct jobs_eta *je);
36
37 struct client_ops const fio_client_ops = {
38         .text           = handle_text,
39         .disk_util      = handle_du,
40         .thread_status  = handle_ts,
41         .group_stats    = handle_gs,
42         .stop           = handle_stop,
43         .start          = handle_start,
44         .eta            = client_display_thread_status,
45         .probe          = handle_probe,
46         .eta_msec       = FIO_CLIENT_DEF_ETA_MSEC,
47         .client_type    = FIO_CLIENT_TYPE_CLI,
48 };
49
50 static struct timespec eta_ts;
51
52 static FLIST_HEAD(client_list);
53 static FLIST_HEAD(eta_list);
54
55 static FLIST_HEAD(arg_list);
56
57 struct thread_stat client_ts;
58 struct group_run_stats client_gs;
59 int sum_stat_clients;
60
61 static int sum_stat_nr;
62 static struct buf_output allclients;
63 static struct json_object *root = NULL;
64 static struct json_object *global_opt_object = NULL;
65 static struct json_array *global_opt_array = NULL;
66 static struct json_array *clients_array = NULL;
67 static struct json_array *du_array = NULL;
68
69 static int error_clients;
70
71 #define FIO_CLIENT_HASH_BITS    7
72 #define FIO_CLIENT_HASH_SZ      (1 << FIO_CLIENT_HASH_BITS)
73 #define FIO_CLIENT_HASH_MASK    (FIO_CLIENT_HASH_SZ - 1)
74 static struct flist_head client_hash[FIO_CLIENT_HASH_SZ];
75
76 static struct cmd_iolog_pdu *convert_iolog(struct fio_net_cmd *, bool *);
77
78 static void fio_client_add_hash(struct fio_client *client)
79 {
80         int bucket = hash_long(client->fd, FIO_CLIENT_HASH_BITS);
81
82         bucket &= FIO_CLIENT_HASH_MASK;
83         flist_add(&client->hash_list, &client_hash[bucket]);
84 }
85
86 static void fio_client_remove_hash(struct fio_client *client)
87 {
88         if (!flist_empty(&client->hash_list))
89                 flist_del_init(&client->hash_list);
90 }
91
92 static void fio_init fio_client_hash_init(void)
93 {
94         int i;
95
96         for (i = 0; i < FIO_CLIENT_HASH_SZ; i++)
97                 INIT_FLIST_HEAD(&client_hash[i]);
98 }
99
100 static int read_data(int fd, void *data, size_t size)
101 {
102         ssize_t ret;
103
104         while (size) {
105                 ret = read(fd, data, size);
106                 if (ret < 0) {
107                         if (errno == EAGAIN || errno == EINTR)
108                                 continue;
109                         break;
110                 } else if (!ret)
111                         break;
112                 else {
113                         data += ret;
114                         size -= ret;
115                 }
116         }
117
118         if (size)
119                 return EAGAIN;
120
121         return 0;
122 }
123
124 static int read_ini_data(int fd, void *data, size_t size)
125 {
126         char *p = data;
127         int ret = 0;
128         FILE *fp;
129         int dupfd;
130
131         dupfd = dup(fd);
132         if (dupfd < 0)
133                 return errno;
134
135         fp = fdopen(dupfd, "r");
136         if (!fp) {
137                 ret = errno;
138                 close(dupfd);
139                 goto out;
140         }
141
142         while (1) {
143                 ssize_t len;
144                 char buf[OPT_LEN_MAX+1], *sub;
145
146                 if (!fgets(buf, sizeof(buf), fp)) {
147                         if (ferror(fp)) {
148                                 if (errno == EAGAIN || errno == EINTR)
149                                         continue;
150                                 ret = errno;
151                         }
152                         break;
153                 }
154
155                 sub = fio_option_dup_subs(buf);
156                 len = strlen(sub);
157                 if (len + 1 > size) {
158                         log_err("fio: no space left to read data\n");
159                         free(sub);
160                         ret = ENOSPC;
161                         break;
162                 }
163
164                 memcpy(p, sub, len);
165                 free(sub);
166                 p += len;
167                 *p = '\0';
168                 size -= len;
169         }
170
171         fclose(fp);
172 out:
173         return ret;
174 }
175
176 static void fio_client_json_init(void)
177 {
178         char time_buf[32];
179         time_t time_p;
180
181         if (!(output_format & FIO_OUTPUT_JSON))
182                 return;
183
184         time(&time_p);
185         os_ctime_r((const time_t *) &time_p, time_buf, sizeof(time_buf));
186         time_buf[strlen(time_buf) - 1] = '\0';
187
188         root = json_create_object();
189         json_object_add_value_string(root, "fio version", fio_version_string);
190         json_object_add_value_int(root, "timestamp", time_p);
191         json_object_add_value_string(root, "time", time_buf);
192
193         if (nr_clients == 1) {
194                 global_opt_object = json_create_object();
195                 json_object_add_value_object(root, "global options", global_opt_object);
196         } else {
197                 global_opt_array = json_create_array();
198                 json_object_add_value_array(root, "global options", global_opt_array);
199         }
200         clients_array = json_create_array();
201         json_object_add_value_array(root, "client_stats", clients_array);
202         du_array = json_create_array();
203         json_object_add_value_array(root, "disk_util", du_array);
204 }
205
206 static void fio_client_json_fini(void)
207 {
208         struct buf_output out;
209
210         if (!root)
211                 return;
212
213         buf_output_init(&out);
214
215         __log_buf(&out, "\n");
216         json_print_object(root, &out);
217         __log_buf(&out, "\n");
218         log_info_buf(out.buf, out.buflen);
219
220         buf_output_free(&out);
221
222         json_free_object(root);
223         root = NULL;
224         global_opt_object = NULL;
225         global_opt_array = NULL;
226         clients_array = NULL;
227         du_array = NULL;
228 }
229
230 static struct fio_client *find_client_by_fd(int fd)
231 {
232         int bucket = hash_long(fd, FIO_CLIENT_HASH_BITS) & FIO_CLIENT_HASH_MASK;
233         struct fio_client *client;
234         struct flist_head *entry;
235
236         flist_for_each(entry, &client_hash[bucket]) {
237                 client = flist_entry(entry, struct fio_client, hash_list);
238
239                 if (client->fd == fd) {
240                         client->refs++;
241                         return client;
242                 }
243         }
244
245         return NULL;
246 }
247
248 void fio_put_client(struct fio_client *client)
249 {
250         if (--client->refs)
251                 return;
252
253         log_info_buf(client->buf.buf, client->buf.buflen);
254         buf_output_free(&client->buf);
255
256         free(client->hostname);
257         if (client->argv)
258                 free(client->argv);
259         if (client->name)
260                 free(client->name);
261         while (client->nr_files) {
262                 struct client_file *cf = &client->files[--client->nr_files];
263
264                 free(cf->file);
265         }
266         if (client->files)
267                 free(client->files);
268         if (client->opt_lists)
269                 free(client->opt_lists);
270
271         if (!client->did_stat)
272                 sum_stat_clients--;
273
274         if (client->error)
275                 error_clients++;
276
277         free(client);
278 }
279
280 static int fio_client_dec_jobs_eta(struct client_eta *eta, client_eta_op eta_fn)
281 {
282         if (!--eta->pending) {
283                 eta_fn(&eta->eta);
284                 free(eta);
285                 return 0;
286         }
287
288         return 1;
289 }
290
291 static void fio_drain_client_text(struct fio_client *client)
292 {
293         do {
294                 struct fio_net_cmd *cmd = NULL;
295
296                 if (fio_server_poll_fd(client->fd, POLLIN, 0))
297                         cmd = fio_net_recv_cmd(client->fd, false);
298                 if (!cmd)
299                         break;
300
301                 if (cmd->opcode == FIO_NET_CMD_TEXT) {
302                         convert_text(cmd);
303                         client->ops->text(client, cmd);
304                 }
305
306                 free(cmd);
307         } while (1);
308 }
309
310 static void remove_client(struct fio_client *client)
311 {
312         assert(client->refs);
313
314         dprint(FD_NET, "client: removed <%s>\n", client->hostname);
315
316         fio_drain_client_text(client);
317
318         if (!flist_empty(&client->list))
319                 flist_del_init(&client->list);
320
321         fio_client_remove_hash(client);
322
323         if (!flist_empty(&client->eta_list)) {
324                 flist_del_init(&client->eta_list);
325                 fio_client_dec_jobs_eta(client->eta_in_flight, client->ops->eta);
326         }
327
328         close(client->fd);
329         client->fd = -1;
330
331         if (client->ops->removed)
332                 client->ops->removed(client);
333
334         nr_clients--;
335         fio_put_client(client);
336 }
337
338 struct fio_client *fio_get_client(struct fio_client *client)
339 {
340         client->refs++;
341         return client;
342 }
343
344 static void __fio_client_add_cmd_option(struct fio_client *client,
345                                         const char *opt)
346 {
347         int index;
348
349         index = client->argc++;
350         client->argv = realloc(client->argv, sizeof(char *) * client->argc);
351         client->argv[index] = strdup(opt);
352         dprint(FD_NET, "client: add cmd %d: %s\n", index, opt);
353 }
354
355 void fio_client_add_cmd_option(void *cookie, const char *opt)
356 {
357         struct fio_client *client = cookie;
358         struct flist_head *entry;
359
360         if (!client || !opt)
361                 return;
362
363         __fio_client_add_cmd_option(client, opt);
364
365         /*
366          * Duplicate arguments to shared client group
367          */
368         flist_for_each(entry, &arg_list) {
369                 client = flist_entry(entry, struct fio_client, arg_list);
370
371                 __fio_client_add_cmd_option(client, opt);
372         }
373 }
374
375 static struct fio_client *get_new_client(void)
376 {
377         struct fio_client *client;
378
379         client = calloc(1, sizeof(*client));
380
381         INIT_FLIST_HEAD(&client->list);
382         INIT_FLIST_HEAD(&client->hash_list);
383         INIT_FLIST_HEAD(&client->arg_list);
384         INIT_FLIST_HEAD(&client->eta_list);
385         INIT_FLIST_HEAD(&client->cmd_list);
386
387         buf_output_init(&client->buf);
388
389         return client;
390 }
391
392 struct fio_client *fio_client_add_explicit(struct client_ops *ops,
393                                            const char *hostname, int type,
394                                            int port)
395 {
396         struct fio_client *client;
397
398         client = get_new_client();
399
400         if (type == Fio_client_socket)
401                 client->is_sock = true;
402         else {
403                 int ipv6;
404
405                 ipv6 = type == Fio_client_ipv6;
406                 if (fio_server_parse_host(hostname, ipv6,
407                                                 &client->addr.sin_addr,
408                                                 &client->addr6.sin6_addr))
409                         goto err;
410
411                 client->port = port;
412         }
413
414         client->fd = -1;
415         client->ops = ops;
416         client->refs = 1;
417         client->type = ops->client_type;
418         client->hostname = strdup(hostname);
419
420         __fio_client_add_cmd_option(client, "fio");
421
422         flist_add(&client->list, &client_list);
423         nr_clients++;
424         dprint(FD_NET, "client: added <%s>\n", client->hostname);
425         return client;
426 err:
427         free(client);
428         return NULL;
429 }
430
431 int fio_client_add_ini_file(void *cookie, const char *ini_file, bool remote)
432 {
433         struct fio_client *client = cookie;
434         struct client_file *cf;
435         size_t new_size;
436         void *new_files;
437
438         if (!client)
439                 return 1;
440
441         dprint(FD_NET, "client <%s>: add ini %s\n", client->hostname, ini_file);
442
443         new_size = (client->nr_files + 1) * sizeof(struct client_file);
444         new_files = realloc(client->files, new_size);
445         if (!new_files)
446                 return 1;
447
448         client->files = new_files;
449         cf = &client->files[client->nr_files];
450         cf->file = strdup(ini_file);
451         cf->remote = remote;
452         client->nr_files++;
453         return 0;
454 }
455
456 int fio_client_add(struct client_ops const *ops, const char *hostname, void **cookie)
457 {
458         struct fio_client *existing = *cookie;
459         struct fio_client *client;
460
461         if (existing) {
462                 /*
463                  * We always add our "exec" name as the option, hence 1
464                  * means empty.
465                  */
466                 if (existing->argc == 1)
467                         flist_add_tail(&existing->arg_list, &arg_list);
468                 else {
469                         while (!flist_empty(&arg_list))
470                                 flist_del_init(arg_list.next);
471                 }
472         }
473
474         client = get_new_client();
475
476         if (fio_server_parse_string(hostname, &client->hostname,
477                                         &client->is_sock, &client->port,
478                                         &client->addr.sin_addr,
479                                         &client->addr6.sin6_addr,
480                                         &client->ipv6)) {
481                 fio_put_client(client);
482                 return -1;
483         }
484
485         client->fd = -1;
486         client->ops = ops;
487         client->refs = 1;
488         client->type = ops->client_type;
489
490         __fio_client_add_cmd_option(client, "fio");
491
492         flist_add(&client->list, &client_list);
493         nr_clients++;
494         dprint(FD_NET, "client: added <%s>\n", client->hostname);
495         *cookie = client;
496         return 0;
497 }
498
499 static const char *server_name(struct fio_client *client, char *buf,
500                                size_t bufsize)
501 {
502         const char *from;
503
504         if (client->ipv6)
505                 from = inet_ntop(AF_INET6, (struct sockaddr *) &client->addr6.sin6_addr, buf, bufsize);
506         else if (client->is_sock)
507                 from = "sock";
508         else
509                 from = inet_ntop(AF_INET, (struct sockaddr *) &client->addr.sin_addr, buf, bufsize);
510
511         return from;
512 }
513
514 static void probe_client(struct fio_client *client)
515 {
516         struct cmd_client_probe_pdu pdu;
517         const char *sname;
518         uint64_t tag;
519         char buf[64];
520
521         dprint(FD_NET, "client: send probe\n");
522
523 #ifdef CONFIG_ZLIB
524         pdu.flags = __le64_to_cpu(FIO_PROBE_FLAG_ZLIB);
525 #else
526         pdu.flags = 0;
527 #endif
528
529         sname = server_name(client, buf, sizeof(buf));
530         memset(pdu.server, 0, sizeof(pdu.server));
531         snprintf((char *) pdu.server, sizeof(pdu.server), "%s", sname);
532
533         fio_net_send_cmd(client->fd, FIO_NET_CMD_PROBE, &pdu, sizeof(pdu), &tag, &client->cmd_list);
534 }
535
536 static int fio_client_connect_ip(struct fio_client *client)
537 {
538         struct sockaddr *addr;
539         socklen_t socklen;
540         int fd, domain;
541
542         if (client->ipv6) {
543                 client->addr6.sin6_family = AF_INET6;
544                 client->addr6.sin6_port = htons(client->port);
545                 domain = AF_INET6;
546                 addr = (struct sockaddr *) &client->addr6;
547                 socklen = sizeof(client->addr6);
548         } else {
549                 client->addr.sin_family = AF_INET;
550                 client->addr.sin_port = htons(client->port);
551                 domain = AF_INET;
552                 addr = (struct sockaddr *) &client->addr;
553                 socklen = sizeof(client->addr);
554         }
555
556         fd = socket(domain, SOCK_STREAM, 0);
557         if (fd < 0) {
558                 int ret = -errno;
559
560                 log_err("fio: socket: %s\n", strerror(errno));
561                 return ret;
562         }
563
564         if (connect(fd, addr, socklen) < 0) {
565                 int ret = -errno;
566
567                 log_err("fio: connect: %s\n", strerror(errno));
568                 log_err("fio: failed to connect to %s:%u\n", client->hostname,
569                                                                 client->port);
570                 close(fd);
571                 return ret;
572         }
573
574         return fd;
575 }
576
577 static int fio_client_connect_sock(struct fio_client *client)
578 {
579         struct sockaddr_un *addr = &client->addr_un;
580         socklen_t len;
581         int fd;
582
583         memset(addr, 0, sizeof(*addr));
584         addr->sun_family = AF_UNIX;
585         snprintf(addr->sun_path, sizeof(addr->sun_path), "%s",
586                  client->hostname);
587
588         fd = socket(AF_UNIX, SOCK_STREAM, 0);
589         if (fd < 0) {
590                 int ret = -errno;
591
592                 log_err("fio: socket: %s\n", strerror(errno));
593                 return ret;
594         }
595
596         len = sizeof(addr->sun_family) + strlen(addr->sun_path) + 1;
597         if (connect(fd, (struct sockaddr *) addr, len) < 0) {
598                 int ret = -errno;
599
600                 log_err("fio: connect; %s\n", strerror(errno));
601                 close(fd);
602                 return ret;
603         }
604
605         return fd;
606 }
607
608 int fio_client_connect(struct fio_client *client)
609 {
610         int fd;
611
612         dprint(FD_NET, "client: connect to host %s\n", client->hostname);
613
614         if (client->is_sock)
615                 fd = fio_client_connect_sock(client);
616         else
617                 fd = fio_client_connect_ip(client);
618
619         dprint(FD_NET, "client: %s connected %d\n", client->hostname, fd);
620
621         if (fd < 0)
622                 return fd;
623
624         client->fd = fd;
625         fio_client_add_hash(client);
626         client->state = Client_connected;
627
628         probe_client(client);
629         return 0;
630 }
631
632 int fio_client_terminate(struct fio_client *client)
633 {
634         return fio_net_send_quit(client->fd);
635 }
636
637 static void fio_clients_terminate(void)
638 {
639         struct flist_head *entry;
640         struct fio_client *client;
641
642         dprint(FD_NET, "client: terminate clients\n");
643
644         flist_for_each(entry, &client_list) {
645                 client = flist_entry(entry, struct fio_client, list);
646                 fio_client_terminate(client);
647         }
648 }
649
650 static void sig_int(int sig)
651 {
652         dprint(FD_NET, "client: got signal %d\n", sig);
653         fio_clients_terminate();
654 }
655
656 static void client_signal_handler(void)
657 {
658         struct sigaction act;
659
660         memset(&act, 0, sizeof(act));
661         act.sa_handler = sig_int;
662         act.sa_flags = SA_RESTART;
663         sigaction(SIGINT, &act, NULL);
664
665         memset(&act, 0, sizeof(act));
666         act.sa_handler = sig_int;
667         act.sa_flags = SA_RESTART;
668         sigaction(SIGTERM, &act, NULL);
669
670 /* Windows uses SIGBREAK as a quit signal from other applications */
671 #ifdef WIN32
672         memset(&act, 0, sizeof(act));
673         act.sa_handler = sig_int;
674         act.sa_flags = SA_RESTART;
675         sigaction(SIGBREAK, &act, NULL);
676 #endif
677
678         memset(&act, 0, sizeof(act));
679         act.sa_handler = sig_show_status;
680         act.sa_flags = SA_RESTART;
681         sigaction(SIGUSR1, &act, NULL);
682 }
683
684 static int send_client_cmd_line(struct fio_client *client)
685 {
686         struct cmd_single_line_pdu *cslp;
687         struct cmd_line_pdu *clp;
688         unsigned long offset;
689         unsigned int *lens;
690         void *pdu;
691         size_t mem;
692         int i, ret;
693
694         dprint(FD_NET, "client: send cmdline %d\n", client->argc);
695
696         lens = malloc(client->argc * sizeof(unsigned int));
697
698         /*
699          * Find out how much mem we need
700          */
701         for (i = 0, mem = 0; i < client->argc; i++) {
702                 lens[i] = strlen(client->argv[i]) + 1;
703                 mem += lens[i];
704         }
705
706         /*
707          * We need one cmd_line_pdu, and argc number of cmd_single_line_pdu
708          */
709         mem += sizeof(*clp) + (client->argc * sizeof(*cslp));
710
711         pdu = malloc(mem);
712         clp = pdu;
713         offset = sizeof(*clp);
714
715         for (i = 0; i < client->argc; i++) {
716                 uint16_t arg_len = lens[i];
717
718                 cslp = pdu + offset;
719                 strcpy((char *) cslp->text, client->argv[i]);
720                 cslp->len = cpu_to_le16(arg_len);
721                 offset += sizeof(*cslp) + arg_len;
722         }
723
724         free(lens);
725         clp->lines = cpu_to_le16(client->argc);
726         clp->client_type = __cpu_to_le16(client->type);
727         ret = fio_net_send_cmd(client->fd, FIO_NET_CMD_JOBLINE, pdu, mem, NULL, NULL);
728         free(pdu);
729         return ret;
730 }
731
732 int fio_clients_connect(void)
733 {
734         struct fio_client *client;
735         struct flist_head *entry, *tmp;
736         int ret;
737
738 #ifdef WIN32
739         WSADATA wsd;
740         WSAStartup(MAKEWORD(2, 2), &wsd);
741 #endif
742
743         dprint(FD_NET, "client: connect all\n");
744
745         client_signal_handler();
746
747         flist_for_each_safe(entry, tmp, &client_list) {
748                 client = flist_entry(entry, struct fio_client, list);
749
750                 ret = fio_client_connect(client);
751                 if (ret) {
752                         remove_client(client);
753                         continue;
754                 }
755
756                 if (client->argc > 1)
757                         send_client_cmd_line(client);
758         }
759
760         return !nr_clients;
761 }
762
763 int fio_start_client(struct fio_client *client)
764 {
765         dprint(FD_NET, "client: start %s\n", client->hostname);
766         return fio_net_send_simple_cmd(client->fd, FIO_NET_CMD_RUN, 0, NULL);
767 }
768
769 int fio_start_all_clients(void)
770 {
771         struct fio_client *client;
772         struct flist_head *entry, *tmp;
773         int ret;
774
775         dprint(FD_NET, "client: start all\n");
776
777         fio_client_json_init();
778
779         flist_for_each_safe(entry, tmp, &client_list) {
780                 client = flist_entry(entry, struct fio_client, list);
781
782                 ret = fio_start_client(client);
783                 if (ret) {
784                         remove_client(client);
785                         continue;
786                 }
787         }
788
789         return flist_empty(&client_list);
790 }
791
792 static int __fio_client_send_remote_ini(struct fio_client *client,
793                                         const char *filename)
794 {
795         struct cmd_load_file_pdu *pdu;
796         size_t p_size;
797         int ret;
798
799         dprint(FD_NET, "send remote ini %s to %s\n", filename, client->hostname);
800
801         p_size = sizeof(*pdu) + strlen(filename) + 1;
802         pdu = calloc(1, p_size);
803         pdu->name_len = strlen(filename);
804         strcpy((char *) pdu->file, filename);
805         pdu->client_type = cpu_to_le16((uint16_t) client->type);
806
807         client->sent_job = true;
808         ret = fio_net_send_cmd(client->fd, FIO_NET_CMD_LOAD_FILE, pdu, p_size,NULL, NULL);
809         free(pdu);
810         return ret;
811 }
812
813 /*
814  * Send file contents to server backend. We could use sendfile(), but to remain
815  * more portable lets just read/write the darn thing.
816  */
817 static int __fio_client_send_local_ini(struct fio_client *client,
818                                        const char *filename)
819 {
820         struct cmd_job_pdu *pdu;
821         size_t p_size;
822         struct stat sb;
823         char *p;
824         void *buf;
825         off_t len;
826         int fd, ret;
827
828         dprint(FD_NET, "send ini %s to %s\n", filename, client->hostname);
829
830         fd = open(filename, O_RDONLY);
831         if (fd < 0) {
832                 ret = -errno;
833                 log_err("fio: job file <%s> open: %s\n", filename, strerror(errno));
834                 return ret;
835         }
836
837         if (fstat(fd, &sb) < 0) {
838                 ret = -errno;
839                 log_err("fio: job file stat: %s\n", strerror(errno));
840                 close(fd);
841                 return ret;
842         }
843
844         /*
845          * Add extra space for variable expansion, but doesn't guarantee.
846          */
847         sb.st_size += OPT_LEN_MAX;
848         p_size = sb.st_size + sizeof(*pdu);
849         pdu = malloc(p_size);
850         buf = pdu->buf;
851
852         len = sb.st_size;
853         p = buf;
854         if (read_ini_data(fd, p, len)) {
855                 log_err("fio: failed reading job file %s\n", filename);
856                 close(fd);
857                 free(pdu);
858                 return 1;
859         }
860
861         pdu->buf_len = __cpu_to_le32(sb.st_size);
862         pdu->client_type = cpu_to_le32(client->type);
863
864         client->sent_job = true;
865         ret = fio_net_send_cmd(client->fd, FIO_NET_CMD_JOB, pdu, p_size, NULL, NULL);
866         free(pdu);
867         close(fd);
868         return ret;
869 }
870
871 int fio_client_send_ini(struct fio_client *client, const char *filename,
872                         bool remote)
873 {
874         int ret;
875
876         if (!remote)
877                 ret = __fio_client_send_local_ini(client, filename);
878         else
879                 ret = __fio_client_send_remote_ini(client, filename);
880
881         if (!ret)
882                 client->sent_job = true;
883
884         return ret;
885 }
886
887 static int fio_client_send_cf(struct fio_client *client,
888                               struct client_file *cf)
889 {
890         return fio_client_send_ini(client, cf->file, cf->remote);
891 }
892
893 int fio_clients_send_ini(const char *filename)
894 {
895         struct fio_client *client;
896         struct flist_head *entry, *tmp;
897
898         flist_for_each_safe(entry, tmp, &client_list) {
899                 bool failed = false;
900
901                 client = flist_entry(entry, struct fio_client, list);
902
903                 if (client->nr_files) {
904                         int i;
905
906                         for (i = 0; i < client->nr_files; i++) {
907                                 struct client_file *cf;
908
909                                 cf = &client->files[i];
910
911                                 if (fio_client_send_cf(client, cf)) {
912                                         failed = true;
913                                         remove_client(client);
914                                         break;
915                                 }
916                         }
917                 }
918                 if (client->sent_job || failed)
919                         continue;
920                 if (!filename || fio_client_send_ini(client, filename, 0))
921                         remove_client(client);
922         }
923
924         return !nr_clients;
925 }
926
927 int fio_client_update_options(struct fio_client *client,
928                               struct thread_options *o, uint64_t *tag)
929 {
930         size_t cmd_sz = offsetof(struct cmd_add_job_pdu, top) +
931                 thread_options_pack_size(o);
932         struct cmd_add_job_pdu *pdu;
933         int ret;
934
935         pdu = malloc(cmd_sz);
936         pdu->thread_number = cpu_to_le32(client->thread_number);
937         pdu->groupid = cpu_to_le32(client->groupid);
938         convert_thread_options_to_net(&pdu->top, o);
939
940         ret = fio_net_send_cmd(client->fd, FIO_NET_CMD_UPDATE_JOB, pdu,
941                                cmd_sz, tag, &client->cmd_list);
942         free(pdu);
943         return ret;
944 }
945
946 static void convert_io_stat(struct io_stat *dst, struct io_stat *src)
947 {
948         dst->max_val    = le64_to_cpu(src->max_val);
949         dst->min_val    = le64_to_cpu(src->min_val);
950         dst->samples    = le64_to_cpu(src->samples);
951
952         /*
953          * Floats arrive as IEEE 754 encoded uint64_t, convert back to double
954          */
955         dst->mean.u.f   = fio_uint64_to_double(le64_to_cpu(dst->mean.u.i));
956         dst->S.u.f      = fio_uint64_to_double(le64_to_cpu(dst->S.u.i));
957 }
958
959 static void convert_ts(struct thread_stat *dst, struct thread_stat *src)
960 {
961         int i, j, k;
962
963         dst->error              = le32_to_cpu(src->error);
964         dst->thread_number      = le32_to_cpu(src->thread_number);
965         dst->groupid            = le32_to_cpu(src->groupid);
966         dst->job_start          = le64_to_cpu(src->job_start);
967         dst->pid                = le32_to_cpu(src->pid);
968         dst->members            = le32_to_cpu(src->members);
969         dst->unified_rw_rep     = le32_to_cpu(src->unified_rw_rep);
970         dst->ioprio             = le32_to_cpu(src->ioprio);
971         dst->disable_prio_stat  = le32_to_cpu(src->disable_prio_stat);
972
973         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
974                 convert_io_stat(&dst->clat_stat[i], &src->clat_stat[i]);
975                 convert_io_stat(&dst->slat_stat[i], &src->slat_stat[i]);
976                 convert_io_stat(&dst->lat_stat[i], &src->lat_stat[i]);
977                 convert_io_stat(&dst->bw_stat[i], &src->bw_stat[i]);
978                 convert_io_stat(&dst->iops_stat[i], &src->iops_stat[i]);
979         }
980         convert_io_stat(&dst->sync_stat, &src->sync_stat);
981
982         dst->usr_time           = le64_to_cpu(src->usr_time);
983         dst->sys_time           = le64_to_cpu(src->sys_time);
984         dst->ctx                = le64_to_cpu(src->ctx);
985         dst->minf               = le64_to_cpu(src->minf);
986         dst->majf               = le64_to_cpu(src->majf);
987         dst->clat_percentiles   = le32_to_cpu(src->clat_percentiles);
988         dst->lat_percentiles    = le32_to_cpu(src->lat_percentiles);
989         dst->slat_percentiles   = le32_to_cpu(src->slat_percentiles);
990         dst->percentile_precision = le64_to_cpu(src->percentile_precision);
991
992         for (i = 0; i < FIO_IO_U_LIST_MAX_LEN; i++) {
993                 fio_fp64_t *fps = &src->percentile_list[i];
994                 fio_fp64_t *fpd = &dst->percentile_list[i];
995
996                 fpd->u.f = fio_uint64_to_double(le64_to_cpu(fps->u.i));
997         }
998
999         for (i = 0; i < FIO_IO_U_MAP_NR; i++) {
1000                 dst->io_u_map[i]        = le64_to_cpu(src->io_u_map[i]);
1001                 dst->io_u_submit[i]     = le64_to_cpu(src->io_u_submit[i]);
1002                 dst->io_u_complete[i]   = le64_to_cpu(src->io_u_complete[i]);
1003         }
1004
1005         for (i = 0; i < FIO_IO_U_LAT_N_NR; i++)
1006                 dst->io_u_lat_n[i]      = le64_to_cpu(src->io_u_lat_n[i]);
1007         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++)
1008                 dst->io_u_lat_u[i]      = le64_to_cpu(src->io_u_lat_u[i]);
1009         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++)
1010                 dst->io_u_lat_m[i]      = le64_to_cpu(src->io_u_lat_m[i]);
1011
1012         for (i = 0; i < FIO_LAT_CNT; i++)
1013                 for (j = 0; j < DDIR_RWDIR_CNT; j++)
1014                         for (k = 0; k < FIO_IO_U_PLAT_NR; k++)
1015                                 dst->io_u_plat[i][j][k] = le64_to_cpu(src->io_u_plat[i][j][k]);
1016
1017         for (j = 0; j < FIO_IO_U_PLAT_NR; j++)
1018                 dst->io_u_sync_plat[j] = le64_to_cpu(src->io_u_sync_plat[j]);
1019
1020         for (i = 0; i < DDIR_RWDIR_SYNC_CNT; i++)
1021                 dst->total_io_u[i]      = le64_to_cpu(src->total_io_u[i]);
1022
1023         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1024                 dst->short_io_u[i]      = le64_to_cpu(src->short_io_u[i]);
1025                 dst->drop_io_u[i]       = le64_to_cpu(src->drop_io_u[i]);
1026         }
1027
1028         dst->total_submit       = le64_to_cpu(src->total_submit);
1029         dst->total_complete     = le64_to_cpu(src->total_complete);
1030         dst->nr_zone_resets     = le64_to_cpu(src->nr_zone_resets);
1031
1032         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1033                 dst->io_bytes[i]        = le64_to_cpu(src->io_bytes[i]);
1034                 dst->runtime[i]         = le64_to_cpu(src->runtime[i]);
1035         }
1036
1037         dst->total_run_time     = le64_to_cpu(src->total_run_time);
1038         dst->continue_on_error  = le16_to_cpu(src->continue_on_error);
1039         dst->total_err_count    = le64_to_cpu(src->total_err_count);
1040         dst->first_error        = le32_to_cpu(src->first_error);
1041         dst->kb_base            = le32_to_cpu(src->kb_base);
1042         dst->unit_base          = le32_to_cpu(src->unit_base);
1043
1044         dst->sig_figs           = le32_to_cpu(src->sig_figs);
1045
1046         dst->latency_depth      = le32_to_cpu(src->latency_depth);
1047         dst->latency_target     = le64_to_cpu(src->latency_target);
1048         dst->latency_window     = le64_to_cpu(src->latency_window);
1049         dst->latency_percentile.u.f = fio_uint64_to_double(le64_to_cpu(src->latency_percentile.u.i));
1050
1051         dst->nr_block_infos     = le64_to_cpu(src->nr_block_infos);
1052         for (i = 0; i < dst->nr_block_infos; i++)
1053                 dst->block_infos[i] = le32_to_cpu(src->block_infos[i]);
1054
1055         dst->ss_dur             = le64_to_cpu(src->ss_dur);
1056         dst->ss_state           = le32_to_cpu(src->ss_state);
1057         dst->ss_head            = le32_to_cpu(src->ss_head);
1058         dst->ss_limit.u.f       = fio_uint64_to_double(le64_to_cpu(src->ss_limit.u.i));
1059         dst->ss_slope.u.f       = fio_uint64_to_double(le64_to_cpu(src->ss_slope.u.i));
1060         dst->ss_deviation.u.f   = fio_uint64_to_double(le64_to_cpu(src->ss_deviation.u.i));
1061         dst->ss_criterion.u.f   = fio_uint64_to_double(le64_to_cpu(src->ss_criterion.u.i));
1062
1063         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1064                 dst->nr_clat_prio[i] = le32_to_cpu(src->nr_clat_prio[i]);
1065                 for (j = 0; j < dst->nr_clat_prio[i]; j++) {
1066                         for (k = 0; k < FIO_IO_U_PLAT_NR; k++)
1067                                 dst->clat_prio[i][j].io_u_plat[k] =
1068                                         le64_to_cpu(src->clat_prio[i][j].io_u_plat[k]);
1069                         convert_io_stat(&dst->clat_prio[i][j].clat_stat,
1070                                         &src->clat_prio[i][j].clat_stat);
1071                         dst->clat_prio[i][j].ioprio =
1072                                 le32_to_cpu(dst->clat_prio[i][j].ioprio);
1073                 }
1074         }
1075
1076         if (dst->ss_state & FIO_SS_DATA) {
1077                 for (i = 0; i < dst->ss_dur; i++ ) {
1078                         dst->ss_iops_data[i] = le64_to_cpu(src->ss_iops_data[i]);
1079                         dst->ss_bw_data[i] = le64_to_cpu(src->ss_bw_data[i]);
1080                 }
1081         }
1082
1083         dst->cachehit           = le64_to_cpu(src->cachehit);
1084         dst->cachemiss          = le64_to_cpu(src->cachemiss);
1085 }
1086
1087 static void convert_gs(struct group_run_stats *dst, struct group_run_stats *src)
1088 {
1089         int i;
1090
1091         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1092                 dst->max_run[i]         = le64_to_cpu(src->max_run[i]);
1093                 dst->min_run[i]         = le64_to_cpu(src->min_run[i]);
1094                 dst->max_bw[i]          = le64_to_cpu(src->max_bw[i]);
1095                 dst->min_bw[i]          = le64_to_cpu(src->min_bw[i]);
1096                 dst->iobytes[i]         = le64_to_cpu(src->iobytes[i]);
1097                 dst->agg[i]             = le64_to_cpu(src->agg[i]);
1098         }
1099
1100         dst->kb_base    = le32_to_cpu(src->kb_base);
1101         dst->unit_base  = le32_to_cpu(src->unit_base);
1102         dst->sig_figs   = le32_to_cpu(src->sig_figs);
1103         dst->groupid    = le32_to_cpu(src->groupid);
1104         dst->unified_rw_rep     = le32_to_cpu(src->unified_rw_rep);
1105 }
1106
1107 static void json_object_add_client_info(struct json_object *obj,
1108                                         struct fio_client *client)
1109 {
1110         const char *hostname = client->hostname ? client->hostname : "";
1111
1112         json_object_add_value_string(obj, "hostname", hostname);
1113         json_object_add_value_int(obj, "port", client->port);
1114 }
1115
1116 static void handle_ts(struct fio_client *client, struct fio_net_cmd *cmd)
1117 {
1118         struct cmd_ts_pdu *p = (struct cmd_ts_pdu *) cmd->payload;
1119         struct flist_head *opt_list = NULL;
1120         struct json_object *tsobj;
1121
1122         if (client->opt_lists && p->ts.thread_number <= client->jobs)
1123                 opt_list = &client->opt_lists[p->ts.thread_number - 1];
1124
1125         tsobj = show_thread_status(&p->ts, &p->rs, opt_list, &client->buf);
1126         if (tsobj) {
1127                 json_object_add_client_info(tsobj, client);
1128                 json_array_add_value_object(clients_array, tsobj);
1129                 if (!client->did_stat && client->global_opts)
1130                         json_array_add_value_object(global_opt_array, client->global_opts);
1131         }
1132         client->did_stat = true;
1133
1134         if (sum_stat_clients <= 1)
1135                 return;
1136
1137         sum_thread_stats(&client_ts, &p->ts);
1138         sum_group_stats(&client_gs, &p->rs);
1139
1140         if (!client_ts.members) {
1141                 /* Arbitrarily use the percentile toggles and percentile list
1142                  * from the first thread_stat that comes our way */
1143                 client_ts.slat_percentiles = p->ts.slat_percentiles;
1144                 client_ts.clat_percentiles = p->ts.clat_percentiles;
1145                 client_ts.lat_percentiles = p->ts.lat_percentiles;
1146
1147                 for (int i = 0; i < FIO_IO_U_LIST_MAX_LEN; i++)
1148                         client_ts.percentile_list[i] = p->ts.percentile_list[i];
1149         }
1150         client_ts.members++;
1151         client_ts.thread_number = p->ts.thread_number;
1152         client_ts.groupid = p->ts.groupid;
1153         client_ts.unified_rw_rep = p->ts.unified_rw_rep;
1154         client_ts.sig_figs = p->ts.sig_figs;
1155
1156         if (++sum_stat_nr == sum_stat_clients) {
1157                 strcpy(client_ts.name, "All clients");
1158                 tsobj = show_thread_status(&client_ts, &client_gs, NULL, &allclients);
1159                 if (tsobj) {
1160                         json_object_add_client_info(tsobj, client);
1161                         json_array_add_value_object(clients_array, tsobj);
1162                 }
1163         }
1164 }
1165
1166 static void handle_gs(struct fio_client *client, struct fio_net_cmd *cmd)
1167 {
1168         struct group_run_stats *gs = (struct group_run_stats *) cmd->payload;
1169
1170         if (output_format & FIO_OUTPUT_NORMAL)
1171                 show_group_stats(gs, &client->buf);
1172 }
1173
1174 static void handle_job_opt(struct fio_client *client, struct fio_net_cmd *cmd)
1175 {
1176         struct cmd_job_option *pdu = (struct cmd_job_option *) cmd->payload;
1177
1178         pdu->global = le16_to_cpu(pdu->global);
1179         pdu->truncated = le16_to_cpu(pdu->truncated);
1180         pdu->groupid = le32_to_cpu(pdu->groupid);
1181
1182         if (pdu->global) {
1183                 struct json_object *global_opts;
1184
1185                 if (!global_opt_object && !global_opt_array)
1186                         return;
1187
1188                 /*
1189                  * If we have only one server connection, add it to the single
1190                  * global option dictionary. When we have connections to
1191                  * multiple servers, add the global option to the
1192                  * server-specific dictionary.
1193                  */
1194                 if (global_opt_object) {
1195                         global_opts = global_opt_object;
1196                 } else {
1197                         if (!client->global_opts) {
1198                                 client->global_opts = json_create_object();
1199                                 json_object_add_client_info(client->global_opts, client);
1200                         }
1201                         global_opts = client->global_opts;
1202                 }
1203
1204                 json_object_add_value_string(global_opts,
1205                                              (const char *)pdu->name,
1206                                              (const char *)pdu->value);
1207                 return;
1208         } else if (client->opt_lists) {
1209                 struct flist_head *opt_list = &client->opt_lists[pdu->groupid];
1210                 struct print_option *p;
1211
1212                 p = malloc(sizeof(*p));
1213                 p->name = strdup((const char *)pdu->name);
1214                 p->value = pdu->value[0] ? strdup((const char *)pdu->value) :
1215                         NULL;
1216                 flist_add_tail(&p->list, opt_list);
1217         }
1218 }
1219
1220 static void handle_text(struct fio_client *client, struct fio_net_cmd *cmd)
1221 {
1222         struct cmd_text_pdu *pdu = (struct cmd_text_pdu *) cmd->payload;
1223         const char *buf = (const char *) pdu->buf;
1224         const char *name;
1225         int fio_unused ret;
1226         struct buf_output out;
1227
1228         buf_output_init(&out);
1229
1230         name = client->name ? client->name : client->hostname;
1231
1232         if (!client->skip_newline && !(output_format & FIO_OUTPUT_TERSE))
1233                 __log_buf(&out, "<%s> ", name);
1234         __log_buf(&out, "%s", buf);
1235         log_info_buf(out.buf, out.buflen);
1236         buf_output_free(&out);
1237         client->skip_newline = strchr(buf, '\n') == NULL;
1238 }
1239
1240 static void convert_agg(struct disk_util_agg *agg)
1241 {
1242         int i;
1243
1244         for (i = 0; i < 2; i++) {
1245                 agg->ios[i]     = le64_to_cpu(agg->ios[i]);
1246                 agg->merges[i]  = le64_to_cpu(agg->merges[i]);
1247                 agg->sectors[i] = le64_to_cpu(agg->sectors[i]);
1248                 agg->ticks[i]   = le64_to_cpu(agg->ticks[i]);
1249         }
1250
1251         agg->io_ticks           = le64_to_cpu(agg->io_ticks);
1252         agg->time_in_queue      = le64_to_cpu(agg->time_in_queue);
1253         agg->slavecount         = le32_to_cpu(agg->slavecount);
1254         agg->max_util.u.f       = fio_uint64_to_double(le64_to_cpu(agg->max_util.u.i));
1255 }
1256
1257 static void convert_dus(struct disk_util_stat *dus)
1258 {
1259         int i;
1260
1261         for (i = 0; i < 2; i++) {
1262                 dus->s.ios[i]           = le64_to_cpu(dus->s.ios[i]);
1263                 dus->s.merges[i]        = le64_to_cpu(dus->s.merges[i]);
1264                 dus->s.sectors[i]       = le64_to_cpu(dus->s.sectors[i]);
1265                 dus->s.ticks[i]         = le64_to_cpu(dus->s.ticks[i]);
1266         }
1267
1268         dus->s.io_ticks         = le64_to_cpu(dus->s.io_ticks);
1269         dus->s.time_in_queue    = le64_to_cpu(dus->s.time_in_queue);
1270         dus->s.msec             = le64_to_cpu(dus->s.msec);
1271 }
1272
1273 static void handle_du(struct fio_client *client, struct fio_net_cmd *cmd)
1274 {
1275         struct cmd_du_pdu *du = (struct cmd_du_pdu *) cmd->payload;
1276
1277         if (!client->disk_stats_shown)
1278                 client->disk_stats_shown = true;
1279
1280         if (output_format & FIO_OUTPUT_JSON) {
1281                 struct json_object *duobj;
1282
1283                 json_array_add_disk_util(&du->dus, &du->agg, du_array);
1284                 duobj = json_array_last_value_object(du_array);
1285                 json_object_add_client_info(duobj, client);
1286         }
1287         if (output_format & FIO_OUTPUT_NORMAL) {
1288                 __log_buf(&client->buf, "\nDisk stats (read/write):\n");
1289                 print_disk_util(&du->dus, &du->agg, 0, &client->buf);
1290         }
1291         if (output_format & FIO_OUTPUT_TERSE && terse_version >= 3) {
1292                 print_disk_util(&du->dus, &du->agg, 1, &client->buf);
1293                 __log_buf(&client->buf, "\n");
1294         }
1295 }
1296
1297 static void convert_jobs_eta(struct jobs_eta *je)
1298 {
1299         int i;
1300
1301         je->nr_running          = le32_to_cpu(je->nr_running);
1302         je->nr_ramp             = le32_to_cpu(je->nr_ramp);
1303         je->nr_pending          = le32_to_cpu(je->nr_pending);
1304         je->nr_setting_up       = le32_to_cpu(je->nr_setting_up);
1305         je->files_open          = le32_to_cpu(je->files_open);
1306
1307         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1308                 je->m_rate[i]   = le64_to_cpu(je->m_rate[i]);
1309                 je->t_rate[i]   = le64_to_cpu(je->t_rate[i]);
1310                 je->m_iops[i]   = le32_to_cpu(je->m_iops[i]);
1311                 je->t_iops[i]   = le32_to_cpu(je->t_iops[i]);
1312                 je->rate[i]     = le64_to_cpu(je->rate[i]);
1313                 je->iops[i]     = le32_to_cpu(je->iops[i]);
1314         }
1315
1316         je->elapsed_sec         = le64_to_cpu(je->elapsed_sec);
1317         je->eta_sec             = le64_to_cpu(je->eta_sec);
1318         je->nr_threads          = le32_to_cpu(je->nr_threads);
1319         je->is_pow2             = le32_to_cpu(je->is_pow2);
1320         je->unit_base           = le32_to_cpu(je->unit_base);
1321         je->sig_figs            = le32_to_cpu(je->sig_figs);
1322 }
1323
1324 void fio_client_sum_jobs_eta(struct jobs_eta *dst, struct jobs_eta *je)
1325 {
1326         int i;
1327
1328         dst->nr_running         += je->nr_running;
1329         dst->nr_ramp            += je->nr_ramp;
1330         dst->nr_pending         += je->nr_pending;
1331         dst->nr_setting_up      += je->nr_setting_up;
1332         dst->files_open         += je->files_open;
1333
1334         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1335                 dst->m_rate[i]  += je->m_rate[i];
1336                 dst->t_rate[i]  += je->t_rate[i];
1337                 dst->m_iops[i]  += je->m_iops[i];
1338                 dst->t_iops[i]  += je->t_iops[i];
1339                 dst->rate[i]    += je->rate[i];
1340                 dst->iops[i]    += je->iops[i];
1341         }
1342
1343         dst->elapsed_sec        += je->elapsed_sec;
1344
1345         if (je->eta_sec > dst->eta_sec)
1346                 dst->eta_sec = je->eta_sec;
1347
1348         dst->nr_threads         += je->nr_threads;
1349
1350         /*
1351          * This wont be correct for multiple strings, but at least it
1352          * works for the basic cases.
1353          */
1354         strcpy((char *) dst->run_str, (char *) je->run_str);
1355 }
1356
1357 static bool remove_reply_cmd(struct fio_client *client, struct fio_net_cmd *cmd)
1358 {
1359         struct fio_net_cmd_reply *reply = NULL;
1360         struct flist_head *entry;
1361
1362         flist_for_each(entry, &client->cmd_list) {
1363                 reply = flist_entry(entry, struct fio_net_cmd_reply, list);
1364
1365                 if (cmd->tag == (uintptr_t) reply)
1366                         break;
1367
1368                 reply = NULL;
1369         }
1370
1371         if (!reply) {
1372                 log_err("fio: client: unable to find matching tag (%llx)\n", (unsigned long long) cmd->tag);
1373                 return false;
1374         }
1375
1376         flist_del(&reply->list);
1377         cmd->tag = reply->saved_tag;
1378         free(reply);
1379         return true;
1380 }
1381
1382 int fio_client_wait_for_reply(struct fio_client *client, uint64_t tag)
1383 {
1384         do {
1385                 struct fio_net_cmd_reply *reply = NULL;
1386                 struct flist_head *entry;
1387
1388                 flist_for_each(entry, &client->cmd_list) {
1389                         reply = flist_entry(entry, struct fio_net_cmd_reply, list);
1390
1391                         if (tag == (uintptr_t) reply)
1392                                 break;
1393
1394                         reply = NULL;
1395                 }
1396
1397                 if (!reply)
1398                         break;
1399
1400                 usleep(1000);
1401         } while (1);
1402
1403         return 0;
1404 }
1405
1406 static void handle_eta(struct fio_client *client, struct fio_net_cmd *cmd)
1407 {
1408         struct jobs_eta *je = (struct jobs_eta *) cmd->payload;
1409         struct client_eta *eta = (struct client_eta *) (uintptr_t) cmd->tag;
1410
1411         dprint(FD_NET, "client: got eta tag %p, %d\n", eta, eta->pending);
1412
1413         assert(client->eta_in_flight == eta);
1414
1415         client->eta_in_flight = NULL;
1416         flist_del_init(&client->eta_list);
1417         client->eta_timeouts = 0;
1418
1419         if (client->ops->jobs_eta)
1420                 client->ops->jobs_eta(client, je);
1421
1422         fio_client_sum_jobs_eta(&eta->eta, je);
1423         fio_client_dec_jobs_eta(eta, client->ops->eta);
1424 }
1425
1426 static void client_flush_hist_samples(FILE *f, int hist_coarseness, void *samples,
1427                                       uint64_t sample_size)
1428 {
1429         struct io_sample *s, *s_tmp;
1430         bool log_offset, log_issue_time;
1431         uint64_t i, j, nr_samples;
1432         struct io_u_plat_entry *entry;
1433         uint64_t *io_u_plat;
1434
1435         int stride = 1 << hist_coarseness;
1436
1437         if (!sample_size)
1438                 return;
1439
1440         s = __get_sample(samples, 0, 0, 0);
1441         log_offset = (s->__ddir & LOG_OFFSET_SAMPLE_BIT) != 0;
1442         log_issue_time = (s->__ddir & LOG_ISSUE_TIME_SAMPLE_BIT) != 0;
1443
1444         nr_samples = sample_size / __log_entry_sz(log_offset, log_issue_time);
1445
1446         for (i = 0; i < nr_samples; i++) {
1447
1448                 s_tmp = __get_sample(samples, log_offset, log_issue_time, i);
1449                 s = (struct io_sample *)((char *)s_tmp +
1450                                          i * sizeof(struct io_u_plat_entry));
1451
1452                 entry = s->data.plat_entry;
1453                 io_u_plat = entry->io_u_plat;
1454
1455                 fprintf(f, "%lu, %u, %llu, ", (unsigned long) s->time,
1456                                                 io_sample_ddir(s), (unsigned long long) s->bs);
1457                 for (j = 0; j < FIO_IO_U_PLAT_NR - stride; j += stride) {
1458                         fprintf(f, "%llu, ", (unsigned long long)hist_sum(j, stride, io_u_plat, NULL));
1459                 }
1460                 fprintf(f, "%llu\n", (unsigned long long)
1461                         hist_sum(FIO_IO_U_PLAT_NR - stride, stride, io_u_plat, NULL));
1462
1463         }
1464 }
1465
1466 static int fio_client_handle_iolog(struct fio_client *client,
1467                                    struct fio_net_cmd *cmd)
1468 {
1469         struct cmd_iolog_pdu *pdu = NULL;
1470         bool store_direct;
1471         char *log_pathname = NULL;
1472         int ret = 0;
1473
1474         pdu = convert_iolog(cmd, &store_direct);
1475         if (!pdu) {
1476                 log_err("fio: failed converting IO log\n");
1477                 ret = 1;
1478                 goto out;
1479         }
1480
1481         /* allocate buffer big enough for next sprintf() call */
1482         log_pathname = malloc(10 + strlen((char *)pdu->name) +
1483                         strlen(client->hostname));
1484         if (!log_pathname) {
1485                 log_err("fio: memory allocation of unique pathname failed\n");
1486                 ret = -1;
1487                 goto out;
1488         }
1489         /* generate a unique pathname for the log file using hostname */
1490         sprintf(log_pathname, "%s.%s", pdu->name, client->hostname);
1491
1492         if (store_direct) {
1493                 ssize_t wrote;
1494                 size_t sz;
1495                 int fd, flags;
1496
1497                 if (pdu->per_job_logs)
1498                         flags = O_WRONLY | O_CREAT | O_TRUNC;
1499                 else
1500                         flags = O_WRONLY | O_CREAT | O_APPEND;
1501                 fd = open((const char *) log_pathname, flags, 0644);
1502                 if (fd < 0) {
1503                         log_err("fio: open log %s: %s\n",
1504                                 log_pathname, strerror(errno));
1505                         ret = 1;
1506                         goto out;
1507                 }
1508
1509                 sz = cmd->pdu_len - sizeof(*pdu);
1510                 wrote = write(fd, pdu->samples, sz);
1511                 close(fd);
1512
1513                 if (wrote != sz) {
1514                         log_err("fio: short write on compressed log\n");
1515                         ret = 1;
1516                         goto out;
1517                 }
1518
1519                 ret = 0;
1520         } else {
1521                 FILE *f;
1522                 const char *mode;
1523
1524                 if (pdu->per_job_logs)
1525                         mode = "w";
1526                 else
1527                         mode = "a";
1528                 f = fopen((const char *) log_pathname, mode);
1529                 if (!f) {
1530                         log_err("fio: fopen log %s : %s\n",
1531                                 log_pathname, strerror(errno));
1532                         ret = 1;
1533                         goto out;
1534                 }
1535
1536                 if (pdu->log_type == IO_LOG_TYPE_HIST) {
1537                         client_flush_hist_samples(f, pdu->log_hist_coarseness, pdu->samples,
1538                                            pdu->nr_samples * sizeof(struct io_sample));
1539                 } else {
1540                         flush_samples(f, pdu->samples,
1541                                         pdu->nr_samples * sizeof(struct io_sample));
1542                 }
1543                 fclose(f);
1544                 ret = 0;
1545         }
1546
1547 out:
1548         if (pdu && pdu != (void *) cmd->payload)
1549                 free(pdu);
1550
1551         if (log_pathname)
1552                 free(log_pathname);
1553
1554         return ret;
1555 }
1556
1557 static void handle_probe(struct fio_client *client, struct fio_net_cmd *cmd)
1558 {
1559         struct cmd_probe_reply_pdu *probe = (struct cmd_probe_reply_pdu *) cmd->payload;
1560         const char *os, *arch;
1561         char bit[16];
1562
1563         os = fio_get_os_string(probe->os);
1564         if (!os)
1565                 os = "unknown";
1566
1567         arch = fio_get_arch_string(probe->arch);
1568         if (!arch)
1569                 os = "unknown";
1570
1571         sprintf(bit, "%d-bit", probe->bpp * 8);
1572         probe->flags = le64_to_cpu(probe->flags);
1573
1574         if (output_format & FIO_OUTPUT_NORMAL) {
1575                 log_info("hostname=%s, be=%u, %s, os=%s, arch=%s, fio=%s, flags=%lx\n",
1576                         probe->hostname, probe->bigendian, bit, os, arch,
1577                         probe->fio_version, (unsigned long) probe->flags);
1578         }
1579
1580         if (!client->name)
1581                 client->name = strdup((char *) probe->hostname);
1582 }
1583
1584 static void handle_start(struct fio_client *client, struct fio_net_cmd *cmd)
1585 {
1586         struct cmd_start_pdu *pdu = (struct cmd_start_pdu *) cmd->payload;
1587
1588         client->state = Client_started;
1589         client->jobs = le32_to_cpu(pdu->jobs);
1590         client->nr_stat = le32_to_cpu(pdu->stat_outputs);
1591
1592         if (client->jobs) {
1593                 int i;
1594
1595                 if (client->opt_lists)
1596                         free(client->opt_lists);
1597
1598                 client->opt_lists = malloc(client->jobs * sizeof(struct flist_head));
1599                 for (i = 0; i < client->jobs; i++)
1600                         INIT_FLIST_HEAD(&client->opt_lists[i]);
1601         }
1602
1603         sum_stat_clients += client->nr_stat;
1604 }
1605
1606 static void handle_stop(struct fio_client *client)
1607 {
1608         if (client->error)
1609                 log_info("client <%s>: exited with error %d\n", client->hostname, client->error);
1610 }
1611
1612 static void convert_stop(struct fio_net_cmd *cmd)
1613 {
1614         struct cmd_end_pdu *pdu = (struct cmd_end_pdu *) cmd->payload;
1615
1616         pdu->error = le32_to_cpu(pdu->error);
1617 }
1618
1619 static void convert_text(struct fio_net_cmd *cmd)
1620 {
1621         struct cmd_text_pdu *pdu = (struct cmd_text_pdu *) cmd->payload;
1622
1623         pdu->level      = le32_to_cpu(pdu->level);
1624         pdu->buf_len    = le32_to_cpu(pdu->buf_len);
1625         pdu->log_sec    = le64_to_cpu(pdu->log_sec);
1626         pdu->log_usec   = le64_to_cpu(pdu->log_usec);
1627 }
1628
1629 static struct cmd_iolog_pdu *convert_iolog_gz(struct fio_net_cmd *cmd,
1630                                               struct cmd_iolog_pdu *pdu)
1631 {
1632 #ifdef CONFIG_ZLIB
1633         struct cmd_iolog_pdu *ret;
1634         z_stream stream;
1635         uint64_t nr_samples;
1636         size_t total;
1637         char *p;
1638         size_t log_entry_size;
1639
1640         stream.zalloc = Z_NULL;
1641         stream.zfree = Z_NULL;
1642         stream.opaque = Z_NULL;
1643         stream.avail_in = 0;
1644         stream.next_in = Z_NULL;
1645
1646         if (inflateInit(&stream) != Z_OK)
1647                 return NULL;
1648
1649         /*
1650          * Get header first, it's not compressed
1651          */
1652         nr_samples = le64_to_cpu(pdu->nr_samples);
1653
1654         log_entry_size = __log_entry_sz(le32_to_cpu(pdu->log_offset),
1655                                         le32_to_cpu(pdu->log_issue_time));
1656         if (pdu->log_type == IO_LOG_TYPE_HIST)
1657                 total = nr_samples * (log_entry_size +
1658                                       sizeof(struct io_u_plat_entry));
1659         else
1660                 total = nr_samples * log_entry_size;
1661         ret = malloc(total + sizeof(*pdu));
1662         ret->nr_samples = nr_samples;
1663
1664         memcpy(ret, pdu, sizeof(*pdu));
1665
1666         p = (char *) ret + sizeof(*pdu);
1667
1668         stream.avail_in = cmd->pdu_len - sizeof(*pdu);
1669         stream.next_in = (void *)((char *) pdu + sizeof(*pdu));
1670         while (stream.avail_in) {
1671                 unsigned int this_chunk = 65536;
1672                 unsigned int this_len;
1673                 int err;
1674
1675                 if (this_chunk > total)
1676                         this_chunk = total;
1677
1678                 stream.avail_out = this_chunk;
1679                 stream.next_out = (void *)p;
1680                 err = inflate(&stream, Z_NO_FLUSH);
1681                 /* may be Z_OK, or Z_STREAM_END */
1682                 if (err < 0) {
1683                         /*
1684                          * Z_STREAM_ERROR and Z_BUF_ERROR can safely be
1685                          * ignored */
1686                         if (err == Z_STREAM_ERROR || err == Z_BUF_ERROR)
1687                                 break;
1688                         log_err("fio: inflate error %d\n", err);
1689                         free(ret);
1690                         ret = NULL;
1691                         goto err;
1692                 }
1693
1694                 this_len = this_chunk - stream.avail_out;
1695                 p += this_len;
1696                 total -= this_len;
1697         }
1698
1699 err:
1700         inflateEnd(&stream);
1701         return ret;
1702 #else
1703         return NULL;
1704 #endif
1705 }
1706
1707 /*
1708  * This has been compressed on the server side, since it can be big.
1709  * Uncompress here.
1710  */
1711 static struct cmd_iolog_pdu *convert_iolog(struct fio_net_cmd *cmd,
1712                                            bool *store_direct)
1713 {
1714         struct cmd_iolog_pdu *pdu = (struct cmd_iolog_pdu *) cmd->payload;
1715         struct cmd_iolog_pdu *ret;
1716         uint64_t i;
1717         int compressed;
1718         void *samples;
1719
1720         *store_direct = false;
1721
1722         /*
1723          * Convert if compressed and we support it. If it's not
1724          * compressed, we need not do anything.
1725          */
1726         compressed = le32_to_cpu(pdu->compressed);
1727         if (compressed == XMIT_COMPRESSED) {
1728 #ifndef CONFIG_ZLIB
1729                 log_err("fio: server sent compressed data by mistake\n");
1730                 return NULL;
1731 #endif
1732                 ret = convert_iolog_gz(cmd, pdu);
1733                 if (!ret) {
1734                         log_err("fio: failed decompressing log\n");
1735                         return NULL;
1736                 }
1737         } else if (compressed == STORE_COMPRESSED) {
1738                 *store_direct = true;
1739                 ret = pdu;
1740         } else
1741                 ret = pdu;
1742
1743         ret->nr_samples         = le64_to_cpu(ret->nr_samples);
1744         ret->thread_number      = le32_to_cpu(ret->thread_number);
1745         ret->log_type           = le32_to_cpu(ret->log_type);
1746         ret->compressed         = le32_to_cpu(ret->compressed);
1747         ret->log_offset         = le32_to_cpu(ret->log_offset);
1748         ret->log_prio           = le32_to_cpu(ret->log_prio);
1749         ret->log_issue_time     = le32_to_cpu(ret->log_issue_time);
1750         ret->log_hist_coarseness = le32_to_cpu(ret->log_hist_coarseness);
1751         ret->per_job_logs       = le32_to_cpu(ret->per_job_logs);
1752
1753         if (*store_direct)
1754                 return ret;
1755
1756         samples = &ret->samples[0];
1757         for (i = 0; i < ret->nr_samples; i++) {
1758                 struct io_sample *s;
1759
1760                 s = __get_sample(samples, ret->log_offset, ret->log_issue_time, i);
1761                 if (ret->log_type == IO_LOG_TYPE_HIST)
1762                         s = (struct io_sample *)((char *)s + sizeof(struct io_u_plat_entry) * i);
1763
1764                 s->time         = le64_to_cpu(s->time);
1765                 if (ret->log_type != IO_LOG_TYPE_HIST) {
1766                         s->data.val.val0        = le64_to_cpu(s->data.val.val0);
1767                         s->data.val.val1        = le64_to_cpu(s->data.val.val1);
1768                 }
1769                 s->__ddir       = __le32_to_cpu(s->__ddir);
1770                 s->bs           = le64_to_cpu(s->bs);
1771                 s->priority     = le16_to_cpu(s->priority);
1772
1773                 if (ret->log_offset)
1774                         s->aux[IOS_AUX_OFFSET_INDEX] =
1775                                 le64_to_cpu(s->aux[IOS_AUX_OFFSET_INDEX]);
1776
1777                 if (ret->log_issue_time)
1778                         s->aux[IOS_AUX_ISSUE_TIME_INDEX] =
1779                                 le64_to_cpu(s->aux[IOS_AUX_ISSUE_TIME_INDEX]);
1780
1781                 if (ret->log_type == IO_LOG_TYPE_HIST) {
1782                         s->data.plat_entry = (struct io_u_plat_entry *)(((char *)s) + sizeof(*s));
1783                         s->data.plat_entry->list.next = NULL;
1784                         s->data.plat_entry->list.prev = NULL;
1785                 }
1786         }
1787
1788         return ret;
1789 }
1790
1791 static void sendfile_reply(int fd, struct cmd_sendfile_reply *rep,
1792                            size_t size, uint64_t tag)
1793 {
1794         rep->error = cpu_to_le32(rep->error);
1795         fio_net_send_cmd(fd, FIO_NET_CMD_SENDFILE, rep, size, &tag, NULL);
1796 }
1797
1798 static int fio_send_file(struct fio_client *client, struct cmd_sendfile *pdu,
1799                          uint64_t tag)
1800 {
1801         struct cmd_sendfile_reply *rep;
1802         struct stat sb;
1803         size_t size;
1804         int fd;
1805
1806         size = sizeof(*rep);
1807         rep = malloc(size);
1808
1809         if (stat((char *)pdu->path, &sb) < 0) {
1810 fail:
1811                 rep->error = errno;
1812                 sendfile_reply(client->fd, rep, size, tag);
1813                 free(rep);
1814                 return 1;
1815         }
1816
1817         size += sb.st_size;
1818         rep = realloc(rep, size);
1819         rep->size = cpu_to_le32((uint32_t) sb.st_size);
1820
1821         fd = open((char *)pdu->path, O_RDONLY);
1822         if (fd == -1 )
1823                 goto fail;
1824
1825         rep->error = read_data(fd, &rep->data, sb.st_size);
1826         sendfile_reply(client->fd, rep, size, tag);
1827         free(rep);
1828         close(fd);
1829         return 0;
1830 }
1831
1832 int fio_handle_client(struct fio_client *client)
1833 {
1834         struct client_ops const *ops = client->ops;
1835         struct fio_net_cmd *cmd;
1836
1837         dprint(FD_NET, "client: handle %s\n", client->hostname);
1838
1839         cmd = fio_net_recv_cmd(client->fd, true);
1840         if (!cmd)
1841                 return 0;
1842
1843         dprint(FD_NET, "client: got cmd op %s from %s (pdu=%u)\n",
1844                 fio_server_op(cmd->opcode), client->hostname, cmd->pdu_len);
1845
1846         client->last_cmd = cmd->opcode;
1847
1848         switch (cmd->opcode) {
1849         case FIO_NET_CMD_QUIT:
1850                 if (ops->quit)
1851                         ops->quit(client, cmd);
1852                 remove_client(client);
1853                 break;
1854         case FIO_NET_CMD_TEXT:
1855                 convert_text(cmd);
1856                 ops->text(client, cmd);
1857                 break;
1858         case FIO_NET_CMD_DU: {
1859                 struct cmd_du_pdu *du = (struct cmd_du_pdu *) cmd->payload;
1860
1861                 convert_dus(&du->dus);
1862                 convert_agg(&du->agg);
1863
1864                 ops->disk_util(client, cmd);
1865                 break;
1866                 }
1867         case FIO_NET_CMD_TS: {
1868                 struct cmd_ts_pdu *p = (struct cmd_ts_pdu *) cmd->payload;
1869                 uint64_t offset;
1870                 int i;
1871
1872                 for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1873                         if (le32_to_cpu(p->ts.nr_clat_prio[i])) {
1874                                 offset = le64_to_cpu(p->ts.clat_prio_offset[i]);
1875                                 p->ts.clat_prio[i] =
1876                                         (struct clat_prio_stat *)((char *)p + offset);
1877                         }
1878                 }
1879
1880                 dprint(FD_NET, "client: ts->ss_state = %u\n", (unsigned int) le32_to_cpu(p->ts.ss_state));
1881                 if (le32_to_cpu(p->ts.ss_state) & FIO_SS_DATA) {
1882                         dprint(FD_NET, "client: received steadystate ring buffers\n");
1883
1884                         offset = le64_to_cpu(p->ts.ss_iops_data_offset);
1885                         p->ts.ss_iops_data = (uint64_t *)((char *)p + offset);
1886
1887                         offset = le64_to_cpu(p->ts.ss_bw_data_offset);
1888                         p->ts.ss_bw_data = (uint64_t *)((char *)p + offset);
1889                 }
1890
1891                 convert_ts(&p->ts, &p->ts);
1892                 convert_gs(&p->rs, &p->rs);
1893
1894                 ops->thread_status(client, cmd);
1895                 break;
1896                 }
1897         case FIO_NET_CMD_GS: {
1898                 struct group_run_stats *gs = (struct group_run_stats *) cmd->payload;
1899
1900                 convert_gs(gs, gs);
1901
1902                 ops->group_stats(client, cmd);
1903                 break;
1904                 }
1905         case FIO_NET_CMD_ETA: {
1906                 struct jobs_eta *je = (struct jobs_eta *) cmd->payload;
1907
1908                 if (!remove_reply_cmd(client, cmd))
1909                         break;
1910                 convert_jobs_eta(je);
1911                 handle_eta(client, cmd);
1912                 break;
1913                 }
1914         case FIO_NET_CMD_PROBE:
1915                 remove_reply_cmd(client, cmd);
1916                 ops->probe(client, cmd);
1917                 break;
1918         case FIO_NET_CMD_SERVER_START:
1919                 client->state = Client_running;
1920                 if (ops->job_start)
1921                         ops->job_start(client, cmd);
1922                 break;
1923         case FIO_NET_CMD_START: {
1924                 struct cmd_start_pdu *pdu = (struct cmd_start_pdu *) cmd->payload;
1925
1926                 pdu->jobs = le32_to_cpu(pdu->jobs);
1927                 ops->start(client, cmd);
1928                 break;
1929                 }
1930         case FIO_NET_CMD_STOP: {
1931                 struct cmd_end_pdu *pdu = (struct cmd_end_pdu *) cmd->payload;
1932
1933                 convert_stop(cmd);
1934                 client->state = Client_stopped;
1935                 client->error = le32_to_cpu(pdu->error);
1936                 client->signal = le32_to_cpu(pdu->signal);
1937                 ops->stop(client);
1938                 break;
1939                 }
1940         case FIO_NET_CMD_ADD_JOB: {
1941                 struct cmd_add_job_pdu *pdu = (struct cmd_add_job_pdu *) cmd->payload;
1942
1943                 client->thread_number = le32_to_cpu(pdu->thread_number);
1944                 client->groupid = le32_to_cpu(pdu->groupid);
1945
1946                 if (ops->add_job)
1947                         ops->add_job(client, cmd);
1948                 break;
1949                 }
1950         case FIO_NET_CMD_IOLOG:
1951                 fio_client_handle_iolog(client, cmd);
1952                 break;
1953         case FIO_NET_CMD_UPDATE_JOB:
1954                 ops->update_job(client, cmd);
1955                 remove_reply_cmd(client, cmd);
1956                 break;
1957         case FIO_NET_CMD_VTRIGGER: {
1958                 struct all_io_list *pdu = (struct all_io_list *) cmd->payload;
1959                 char buf[128];
1960                 int off = 0;
1961
1962                 if (aux_path) {
1963                         strcpy(buf, aux_path);
1964                         off = strlen(buf);
1965                 }
1966
1967                 __verify_save_state(pdu, server_name(client, &buf[off], sizeof(buf) - off));
1968                 exec_trigger(trigger_cmd);
1969                 break;
1970                 }
1971         case FIO_NET_CMD_SENDFILE: {
1972                 struct cmd_sendfile *pdu = (struct cmd_sendfile *) cmd->payload;
1973                 fio_send_file(client, pdu, cmd->tag);
1974                 break;
1975                 }
1976         case FIO_NET_CMD_JOB_OPT: {
1977                 handle_job_opt(client, cmd);
1978                 break;
1979         }
1980         default:
1981                 log_err("fio: unknown client op: %s\n", fio_server_op(cmd->opcode));
1982                 break;
1983         }
1984
1985         free(cmd);
1986         return 1;
1987 }
1988
1989 int fio_clients_send_trigger(const char *cmd)
1990 {
1991         struct flist_head *entry;
1992         struct fio_client *client;
1993         size_t slen;
1994
1995         dprint(FD_NET, "client: send vtrigger: %s\n", cmd);
1996
1997         if (!cmd)
1998                 slen = 0;
1999         else
2000                 slen = strlen(cmd);
2001
2002         flist_for_each(entry, &client_list) {
2003                 struct cmd_vtrigger_pdu *pdu;
2004
2005                 client = flist_entry(entry, struct fio_client, list);
2006
2007                 pdu = malloc(sizeof(*pdu) + slen);
2008                 pdu->len = cpu_to_le16((uint16_t) slen);
2009                 if (slen)
2010                         memcpy(pdu->cmd, cmd, slen);
2011                 fio_net_send_cmd(client->fd, FIO_NET_CMD_VTRIGGER, pdu,
2012                                         sizeof(*pdu) + slen, NULL, NULL);
2013                 free(pdu);
2014         }
2015
2016         return 0;
2017 }
2018
2019 static void request_client_etas(struct client_ops const *ops)
2020 {
2021         struct fio_client *client;
2022         struct flist_head *entry;
2023         struct client_eta *eta;
2024         int skipped = 0;
2025
2026         if (eta_print == FIO_ETA_NEVER)
2027                 return;
2028
2029         dprint(FD_NET, "client: request eta (%d)\n", nr_clients);
2030
2031         eta = calloc(1, sizeof(*eta) + __THREAD_RUNSTR_SZ(REAL_MAX_JOBS));
2032         eta->pending = nr_clients;
2033
2034         flist_for_each(entry, &client_list) {
2035                 client = flist_entry(entry, struct fio_client, list);
2036
2037                 if (!flist_empty(&client->eta_list)) {
2038                         skipped++;
2039                         continue;
2040                 }
2041                 if (client->state != Client_running)
2042                         continue;
2043
2044                 assert(!client->eta_in_flight);
2045                 flist_add_tail(&client->eta_list, &eta_list);
2046                 client->eta_in_flight = eta;
2047                 fio_net_send_simple_cmd(client->fd, FIO_NET_CMD_SEND_ETA,
2048                                         (uintptr_t) eta, &client->cmd_list);
2049         }
2050
2051         while (skipped--) {
2052                 if (!fio_client_dec_jobs_eta(eta, ops->eta))
2053                         break;
2054         }
2055
2056         dprint(FD_NET, "client: requested eta tag %p\n", eta);
2057 }
2058
2059 /*
2060  * A single SEND_ETA timeout isn't fatal. Attempt to recover.
2061  */
2062 static int handle_cmd_timeout(struct fio_client *client,
2063                               struct fio_net_cmd_reply *reply)
2064 {
2065         uint16_t reply_opcode = reply->opcode;
2066
2067         flist_del(&reply->list);
2068         free(reply);
2069
2070         if (reply_opcode != FIO_NET_CMD_SEND_ETA)
2071                 return 1;
2072
2073         log_info("client <%s>: timeout on SEND_ETA\n", client->hostname);
2074
2075         flist_del_init(&client->eta_list);
2076         if (client->eta_in_flight) {
2077                 fio_client_dec_jobs_eta(client->eta_in_flight, client->ops->eta);
2078                 client->eta_in_flight = NULL;
2079         }
2080
2081         /*
2082          * If we fail 5 in a row, give up...
2083          */
2084         if (client->eta_timeouts++ > 5)
2085                 return 1;
2086
2087         return 0;
2088 }
2089
2090 static int client_check_cmd_timeout(struct fio_client *client,
2091                                     struct timespec *now)
2092 {
2093         struct fio_net_cmd_reply *reply;
2094         struct flist_head *entry, *tmp;
2095         int ret = 0;
2096
2097         flist_for_each_safe(entry, tmp, &client->cmd_list) {
2098                 unsigned int op;
2099
2100                 reply = flist_entry(entry, struct fio_net_cmd_reply, list);
2101
2102                 if (mtime_since(&reply->ts, now) < FIO_NET_CLIENT_TIMEOUT)
2103                         continue;
2104
2105                 op = reply->opcode;
2106                 if (!handle_cmd_timeout(client, reply))
2107                         continue;
2108
2109                 log_err("fio: client %s, timeout on cmd %s\n", client->hostname,
2110                                                 fio_server_op(op));
2111                 ret = 1;
2112         }
2113
2114         return flist_empty(&client->cmd_list) && ret;
2115 }
2116
2117 static int fio_check_clients_timed_out(void)
2118 {
2119         struct fio_client *client;
2120         struct flist_head *entry, *tmp;
2121         struct timespec ts;
2122         int ret = 0;
2123
2124         fio_gettime(&ts, NULL);
2125
2126         flist_for_each_safe(entry, tmp, &client_list) {
2127                 client = flist_entry(entry, struct fio_client, list);
2128
2129                 if (flist_empty(&client->cmd_list))
2130                         continue;
2131
2132                 if (!client_check_cmd_timeout(client, &ts))
2133                         continue;
2134
2135                 if (client->ops->timed_out)
2136                         client->ops->timed_out(client);
2137                 else
2138                         log_err("fio: client %s timed out\n", client->hostname);
2139
2140                 if (client->last_cmd != FIO_NET_CMD_VTRIGGER)
2141                         client->error = ETIMEDOUT;
2142                 else
2143                         log_info("fio: ignoring timeout due to vtrigger\n");
2144                 remove_client(client);
2145                 ret = 1;
2146         }
2147
2148         return ret;
2149 }
2150
2151 int fio_handle_clients(struct client_ops const *ops)
2152 {
2153         struct pollfd *pfds;
2154         int i, ret = 0, retval = 0;
2155
2156         fio_gettime(&eta_ts, NULL);
2157
2158         pfds = malloc(nr_clients * sizeof(struct pollfd));
2159
2160         init_thread_stat(&client_ts);
2161         init_group_run_stat(&client_gs);
2162
2163         while (!exit_backend && nr_clients) {
2164                 struct flist_head *entry, *tmp;
2165                 struct fio_client *client;
2166
2167                 i = 0;
2168                 flist_for_each_safe(entry, tmp, &client_list) {
2169                         client = flist_entry(entry, struct fio_client, list);
2170
2171                         if (!client->sent_job && !client->ops->stay_connected &&
2172                             flist_empty(&client->cmd_list)) {
2173                                 remove_client(client);
2174                                 continue;
2175                         }
2176
2177                         pfds[i].fd = client->fd;
2178                         pfds[i].events = POLLIN;
2179                         i++;
2180                 }
2181
2182                 if (!nr_clients)
2183                         break;
2184
2185                 assert(i == nr_clients);
2186
2187                 do {
2188                         struct timespec ts;
2189                         int timeout;
2190
2191                         fio_gettime(&ts, NULL);
2192                         if (eta_time_within_slack(mtime_since(&eta_ts, &ts))) {
2193                                 request_client_etas(ops);
2194                                 memcpy(&eta_ts, &ts, sizeof(ts));
2195
2196                                 if (fio_check_clients_timed_out())
2197                                         break;
2198                         }
2199
2200                         check_trigger_file();
2201
2202                         timeout = min(100u, ops->eta_msec);
2203
2204                         ret = poll(pfds, nr_clients, timeout);
2205                         if (ret < 0) {
2206                                 if (errno == EINTR)
2207                                         continue;
2208                                 log_err("fio: poll clients: %s\n", strerror(errno));
2209                                 break;
2210                         } else if (!ret)
2211                                 continue;
2212                 } while (ret <= 0);
2213
2214                 for (i = 0; i < nr_clients; i++) {
2215                         if (!(pfds[i].revents & POLLIN))
2216                                 continue;
2217
2218                         client = find_client_by_fd(pfds[i].fd);
2219                         if (!client) {
2220                                 log_err("fio: unknown client fd %ld\n", (long) pfds[i].fd);
2221                                 continue;
2222                         }
2223                         if (!fio_handle_client(client)) {
2224                                 log_info("client: host=%s disconnected\n",
2225                                                 client->hostname);
2226                                 remove_client(client);
2227                                 retval = 1;
2228                         } else if (client->error)
2229                                 retval = 1;
2230                         fio_put_client(client);
2231                 }
2232         }
2233
2234         log_info_buf(allclients.buf, allclients.buflen);
2235         buf_output_free(&allclients);
2236
2237         fio_client_json_fini();
2238
2239         free_clat_prio_stats(&client_ts);
2240         free(pfds);
2241         return retval || error_clients;
2242 }
2243
2244 static void client_display_thread_status(struct jobs_eta *je)
2245 {
2246         if (!(output_format & FIO_OUTPUT_JSON))
2247                 display_thread_status(je);
2248 }