a0ef1f37eeeb0f9728f08ff6bd5f0d0cf480ee96
[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
37 #include "ftsbench.h"
38
39 typedef enum RDBMS {
40         PostgreSQL = 0,
41         MySQL = 1,
42         NULLSQL
43 } RDBMS;
44
45 typedef struct RDBMSDesc {
46         RDBMS   rdbms;
47         char    *shortname;
48         char    *longname;
49         ftsDB*  (*init)(char *);
50 } RDBMSDesc;
51
52 static RDBMSDesc DBDesc[] = {
53         { PostgreSQL, "pgsql", "PostgreSQL", PGInit }, 
54         { MySQL,          "mysql", "MySQL",      MYInit },
55         { NULLSQL,        NULL,    NULL,         NULL   }
56 };
57
58 static void
59 usage() {
60         char buf[1024];
61         int i, first=0;
62
63         *buf = '\0';
64         for(i=0; DBDesc[i].rdbms != NULLSQL; i++) {
65                 if ( DBDesc[i].init == NULL )
66                         continue;
67                 if ( first != 0 )
68                         strcat(buf, ", ");
69                 strcat(buf, DBDesc[i].shortname);
70                 if ( first == 0 ) 
71                         strcat(buf, "(default)");
72                 first++;
73         }
74
75         fputs(
76                 "Copyright (c) 2006 Teodor Sigaev <teodor@sigaev.ru>. All rights reserved.\n"
77                 "ftsbench - full text search benchmark for RDBMS\n"
78                 "Initialization of DB:\n"
79                 "ftsbench -i [-b RDBMS] [-n NUMROW] [-l LEXFILE] [-g GAMMAFILE] [-f FLAGS] [-q] -d DBNAME\n"
80                 "  -b RDBMS\t- type of DB: ",
81                 stdout
82         );
83         fputs( buf, stdout );
84         fputs(
85                 "\n"
86                 "  -n NUMROW - number of row in table\n"
87                 "  -l LEXFILE - file with words and its frequents (default gendata/lex)\n"
88                 "  -g GAMMAFILE - file with doc's length distribution (default gendata/gamma-lens)\n"
89                 "  -l FLGAS - options for db's schema (see below)\n"
90                 "  -q - do not print progress message\n",
91                 stdout
92         );
93         fputs(
94                 "Run tests:\n"
95                 "ftsbench [-b RDBMS] [-c NCLIENTS] [-n NUMQUERY] [-l LEXFILE] [-g GAMMAFILE] [-f FLAGS] [-q] -d DBNAME\n"
96                 "  -b RDBMS\t- type of DB: ",
97                 stdout
98         );
99         fputs( buf, stdout );
100         fputs(
101                 "\n"
102                 "  -c NCLIENTS - number of clients in parallel\n"
103                 "  -n NUMQUERY - number of queries per client\n"
104                 "  -l LEXFILE - file with words and its frequents (default gendata/query-lex)\n"
105                 "  -g GAMMAFILE - file with doc's length distribution (default gendata/query-lens)\n"
106                 "  -l FLGAS - options for db's schema (see below)\n"
107                 "  -q - do not print progress message\n",
108                 stdout
109         );
110         fputs(
111                 "FLAGS are comma-separate list of:\n"
112                 "  gin  - use GIN index\n"
113                 "  gist - use GiST index\n"
114                 "  func - use functional index\n"
115                 "  and  - AND'ing lexemes in query (default)\n"
116                 "  or   - OR'ing lexemes in query\n",
117                 stdout
118         );
119         exit(1);
120 }
121
122 static RDBMS
123 getRDBMS(char *name) {
124         int     i;
125
126         for(i=0; DBDesc[i].rdbms != NULLSQL; i++) {
127                 if ( name == NULL ) {
128                         if ( DBDesc[i].init )
129                                 return DBDesc[i].rdbms; 
130                 } else if ( strcasecmp(name,DBDesc[i].shortname) == 0 ) {
131                         if ( DBDesc[i].init == NULL ) {
132                                 fprintf(stderr,"Support of '%s' isn't compiled-in\n", DBDesc[i].longname);
133                                 exit(1);
134                         }
135                         return DBDesc[i].rdbms;
136                 }
137         }
138
139         fprintf(stderr,"Can't find a RDBMS\n");
140         exit(1);
141         
142         return NULLSQL;
143 }
144
145 static int
146 getFLAGS(char *flg) {
147         int flags = 0;
148
149         if ( strcasestr(flg,"gist") )
150                 flags |= FLG_GIST;
151         if ( strcasestr(flg,"gin") )
152                 flags |= FLG_GIN;
153         if ( strcasestr(flg,"func") )
154                 flags |= FLG_FUNC;
155         if ( strcasestr(flg,"and") )
156                 flags |= FLG_AND;
157         if ( strcasestr(flg,"or") )
158                 flags |= FLG_OR;
159
160         if ( (flags & FLG_GIST) && (flags & FLG_GIN) ) {
161                 fprintf(stderr,"GIN and GiST flags are mutually exclusive\n");
162                 exit(1);
163         }
164         if ( (flags & FLG_AND) && (flags & FLG_OR) ) {
165                 fprintf(stderr,"AND and OR flags are mutually exclusive\n");
166                 exit(1);
167         }
168
169         return flags;
170 }
171
172 static ftsDB **
173 initConnections(RDBMS rdbms, int n, char *connstr) {
174         ftsDB   **dbs = (ftsDB**)malloc(sizeof(ftsDB*) * n);
175         int i;
176
177         if (!dbs) {
178                 fprintf(stderr,"Not enough mwmory\n");
179                 exit(1);
180         }
181
182         for(i=0;i<n;i++) { 
183                 dbs[i] = DBDesc[rdbms].init(connstr);
184                 pthread_mutex_init(&dbs[i]->nqueryMutex, NULL);
185         }
186
187         return dbs;
188 }
189
190 static double
191 timediff(struct timeval *begin, struct timeval *end) {
192     return ((double)( end->tv_sec - begin->tv_sec )) + ( (double)( end->tv_usec-begin->tv_usec ) ) / 1.0e+6;
193 }
194
195 static double
196 elapsedtime(struct timeval *begin) {
197     struct timeval end;
198         gettimeofday(&end,NULL);
199         return timediff(begin,&end);
200 }
201
202 static int benchFlags  = 0;
203 static int benchCount  = 0;
204 static pthread_cond_t condFinish = PTHREAD_COND_INITIALIZER;
205 static pthread_mutex_t mutexFinish = PTHREAD_MUTEX_INITIALIZER;
206 static pthread_mutex_t mutexWordGen = PTHREAD_MUTEX_INITIALIZER;
207
208 static void*
209 execBench(void *in) {
210         ftsDB *db = (ftsDB*)in;
211         int i;
212         char **words;
213
214         for(i=0;i<benchCount;i++) {
215                 /*
216                  * generate_querywords() isn't a thread safe
217                  */
218                 pthread_mutex_lock( &mutexWordGen );
219                 words = generate_querywords();
220                 pthread_mutex_unlock( &mutexWordGen );
221
222                 db->execQuery(db, words, benchFlags);
223                 free(words);
224         }
225
226         /*
227          * send message about exitting
228          */
229     pthread_mutex_lock( &mutexFinish );
230         pthread_cond_broadcast( &condFinish );
231         pthread_mutex_unlock( &mutexFinish );
232
233         return NULL;    
234 }
235
236 extern char *optarg;
237
238 int
239 main(int argn, char *argv[]) {
240         int             initMode = 0;
241         int             n = 0, nclients = 1;
242         char    *lex = NULL;
243         char    *doc = NULL;
244         char    *dbname = NULL;
245         RDBMS   rdbms = NULLSQL;
246         int             flags = 0;
247         int i;
248         int             quiet = 0;
249         StringBuf       b = {NULL,0,0};
250
251         while((i=getopt(argn,argv,"ib:n:l:g:d:c:hf:q")) != EOF) {
252                 switch(i) {
253                         case 'i': initMode = 1; break;
254                         case 'b': rdbms = getRDBMS(optarg); break;
255                         case 'n': n=atoi(optarg); break;
256                         case 'c': nclients=atoi(optarg); break;
257                         case 'l': lex = strdup(optarg); break;
258                         case 'g': doc = strdup(optarg); break;
259                         case 'd': dbname = strdup(optarg); break;
260                         case 'f': flags = getFLAGS(optarg); break;
261                         case 'q': quiet = 1; break;
262                         case 'h':
263                         default:
264                                 usage();
265                 }
266         }
267
268         if (rdbms == NULLSQL)
269                 rdbms = getRDBMS(NULL);
270
271         if ( dbname == NULL || n<0 || nclients<1 )
272                 usage();
273
274         printf("Running with '%s' RDBMS\n", DBDesc[ rdbms ].longname); 
275
276         if ( initMode ) {
277                 ftsDB   *db = *initConnections(rdbms, 1, dbname);
278                 time_t  prev;
279
280                 if (!lex)  lex = "gendata/lex";
281                 if (!doc)  doc = "gendata/gamma-lens";
282                 finnegan_init(lex, doc);
283
284                 db->startCreateScheme(db, flags);
285                 prev = time(NULL);
286                 for(i=0;i<n;i++) {
287                         generate_doc(&b);
288                         db->InsertRow(db, i+1, b.str);
289                         if ( !quiet && prev!=time(NULL) ) {
290                                 printf("\r%d(%.02f%%) rows inserted", i, (100.0*i)/n);
291                                 fflush(stdout);
292                                 prev = time(NULL);
293                         }
294                 }
295                 printf("%s%d(100.00%%) rows inserted. Finalyze insertion... ", 
296                         (quiet) ? "" : "\r", i);
297                 fflush(stdout);
298                 db->finishCreateScheme(db);
299                 printf("done\n");
300                 db->Close(db);
301         } else {
302                 ftsDB   **dbs = initConnections(rdbms, nclients, dbname);
303                 pthread_t       *tid = (pthread_t*)malloc( sizeof(pthread_t) * nclients);
304                 struct  timeval begin;
305                 double  elapsed;
306                 int     total=0, nres=0;
307                 struct      timespec  sleepTo = { 0, 0 };
308
309                 /*
310                  * startup generator
311                  */
312                 if (!lex)  lex = "gendata/query-lex";
313                 if (!doc)  doc = "gendata/query-lens";
314                 finnegan_init(lex, doc);
315
316                 /*
317                  * Initial query
318                  */
319                 if ( !quiet ) {
320                         printf("\r0(0.00%%) queries proceed");
321                         fflush(stdout);
322                 }
323                 benchFlags = flags;
324                 benchCount = n;
325
326                 gettimeofday(&begin,NULL);
327
328         pthread_mutex_lock( &mutexFinish );
329                 for(i=0;i<nclients;i++) {
330                         if ( pthread_create(tid+i, NULL, execBench, (void*)dbs[i]) != 0 ) {
331                                 fprintf(stderr,"pthread_create failed: %s\n", strerror(errno));
332                                 exit(1);
333                         }
334                 }
335
336                 for(;;) {
337                         int res, ntogo = 0;
338
339                         total = 0;
340                         for(i=0;i<nclients;i++) {
341                                 pthread_mutex_lock(&dbs[i]->nqueryMutex);
342                                 total +=dbs[i]->nquery;
343                                 if ( dbs[i]->nquery < n )
344                                         ntogo++;
345                                 pthread_mutex_unlock(&dbs[i]->nqueryMutex);
346                         }
347
348                         if ( ntogo == 0 ) 
349                                 break;
350
351                         if ( !quiet ) {
352                                 printf("\r%d(%.02f%%) queries proceed", total, (100.0*(float)total)/(nclients * n));
353                                 fflush(stdout);
354                         }
355                         
356                         sleepTo.tv_sec = time(NULL) + 1;
357                         res = pthread_cond_timedwait( &condFinish, &mutexFinish, &sleepTo );
358
359                         if ( !(res == ETIMEDOUT || res == 0) ) {
360                                 fprintf(stderr,"pthread_cond_timedwait failed: %s\n", strerror(errno));
361                                 exit(1);
362                         }
363                 }
364                 elapsed = elapsedtime(&begin);
365                 pthread_mutex_unlock( &mutexFinish );
366
367                 for(i=0;i<nclients;i++) {
368                         pthread_join(tid[i], NULL);
369                         nres += dbs[i]->nres;
370                         dbs[i]->Close(dbs[i]);
371                 }
372
373                 printf("%s%d(%.02f%%) queries proceed\n", 
374                         (quiet) ? "" : "\r", total, (100.0*(float)total)/(nclients * n));
375                 printf("Total number of result: %d\n", nres);
376                 printf("Total time: %.02f sec, Queries per second: %.02f\n", elapsed, total/elapsed);
377                 fflush(stdout);
378         }
379
380         return 0;
381 }