02323531d191e62744c9e2f38e776248c29a7abc
[ftsbench.git] / ftsbench.c
1 /*
2  * Copyright (c) 2006 Teodor Sigaev <teodor@sigaev.ru>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *        notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *        notice, this list of conditions and the following disclaimer in the
12  *        documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the author nor the names of any co-contributors
14  *        may be used to endorse or promote products derived from this software
15  *        without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
23  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
26  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <sys/time.h>
36 #include <stdarg.h>
37
38 #include "ftsbench.h"
39
40 typedef enum RDBMS {
41         PostgreSQL = 0,
42         MySQL = 1,
43         NULLSQL
44 } RDBMS;
45
46 typedef struct RDBMSDesc {
47         RDBMS   rdbms;
48         char    *shortname;
49         char    *longname;
50         ftsDB*  (*init)(char *);
51 } RDBMSDesc;
52
53 static RDBMSDesc DBDesc[] = {
54         { PostgreSQL, "pgsql", "PostgreSQL", PGInit }, 
55         { MySQL,          "mysql", "MySQL",      MYInit },
56         { NULLSQL,        NULL,    NULL,         NULL   }
57 };
58
59 static void
60 usage() {
61         char buf[1024];
62         int i, first=0;
63
64         *buf = '\0';
65         for(i=0; DBDesc[i].rdbms != NULLSQL; i++) {
66                 if ( DBDesc[i].init == NULL )
67                         continue;
68                 if ( first != 0 )
69                         strcat(buf, ", ");
70                 strcat(buf, DBDesc[i].shortname);
71                 if ( first == 0 ) 
72                         strcat(buf, "(default)");
73                 first++;
74         }
75
76         fputs(
77                 "Copyright (c) 2006 Teodor Sigaev <teodor@sigaev.ru>. All rights reserved.\n"
78                 "ftsbench - full text search benchmark for RDBMS\n"
79                 "Initialization of DB:\n"
80                 "ftsbench -i [-b RDBMS] [-n NUMROW] [-l LEXFILE] [-g GAMMAFILE] [-f FLAGS] [-q | -s ID] -d DBNAME\n"
81                 "  -b RDBMS\t- type of DB: ",
82                 stdout
83         );
84         fputs( buf, stdout );
85         fputs(
86                 "\n"
87                 "  -n NUMROW - number of row in table\n"
88                 "  -l LEXFILE - file with words and its frequents (default gendata/lex)\n"
89                 "  -g GAMMAFILE - file with doc's length distribution (default \n"
90                 "                 gendata/gamma-lens)\n"
91                 "  -l FLGAS - options for db's schema (see below)\n"
92                 "  -s ID - SQL mode: output is a SQL queries, ID is an identifier for insert\n"
93                 "          statement\n"
94                 "  -q - do not print progress message\n",
95                 stdout
96         );
97         fputs(
98                 "Run tests:\n"
99                 "ftsbench [-b RDBMS] [-c NCLIENTS] [-n NUMQUERY] [-l LEXFILE] [-g GAMMAFILE] [-f FLAGS] [-q | -s ID [-r]] -d DBNAME\n"
100                 "  -b RDBMS\t- type of DB: ",
101                 stdout
102         );
103         fputs( buf, stdout );
104         fputs(
105                 "\n"
106                 "  -c NCLIENTS - number of clients in parallel\n"
107                 "  -n NUMQUERY - number of queries per client\n"
108                 "  -l LEXFILE - file with words and its frequents (default gendata/query-lex)\n"
109                 "  -g GAMMAFILE - file with doc's length distribution (default \n"
110                 "                 gendata/query-lens)\n"
111                 "  -l FLGAS - options for db's schema (see below)\n"
112                 "  -s ID - SQL mode: output is a SQL queries, ID is an identifier for insert\n"
113                 "          statement\n"
114                 "  -r - row mode: timing every query\n"
115                 "  -q - do not print progress message\n",
116                 stdout
117         );
118         fputs(
119                 "FLAGS are comma-separate list of:\n"
120                 "  gin  - use GIN index\n"
121                 "  gist - use GiST index\n"
122                 "  func - use functional index\n"
123                 "  and  - AND'ing lexemes in query (default)\n"
124                 "  or   - OR'ing lexemes in query\n",
125                 stdout
126         );
127         fputs(
128                 "Print SQL-scheme for statistics:\n"
129                 "ftsbench -S\n",
130                 stdout
131         );
132         exit(1);
133 }
134
135 static RDBMS
136 getRDBMS(char *name) {
137         int     i;
138
139         for(i=0; DBDesc[i].rdbms != NULLSQL; i++) {
140                 if ( name == NULL ) {
141                         if ( DBDesc[i].init )
142                                 return DBDesc[i].rdbms; 
143                 } else if ( strcasecmp(name,DBDesc[i].shortname) == 0 ) {
144                         if ( DBDesc[i].init == NULL ) {
145                                 fprintf(stderr,"Support of '%s' isn't compiled-in\n", DBDesc[i].longname);
146                                 exit(1);
147                         }
148                         return DBDesc[i].rdbms;
149                 }
150         }
151
152         fprintf(stderr,"Can't find a RDBMS\n");
153         exit(1);
154         
155         return NULLSQL;
156 }
157
158 static int
159 getFLAGS(char *flg) {
160         int flags = 0;
161
162         if ( strcasestr(flg,"gist") )
163                 flags |= FLG_GIST;
164         if ( strcasestr(flg,"gin") )
165                 flags |= FLG_GIN;
166         if ( strcasestr(flg,"func") )
167                 flags |= FLG_FUNC;
168         if ( strcasestr(flg,"and") )
169                 flags |= FLG_AND;
170         if ( strcasestr(flg,"or") )
171                 flags |= FLG_OR;
172
173         if ( (flags & FLG_GIST) && (flags & FLG_GIN) ) {
174                 fprintf(stderr,"GIN and GiST flags are mutually exclusive\n");
175                 exit(1);
176         }
177         if ( (flags & FLG_AND) && (flags & FLG_OR) ) {
178                 fprintf(stderr,"AND and OR flags are mutually exclusive\n");
179                 exit(1);
180         } else if ( ( flags & ( FLG_AND | FLG_OR ) ) == 0 )
181                 flags |= FLG_AND;
182
183         return flags;
184 }
185
186 static ftsDB **
187 initConnections(RDBMS rdbms, int n, char *connstr) {
188         ftsDB   **dbs = (ftsDB**)malloc(sizeof(ftsDB*) * n);
189         int i;
190
191         if (!dbs) {
192                 fprintf(stderr,"Not enough mwmory\n");
193                 exit(1);
194         }
195
196         for(i=0;i<n;i++) { 
197                 dbs[i] = DBDesc[rdbms].init(connstr);
198                 pthread_mutex_init(&dbs[i]->nqueryMutex, NULL);
199         }
200
201         return dbs;
202 }
203
204 static double
205 timediff(struct timeval *begin, struct timeval *end) {
206     return ((double)( end->tv_sec - begin->tv_sec )) + ( (double)( end->tv_usec-begin->tv_usec ) ) / 1.0e+6;
207 }
208
209 static double
210 elapsedtime(struct timeval *begin) {
211     struct timeval end;
212         gettimeofday(&end,NULL);
213         return timediff(begin,&end);
214 }
215
216 static int Id = 0;
217 static int sqlMode = 0;
218 static int rowMode = 0;
219 static int benchFlags  = 0;
220 static int benchCount  = 0;
221 static int nClients  = 0;
222 static pthread_cond_t condFinish = PTHREAD_COND_INITIALIZER;
223 static pthread_mutex_t mutexFinish = PTHREAD_MUTEX_INITIALIZER;
224 static pthread_mutex_t mutexWordGen = PTHREAD_MUTEX_INITIALIZER;
225
226 /*
227  * main test function, executed in thread
228  */
229 static void*
230 execBench(void *in) {
231         ftsDB *db = (ftsDB*)in;
232         int i, nres=0;
233         char **words;
234         struct  timeval begin;
235         double  elapsed;
236
237         for(i=0;i<benchCount;i++) {
238                 /*
239                  * generate_querywords() isn't a thread safe
240                  */
241                 pthread_mutex_lock( &mutexWordGen );
242                 words = generate_querywords();
243                 pthread_mutex_unlock( &mutexWordGen );
244                 
245                 if ( rowMode ) 
246                         gettimeofday(&begin,NULL);
247
248                 db->execQuery(db, words, benchFlags);
249
250                 if ( rowMode ) {
251                         elapsed = elapsedtime(&begin);
252                         printf("INSERT INTO fb_row (id, f_and, f_or, nclients, nres, elapsed) VALUES (%d, '%c', '%c', %d, %d, %g);\n",
253                                         Id,
254                                         ( benchFlags & FLG_AND ) ? 't' : 'f',
255                                         ( benchFlags & FLG_OR ) ? 't' : 'f',
256                                         nClients,
257                                         db->nres - nres,
258                                         elapsed
259                         );
260                         nres = db->nres;
261                 }
262                 free(words);
263         }
264
265         /*
266          * send message about exitting
267          */
268     pthread_mutex_lock( &mutexFinish );
269         pthread_cond_broadcast( &condFinish );
270         pthread_mutex_unlock( &mutexFinish );
271
272         return NULL;    
273 }
274
275 void
276 report(const char *format, ...) {
277         va_list args;
278
279         if (benchFlags & FLG_SQL)
280                 return;
281
282         va_start(args, format);
283         vfprintf(stdout, format, args);
284         va_end(args);
285
286         fflush(stdout);
287 }
288
289 extern char *optarg;
290
291 int
292 main(int argn, char *argv[]) {
293         int             initMode = 0;
294         int             n = 0;
295         char    *lex = NULL;
296         char    *doc = NULL;
297         char    *dbname = NULL;
298         RDBMS   rdbms = NULLSQL;
299         int             flags = 0;
300         int     i;
301         int             quiet = 0, scheme=0;
302         StringBuf       b = {NULL,0,0};
303         struct  timeval begin;
304         double  elapsed;
305
306         while((i=getopt(argn,argv,"ib:n:l:g:d:c:hf:qSs:r")) != EOF) {
307                 switch(i) {
308                         case 'i': initMode = 1; break;
309                         case 'b': rdbms = getRDBMS(optarg); break;
310                         case 'n': n=atoi(optarg); break;
311                         case 'c': nClients=atoi(optarg); break;
312                         case 'l': lex = strdup(optarg); break;
313                         case 'g': doc = strdup(optarg); break;
314                         case 'd': dbname = strdup(optarg); break;
315                         case 'f': flags = getFLAGS(optarg); break;
316                         case 'q': quiet = 1; break;
317                         case 'S': scheme = 1; break;
318                         case 's': sqlMode = 1; Id = atoi(optarg); break;
319                         case 'r': rowMode = 1; break;
320                         case 'h':
321                         default:
322                                 usage();
323                 }
324         }
325
326         if ( scheme ) {
327                 printScheme();
328                 return 0;
329         }
330
331         if (rdbms == NULLSQL)
332                 rdbms = getRDBMS(NULL);
333
334         if ( dbname == NULL || n<0 || (initMode == 0 && nClients<1) ) 
335                 usage();
336
337         if ( sqlMode ) {
338                 quiet = 1;
339                 flags |= FLG_SQL;
340         } else
341                 rowMode = 0;
342
343         benchFlags = flags;
344         benchCount = n;
345
346         report("Running with '%s' RDBMS\n", DBDesc[ rdbms ].longname); 
347
348         if ( initMode ) {
349                 ftsDB   *db = *initConnections(rdbms, 1, dbname);
350                 time_t  prev;
351
352                 if (!lex)  lex = "gendata/lex";
353                 if (!doc)  doc = "gendata/gamma-lens";
354                 finnegan_init(lex, doc, sqlMode);
355
356                 gettimeofday(&begin,NULL);
357
358                 db->startCreateScheme(db, flags);
359                 prev = time(NULL);
360                 for(i=0;i<n;i++) {
361                         generate_doc(&b);
362                         db->InsertRow(db, i+1, b.str);
363                         if ( !quiet && prev!=time(NULL) ) {
364                                 report("\r%d(%.02f%%) rows inserted", i, (100.0*i)/n);
365                                 prev = time(NULL);
366                         }
367                 }
368
369                 report("%s%d(100.00%%) rows inserted. Finalyze insertion... ", 
370                         (quiet) ? "" : "\r", i);
371                 db->finishCreateScheme(db);
372                 elapsed = elapsedtime(&begin);
373
374                 report("done\nTime: %.02f secs\n", elapsed);
375                 if (sqlMode) {
376                         printf("INSERT INTO fb_create (id, rdbms, f_gin, f_gist, f_func, rows, elapsed) VALUES (%d, '%s', '%c', '%c', '%c', %d, %g);\n",
377                                         Id,
378                                         DBDesc[ rdbms ].shortname,
379                                         ( flags & FLG_GIN ) ? 't' : 'f',
380                                         ( flags & FLG_GIST ) ? 't' : 'f',
381                                         ( flags & FLG_FUNC ) ? 't' : 'f',
382                                         n,
383                                         elapsed
384                         );
385                 }
386                 db->Close(db);
387         } else {
388                 ftsDB   **dbs = initConnections(rdbms, nClients, dbname);
389                 pthread_t       *tid = (pthread_t*)malloc( sizeof(pthread_t) * nClients);
390                 struct  timeval begin;
391                 int     total=0, nres=0;
392                 struct      timespec  sleepTo = { 0, 0 };
393
394                 /*
395                  * startup generator
396                  */
397                 if (!lex)  lex = "gendata/query-lex";
398                 if (!doc)  doc = "gendata/query-lens";
399                 finnegan_init(lex, doc, sqlMode);
400
401                 /*
402                  * Initial query
403                  */
404                 if ( !quiet ) 
405                         report("\r0(0.00%%) queries proceed");
406
407                 gettimeofday(&begin,NULL);
408
409         pthread_mutex_lock( &mutexFinish );
410                 for(i=0;i<nClients;i++) {
411                         if ( pthread_create(tid+i, NULL, execBench, (void*)dbs[i]) != 0 ) {
412                                 fprintf(stderr,"pthread_create failed: %s\n", strerror(errno));
413                                 exit(1);
414                         }
415                 }
416
417                 for(;;) {
418                         int res, ntogo = 0;
419
420                         total = 0;
421                         for(i=0;i<nClients;i++) {
422                                 pthread_mutex_lock(&dbs[i]->nqueryMutex);
423                                 total +=dbs[i]->nquery;
424                                 if ( dbs[i]->nquery < n )
425                                         ntogo++;
426                                 pthread_mutex_unlock(&dbs[i]->nqueryMutex);
427                         }
428
429                         if ( ntogo == 0 ) 
430                                 break;
431
432                         if ( !quiet ) 
433                                 report("\r%d(%.02f%%) queries proceed", total, (100.0*(float)total)/(nClients * n));
434                         
435                         sleepTo.tv_sec = time(NULL) + 1;
436                         res = pthread_cond_timedwait( &condFinish, &mutexFinish, &sleepTo );
437
438                         if ( !(res == ETIMEDOUT || res == 0) ) {
439                                 fprintf(stderr,"pthread_cond_timedwait failed: %s\n", strerror(errno));
440                                 exit(1);
441                         }
442                 }
443                 elapsed = elapsedtime(&begin);
444                 pthread_mutex_unlock( &mutexFinish );
445
446                 for(i=0;i<nClients;i++) {
447                         pthread_join(tid[i], NULL);
448                         nres += dbs[i]->nres;
449                         dbs[i]->Close(dbs[i]);
450                 }
451
452                 report("%s%d(%.02f%%) queries proceed\n", 
453                         (quiet) ? "" : "\r", total, (100.0*(float)total)/(nClients * n));
454                 report("Total number of result: %d\n", nres);
455                 report("Total time: %.02f sec, Queries per second: %.02f\n", elapsed, total/elapsed);
456                 if (sqlMode && !rowMode) {
457                         printf("INSERT INTO fb_search (id, f_and, f_or, nclients, nqueries, nres, elapsed) VALUES (%d, '%c', '%c', %d, %d, %d, %g);\n",
458                                         Id,
459                                         ( flags & FLG_AND ) ? 't' : 'f',
460                                         ( flags & FLG_OR ) ? 't' : 'f',
461                                         nClients,
462                                         n,
463                                         nres,
464                                         elapsed
465                         );
466                 }
467         }
468
469         return 0;
470 }