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