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