gfio: use ffz64 for 64-bit types
[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 struct client_ops fio_client_ops = {
37         .text           = handle_text,
38         .disk_util      = handle_du,
39         .thread_status  = handle_ts,
40         .group_stats    = handle_gs,
41         .stop           = handle_stop,
42         .start          = handle_start,
43         .eta            = display_thread_status,
44         .probe          = handle_probe,
45         .eta_msec       = FIO_CLIENT_DEF_ETA_MSEC,
46         .client_type    = FIO_CLIENT_TYPE_CLI,
47 };
48
49 static struct timeval eta_tv;
50
51 static FLIST_HEAD(client_list);
52 static FLIST_HEAD(eta_list);
53
54 static FLIST_HEAD(arg_list);
55
56 struct thread_stat client_ts;
57 struct group_run_stats client_gs;
58 int sum_stat_clients;
59
60 static int sum_stat_nr;
61 static struct json_object *root = NULL;
62 static struct json_object *job_opt_object = NULL;
63 static struct json_array *clients_array = NULL;
64 static struct json_array *du_array = NULL;
65
66 static int error_clients;
67
68 #define FIO_CLIENT_HASH_BITS    7
69 #define FIO_CLIENT_HASH_SZ      (1 << FIO_CLIENT_HASH_BITS)
70 #define FIO_CLIENT_HASH_MASK    (FIO_CLIENT_HASH_SZ - 1)
71 static struct flist_head client_hash[FIO_CLIENT_HASH_SZ];
72
73 static struct cmd_iolog_pdu *convert_iolog(struct fio_net_cmd *, bool *);
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 int fio_client_handle_iolog(struct fio_client *client,
1230                                    struct fio_net_cmd *cmd)
1231 {
1232         struct cmd_iolog_pdu *pdu;
1233         bool store_direct;
1234
1235         pdu = convert_iolog(cmd, &store_direct);
1236         if (!pdu) {
1237                 log_err("fio: failed converting IO log\n");
1238                 return 1;
1239         }
1240
1241         if (store_direct) {
1242                 ssize_t ret;
1243                 size_t sz;
1244                 int fd;
1245
1246                 fd = open((const char *) pdu->name,
1247                                 O_WRONLY | O_CREAT | O_TRUNC, 0644);
1248                 if (fd < 0) {
1249                         log_err("fio: open log: %s\n", strerror(errno));
1250                         return 1;
1251                 }
1252
1253                 sz = cmd->pdu_len - sizeof(*pdu);
1254                 ret = write(fd, pdu->samples, sz);
1255                 close(fd);
1256
1257                 if (ret != sz) {
1258                         log_err("fio: short write on compressed log\n");
1259                         return 1;
1260                 }
1261
1262                 return 0;
1263         } else {
1264                 FILE *f;
1265
1266                 f = fopen((const char *) pdu->name, "w");
1267                 if (!f) {
1268                         log_err("fio: fopen log: %s\n", strerror(errno));
1269                         return 1;
1270                 }
1271
1272                 flush_samples(f, pdu->samples,
1273                                 pdu->nr_samples * sizeof(struct io_sample));
1274                 fclose(f);
1275                 return 0;
1276         }
1277 }
1278
1279 static void handle_probe(struct fio_client *client, struct fio_net_cmd *cmd)
1280 {
1281         struct cmd_probe_reply_pdu *probe = (struct cmd_probe_reply_pdu *) cmd->payload;
1282         const char *os, *arch;
1283         char bit[16];
1284
1285         os = fio_get_os_string(probe->os);
1286         if (!os)
1287                 os = "unknown";
1288
1289         arch = fio_get_arch_string(probe->arch);
1290         if (!arch)
1291                 os = "unknown";
1292
1293         sprintf(bit, "%d-bit", probe->bpp * 8);
1294         probe->flags = le64_to_cpu(probe->flags);
1295
1296         log_info("hostname=%s, be=%u, %s, os=%s, arch=%s, fio=%s, flags=%lx\n",
1297                 probe->hostname, probe->bigendian, bit, os, arch,
1298                 probe->fio_version, (unsigned long) probe->flags);
1299
1300         if (!client->name)
1301                 client->name = strdup((char *) probe->hostname);
1302 }
1303
1304 static void handle_start(struct fio_client *client, struct fio_net_cmd *cmd)
1305 {
1306         struct cmd_start_pdu *pdu = (struct cmd_start_pdu *) cmd->payload;
1307
1308         client->state = Client_started;
1309         client->jobs = le32_to_cpu(pdu->jobs);
1310         client->nr_stat = le32_to_cpu(pdu->stat_outputs);
1311
1312         if (client->jobs) {
1313                 int i;
1314
1315                 if (client->opt_lists)
1316                         free(client->opt_lists);
1317
1318                 client->opt_lists = malloc(client->jobs * sizeof(struct flist_head));
1319                 for (i = 0; i < client->jobs; i++)
1320                         INIT_FLIST_HEAD(&client->opt_lists[i]);
1321         }
1322
1323         sum_stat_clients += client->nr_stat;
1324 }
1325
1326 static void handle_stop(struct fio_client *client, struct fio_net_cmd *cmd)
1327 {
1328         if (client->error)
1329                 log_info("client <%s>: exited with error %d\n", client->hostname, client->error);
1330 }
1331
1332 static void convert_stop(struct fio_net_cmd *cmd)
1333 {
1334         struct cmd_end_pdu *pdu = (struct cmd_end_pdu *) cmd->payload;
1335
1336         pdu->error = le32_to_cpu(pdu->error);
1337 }
1338
1339 static void convert_text(struct fio_net_cmd *cmd)
1340 {
1341         struct cmd_text_pdu *pdu = (struct cmd_text_pdu *) cmd->payload;
1342
1343         pdu->level      = le32_to_cpu(pdu->level);
1344         pdu->buf_len    = le32_to_cpu(pdu->buf_len);
1345         pdu->log_sec    = le64_to_cpu(pdu->log_sec);
1346         pdu->log_usec   = le64_to_cpu(pdu->log_usec);
1347 }
1348
1349 static struct cmd_iolog_pdu *convert_iolog_gz(struct fio_net_cmd *cmd,
1350                                               struct cmd_iolog_pdu *pdu)
1351 {
1352 #ifdef CONFIG_ZLIB
1353         struct cmd_iolog_pdu *ret;
1354         z_stream stream;
1355         uint32_t nr_samples;
1356         size_t total;
1357         void *p;
1358
1359         stream.zalloc = Z_NULL;
1360         stream.zfree = Z_NULL;
1361         stream.opaque = Z_NULL;
1362         stream.avail_in = 0;
1363         stream.next_in = Z_NULL;
1364
1365         if (inflateInit(&stream) != Z_OK)
1366                 return NULL;
1367
1368         /*
1369          * Get header first, it's not compressed
1370          */
1371         nr_samples = le64_to_cpu(pdu->nr_samples);
1372
1373         total = nr_samples * __log_entry_sz(le32_to_cpu(pdu->log_offset));
1374         ret = malloc(total + sizeof(*pdu));
1375         ret->nr_samples = nr_samples;
1376
1377         memcpy(ret, pdu, sizeof(*pdu));
1378
1379         p = (void *) ret + sizeof(*pdu);
1380
1381         stream.avail_in = cmd->pdu_len - sizeof(*pdu);
1382         stream.next_in = (void *) pdu + sizeof(*pdu);
1383         while (stream.avail_in) {
1384                 unsigned int this_chunk = 65536;
1385                 unsigned int this_len;
1386                 int err;
1387
1388                 if (this_chunk > total)
1389                         this_chunk = total;
1390
1391                 stream.avail_out = this_chunk;
1392                 stream.next_out = p;
1393                 err = inflate(&stream, Z_NO_FLUSH);
1394                 /* may be Z_OK, or Z_STREAM_END */
1395                 if (err < 0) {
1396                         log_err("fio: inflate error %d\n", err);
1397                         free(ret);
1398                         ret = NULL;
1399                         goto err;
1400                 }
1401
1402                 this_len = this_chunk - stream.avail_out;
1403                 p += this_len;
1404                 total -= this_len;
1405         }
1406
1407 err:
1408         inflateEnd(&stream);
1409         return ret;
1410 #else
1411         return NULL;
1412 #endif
1413 }
1414
1415 /*
1416  * This has been compressed on the server side, since it can be big.
1417  * Uncompress here.
1418  */
1419 static struct cmd_iolog_pdu *convert_iolog(struct fio_net_cmd *cmd,
1420                                            bool *store_direct)
1421 {
1422         struct cmd_iolog_pdu *pdu = (struct cmd_iolog_pdu *) cmd->payload;
1423         struct cmd_iolog_pdu *ret;
1424         uint64_t i;
1425         int compressed;
1426         void *samples;
1427
1428         *store_direct = false;
1429
1430         /*
1431          * Convert if compressed and we support it. If it's not
1432          * compressed, we need not do anything.
1433          */
1434         compressed = le32_to_cpu(pdu->compressed);
1435         if (compressed == XMIT_COMPRESSED) {
1436 #ifndef CONFIG_ZLIB
1437                 log_err("fio: server sent compressed data by mistake\n");
1438                 return NULL;
1439 #endif
1440                 ret = convert_iolog_gz(cmd, pdu);
1441                 printf("compressed iolog, %p\n", ret);
1442                 if (!ret) {
1443                         log_err("fio: failed decompressing log\n");
1444                         return NULL;
1445                 }
1446         } else if (compressed == STORE_COMPRESSED) {
1447                 *store_direct = true;
1448                 ret = pdu;
1449         } else
1450                 ret = pdu;
1451
1452         ret->nr_samples         = le64_to_cpu(ret->nr_samples);
1453         ret->thread_number      = le32_to_cpu(ret->thread_number);
1454         ret->log_type           = le32_to_cpu(ret->log_type);
1455         ret->compressed         = le32_to_cpu(ret->compressed);
1456         ret->log_offset         = le32_to_cpu(ret->log_offset);
1457
1458         if (*store_direct)
1459                 return ret;
1460
1461         samples = &ret->samples[0];
1462         for (i = 0; i < ret->nr_samples; i++) {
1463                 struct io_sample *s;
1464
1465                 s = __get_sample(samples, ret->log_offset, i);
1466                 s->time         = le64_to_cpu(s->time);
1467                 s->val          = le64_to_cpu(s->val);
1468                 s->__ddir       = le32_to_cpu(s->__ddir);
1469                 s->bs           = le32_to_cpu(s->bs);
1470
1471                 if (ret->log_offset) {
1472                         struct io_sample_offset *so = (void *) s;
1473
1474                         so->offset = le64_to_cpu(so->offset);
1475                 }
1476         }
1477
1478         return ret;
1479 }
1480
1481 static void sendfile_reply(int fd, struct cmd_sendfile_reply *rep,
1482                            size_t size, uint64_t tag)
1483 {
1484         rep->error = cpu_to_le32(rep->error);
1485         fio_net_send_cmd(fd, FIO_NET_CMD_SENDFILE, rep, size, &tag, NULL);
1486 }
1487
1488 static int send_file(struct fio_client *client, struct cmd_sendfile *pdu,
1489                      uint64_t tag)
1490 {
1491         struct cmd_sendfile_reply *rep;
1492         struct stat sb;
1493         size_t size;
1494         int fd;
1495
1496         size = sizeof(*rep);
1497         rep = malloc(size);
1498
1499         if (stat((char *)pdu->path, &sb) < 0) {
1500 fail:
1501                 rep->error = errno;
1502                 sendfile_reply(client->fd, rep, size, tag);
1503                 free(rep);
1504                 return 1;
1505         }
1506
1507         size += sb.st_size;
1508         rep = realloc(rep, size);
1509         rep->size = cpu_to_le32((uint32_t) sb.st_size);
1510
1511         fd = open((char *)pdu->path, O_RDONLY);
1512         if (fd == -1 )
1513                 goto fail;
1514
1515         rep->error = read_data(fd, &rep->data, sb.st_size);
1516         sendfile_reply(client->fd, rep, size, tag);
1517         free(rep);
1518         close(fd);
1519         return 0;
1520 }
1521
1522 int fio_handle_client(struct fio_client *client)
1523 {
1524         struct client_ops *ops = client->ops;
1525         struct fio_net_cmd *cmd;
1526
1527         dprint(FD_NET, "client: handle %s\n", client->hostname);
1528
1529         cmd = fio_net_recv_cmd(client->fd);
1530         if (!cmd)
1531                 return 0;
1532
1533         dprint(FD_NET, "client: got cmd op %s from %s (pdu=%u)\n",
1534                 fio_server_op(cmd->opcode), client->hostname, cmd->pdu_len);
1535
1536         switch (cmd->opcode) {
1537         case FIO_NET_CMD_QUIT:
1538                 if (ops->quit)
1539                         ops->quit(client, cmd);
1540                 remove_client(client);
1541                 break;
1542         case FIO_NET_CMD_TEXT:
1543                 convert_text(cmd);
1544                 ops->text(client, cmd);
1545                 break;
1546         case FIO_NET_CMD_DU: {
1547                 struct cmd_du_pdu *du = (struct cmd_du_pdu *) cmd->payload;
1548
1549                 convert_dus(&du->dus);
1550                 convert_agg(&du->agg);
1551
1552                 ops->disk_util(client, cmd);
1553                 break;
1554                 }
1555         case FIO_NET_CMD_TS: {
1556                 struct cmd_ts_pdu *p = (struct cmd_ts_pdu *) cmd->payload;
1557
1558                 convert_ts(&p->ts, &p->ts);
1559                 convert_gs(&p->rs, &p->rs);
1560
1561                 ops->thread_status(client, cmd);
1562                 break;
1563                 }
1564         case FIO_NET_CMD_GS: {
1565                 struct group_run_stats *gs = (struct group_run_stats *) cmd->payload;
1566
1567                 convert_gs(gs, gs);
1568
1569                 ops->group_stats(client, cmd);
1570                 break;
1571                 }
1572         case FIO_NET_CMD_ETA: {
1573                 struct jobs_eta *je = (struct jobs_eta *) cmd->payload;
1574
1575                 remove_reply_cmd(client, cmd);
1576                 convert_jobs_eta(je);
1577                 handle_eta(client, cmd);
1578                 break;
1579                 }
1580         case FIO_NET_CMD_PROBE:
1581                 remove_reply_cmd(client, cmd);
1582                 ops->probe(client, cmd);
1583                 break;
1584         case FIO_NET_CMD_SERVER_START:
1585                 client->state = Client_running;
1586                 if (ops->job_start)
1587                         ops->job_start(client, cmd);
1588                 break;
1589         case FIO_NET_CMD_START: {
1590                 struct cmd_start_pdu *pdu = (struct cmd_start_pdu *) cmd->payload;
1591
1592                 pdu->jobs = le32_to_cpu(pdu->jobs);
1593                 ops->start(client, cmd);
1594                 break;
1595                 }
1596         case FIO_NET_CMD_STOP: {
1597                 struct cmd_end_pdu *pdu = (struct cmd_end_pdu *) cmd->payload;
1598
1599                 convert_stop(cmd);
1600                 client->state = Client_stopped;
1601                 client->error = le32_to_cpu(pdu->error);
1602                 client->signal = le32_to_cpu(pdu->signal);
1603                 ops->stop(client, cmd);
1604                 break;
1605                 }
1606         case FIO_NET_CMD_ADD_JOB: {
1607                 struct cmd_add_job_pdu *pdu = (struct cmd_add_job_pdu *) cmd->payload;
1608
1609                 client->thread_number = le32_to_cpu(pdu->thread_number);
1610                 client->groupid = le32_to_cpu(pdu->groupid);
1611
1612                 if (ops->add_job)
1613                         ops->add_job(client, cmd);
1614                 break;
1615                 }
1616         case FIO_NET_CMD_IOLOG:
1617                 fio_client_handle_iolog(client, cmd);
1618                 break;
1619         case FIO_NET_CMD_UPDATE_JOB:
1620                 ops->update_job(client, cmd);
1621                 remove_reply_cmd(client, cmd);
1622                 break;
1623         case FIO_NET_CMD_VTRIGGER: {
1624                 struct all_io_list *pdu = (struct all_io_list *) cmd->payload;
1625                 char buf[128];
1626                 int off = 0;
1627
1628                 if (aux_path) {
1629                         strcpy(buf, aux_path);
1630                         off = strlen(buf);
1631                 }
1632
1633                 __verify_save_state(pdu, server_name(client, &buf[off], sizeof(buf) - off));
1634                 exec_trigger(trigger_cmd);
1635                 break;
1636                 }
1637         case FIO_NET_CMD_SENDFILE: {
1638                 struct cmd_sendfile *pdu = (struct cmd_sendfile *) cmd->payload;
1639                 send_file(client, pdu, cmd->tag);
1640                 break;
1641                 }
1642         case FIO_NET_CMD_JOB_OPT: {
1643                 handle_job_opt(client, cmd);
1644                 break;
1645         }
1646         default:
1647                 log_err("fio: unknown client op: %s\n", fio_server_op(cmd->opcode));
1648                 break;
1649         }
1650
1651         free(cmd);
1652         return 1;
1653 }
1654
1655 int fio_clients_send_trigger(const char *cmd)
1656 {
1657         struct flist_head *entry;
1658         struct fio_client *client;
1659         size_t slen;
1660
1661         dprint(FD_NET, "client: send vtrigger: %s\n", cmd);
1662
1663         if (!cmd)
1664                 slen = 0;
1665         else
1666                 slen = strlen(cmd);
1667
1668         flist_for_each(entry, &client_list) {
1669                 struct cmd_vtrigger_pdu *pdu;
1670
1671                 client = flist_entry(entry, struct fio_client, list);
1672
1673                 pdu = malloc(sizeof(*pdu) + slen);
1674                 pdu->len = cpu_to_le16((uint16_t) slen);
1675                 if (slen)
1676                         memcpy(pdu->cmd, cmd, slen);
1677                 fio_net_send_cmd(client->fd, FIO_NET_CMD_VTRIGGER, pdu,
1678                                         sizeof(*pdu) + slen, NULL, NULL);
1679                 free(pdu);
1680         }
1681
1682         return 0;
1683 }
1684
1685 static void request_client_etas(struct client_ops *ops)
1686 {
1687         struct fio_client *client;
1688         struct flist_head *entry;
1689         struct client_eta *eta;
1690         int skipped = 0;
1691
1692         dprint(FD_NET, "client: request eta (%d)\n", nr_clients);
1693
1694         eta = calloc(1, sizeof(*eta) + __THREAD_RUNSTR_SZ(REAL_MAX_JOBS));
1695         eta->pending = nr_clients;
1696
1697         flist_for_each(entry, &client_list) {
1698                 client = flist_entry(entry, struct fio_client, list);
1699
1700                 if (!flist_empty(&client->eta_list)) {
1701                         skipped++;
1702                         continue;
1703                 }
1704                 if (client->state != Client_running)
1705                         continue;
1706
1707                 assert(!client->eta_in_flight);
1708                 flist_add_tail(&client->eta_list, &eta_list);
1709                 client->eta_in_flight = eta;
1710                 fio_net_send_simple_cmd(client->fd, FIO_NET_CMD_SEND_ETA,
1711                                         (uintptr_t) eta, &client->cmd_list);
1712         }
1713
1714         while (skipped--) {
1715                 if (!fio_client_dec_jobs_eta(eta, ops->eta))
1716                         break;
1717         }
1718
1719         dprint(FD_NET, "client: requested eta tag %p\n", eta);
1720 }
1721
1722 /*
1723  * A single SEND_ETA timeout isn't fatal. Attempt to recover.
1724  */
1725 static int handle_cmd_timeout(struct fio_client *client,
1726                               struct fio_net_cmd_reply *reply)
1727 {
1728         flist_del(&reply->list);
1729         free(reply);
1730
1731         if (reply->opcode != FIO_NET_CMD_SEND_ETA)
1732                 return 1;
1733
1734         log_info("client <%s>: timeout on SEND_ETA\n", client->hostname);
1735
1736         flist_del_init(&client->eta_list);
1737         if (client->eta_in_flight) {
1738                 fio_client_dec_jobs_eta(client->eta_in_flight, client->ops->eta);
1739                 client->eta_in_flight = NULL;
1740         }
1741
1742         /*
1743          * If we fail 5 in a row, give up...
1744          */
1745         if (client->eta_timeouts++ > 5)
1746                 return 1;
1747
1748         return 0;
1749 }
1750
1751 static int client_check_cmd_timeout(struct fio_client *client,
1752                                     struct timeval *now)
1753 {
1754         struct fio_net_cmd_reply *reply;
1755         struct flist_head *entry, *tmp;
1756         int ret = 0;
1757
1758         flist_for_each_safe(entry, tmp, &client->cmd_list) {
1759                 reply = flist_entry(entry, struct fio_net_cmd_reply, list);
1760
1761                 if (mtime_since(&reply->tv, now) < FIO_NET_CLIENT_TIMEOUT)
1762                         continue;
1763
1764                 if (!handle_cmd_timeout(client, reply))
1765                         continue;
1766
1767                 log_err("fio: client %s, timeout on cmd %s\n", client->hostname,
1768                                                 fio_server_op(reply->opcode));
1769                 ret = 1;
1770         }
1771
1772         return flist_empty(&client->cmd_list) && ret;
1773 }
1774
1775 static int fio_check_clients_timed_out(void)
1776 {
1777         struct fio_client *client;
1778         struct flist_head *entry, *tmp;
1779         struct timeval tv;
1780         int ret = 0;
1781
1782         fio_gettime(&tv, NULL);
1783
1784         flist_for_each_safe(entry, tmp, &client_list) {
1785                 client = flist_entry(entry, struct fio_client, list);
1786
1787                 if (flist_empty(&client->cmd_list))
1788                         continue;
1789
1790                 if (!client_check_cmd_timeout(client, &tv))
1791                         continue;
1792
1793                 if (client->ops->timed_out)
1794                         client->ops->timed_out(client);
1795                 else
1796                         log_err("fio: client %s timed out\n", client->hostname);
1797
1798                 client->error = ETIMEDOUT;
1799                 remove_client(client);
1800                 ret = 1;
1801         }
1802
1803         return ret;
1804 }
1805
1806 int fio_handle_clients(struct client_ops *ops)
1807 {
1808         struct pollfd *pfds;
1809         int i, ret = 0, retval = 0;
1810
1811         fio_gettime(&eta_tv, NULL);
1812
1813         pfds = malloc(nr_clients * sizeof(struct pollfd));
1814
1815         init_thread_stat(&client_ts);
1816         init_group_run_stat(&client_gs);
1817
1818         while (!exit_backend && nr_clients) {
1819                 struct flist_head *entry, *tmp;
1820                 struct fio_client *client;
1821
1822                 i = 0;
1823                 flist_for_each_safe(entry, tmp, &client_list) {
1824                         client = flist_entry(entry, struct fio_client, list);
1825
1826                         if (!client->sent_job && !client->ops->stay_connected &&
1827                             flist_empty(&client->cmd_list)) {
1828                                 remove_client(client);
1829                                 continue;
1830                         }
1831
1832                         pfds[i].fd = client->fd;
1833                         pfds[i].events = POLLIN;
1834                         i++;
1835                 }
1836
1837                 if (!nr_clients)
1838                         break;
1839
1840                 assert(i == nr_clients);
1841
1842                 do {
1843                         struct timeval tv;
1844                         int timeout;
1845
1846                         fio_gettime(&tv, NULL);
1847                         if (mtime_since(&eta_tv, &tv) >= 900) {
1848                                 request_client_etas(ops);
1849                                 memcpy(&eta_tv, &tv, sizeof(tv));
1850
1851                                 if (fio_check_clients_timed_out())
1852                                         break;
1853                         }
1854
1855                         check_trigger_file();
1856
1857                         timeout = min(100u, ops->eta_msec);
1858
1859                         ret = poll(pfds, nr_clients, timeout);
1860                         if (ret < 0) {
1861                                 if (errno == EINTR)
1862                                         continue;
1863                                 log_err("fio: poll clients: %s\n", strerror(errno));
1864                                 break;
1865                         } else if (!ret)
1866                                 continue;
1867                 } while (ret <= 0);
1868
1869                 for (i = 0; i < nr_clients; i++) {
1870                         if (!(pfds[i].revents & POLLIN))
1871                                 continue;
1872
1873                         client = find_client_by_fd(pfds[i].fd);
1874                         if (!client) {
1875                                 log_err("fio: unknown client fd %ld\n", (long) pfds[i].fd);
1876                                 continue;
1877                         }
1878                         if (!fio_handle_client(client)) {
1879                                 log_info("client: host=%s disconnected\n",
1880                                                 client->hostname);
1881                                 remove_client(client);
1882                                 retval = 1;
1883                         } else if (client->error)
1884                                 retval = 1;
1885                         fio_put_client(client);
1886                 }
1887         }
1888
1889         fio_client_json_fini();
1890
1891         free(pfds);
1892         return retval || error_clients;
1893 }