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