add .gitignore
[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 FLAGS - 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 FLAGS - 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                                 fatal("Support of '%s' isn't compiled-in\n", DBDesc[i].longname);
146
147                         return DBDesc[i].rdbms;
148                 }
149         }
150
151         fatal("Can't find a RDBMS\n");
152         
153         return NULLSQL;
154 }
155
156 static int
157 getFLAGS(char *flg) {
158         int flags = 0;
159
160         if ( strcasestr(flg,"gist") )
161                 flags |= FLG_GIST;
162         if ( strcasestr(flg,"gin") )
163                 flags |= FLG_GIN;
164         if ( strcasestr(flg,"func") )
165                 flags |= FLG_FUNC;
166         if ( strcasestr(flg,"and") )
167                 flags |= FLG_AND;
168         if ( strcasestr(flg,"or") )
169                 flags |= FLG_OR;
170
171         if ( (flags & FLG_GIST) && (flags & FLG_GIN) ) 
172                 fatal("GIN and GiST flags are mutually exclusive\n");
173         if ( (flags & FLG_AND) && (flags & FLG_OR) ) 
174                 fatal("AND and OR flags are mutually exclusive\n");
175         else if ( ( flags & ( FLG_AND | FLG_OR ) ) == 0 )
176                 flags |= FLG_AND;
177
178         return flags;
179 }
180
181 static ftsDB **
182 initConnections(RDBMS rdbms, int n, char *connstr) {
183         ftsDB   **dbs = (ftsDB**)malloc(sizeof(ftsDB*) * n);
184         int i;
185
186         if (!dbs) 
187                 fatal("Not enough mwmory\n");
188
189         for(i=0;i<n;i++) { 
190                 dbs[i] = DBDesc[rdbms].init(connstr);
191                 pthread_mutex_init(&dbs[i]->nqueryMutex, NULL);
192         }
193
194         return dbs;
195 }
196
197 static double
198 timediff(struct timeval *begin, struct timeval *end) {
199     return ((double)( end->tv_sec - begin->tv_sec )) + ( (double)( end->tv_usec-begin->tv_usec ) ) / 1.0e+6;
200 }
201
202 static double
203 elapsedtime(struct timeval *begin) {
204     struct timeval end;
205         gettimeofday(&end,NULL);
206         return timediff(begin,&end);
207 }
208
209 static int Id = 0;
210 static int sqlMode = 0;
211 static int rowMode = 0;
212 static int benchFlags  = 0;
213 static int benchCount  = 0;
214 static int nClients  = 0;
215 static pthread_cond_t condFinish = PTHREAD_COND_INITIALIZER;
216 static pthread_mutex_t mutexFinish = PTHREAD_MUTEX_INITIALIZER;
217 static pthread_mutex_t mutexWordGen = PTHREAD_MUTEX_INITIALIZER;
218
219 static void
220 printQueryWords(StringBuf *b, char **words) {
221         char **wptr = words, *ptr;
222
223         b->strlen = 0;
224         while(*wptr) {
225                 if ( wptr != words ) 
226                         sb_add(b, " ", 1);
227
228                 ptr = *wptr;
229                 while( *ptr ) {
230                         if ( *ptr == '\'' )
231                                 sb_add( b, "'", 1 );
232                         sb_add( b, ptr, 1 );
233                         ptr++;
234                 }
235
236                 wptr++;
237         }
238 }
239
240 /*
241  * main test function, executed in thread
242  */
243 static void*
244 execBench(void *in) {
245         ftsDB *db = (ftsDB*)in;
246         int i, nres=0;
247         char **words;
248         struct  timeval begin;
249         double  elapsed;
250         StringBuf       b = {NULL,0,0};
251
252         for(i=0;i<benchCount;i++) {
253                 /*
254                  * generate_querywords() isn't a thread safe
255                  */
256                 pthread_mutex_lock( &mutexWordGen );
257                 words = generate_querywords();
258                 pthread_mutex_unlock( &mutexWordGen );
259                 
260                 if ( rowMode ) 
261                         gettimeofday(&begin,NULL);
262
263                 db->execQuery(db, words, benchFlags);
264
265                 if ( rowMode ) {
266                         elapsed = elapsedtime(&begin);
267                         printQueryWords(&b, words);
268
269                         printf("INSERT INTO fb_row (id, f_and, f_or, nclients, query, nres, elapsed) VALUES (%d, '%c', '%c', %d, '%s', %d, %g);\n",
270                                         Id,
271                                         ( benchFlags & FLG_AND ) ? 't' : 'f',
272                                         ( benchFlags & FLG_OR ) ? 't' : 'f',
273                                         nClients,
274                                         b.str,
275                                         db->nres - nres,
276                                         elapsed
277                         );
278                         nres = db->nres;
279                 }
280                 free(words);
281         }
282
283         /*
284          * send message about exitting
285          */
286     pthread_mutex_lock( &mutexFinish );
287         pthread_cond_broadcast( &condFinish );
288         pthread_mutex_unlock( &mutexFinish );
289
290         return NULL;    
291 }
292
293 void
294 report(const char *format, ...) {
295         va_list args;
296
297         if (sqlMode)
298                 return;
299
300         va_start(args, format);
301         vfprintf(stdout, format, args);
302         va_end(args);
303
304         fflush(stdout);
305 }
306
307 void
308 fatal(const char *format, ...) {
309         va_list args;
310
311         va_start(args, format);
312         vfprintf(stderr, format, args);
313         va_end(args);
314
315         fflush(stderr);
316
317         exit(1);
318 }
319
320
321 extern char *optarg;
322
323 int
324 main(int argn, char *argv[]) {
325         int             initMode = 0;
326         int             n = 0;
327         char    *lex = NULL;
328         char    *doc = NULL;
329         char    *dbname = NULL;
330         RDBMS   rdbms = NULLSQL;
331         int             flags = 0;
332         int     i;
333         int             quiet = 0, scheme=0;
334         StringBuf       b = {NULL,0,0};
335         struct  timeval begin;
336         double  elapsed;
337
338         while((i=getopt(argn,argv,"ib:n:l:g:d:c:hf:qSs:r")) != EOF) {
339                 switch(i) {
340                         case 'i': initMode = 1; break;
341                         case 'b': rdbms = getRDBMS(optarg); break;
342                         case 'n': n=atoi(optarg); break;
343                         case 'c': nClients=atoi(optarg); break;
344                         case 'l': lex = strdup(optarg); break;
345                         case 'g': doc = strdup(optarg); break;
346                         case 'd': dbname = strdup(optarg); break;
347                         case 'f': flags = getFLAGS(optarg); break;
348                         case 'q': quiet = 1; break;
349                         case 'S': scheme = 1; break;
350                         case 's': sqlMode = 1; Id = atoi(optarg); break;
351                         case 'r': rowMode = 1; break;
352                         case 'h':
353                         default:
354                                 usage();
355                 }
356         }
357
358         if ( scheme ) {
359                 printScheme();
360                 return 0;
361         }
362
363         if (rdbms == NULLSQL)
364                 rdbms = getRDBMS(NULL);
365
366         if ( dbname == NULL || n<0 || (initMode == 0 && nClients<1) ) 
367                 usage();
368
369         if ( sqlMode ) 
370                 quiet = 1;
371         else
372                 rowMode = 0;
373
374         benchFlags = flags;
375         benchCount = n;
376
377         report("Running with '%s' RDBMS\n", DBDesc[ rdbms ].longname); 
378
379         if ( initMode ) {
380                 ftsDB   *db = *initConnections(rdbms, 1, dbname);
381                 time_t  prev;
382
383                 if (!lex)  lex = "gendata/lex";
384                 if (!doc)  doc = "gendata/gamma-lens";
385                 finnegan_init(lex, doc, sqlMode);
386
387                 gettimeofday(&begin,NULL);
388
389                 db->startCreateScheme(db, flags);
390                 prev = time(NULL);
391                 for(i=0;i<n;i++) {
392                         generate_doc(&b);
393                         db->InsertRow(db, i+1, b.str);
394                         if ( !quiet && prev!=time(NULL) ) {
395                                 report("\r%d(%.02f%%) rows inserted", i, (100.0*i)/n);
396                                 prev = time(NULL);
397                         }
398                 }
399
400                 report("%s%d(100.00%%) rows inserted. Finalyze insertion... ", 
401                         (quiet) ? "" : "\r", i);
402                 db->finishCreateScheme(db);
403                 elapsed = elapsedtime(&begin);
404
405                 report("done\nTime: %.02f secs\n", elapsed);
406                 if (sqlMode) {
407                         printf("INSERT INTO fb_create (id, rdbms, f_gin, f_gist, f_func, rows, elapsed) VALUES (%d, '%s', '%c', '%c', '%c', %d, %g);\n",
408                                         Id,
409                                         DBDesc[ rdbms ].shortname,
410                                         ( flags & FLG_GIN ) ? 't' : 'f',
411                                         ( flags & FLG_GIST ) ? 't' : 'f',
412                                         ( flags & FLG_FUNC ) ? 't' : 'f',
413                                         n,
414                                         elapsed
415                         );
416                 }
417                 db->Close(db);
418         } else {
419                 ftsDB   **dbs = initConnections(rdbms, nClients, dbname);
420                 pthread_t       *tid = (pthread_t*)malloc( sizeof(pthread_t) * nClients);
421                 struct  timeval begin;
422                 int     total=0, nres=0;
423                 struct      timespec  sleepTo = { 0, 0 };
424
425                 /*
426                  * startup generator
427                  */
428                 if (!lex)  lex = "gendata/query-lex";
429                 if (!doc)  doc = "gendata/query-lens";
430                 finnegan_init(lex, doc, sqlMode);
431
432                 /*
433                  * Initial query
434                  */
435                 if ( !quiet ) 
436                         report("\r0(0.00%%) queries proceed");
437
438                 gettimeofday(&begin,NULL);
439
440         pthread_mutex_lock( &mutexFinish );
441                 for(i=0;i<nClients;i++) {
442                         if ( pthread_create(tid+i, NULL, execBench, (void*)dbs[i]) != 0 ) 
443                                 fatal("pthread_create failed: %s\n", strerror(errno));
444                 }
445
446                 for(;;) {
447                         int res, ntogo = 0;
448
449                         total = 0;
450                         for(i=0;i<nClients;i++) {
451                                 pthread_mutex_lock(&dbs[i]->nqueryMutex);
452                                 total +=dbs[i]->nquery;
453                                 if ( dbs[i]->nquery < n )
454                                         ntogo++;
455                                 pthread_mutex_unlock(&dbs[i]->nqueryMutex);
456                         }
457
458                         if ( ntogo == 0 ) 
459                                 break;
460
461                         if ( !quiet ) 
462                                 report("\r%d(%.02f%%) queries proceed", total, (100.0*(float)total)/(nClients * n));
463                         
464                         sleepTo.tv_sec = time(NULL) + 1;
465                         res = pthread_cond_timedwait( &condFinish, &mutexFinish, &sleepTo );
466
467                         if ( !(res == ETIMEDOUT || res == 0) ) 
468                                 fatal("pthread_cond_timedwait failed: %s\n", strerror(errno));
469                 }
470                 elapsed = elapsedtime(&begin);
471                 pthread_mutex_unlock( &mutexFinish );
472
473                 for(i=0;i<nClients;i++) {
474                         pthread_join(tid[i], NULL);
475                         nres += dbs[i]->nres;
476                         dbs[i]->Close(dbs[i]);
477                 }
478
479                 report("%s%d(%.02f%%) queries proceed\n", 
480                         (quiet) ? "" : "\r", total, (100.0*(float)total)/(nClients * n));
481                 report("Total number of result: %d\n", nres);
482                 report("Total time: %.02f sec, Queries per second: %.02f\n", elapsed, total/elapsed);
483                 if (sqlMode && !rowMode) {
484                         printf("INSERT INTO fb_search (id, f_and, f_or, nclients, nqueries, nres, elapsed) VALUES (%d, '%c', '%c', %d, %d, %d, %g);\n",
485                                         Id,
486                                         ( flags & FLG_AND ) ? 't' : 'f',
487                                         ( flags & FLG_OR ) ? 't' : 'f',
488                                         nClients,
489                                         n,
490                                         nres,
491                                         elapsed
492                         );
493                 }
494         }
495
496         return 0;
497 }