218b0bd8134808a756a9f87ea59fbed62db66532
[nbd.git] / nbd-tester-client.c
1 /*
2  * Test client to test the NBD server. Doesn't do anything useful, except
3  * checking that the server does, actually, work.
4  *
5  * Note that the only 'real' test is to check the client against a kernel. If
6  * it works here but does not work in the kernel, then that's most likely a bug
7  * in this program and/or in nbd-server.
8  *
9  * Copyright(c) 2006  Wouter Verhelst
10  *
11  * This program is Free Software; you can redistribute it and/or modify it
12  * under the terms of the GNU General Public License as published by the Free
13  * Software Foundation, in version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
18  * more details.
19  *
20  * You should have received a copy of the GNU General Public License along with
21  * this program; if not, write to the Free Software Foundation, Inc., 51
22  * Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
23  */
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <stdbool.h>
27 #include <string.h>
28 #include <sys/time.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <syslog.h>
32 #include <unistd.h>
33 #include "config.h"
34 #include "lfs.h"
35 #define MY_NAME "nbd-tester-client"
36 #include "cliserv.h"
37
38 #include <netinet/in.h>
39 #include <glib.h>
40
41 static gchar errstr[1024];
42 const static int errstr_len=1024;
43
44 static uint64_t size;
45
46 typedef enum {
47         CONNECTION_TYPE_NONE,
48         CONNECTION_TYPE_CONNECT,
49         CONNECTION_TYPE_INIT_PASSWD,
50         CONNECTION_TYPE_CLISERV,
51         CONNECTION_TYPE_FULL,
52 } CONNECTION_TYPE;
53
54 typedef enum {
55         CONNECTION_CLOSE_PROPERLY,
56         CONNECTION_CLOSE_FAST,
57 } CLOSE_TYPE;
58
59 #define TEST_WRITE (1<<0)
60 #define TEST_FLUSH (1<<1)
61
62 int timeval_subtract (struct timeval *result, struct timeval *x,
63                       struct timeval *y) {
64         if (x->tv_usec < y->tv_usec) {
65                 int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
66                 y->tv_usec -= 1000000 * nsec;
67                 y->tv_sec += nsec;
68         }
69         
70         if (x->tv_usec - y->tv_usec > 1000000) {
71                 int nsec = (x->tv_usec - y->tv_usec) / 1000000;
72                 y->tv_usec += 1000000 * nsec;
73                 y->tv_sec -= nsec;
74         }
75         
76         result->tv_sec = x->tv_sec - y->tv_sec;
77         result->tv_usec = x->tv_usec - y->tv_usec;
78         
79         return x->tv_sec < y->tv_sec;
80 }
81
82 double timeval_diff_to_double (struct timeval * x, struct timeval * y) {
83         struct timeval r;
84         timeval_subtract(&r, x, y);
85         return r.tv_sec * 1.0 + r.tv_usec/1000000.0;
86 }
87
88 static inline int read_all(int f, void *buf, size_t len) {
89         ssize_t res;
90         size_t retval=0;
91
92         while(len>0) {
93                 if((res=read(f, buf, len)) <=0) {
94                         snprintf(errstr, errstr_len, "Read failed: %s", strerror(errno));
95                         return -1;
96                 }
97                 len-=res;
98                 buf+=res;
99                 retval+=res;
100         }
101         return retval;
102 }
103
104 static inline int write_all(int f, void *buf, size_t len) {
105         ssize_t res;
106         size_t retval=0;
107
108         while(len>0) {
109                 if((res=write(f, buf, len)) <=0) {
110                         snprintf(errstr, errstr_len, "Write failed: %s", strerror(errno));
111                         return -1;
112                 }
113                 len-=res;
114                 buf+=res;
115                 retval+=res;
116         }
117         return retval;
118 }
119
120 #define READ_ALL_ERRCHK(f, buf, len, whereto, errmsg...) if((read_all(f, buf, len))<=0) { snprintf(errstr, errstr_len, ##errmsg); goto whereto; }
121 #define READ_ALL_ERR_RT(f, buf, len, whereto, rval, errmsg...) if((read_all(f, buf, len))<=0) { snprintf(errstr, errstr_len, ##errmsg); retval = rval; goto whereto; }
122
123 #define WRITE_ALL_ERRCHK(f, buf, len, whereto, errmsg...) if((write_all(f, buf, len))<=0) { snprintf(errstr, errstr_len, ##errmsg); goto whereto; }
124 #define WRITE_ALL_ERR_RT(f, buf, len, whereto, rval, errmsg...) if((write_all(f, buf, len))<=0) { snprintf(errstr, errstr_len, ##errmsg); retval = rval; goto whereto; }
125
126 int setup_connection(gchar *hostname, int port, gchar* name, CONNECTION_TYPE ctype) {
127         int sock;
128         struct hostent *host;
129         struct sockaddr_in addr;
130         char buf[256];
131         uint64_t mymagic = (name ? opts_magic : cliserv_magic);
132         u64 tmp64;
133         uint32_t tmp32 = 0;
134
135         sock=0;
136         if(ctype<CONNECTION_TYPE_CONNECT)
137                 goto end;
138         if((sock=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))<0) {
139                 strncpy(errstr, strerror(errno), errstr_len);
140                 goto err;
141         }
142         setmysockopt(sock);
143         if(!(host=gethostbyname(hostname))) {
144                 strncpy(errstr, strerror(errno), errstr_len);
145                 goto err_open;
146         }
147         addr.sin_family=AF_INET;
148         addr.sin_port=htons(port);
149         addr.sin_addr.s_addr=*((int *) host->h_addr);
150         if((connect(sock, (struct sockaddr *)&addr, sizeof(addr))<0)) {
151                 strncpy(errstr, strerror(errno), errstr_len);
152                 goto err_open;
153         }
154         if(ctype<CONNECTION_TYPE_INIT_PASSWD)
155                 goto end;
156         READ_ALL_ERRCHK(sock, buf, strlen(INIT_PASSWD), err_open, "Could not read INIT_PASSWD: %s", strerror(errno));
157         if(strlen(buf)==0) {
158                 snprintf(errstr, errstr_len, "Server closed connection");
159                 goto err_open;
160         }
161         if(strncmp(buf, INIT_PASSWD, strlen(INIT_PASSWD))) {
162                 snprintf(errstr, errstr_len, "INIT_PASSWD does not match");
163                 goto err_open;
164         }
165         if(ctype<CONNECTION_TYPE_CLISERV)
166                 goto end;
167         READ_ALL_ERRCHK(sock, &tmp64, sizeof(tmp64), err_open, "Could not read cliserv_magic: %s", strerror(errno));
168         tmp64=ntohll(tmp64);
169         if(tmp64 != mymagic) {
170                 strncpy(errstr, "mymagic does not match", errstr_len);
171                 goto err_open;
172         }
173         if(ctype<CONNECTION_TYPE_FULL)
174                 goto end;
175         if(!name) {
176                 READ_ALL_ERRCHK(sock, &size, sizeof(size), err_open, "Could not read size: %s", strerror(errno));
177                 size=ntohll(size);
178                 READ_ALL_ERRCHK(sock, buf, 128, err_open, "Could not read data: %s", strerror(errno));
179                 goto end;
180         }
181         /* flags */
182         READ_ALL_ERRCHK(sock, buf, sizeof(uint16_t), err_open, "Could not read reserved field: %s", strerror(errno));
183         /* reserved field */
184         WRITE_ALL_ERRCHK(sock, &tmp32, sizeof(tmp32), err_open, "Could not write reserved field: %s", strerror(errno));
185         /* magic */
186         tmp64 = htonll(opts_magic);
187         WRITE_ALL_ERRCHK(sock, &tmp64, sizeof(tmp64), err_open, "Could not write magic: %s", strerror(errno));
188         /* name */
189         tmp32 = htonl(NBD_OPT_EXPORT_NAME);
190         WRITE_ALL_ERRCHK(sock, &tmp32, sizeof(tmp32), err_open, "Could not write option: %s", strerror(errno));
191         tmp32 = htonl((uint32_t)strlen(name));
192         WRITE_ALL_ERRCHK(sock, &tmp32, sizeof(tmp32), err_open, "Could not write name length: %s", strerror(errno));
193         WRITE_ALL_ERRCHK(sock, name, strlen(name), err_open, "Could not write name:: %s", strerror(errno));
194         READ_ALL_ERRCHK(sock, &size, sizeof(size), err_open, "Could not read size: %s", strerror(errno));
195         size = ntohll(size);
196         uint16_t flags;
197         READ_ALL_ERRCHK(sock, buf, sizeof(uint16_t), err_open, "Could not read flags: %s", strerror(errno));
198         flags = ntohs(flags);
199         READ_ALL_ERRCHK(sock, buf, 124, err_open, "Could not read reserved zeroes: %s", strerror(errno));
200         goto end;
201 err_open:
202         close(sock);
203 err:
204         sock=-1;
205 end:
206         return sock;
207 }
208
209 int close_connection(int sock, CLOSE_TYPE type) {
210         struct nbd_request req;
211         u64 counter=0;
212
213         switch(type) {
214                 case CONNECTION_CLOSE_PROPERLY:
215                         req.magic=htonl(NBD_REQUEST_MAGIC);
216                         req.type=htonl(NBD_CMD_DISC);
217                         memcpy(&(req.handle), &(counter), sizeof(counter));
218                         counter++;
219                         req.from=0;
220                         req.len=0;
221                         if(write(sock, &req, sizeof(req))<0) {
222                                 snprintf(errstr, errstr_len, "Could not write to socket: %s", strerror(errno));
223                                 return -1;
224                         }
225                 case CONNECTION_CLOSE_FAST:
226                         if(close(sock)<0) {
227                                 snprintf(errstr, errstr_len, "Could not close socket: %s", strerror(errno));
228                                 return -1;
229                         }
230                         break;
231                 default:
232                         g_critical("Your compiler is on crack!"); /* or I am buggy */
233                         return -1;
234         }
235         return 0;
236 }
237
238 int read_packet_check_header(int sock, size_t datasize, long long int curhandle) {
239         struct nbd_reply rep;
240         int retval=0;
241         char buf[datasize];
242
243         READ_ALL_ERR_RT(sock, &rep, sizeof(rep), end, -1, "Could not read reply header: %s", strerror(errno));
244         rep.magic=ntohl(rep.magic);
245         rep.error=ntohl(rep.error);
246         if(rep.magic!=NBD_REPLY_MAGIC) {
247                 snprintf(errstr, errstr_len, "Received package with incorrect reply_magic. Index of sent packages is %lld (0x%llX), received handle is %lld (0x%llX). Received magic 0x%lX, expected 0x%lX", (long long int)curhandle, (long long unsigned int)curhandle, (long long int)*((u64*)rep.handle), (long long unsigned int)*((u64*)rep.handle), (long unsigned int)rep.magic, (long unsigned int)NBD_REPLY_MAGIC);
248                 retval=-1;
249                 goto end;
250         }
251         if(rep.error) {
252                 snprintf(errstr, errstr_len, "Received error from server: %ld (0x%lX). Handle is %lld (0x%llX).", (long int)rep.error, (long unsigned int)rep.error, (long long int)(*((u64*)rep.handle)), (long long unsigned int)*((u64*)rep.handle));
253                 retval=-1;
254                 goto end;
255         }
256         if (datasize)
257                 READ_ALL_ERR_RT(sock, &buf, datasize, end, -1, "Could not read data: %s", strerror(errno));
258
259 end:
260         return retval;
261 }
262
263 int oversize_test(gchar* hostname, int port, char* name, int sock,
264                   char sock_is_open, char close_sock, int testflags) {
265         int retval=0;
266         struct nbd_request req;
267         struct nbd_reply rep;
268         int request=0;
269         int i=0;
270         pid_t mypid = getpid();
271         char buf[((1024*1024)+sizeof(struct nbd_request)/2)<<1];
272         bool got_err;
273
274         /* This should work */
275         if(!sock_is_open) {
276                 if((sock=setup_connection(hostname, port, name, CONNECTION_TYPE_FULL))<0) {
277                         g_warning("Could not open socket: %s", errstr);
278                         retval=-1;
279                         goto err;
280                 }
281         }
282         req.magic=htonl(NBD_REQUEST_MAGIC);
283         req.type=htonl(NBD_CMD_READ);
284         req.len=htonl(1024*1024);
285         memcpy(&(req.handle),&i,sizeof(i));
286         req.from=htonll(i);
287         WRITE_ALL_ERR_RT(sock, &req, sizeof(req), err, -1, "Could not write request: %s", strerror(errno));
288         printf("%d: testing oversized request: %d: ", getpid(), ntohl(req.len));
289         READ_ALL_ERR_RT(sock, &rep, sizeof(struct nbd_reply), err, -1, "Could not read reply header: %s", strerror(errno));
290         READ_ALL_ERR_RT(sock, &buf, ntohl(req.len), err, -1, "Could not read data: %s", strerror(errno));
291         if(rep.error) {
292                 snprintf(errstr, errstr_len, "Received unexpected error: %d", rep.error);
293                 retval=-1;
294                 goto err;
295         } else {
296                 printf("OK\n");
297         }
298         /* This probably should not work */
299         i++; req.from=htonll(i);
300         req.len = htonl(ntohl(req.len) + sizeof(struct nbd_request) / 2);
301         WRITE_ALL_ERR_RT(sock, &req, sizeof(req), err, -1, "Could not write request: %s", strerror(errno));
302         printf("%d: testing oversized request: %d: ", getpid(), ntohl(req.len));
303         READ_ALL_ERR_RT(sock, &rep, sizeof(struct nbd_reply), err, -1, "Could not read reply header: %s", strerror(errno));
304         READ_ALL_ERR_RT(sock, &buf, ntohl(req.len), err, -1, "Could not read data: %s", strerror(errno));
305         if(rep.error) {
306                 printf("Received expected error\n");
307                 got_err=true;
308         } else {
309                 printf("OK\n");
310                 got_err=false;
311         }
312         /* ... unless this works, too */
313         i++; req.from=htonll(i);
314         req.len = htonl(ntohl(req.len) << 1);
315         WRITE_ALL_ERR_RT(sock, &req, sizeof(req), err, -1, "Could not write request: %s", strerror(errno));
316         printf("%d: testing oversized request: %d: ", getpid(), ntohl(req.len));
317         READ_ALL_ERR_RT(sock, &rep, sizeof(struct nbd_reply), err, -1, "Could not read reply header: %s", strerror(errno));
318         READ_ALL_ERR_RT(sock, &buf, ntohl(req.len), err, -1, "Could not read data: %s", strerror(errno));
319         if(rep.error) {
320                 printf("error\n");
321         } else {
322                 printf("OK\n");
323         }
324         if((rep.error && !got_err) || (!rep.error && got_err)) {
325                 printf("Received unexpected error\n");
326                 retval=-1;
327         }
328   err:
329         return retval;
330 }
331
332 int throughput_test(gchar* hostname, int port, char* name, int sock,
333                     char sock_is_open, char close_sock, int testflags) {
334         long long int i;
335         char buf[1024];
336         char writebuf[1024];
337         struct nbd_request req;
338         int requests=0;
339         fd_set set;
340         struct timeval tv;
341         struct timeval start;
342         struct timeval stop;
343         double timespan;
344         double speed;
345         char speedchar[2] = { '\0', '\0' };
346         int retval=0;
347         size_t tmp;
348         signed int do_write=TRUE;
349         pid_t mypid = getpid();
350
351         memset (writebuf, 'X', sizeof(1024));
352         size=0;
353         if(!sock_is_open) {
354                 if((sock=setup_connection(hostname, port, name, CONNECTION_TYPE_FULL))<0) {
355                         g_warning("Could not open socket: %s", errstr);
356                         retval=-1;
357                         goto err;
358                 }
359         }
360         req.magic=htonl(NBD_REQUEST_MAGIC);
361         req.type=htonl((testflags & TEST_WRITE)?NBD_CMD_WRITE:NBD_CMD_READ);
362         req.len=htonl(1024);
363         if(gettimeofday(&start, NULL)<0) {
364                 retval=-1;
365                 snprintf(errstr, errstr_len, "Could not measure start time: %s", strerror(errno));
366                 goto err_open;
367         }
368         for(i=0;i+1024<=size;i+=1024) {
369                 if(do_write) {
370                         memcpy(&(req.handle),&i,sizeof(i));
371                         req.from=htonll(i);
372                         if (write_all(sock, &req, sizeof(req)) <0) {
373                                 retval=-1;
374                                 goto err_open;
375                         }
376                         if (testflags & TEST_WRITE) {
377                                 if (write_all(sock, writebuf, 1024) <0) {
378                                         retval=-1;
379                                         goto err_open;
380                                 }
381                         }
382                         printf("%d: Requests(+): %d\n", (int)mypid, ++requests);
383                 }
384                 do {
385                         FD_ZERO(&set);
386                         FD_SET(sock, &set);
387                         tv.tv_sec=0;
388                         tv.tv_usec=0;
389                         select(sock+1, &set, NULL, NULL, &tv);
390                         if(FD_ISSET(sock, &set)) {
391                                 /* Okay, there's something ready for
392                                  * reading here */
393                                 if(read_packet_check_header(sock, (testflags & TEST_WRITE)?0:1024, i)<0) {
394                                         retval=-1;
395                                         goto err_open;
396                                 }
397                                 printf("%d: Requests(-): %d\n", (int)mypid, --requests);
398                         }
399                 } while FD_ISSET(sock, &set);
400                 /* Now wait until we can write again or until a second have
401                  * passed, whichever comes first*/
402                 FD_ZERO(&set);
403                 FD_SET(sock, &set);
404                 tv.tv_sec=1;
405                 tv.tv_usec=0;
406                 do_write=select(sock+1,NULL,&set,NULL,&tv);
407                 if(!do_write) printf("Select finished\n");
408                 if(do_write<0) {
409                         snprintf(errstr, errstr_len, "select: %s", strerror(errno));
410                         retval=-1;
411                         goto err_open;
412                 }
413         }
414         /* Now empty the read buffer */
415         do {
416                 FD_ZERO(&set);
417                 FD_SET(sock, &set);
418                 tv.tv_sec=0;
419                 tv.tv_usec=0;
420                 select(sock+1, &set, NULL, NULL, &tv);
421                 if(FD_ISSET(sock, &set)) {
422                         /* Okay, there's something ready for
423                          * reading here */
424                         read_packet_check_header(sock, (testflags & TEST_WRITE)?0:1024, i);
425                         printf("%d: Requests(-): %d\n", (int)mypid, --requests);
426                 }
427         } while (requests);
428         if(gettimeofday(&stop, NULL)<0) {
429                 retval=-1;
430                 snprintf(errstr, errstr_len, "Could not measure end time: %s", strerror(errno));
431                 goto err_open;
432         }
433         timespan=timeval_diff_to_double(&stop, &start);
434         speed=size/timespan;
435         if(speed>1024) {
436                 speed=speed/1024.0;
437                 speedchar[0]='K';
438         }
439         if(speed>1024) {
440                 speed=speed/1024.0;
441                 speedchar[0]='M';
442         }
443         if(speed>1024) {
444                 speed=speed/1024.0;
445                 speedchar[0]='G';
446         }
447         g_message("%d: Throughput %s test complete. Took %.3f seconds to complete, %.3f%sib/s", (int)getpid(), (testflags & TEST_WRITE)?"write":"read", timespan, speed, speedchar);
448
449 err_open:
450         if(close_sock) {
451                 close_connection(sock, CONNECTION_CLOSE_PROPERLY);
452         }
453 err:
454         return retval;
455 }
456
457 typedef int (*testfunc)(gchar*, int, char*, int, char, char, int);
458
459 int main(int argc, char**argv) {
460         gchar *hostname;
461         long int p = 0;
462         char* name = NULL;
463         int sock=0;
464         int c;
465         bool want_port = TRUE;
466         int nonopt=0;
467         int testflags=0;
468         testfunc test = throughput_test;
469
470         if(argc<3) {
471                 g_message("%d: Not enough arguments", (int)getpid());
472                 g_message("%d: Usage: %s <hostname> <port>", (int)getpid(), argv[0]);
473                 g_message("%d: Or: %s <hostname> -N <exportname>", (int)getpid(), argv[0]);
474                 exit(EXIT_FAILURE);
475         }
476         logging();
477         while((c=getopt(argc, argv, "-N:owf"))>=0) {
478                 switch(c) {
479                         case 1:
480                                 switch(nonopt) {
481                                         case 0:
482                                                 hostname=g_strdup(optarg);
483                                                 nonopt++;
484                                                 break;
485                                         case 1:
486                                                 if(want_port)
487                                                 p=(strtol(argv[2], NULL, 0));
488                                                 if(p==LONG_MIN||p==LONG_MAX) {
489                                                         g_critical("Could not parse port number: %s", strerror(errno));
490                                                         exit(EXIT_FAILURE);
491                                                 }
492                                                 break;
493                                 }
494                                 break;
495                         case 'N':
496                                 name=g_strdup(optarg);
497                                 p = 10809;
498                                 want_port = false;
499                                 break;
500                         case 'o':
501                                 test=oversize_test;
502                                 break;
503                         case 'w':
504                                 testflags|=TEST_WRITE;
505                                 break;
506                         case 'f':
507                                 testflags|=TEST_FLUSH;
508                                 break;
509                 }
510         }
511
512         if(test(hostname, (int)p, name, sock, FALSE, TRUE, testflags)<0) {
513                 g_warning("Could not run test: %s", errstr);
514                 exit(EXIT_FAILURE);
515         }
516
517         return 0;
518 }